otpauth.esm.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866
  1. //! otpauth 9.3.1 | (c) Héctor Molinero Fernández | MIT | https://github.com/hectorm/otpauth
  2. //! noble-hashes 1.4.0 | (c) Paul Miller | MIT | https://github.com/paulmillr/noble-hashes
  3. /// <reference types="./otpauth.d.ts" />
  4. // @ts-nocheck
  5. /**
  6. * Converts an integer to an Uint8Array.
  7. * @param {number} num Integer.
  8. * @returns {Uint8Array} Uint8Array.
  9. */ const uintDecode = (num)=>{
  10. const buf = new ArrayBuffer(8);
  11. const arr = new Uint8Array(buf);
  12. let acc = num;
  13. for(let i = 7; i >= 0; i--){
  14. if (acc === 0) break;
  15. arr[i] = acc & 255;
  16. acc -= arr[i];
  17. acc /= 256;
  18. }
  19. return arr;
  20. };
  21. function number(n) {
  22. if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);
  23. }
  24. // copied from utils
  25. function isBytes(a) {
  26. return a instanceof Uint8Array || a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array';
  27. }
  28. function bytes(b, ...lengths) {
  29. if (!isBytes(b)) throw new Error('Uint8Array expected');
  30. if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
  31. }
  32. function hash(h) {
  33. if (typeof h !== 'function' || typeof h.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor');
  34. number(h.outputLen);
  35. number(h.blockLen);
  36. }
  37. function exists(instance, checkFinished = true) {
  38. if (instance.destroyed) throw new Error('Hash instance has been destroyed');
  39. if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');
  40. }
  41. function output(out, instance) {
  42. bytes(out);
  43. const min = instance.outputLen;
  44. if (out.length < min) {
  45. throw new Error(`digestInto() expects output buffer of length at least ${min}`);
  46. }
  47. }
  48. /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
  49. // node.js versions earlier than v19 don't declare it in global scope.
  50. // For node.js, package.json#exports field mapping rewrites import
  51. // from `crypto` to `cryptoNode`, which imports native module.
  52. // Makes the utils un-importable in browsers without a bundler.
  53. // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
  54. const u32 = (arr)=>new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
  55. // Cast array to view
  56. const createView = (arr)=>new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
  57. // The rotate right (circular right shift) operation for uint32
  58. const rotr = (word, shift)=>word << 32 - shift | word >>> shift;
  59. // The rotate left (circular left shift) operation for uint32
  60. const rotl = (word, shift)=>word << shift | word >>> 32 - shift >>> 0;
  61. const isLE = new Uint8Array(new Uint32Array([
  62. 0x11223344
  63. ]).buffer)[0] === 0x44;
  64. // The byte swap operation for uint32
  65. const byteSwap = (word)=>word << 24 & 0xff000000 | word << 8 & 0xff0000 | word >>> 8 & 0xff00 | word >>> 24 & 0xff;
  66. // In place byte swap for Uint32Array
  67. function byteSwap32(arr) {
  68. for(let i = 0; i < arr.length; i++){
  69. arr[i] = byteSwap(arr[i]);
  70. }
  71. }
  72. /**
  73. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  74. */ function utf8ToBytes(str) {
  75. if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  76. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  77. }
  78. /**
  79. * Normalizes (non-hex) string or Uint8Array to Uint8Array.
  80. * Warning: when Uint8Array is passed, it would NOT get copied.
  81. * Keep in mind for future mutable operations.
  82. */ function toBytes(data) {
  83. if (typeof data === 'string') data = utf8ToBytes(data);
  84. bytes(data);
  85. return data;
  86. }
  87. // For runtime check if class implements interface
  88. class Hash {
  89. // Safe version that clones internal state
  90. clone() {
  91. return this._cloneInto();
  92. }
  93. }
  94. function wrapConstructor(hashCons) {
  95. const hashC = (msg)=>hashCons().update(toBytes(msg)).digest();
  96. const tmp = hashCons();
  97. hashC.outputLen = tmp.outputLen;
  98. hashC.blockLen = tmp.blockLen;
  99. hashC.create = ()=>hashCons();
  100. return hashC;
  101. }
  102. // HMAC (RFC 2104)
  103. class HMAC extends Hash {
  104. update(buf) {
  105. exists(this);
  106. this.iHash.update(buf);
  107. return this;
  108. }
  109. digestInto(out) {
  110. exists(this);
  111. bytes(out, this.outputLen);
  112. this.finished = true;
  113. this.iHash.digestInto(out);
  114. this.oHash.update(out);
  115. this.oHash.digestInto(out);
  116. this.destroy();
  117. }
  118. digest() {
  119. const out = new Uint8Array(this.oHash.outputLen);
  120. this.digestInto(out);
  121. return out;
  122. }
  123. _cloneInto(to) {
  124. // Create new instance without calling constructor since key already in state and we don't know it.
  125. to || (to = Object.create(Object.getPrototypeOf(this), {}));
  126. const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
  127. to = to;
  128. to.finished = finished;
  129. to.destroyed = destroyed;
  130. to.blockLen = blockLen;
  131. to.outputLen = outputLen;
  132. to.oHash = oHash._cloneInto(to.oHash);
  133. to.iHash = iHash._cloneInto(to.iHash);
  134. return to;
  135. }
  136. destroy() {
  137. this.destroyed = true;
  138. this.oHash.destroy();
  139. this.iHash.destroy();
  140. }
  141. constructor(hash$1, _key){
  142. super();
  143. this.finished = false;
  144. this.destroyed = false;
  145. hash(hash$1);
  146. const key = toBytes(_key);
  147. this.iHash = hash$1.create();
  148. if (typeof this.iHash.update !== 'function') throw new Error('Expected instance of class which extends utils.Hash');
  149. this.blockLen = this.iHash.blockLen;
  150. this.outputLen = this.iHash.outputLen;
  151. const blockLen = this.blockLen;
  152. const pad = new Uint8Array(blockLen);
  153. // blockLen can be bigger than outputLen
  154. pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
  155. for(let i = 0; i < pad.length; i++)pad[i] ^= 0x36;
  156. this.iHash.update(pad);
  157. // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
  158. this.oHash = hash$1.create();
  159. // Undo internal XOR && apply outer XOR
  160. for(let i = 0; i < pad.length; i++)pad[i] ^= 0x36 ^ 0x5c;
  161. this.oHash.update(pad);
  162. pad.fill(0);
  163. }
  164. }
  165. /**
  166. * HMAC: RFC2104 message authentication code.
  167. * @param hash - function that would be used e.g. sha256
  168. * @param key - message key
  169. * @param message - message data
  170. */ const hmac = (hash, key, message)=>new HMAC(hash, key).update(message).digest();
  171. hmac.create = (hash, key)=>new HMAC(hash, key);
  172. // Polyfill for Safari 14
  173. function setBigUint64(view, byteOffset, value, isLE) {
  174. if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);
  175. const _32n = BigInt(32);
  176. const _u32_max = BigInt(0xffffffff);
  177. const wh = Number(value >> _32n & _u32_max);
  178. const wl = Number(value & _u32_max);
  179. const h = isLE ? 4 : 0;
  180. const l = isLE ? 0 : 4;
  181. view.setUint32(byteOffset + h, wh, isLE);
  182. view.setUint32(byteOffset + l, wl, isLE);
  183. }
  184. // Choice: a ? b : c
  185. const Chi = (a, b, c)=>a & b ^ ~a & c;
  186. // Majority function, true if any two inpust is true
  187. const Maj = (a, b, c)=>a & b ^ a & c ^ b & c;
  188. /**
  189. * Merkle-Damgard hash construction base class.
  190. * Could be used to create MD5, RIPEMD, SHA1, SHA2.
  191. */ class HashMD extends Hash {
  192. update(data) {
  193. exists(this);
  194. const { view, buffer, blockLen } = this;
  195. data = toBytes(data);
  196. const len = data.length;
  197. for(let pos = 0; pos < len;){
  198. const take = Math.min(blockLen - this.pos, len - pos);
  199. // Fast path: we have at least one block in input, cast it to view and process
  200. if (take === blockLen) {
  201. const dataView = createView(data);
  202. for(; blockLen <= len - pos; pos += blockLen)this.process(dataView, pos);
  203. continue;
  204. }
  205. buffer.set(data.subarray(pos, pos + take), this.pos);
  206. this.pos += take;
  207. pos += take;
  208. if (this.pos === blockLen) {
  209. this.process(view, 0);
  210. this.pos = 0;
  211. }
  212. }
  213. this.length += data.length;
  214. this.roundClean();
  215. return this;
  216. }
  217. digestInto(out) {
  218. exists(this);
  219. output(out, this);
  220. this.finished = true;
  221. // Padding
  222. // We can avoid allocation of buffer for padding completely if it
  223. // was previously not allocated here. But it won't change performance.
  224. const { buffer, view, blockLen, isLE } = this;
  225. let { pos } = this;
  226. // append the bit '1' to the message
  227. buffer[pos++] = 0b10000000;
  228. this.buffer.subarray(pos).fill(0);
  229. // we have less than padOffset left in buffer, so we cannot put length in
  230. // current block, need process it and pad again
  231. if (this.padOffset > blockLen - pos) {
  232. this.process(view, 0);
  233. pos = 0;
  234. }
  235. // Pad until full block byte with zeros
  236. for(let i = pos; i < blockLen; i++)buffer[i] = 0;
  237. // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
  238. // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
  239. // So we just write lowest 64 bits of that value.
  240. setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
  241. this.process(view, 0);
  242. const oview = createView(out);
  243. const len = this.outputLen;
  244. // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
  245. if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');
  246. const outLen = len / 4;
  247. const state = this.get();
  248. if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');
  249. for(let i = 0; i < outLen; i++)oview.setUint32(4 * i, state[i], isLE);
  250. }
  251. digest() {
  252. const { buffer, outputLen } = this;
  253. this.digestInto(buffer);
  254. const res = buffer.slice(0, outputLen);
  255. this.destroy();
  256. return res;
  257. }
  258. _cloneInto(to) {
  259. to || (to = new this.constructor());
  260. to.set(...this.get());
  261. const { blockLen, buffer, length, finished, destroyed, pos } = this;
  262. to.length = length;
  263. to.pos = pos;
  264. to.finished = finished;
  265. to.destroyed = destroyed;
  266. if (length % blockLen) to.buffer.set(buffer);
  267. return to;
  268. }
  269. constructor(blockLen, outputLen, padOffset, isLE){
  270. super();
  271. this.blockLen = blockLen;
  272. this.outputLen = outputLen;
  273. this.padOffset = padOffset;
  274. this.isLE = isLE;
  275. this.finished = false;
  276. this.length = 0;
  277. this.pos = 0;
  278. this.destroyed = false;
  279. this.buffer = new Uint8Array(blockLen);
  280. this.view = createView(this.buffer);
  281. }
  282. }
  283. // SHA1 (RFC 3174) was cryptographically broken. It's still used. Don't use it for a new protocol.
  284. // Initial state
  285. const SHA1_IV = /* @__PURE__ */ new Uint32Array([
  286. 0x67452301,
  287. 0xefcdab89,
  288. 0x98badcfe,
  289. 0x10325476,
  290. 0xc3d2e1f0
  291. ]);
  292. // Temporary buffer, not used to store anything between runs
  293. // Named this way because it matches specification.
  294. const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
  295. class SHA1 extends HashMD {
  296. get() {
  297. const { A, B, C, D, E } = this;
  298. return [
  299. A,
  300. B,
  301. C,
  302. D,
  303. E
  304. ];
  305. }
  306. set(A, B, C, D, E) {
  307. this.A = A | 0;
  308. this.B = B | 0;
  309. this.C = C | 0;
  310. this.D = D | 0;
  311. this.E = E | 0;
  312. }
  313. process(view, offset) {
  314. for(let i = 0; i < 16; i++, offset += 4)SHA1_W[i] = view.getUint32(offset, false);
  315. 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);
  316. // Compression function main loop, 80 rounds
  317. let { A, B, C, D, E } = this;
  318. for(let i = 0; i < 80; i++){
  319. let F, K;
  320. if (i < 20) {
  321. F = Chi(B, C, D);
  322. K = 0x5a827999;
  323. } else if (i < 40) {
  324. F = B ^ C ^ D;
  325. K = 0x6ed9eba1;
  326. } else if (i < 60) {
  327. F = Maj(B, C, D);
  328. K = 0x8f1bbcdc;
  329. } else {
  330. F = B ^ C ^ D;
  331. K = 0xca62c1d6;
  332. }
  333. const T = rotl(A, 5) + F + E + K + SHA1_W[i] | 0;
  334. E = D;
  335. D = C;
  336. C = rotl(B, 30);
  337. B = A;
  338. A = T;
  339. }
  340. // Add the compressed chunk to the current hash value
  341. A = A + this.A | 0;
  342. B = B + this.B | 0;
  343. C = C + this.C | 0;
  344. D = D + this.D | 0;
  345. E = E + this.E | 0;
  346. this.set(A, B, C, D, E);
  347. }
  348. roundClean() {
  349. SHA1_W.fill(0);
  350. }
  351. destroy() {
  352. this.set(0, 0, 0, 0, 0);
  353. this.buffer.fill(0);
  354. }
  355. constructor(){
  356. super(64, 20, 8, false);
  357. this.A = SHA1_IV[0] | 0;
  358. this.B = SHA1_IV[1] | 0;
  359. this.C = SHA1_IV[2] | 0;
  360. this.D = SHA1_IV[3] | 0;
  361. this.E = SHA1_IV[4] | 0;
  362. }
  363. }
  364. const sha1 = /* @__PURE__ */ wrapConstructor(()=>new SHA1());
  365. // SHA2-256 need to try 2^128 hashes to execute birthday attack.
  366. // BTC network is doing 2^67 hashes/sec as per early 2023.
  367. // Round constants:
  368. // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
  369. // prettier-ignore
  370. const SHA256_K = /* @__PURE__ */ new Uint32Array([
  371. 0x428a2f98,
  372. 0x71374491,
  373. 0xb5c0fbcf,
  374. 0xe9b5dba5,
  375. 0x3956c25b,
  376. 0x59f111f1,
  377. 0x923f82a4,
  378. 0xab1c5ed5,
  379. 0xd807aa98,
  380. 0x12835b01,
  381. 0x243185be,
  382. 0x550c7dc3,
  383. 0x72be5d74,
  384. 0x80deb1fe,
  385. 0x9bdc06a7,
  386. 0xc19bf174,
  387. 0xe49b69c1,
  388. 0xefbe4786,
  389. 0x0fc19dc6,
  390. 0x240ca1cc,
  391. 0x2de92c6f,
  392. 0x4a7484aa,
  393. 0x5cb0a9dc,
  394. 0x76f988da,
  395. 0x983e5152,
  396. 0xa831c66d,
  397. 0xb00327c8,
  398. 0xbf597fc7,
  399. 0xc6e00bf3,
  400. 0xd5a79147,
  401. 0x06ca6351,
  402. 0x14292967,
  403. 0x27b70a85,
  404. 0x2e1b2138,
  405. 0x4d2c6dfc,
  406. 0x53380d13,
  407. 0x650a7354,
  408. 0x766a0abb,
  409. 0x81c2c92e,
  410. 0x92722c85,
  411. 0xa2bfe8a1,
  412. 0xa81a664b,
  413. 0xc24b8b70,
  414. 0xc76c51a3,
  415. 0xd192e819,
  416. 0xd6990624,
  417. 0xf40e3585,
  418. 0x106aa070,
  419. 0x19a4c116,
  420. 0x1e376c08,
  421. 0x2748774c,
  422. 0x34b0bcb5,
  423. 0x391c0cb3,
  424. 0x4ed8aa4a,
  425. 0x5b9cca4f,
  426. 0x682e6ff3,
  427. 0x748f82ee,
  428. 0x78a5636f,
  429. 0x84c87814,
  430. 0x8cc70208,
  431. 0x90befffa,
  432. 0xa4506ceb,
  433. 0xbef9a3f7,
  434. 0xc67178f2
  435. ]);
  436. // Initial state:
  437. // first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
  438. // prettier-ignore
  439. const SHA256_IV = /* @__PURE__ */ new Uint32Array([
  440. 0x6a09e667,
  441. 0xbb67ae85,
  442. 0x3c6ef372,
  443. 0xa54ff53a,
  444. 0x510e527f,
  445. 0x9b05688c,
  446. 0x1f83d9ab,
  447. 0x5be0cd19
  448. ]);
  449. // Temporary buffer, not used to store anything between runs
  450. // Named this way because it matches specification.
  451. const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
  452. class SHA256 extends HashMD {
  453. get() {
  454. const { A, B, C, D, E, F, G, H } = this;
  455. return [
  456. A,
  457. B,
  458. C,
  459. D,
  460. E,
  461. F,
  462. G,
  463. H
  464. ];
  465. }
  466. // prettier-ignore
  467. set(A, B, C, D, E, F, G, H) {
  468. this.A = A | 0;
  469. this.B = B | 0;
  470. this.C = C | 0;
  471. this.D = D | 0;
  472. this.E = E | 0;
  473. this.F = F | 0;
  474. this.G = G | 0;
  475. this.H = H | 0;
  476. }
  477. process(view, offset) {
  478. // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
  479. for(let i = 0; i < 16; i++, offset += 4)SHA256_W[i] = view.getUint32(offset, false);
  480. for(let i = 16; i < 64; i++){
  481. const W15 = SHA256_W[i - 15];
  482. const W2 = SHA256_W[i - 2];
  483. const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
  484. const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
  485. SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
  486. }
  487. // Compression function main loop, 64 rounds
  488. let { A, B, C, D, E, F, G, H } = this;
  489. for(let i = 0; i < 64; i++){
  490. const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
  491. const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
  492. const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
  493. const T2 = sigma0 + Maj(A, B, C) | 0;
  494. H = G;
  495. G = F;
  496. F = E;
  497. E = D + T1 | 0;
  498. D = C;
  499. C = B;
  500. B = A;
  501. A = T1 + T2 | 0;
  502. }
  503. // Add the compressed chunk to the current hash value
  504. A = A + this.A | 0;
  505. B = B + this.B | 0;
  506. C = C + this.C | 0;
  507. D = D + this.D | 0;
  508. E = E + this.E | 0;
  509. F = F + this.F | 0;
  510. G = G + this.G | 0;
  511. H = H + this.H | 0;
  512. this.set(A, B, C, D, E, F, G, H);
  513. }
  514. roundClean() {
  515. SHA256_W.fill(0);
  516. }
  517. destroy() {
  518. this.set(0, 0, 0, 0, 0, 0, 0, 0);
  519. this.buffer.fill(0);
  520. }
  521. constructor(){
  522. super(64, 32, 8, false);
  523. // We cannot use array here since array allows indexing by variable
  524. // which means optimizer/compiler cannot use registers.
  525. this.A = SHA256_IV[0] | 0;
  526. this.B = SHA256_IV[1] | 0;
  527. this.C = SHA256_IV[2] | 0;
  528. this.D = SHA256_IV[3] | 0;
  529. this.E = SHA256_IV[4] | 0;
  530. this.F = SHA256_IV[5] | 0;
  531. this.G = SHA256_IV[6] | 0;
  532. this.H = SHA256_IV[7] | 0;
  533. }
  534. }
  535. // Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
  536. class SHA224 extends SHA256 {
  537. constructor(){
  538. super();
  539. this.A = 0xc1059ed8 | 0;
  540. this.B = 0x367cd507 | 0;
  541. this.C = 0x3070dd17 | 0;
  542. this.D = 0xf70e5939 | 0;
  543. this.E = 0xffc00b31 | 0;
  544. this.F = 0x68581511 | 0;
  545. this.G = 0x64f98fa7 | 0;
  546. this.H = 0xbefa4fa4 | 0;
  547. this.outputLen = 28;
  548. }
  549. }
  550. /**
  551. * SHA2-256 hash function
  552. * @param message - data that would be hashed
  553. */ const sha256 = /* @__PURE__ */ wrapConstructor(()=>new SHA256());
  554. const sha224 = /* @__PURE__ */ wrapConstructor(()=>new SHA224());
  555. const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
  556. const _32n = /* @__PURE__ */ BigInt(32);
  557. // We are not using BigUint64Array, because they are extremely slow as per 2022
  558. function fromBig(n, le = false) {
  559. if (le) return {
  560. h: Number(n & U32_MASK64),
  561. l: Number(n >> _32n & U32_MASK64)
  562. };
  563. return {
  564. h: Number(n >> _32n & U32_MASK64) | 0,
  565. l: Number(n & U32_MASK64) | 0
  566. };
  567. }
  568. function split(lst, le = false) {
  569. let Ah = new Uint32Array(lst.length);
  570. let Al = new Uint32Array(lst.length);
  571. for(let i = 0; i < lst.length; i++){
  572. const { h, l } = fromBig(lst[i], le);
  573. [Ah[i], Al[i]] = [
  574. h,
  575. l
  576. ];
  577. }
  578. return [
  579. Ah,
  580. Al
  581. ];
  582. }
  583. const toBig = (h, l)=>BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
  584. // for Shift in [0, 32)
  585. const shrSH = (h, _l, s)=>h >>> s;
  586. const shrSL = (h, l, s)=>h << 32 - s | l >>> s;
  587. // Right rotate for Shift in [1, 32)
  588. const rotrSH = (h, l, s)=>h >>> s | l << 32 - s;
  589. const rotrSL = (h, l, s)=>h << 32 - s | l >>> s;
  590. // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
  591. const rotrBH = (h, l, s)=>h << 64 - s | l >>> s - 32;
  592. const rotrBL = (h, l, s)=>h >>> s - 32 | l << 64 - s;
  593. // Right rotate for shift===32 (just swaps l&h)
  594. const rotr32H = (_h, l)=>l;
  595. const rotr32L = (h, _l)=>h;
  596. // Left rotate for Shift in [1, 32)
  597. const rotlSH = (h, l, s)=>h << s | l >>> 32 - s;
  598. const rotlSL = (h, l, s)=>l << s | h >>> 32 - s;
  599. // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
  600. const rotlBH = (h, l, s)=>l << s - 32 | h >>> 64 - s;
  601. const rotlBL = (h, l, s)=>h << s - 32 | l >>> 64 - s;
  602. // JS uses 32-bit signed integers for bitwise operations which means we cannot
  603. // simple take carry out of low bit sum by shift, we need to use division.
  604. function add(Ah, Al, Bh, Bl) {
  605. const l = (Al >>> 0) + (Bl >>> 0);
  606. return {
  607. h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
  608. l: l | 0
  609. };
  610. }
  611. // Addition with more than 2 elements
  612. const add3L = (Al, Bl, Cl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
  613. const add3H = (low, Ah, Bh, Ch)=>Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
  614. const add4L = (Al, Bl, Cl, Dl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
  615. const add4H = (low, Ah, Bh, Ch, Dh)=>Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
  616. const add5L = (Al, Bl, Cl, Dl, El)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
  617. const add5H = (low, Ah, Bh, Ch, Dh, Eh)=>Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
  618. // prettier-ignore
  619. const u64 = {
  620. fromBig,
  621. split,
  622. toBig,
  623. shrSH,
  624. shrSL,
  625. rotrSH,
  626. rotrSL,
  627. rotrBH,
  628. rotrBL,
  629. rotr32H,
  630. rotr32L,
  631. rotlSH,
  632. rotlSL,
  633. rotlBH,
  634. rotlBL,
  635. add,
  636. add3L,
  637. add3H,
  638. add4L,
  639. add4H,
  640. add5H,
  641. add5L
  642. };
  643. // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
  644. // prettier-ignore
  645. const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (()=>u64.split([
  646. '0x428a2f98d728ae22',
  647. '0x7137449123ef65cd',
  648. '0xb5c0fbcfec4d3b2f',
  649. '0xe9b5dba58189dbbc',
  650. '0x3956c25bf348b538',
  651. '0x59f111f1b605d019',
  652. '0x923f82a4af194f9b',
  653. '0xab1c5ed5da6d8118',
  654. '0xd807aa98a3030242',
  655. '0x12835b0145706fbe',
  656. '0x243185be4ee4b28c',
  657. '0x550c7dc3d5ffb4e2',
  658. '0x72be5d74f27b896f',
  659. '0x80deb1fe3b1696b1',
  660. '0x9bdc06a725c71235',
  661. '0xc19bf174cf692694',
  662. '0xe49b69c19ef14ad2',
  663. '0xefbe4786384f25e3',
  664. '0x0fc19dc68b8cd5b5',
  665. '0x240ca1cc77ac9c65',
  666. '0x2de92c6f592b0275',
  667. '0x4a7484aa6ea6e483',
  668. '0x5cb0a9dcbd41fbd4',
  669. '0x76f988da831153b5',
  670. '0x983e5152ee66dfab',
  671. '0xa831c66d2db43210',
  672. '0xb00327c898fb213f',
  673. '0xbf597fc7beef0ee4',
  674. '0xc6e00bf33da88fc2',
  675. '0xd5a79147930aa725',
  676. '0x06ca6351e003826f',
  677. '0x142929670a0e6e70',
  678. '0x27b70a8546d22ffc',
  679. '0x2e1b21385c26c926',
  680. '0x4d2c6dfc5ac42aed',
  681. '0x53380d139d95b3df',
  682. '0x650a73548baf63de',
  683. '0x766a0abb3c77b2a8',
  684. '0x81c2c92e47edaee6',
  685. '0x92722c851482353b',
  686. '0xa2bfe8a14cf10364',
  687. '0xa81a664bbc423001',
  688. '0xc24b8b70d0f89791',
  689. '0xc76c51a30654be30',
  690. '0xd192e819d6ef5218',
  691. '0xd69906245565a910',
  692. '0xf40e35855771202a',
  693. '0x106aa07032bbd1b8',
  694. '0x19a4c116b8d2d0c8',
  695. '0x1e376c085141ab53',
  696. '0x2748774cdf8eeb99',
  697. '0x34b0bcb5e19b48a8',
  698. '0x391c0cb3c5c95a63',
  699. '0x4ed8aa4ae3418acb',
  700. '0x5b9cca4f7763e373',
  701. '0x682e6ff3d6b2b8a3',
  702. '0x748f82ee5defb2fc',
  703. '0x78a5636f43172f60',
  704. '0x84c87814a1f0ab72',
  705. '0x8cc702081a6439ec',
  706. '0x90befffa23631e28',
  707. '0xa4506cebde82bde9',
  708. '0xbef9a3f7b2c67915',
  709. '0xc67178f2e372532b',
  710. '0xca273eceea26619c',
  711. '0xd186b8c721c0c207',
  712. '0xeada7dd6cde0eb1e',
  713. '0xf57d4f7fee6ed178',
  714. '0x06f067aa72176fba',
  715. '0x0a637dc5a2c898a6',
  716. '0x113f9804bef90dae',
  717. '0x1b710b35131c471b',
  718. '0x28db77f523047d84',
  719. '0x32caab7b40c72493',
  720. '0x3c9ebe0a15c9bebc',
  721. '0x431d67c49c100d4c',
  722. '0x4cc5d4becb3e42b6',
  723. '0x597f299cfc657e2a',
  724. '0x5fcb6fab3ad6faec',
  725. '0x6c44198c4a475817'
  726. ].map((n)=>BigInt(n))))();
  727. // Temporary buffer, not used to store anything between runs
  728. const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
  729. const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
  730. class SHA512 extends HashMD {
  731. // prettier-ignore
  732. get() {
  733. const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
  734. return [
  735. Ah,
  736. Al,
  737. Bh,
  738. Bl,
  739. Ch,
  740. Cl,
  741. Dh,
  742. Dl,
  743. Eh,
  744. El,
  745. Fh,
  746. Fl,
  747. Gh,
  748. Gl,
  749. Hh,
  750. Hl
  751. ];
  752. }
  753. // prettier-ignore
  754. set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
  755. this.Ah = Ah | 0;
  756. this.Al = Al | 0;
  757. this.Bh = Bh | 0;
  758. this.Bl = Bl | 0;
  759. this.Ch = Ch | 0;
  760. this.Cl = Cl | 0;
  761. this.Dh = Dh | 0;
  762. this.Dl = Dl | 0;
  763. this.Eh = Eh | 0;
  764. this.El = El | 0;
  765. this.Fh = Fh | 0;
  766. this.Fl = Fl | 0;
  767. this.Gh = Gh | 0;
  768. this.Gl = Gl | 0;
  769. this.Hh = Hh | 0;
  770. this.Hl = Hl | 0;
  771. }
  772. process(view, offset) {
  773. // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
  774. for(let i = 0; i < 16; i++, offset += 4){
  775. SHA512_W_H[i] = view.getUint32(offset);
  776. SHA512_W_L[i] = view.getUint32(offset += 4);
  777. }
  778. for(let i = 16; i < 80; i++){
  779. // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
  780. const W15h = SHA512_W_H[i - 15] | 0;
  781. const W15l = SHA512_W_L[i - 15] | 0;
  782. const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
  783. const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
  784. // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
  785. const W2h = SHA512_W_H[i - 2] | 0;
  786. const W2l = SHA512_W_L[i - 2] | 0;
  787. const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
  788. const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
  789. // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
  790. const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
  791. const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
  792. SHA512_W_H[i] = SUMh | 0;
  793. SHA512_W_L[i] = SUMl | 0;
  794. }
  795. let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
  796. // Compression function main loop, 80 rounds
  797. for(let i = 0; i < 80; i++){
  798. // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
  799. const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
  800. const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
  801. //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
  802. const CHIh = Eh & Fh ^ ~Eh & Gh;
  803. const CHIl = El & Fl ^ ~El & Gl;
  804. // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
  805. // prettier-ignore
  806. const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
  807. const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
  808. const T1l = T1ll | 0;
  809. // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
  810. const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
  811. const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
  812. const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
  813. const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
  814. Hh = Gh | 0;
  815. Hl = Gl | 0;
  816. Gh = Fh | 0;
  817. Gl = Fl | 0;
  818. Fh = Eh | 0;
  819. Fl = El | 0;
  820. ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
  821. Dh = Ch | 0;
  822. Dl = Cl | 0;
  823. Ch = Bh | 0;
  824. Cl = Bl | 0;
  825. Bh = Ah | 0;
  826. Bl = Al | 0;
  827. const All = u64.add3L(T1l, sigma0l, MAJl);
  828. Ah = u64.add3H(All, T1h, sigma0h, MAJh);
  829. Al = All | 0;
  830. }
  831. // Add the compressed chunk to the current hash value
  832. ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
  833. ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
  834. ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
  835. ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
  836. ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
  837. ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
  838. ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
  839. ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
  840. this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
  841. }
  842. roundClean() {
  843. SHA512_W_H.fill(0);
  844. SHA512_W_L.fill(0);
  845. }
  846. destroy() {
  847. this.buffer.fill(0);
  848. this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  849. }
  850. constructor(){
  851. super(128, 64, 16, false);
  852. // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
  853. // Also looks cleaner and easier to verify with spec.
  854. // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
  855. // h -- high 32 bits, l -- low 32 bits
  856. this.Ah = 0x6a09e667 | 0;
  857. this.Al = 0xf3bcc908 | 0;
  858. this.Bh = 0xbb67ae85 | 0;
  859. this.Bl = 0x84caa73b | 0;
  860. this.Ch = 0x3c6ef372 | 0;
  861. this.Cl = 0xfe94f82b | 0;
  862. this.Dh = 0xa54ff53a | 0;
  863. this.Dl = 0x5f1d36f1 | 0;
  864. this.Eh = 0x510e527f | 0;
  865. this.El = 0xade682d1 | 0;
  866. this.Fh = 0x9b05688c | 0;
  867. this.Fl = 0x2b3e6c1f | 0;
  868. this.Gh = 0x1f83d9ab | 0;
  869. this.Gl = 0xfb41bd6b | 0;
  870. this.Hh = 0x5be0cd19 | 0;
  871. this.Hl = 0x137e2179 | 0;
  872. }
  873. }
  874. class SHA384 extends SHA512 {
  875. constructor(){
  876. super();
  877. // h -- high 32 bits, l -- low 32 bits
  878. this.Ah = 0xcbbb9d5d | 0;
  879. this.Al = 0xc1059ed8 | 0;
  880. this.Bh = 0x629a292a | 0;
  881. this.Bl = 0x367cd507 | 0;
  882. this.Ch = 0x9159015a | 0;
  883. this.Cl = 0x3070dd17 | 0;
  884. this.Dh = 0x152fecd8 | 0;
  885. this.Dl = 0xf70e5939 | 0;
  886. this.Eh = 0x67332667 | 0;
  887. this.El = 0xffc00b31 | 0;
  888. this.Fh = 0x8eb44a87 | 0;
  889. this.Fl = 0x68581511 | 0;
  890. this.Gh = 0xdb0c2e0d | 0;
  891. this.Gl = 0x64f98fa7 | 0;
  892. this.Hh = 0x47b5481d | 0;
  893. this.Hl = 0xbefa4fa4 | 0;
  894. this.outputLen = 48;
  895. }
  896. }
  897. const sha512 = /* @__PURE__ */ wrapConstructor(()=>new SHA512());
  898. const sha384 = /* @__PURE__ */ wrapConstructor(()=>new SHA384());
  899. // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
  900. // It's called a sponge function.
  901. // Various per round constants calculations
  902. const SHA3_PI = [];
  903. const SHA3_ROTL = [];
  904. const _SHA3_IOTA = [];
  905. const _0n = /* @__PURE__ */ BigInt(0);
  906. const _1n = /* @__PURE__ */ BigInt(1);
  907. const _2n = /* @__PURE__ */ BigInt(2);
  908. const _7n = /* @__PURE__ */ BigInt(7);
  909. const _256n = /* @__PURE__ */ BigInt(256);
  910. const _0x71n = /* @__PURE__ */ BigInt(0x71);
  911. for(let round = 0, R = _1n, x = 1, y = 0; round < 24; round++){
  912. // Pi
  913. [x, y] = [
  914. y,
  915. (2 * x + 3 * y) % 5
  916. ];
  917. SHA3_PI.push(2 * (5 * y + x));
  918. // Rotational
  919. SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
  920. // Iota
  921. let t = _0n;
  922. for(let j = 0; j < 7; j++){
  923. R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
  924. if (R & _2n) t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
  925. }
  926. _SHA3_IOTA.push(t);
  927. }
  928. const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);
  929. // Left rotation (without 0, 32, 64)
  930. const rotlH = (h, l, s)=>s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
  931. const rotlL = (h, l, s)=>s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
  932. // Same as keccakf1600, but allows to skip some rounds
  933. function keccakP(s, rounds = 24) {
  934. const B = new Uint32Array(5 * 2);
  935. // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
  936. for(let round = 24 - rounds; round < 24; round++){
  937. // Theta θ
  938. for(let x = 0; x < 10; x++)B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
  939. for(let x = 0; x < 10; x += 2){
  940. const idx1 = (x + 8) % 10;
  941. const idx0 = (x + 2) % 10;
  942. const B0 = B[idx0];
  943. const B1 = B[idx0 + 1];
  944. const Th = rotlH(B0, B1, 1) ^ B[idx1];
  945. const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
  946. for(let y = 0; y < 50; y += 10){
  947. s[x + y] ^= Th;
  948. s[x + y + 1] ^= Tl;
  949. }
  950. }
  951. // Rho (ρ) and Pi (π)
  952. let curH = s[2];
  953. let curL = s[3];
  954. for(let t = 0; t < 24; t++){
  955. const shift = SHA3_ROTL[t];
  956. const Th = rotlH(curH, curL, shift);
  957. const Tl = rotlL(curH, curL, shift);
  958. const PI = SHA3_PI[t];
  959. curH = s[PI];
  960. curL = s[PI + 1];
  961. s[PI] = Th;
  962. s[PI + 1] = Tl;
  963. }
  964. // Chi (χ)
  965. for(let y = 0; y < 50; y += 10){
  966. for(let x = 0; x < 10; x++)B[x] = s[y + x];
  967. for(let x = 0; x < 10; x++)s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
  968. }
  969. // Iota (ι)
  970. s[0] ^= SHA3_IOTA_H[round];
  971. s[1] ^= SHA3_IOTA_L[round];
  972. }
  973. B.fill(0);
  974. }
  975. class Keccak extends Hash {
  976. keccak() {
  977. if (!isLE) byteSwap32(this.state32);
  978. keccakP(this.state32, this.rounds);
  979. if (!isLE) byteSwap32(this.state32);
  980. this.posOut = 0;
  981. this.pos = 0;
  982. }
  983. update(data) {
  984. exists(this);
  985. const { blockLen, state } = this;
  986. data = toBytes(data);
  987. const len = data.length;
  988. for(let pos = 0; pos < len;){
  989. const take = Math.min(blockLen - this.pos, len - pos);
  990. for(let i = 0; i < take; i++)state[this.pos++] ^= data[pos++];
  991. if (this.pos === blockLen) this.keccak();
  992. }
  993. return this;
  994. }
  995. finish() {
  996. if (this.finished) return;
  997. this.finished = true;
  998. const { state, suffix, pos, blockLen } = this;
  999. // Do the padding
  1000. state[pos] ^= suffix;
  1001. if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();
  1002. state[blockLen - 1] ^= 0x80;
  1003. this.keccak();
  1004. }
  1005. writeInto(out) {
  1006. exists(this, false);
  1007. bytes(out);
  1008. this.finish();
  1009. const bufferOut = this.state;
  1010. const { blockLen } = this;
  1011. for(let pos = 0, len = out.length; pos < len;){
  1012. if (this.posOut >= blockLen) this.keccak();
  1013. const take = Math.min(blockLen - this.posOut, len - pos);
  1014. out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
  1015. this.posOut += take;
  1016. pos += take;
  1017. }
  1018. return out;
  1019. }
  1020. xofInto(out) {
  1021. // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
  1022. if (!this.enableXOF) throw new Error('XOF is not possible for this instance');
  1023. return this.writeInto(out);
  1024. }
  1025. xof(bytes) {
  1026. number(bytes);
  1027. return this.xofInto(new Uint8Array(bytes));
  1028. }
  1029. digestInto(out) {
  1030. output(out, this);
  1031. if (this.finished) throw new Error('digest() was already called');
  1032. this.writeInto(out);
  1033. this.destroy();
  1034. return out;
  1035. }
  1036. digest() {
  1037. return this.digestInto(new Uint8Array(this.outputLen));
  1038. }
  1039. destroy() {
  1040. this.destroyed = true;
  1041. this.state.fill(0);
  1042. }
  1043. _cloneInto(to) {
  1044. const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
  1045. to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
  1046. to.state32.set(this.state32);
  1047. to.pos = this.pos;
  1048. to.posOut = this.posOut;
  1049. to.finished = this.finished;
  1050. to.rounds = rounds;
  1051. // Suffix can change in cSHAKE
  1052. to.suffix = suffix;
  1053. to.outputLen = outputLen;
  1054. to.enableXOF = enableXOF;
  1055. to.destroyed = this.destroyed;
  1056. return to;
  1057. }
  1058. // NOTE: we accept arguments in bytes instead of bits here.
  1059. constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24){
  1060. super();
  1061. this.blockLen = blockLen;
  1062. this.suffix = suffix;
  1063. this.outputLen = outputLen;
  1064. this.enableXOF = enableXOF;
  1065. this.rounds = rounds;
  1066. this.pos = 0;
  1067. this.posOut = 0;
  1068. this.finished = false;
  1069. this.destroyed = false;
  1070. // Can be passed from user as dkLen
  1071. number(outputLen);
  1072. // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
  1073. if (0 >= this.blockLen || this.blockLen >= 200) throw new Error('Sha3 supports only keccak-f1600 function');
  1074. this.state = new Uint8Array(200);
  1075. this.state32 = u32(this.state);
  1076. }
  1077. }
  1078. const gen = (suffix, blockLen, outputLen)=>wrapConstructor(()=>new Keccak(blockLen, suffix, outputLen));
  1079. const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);
  1080. /**
  1081. * SHA3-256 hash function
  1082. * @param message - that would be hashed
  1083. */ const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);
  1084. const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);
  1085. const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);
  1086. /**
  1087. * "globalThis" ponyfill.
  1088. * @see [A horrifying globalThis polyfill in universal JavaScript](https://mathiasbynens.be/notes/globalthis)
  1089. * @type {Object.<string, *>}
  1090. */ const globalScope = (()=>{
  1091. if (typeof globalThis === "object") return globalThis;
  1092. else {
  1093. Object.defineProperty(Object.prototype, "__GLOBALTHIS__", {
  1094. get () {
  1095. return this;
  1096. },
  1097. configurable: true
  1098. });
  1099. try {
  1100. // @ts-ignore
  1101. // eslint-disable-next-line no-undef
  1102. if (typeof __GLOBALTHIS__ !== "undefined") return __GLOBALTHIS__;
  1103. } finally{
  1104. // @ts-ignore
  1105. delete Object.prototype.__GLOBALTHIS__;
  1106. }
  1107. }
  1108. // Still unable to determine "globalThis", fall back to a naive method.
  1109. if (typeof self !== "undefined") return self;
  1110. else if (typeof window !== "undefined") return window;
  1111. else if (typeof global !== "undefined") return global;
  1112. return undefined;
  1113. })();
  1114. /**
  1115. * OpenSSL-Noble hashes map.
  1116. * @type {Object.<string, sha1|sha224|sha256|sha384|sha512|sha3_224|sha3_256|sha3_384|sha3_512>}
  1117. */ const OPENSSL_NOBLE_HASHES = {
  1118. SHA1: sha1,
  1119. SHA224: sha224,
  1120. SHA256: sha256,
  1121. SHA384: sha384,
  1122. SHA512: sha512,
  1123. "SHA3-224": sha3_224,
  1124. "SHA3-256": sha3_256,
  1125. "SHA3-384": sha3_384,
  1126. "SHA3-512": sha3_512
  1127. };
  1128. /**
  1129. * Calculates an HMAC digest.
  1130. * In Node.js, the command "openssl list -digest-algorithms" displays the available digest algorithms.
  1131. * @param {string} algorithm Algorithm.
  1132. * @param {Uint8Array} key Key.
  1133. * @param {Uint8Array} message Message.
  1134. * @returns {Uint8Array} Digest.
  1135. */ const hmacDigest = (algorithm, key, message)=>{
  1136. if (hmac) {
  1137. const hash = OPENSSL_NOBLE_HASHES[algorithm.toUpperCase()];
  1138. if (!hash) throw new TypeError("Unknown hash function");
  1139. return hmac(hash, key, message);
  1140. } else {
  1141. throw new Error("Missing HMAC function");
  1142. }
  1143. };
  1144. /**
  1145. * RFC 4648 base32 alphabet without pad.
  1146. * @type {string}
  1147. */ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  1148. /**
  1149. * Converts a base32 string to an Uint8Array (RFC 4648).
  1150. * @see [LinusU/base32-decode](https://github.com/LinusU/base32-decode)
  1151. * @param {string} str Base32 string.
  1152. * @returns {Uint8Array} Uint8Array.
  1153. */ const base32Decode = (str)=>{
  1154. // Canonicalize to all upper case and remove padding if it exists.
  1155. let end = str.length;
  1156. while(str[end - 1] === "=")--end;
  1157. const cstr = (end < str.length ? str.substring(0, end) : str).toUpperCase();
  1158. const buf = new ArrayBuffer(cstr.length * 5 / 8 | 0);
  1159. const arr = new Uint8Array(buf);
  1160. let bits = 0;
  1161. let value = 0;
  1162. let index = 0;
  1163. for(let i = 0; i < cstr.length; i++){
  1164. const idx = ALPHABET.indexOf(cstr[i]);
  1165. if (idx === -1) throw new TypeError(`Invalid character found: ${cstr[i]}`);
  1166. value = value << 5 | idx;
  1167. bits += 5;
  1168. if (bits >= 8) {
  1169. bits -= 8;
  1170. arr[index++] = value >>> bits;
  1171. }
  1172. }
  1173. return arr;
  1174. };
  1175. /**
  1176. * Converts an Uint8Array to a base32 string (RFC 4648).
  1177. * @see [LinusU/base32-encode](https://github.com/LinusU/base32-encode)
  1178. * @param {Uint8Array} arr Uint8Array.
  1179. * @returns {string} Base32 string.
  1180. */ const base32Encode = (arr)=>{
  1181. let bits = 0;
  1182. let value = 0;
  1183. let str = "";
  1184. for(let i = 0; i < arr.length; i++){
  1185. value = value << 8 | arr[i];
  1186. bits += 8;
  1187. while(bits >= 5){
  1188. str += ALPHABET[value >>> bits - 5 & 31];
  1189. bits -= 5;
  1190. }
  1191. }
  1192. if (bits > 0) {
  1193. str += ALPHABET[value << 5 - bits & 31];
  1194. }
  1195. return str;
  1196. };
  1197. /**
  1198. * Converts a hexadecimal string to an Uint8Array.
  1199. * @param {string} str Hexadecimal string.
  1200. * @returns {Uint8Array} Uint8Array.
  1201. */ const hexDecode = (str)=>{
  1202. const buf = new ArrayBuffer(str.length / 2);
  1203. const arr = new Uint8Array(buf);
  1204. for(let i = 0; i < str.length; i += 2){
  1205. arr[i / 2] = parseInt(str.substring(i, i + 2), 16);
  1206. }
  1207. return arr;
  1208. };
  1209. /**
  1210. * Converts an Uint8Array to a hexadecimal string.
  1211. * @param {Uint8Array} arr Uint8Array.
  1212. * @returns {string} Hexadecimal string.
  1213. */ const hexEncode = (arr)=>{
  1214. let str = "";
  1215. for(let i = 0; i < arr.length; i++){
  1216. const hex = arr[i].toString(16);
  1217. if (hex.length === 1) str += "0";
  1218. str += hex;
  1219. }
  1220. return str.toUpperCase();
  1221. };
  1222. /**
  1223. * Converts a Latin-1 string to an Uint8Array.
  1224. * @param {string} str Latin-1 string.
  1225. * @returns {Uint8Array} Uint8Array.
  1226. */ const latin1Decode = (str)=>{
  1227. const buf = new ArrayBuffer(str.length);
  1228. const arr = new Uint8Array(buf);
  1229. for(let i = 0; i < str.length; i++){
  1230. arr[i] = str.charCodeAt(i) & 0xff;
  1231. }
  1232. return arr;
  1233. };
  1234. /**
  1235. * Converts an Uint8Array to a Latin-1 string.
  1236. * @param {Uint8Array} arr Uint8Array.
  1237. * @returns {string} Latin-1 string.
  1238. */ const latin1Encode = (arr)=>{
  1239. let str = "";
  1240. for(let i = 0; i < arr.length; i++){
  1241. str += String.fromCharCode(arr[i]);
  1242. }
  1243. return str;
  1244. };
  1245. /**
  1246. * TextEncoder instance.
  1247. * @type {TextEncoder|null}
  1248. */ const ENCODER = globalScope.TextEncoder ? new globalScope.TextEncoder() : null;
  1249. /**
  1250. * TextDecoder instance.
  1251. * @type {TextDecoder|null}
  1252. */ const DECODER = globalScope.TextDecoder ? new globalScope.TextDecoder() : null;
  1253. /**
  1254. * Converts an UTF-8 string to an Uint8Array.
  1255. * @param {string} str String.
  1256. * @returns {Uint8Array} Uint8Array.
  1257. */ const utf8Decode = (str)=>{
  1258. if (!ENCODER) {
  1259. throw new Error("Encoding API not available");
  1260. }
  1261. return ENCODER.encode(str);
  1262. };
  1263. /**
  1264. * Converts an Uint8Array to an UTF-8 string.
  1265. * @param {Uint8Array} arr Uint8Array.
  1266. * @returns {string} String.
  1267. */ const utf8Encode = (arr)=>{
  1268. if (!DECODER) {
  1269. throw new Error("Encoding API not available");
  1270. }
  1271. return DECODER.decode(arr);
  1272. };
  1273. /**
  1274. * Returns random bytes.
  1275. * @param {number} size Size.
  1276. * @returns {Uint8Array} Random bytes.
  1277. */ const randomBytes = (size)=>{
  1278. {
  1279. if (!globalScope.crypto?.getRandomValues) {
  1280. throw new Error("Cryptography API not available");
  1281. }
  1282. return globalScope.crypto.getRandomValues(new Uint8Array(size));
  1283. }
  1284. };
  1285. /**
  1286. * OTP secret key.
  1287. */ class Secret {
  1288. /**
  1289. * Converts a Latin-1 string to a Secret object.
  1290. * @param {string} str Latin-1 string.
  1291. * @returns {Secret} Secret object.
  1292. */ static fromLatin1(str) {
  1293. return new Secret({
  1294. buffer: latin1Decode(str).buffer
  1295. });
  1296. }
  1297. /**
  1298. * Converts an UTF-8 string to a Secret object.
  1299. * @param {string} str UTF-8 string.
  1300. * @returns {Secret} Secret object.
  1301. */ static fromUTF8(str) {
  1302. return new Secret({
  1303. buffer: utf8Decode(str).buffer
  1304. });
  1305. }
  1306. /**
  1307. * Converts a base32 string to a Secret object.
  1308. * @param {string} str Base32 string.
  1309. * @returns {Secret} Secret object.
  1310. */ static fromBase32(str) {
  1311. return new Secret({
  1312. buffer: base32Decode(str).buffer
  1313. });
  1314. }
  1315. /**
  1316. * Converts a hexadecimal string to a Secret object.
  1317. * @param {string} str Hexadecimal string.
  1318. * @returns {Secret} Secret object.
  1319. */ static fromHex(str) {
  1320. return new Secret({
  1321. buffer: hexDecode(str).buffer
  1322. });
  1323. }
  1324. /**
  1325. * Secret key buffer.
  1326. * @deprecated For backward compatibility, the "bytes" property should be used instead.
  1327. * @type {ArrayBufferLike}
  1328. */ get buffer() {
  1329. return this.bytes.buffer;
  1330. }
  1331. /**
  1332. * Latin-1 string representation of secret key.
  1333. * @type {string}
  1334. */ get latin1() {
  1335. Object.defineProperty(this, "latin1", {
  1336. enumerable: true,
  1337. writable: false,
  1338. configurable: false,
  1339. value: latin1Encode(this.bytes)
  1340. });
  1341. return this.latin1;
  1342. }
  1343. /**
  1344. * UTF-8 string representation of secret key.
  1345. * @type {string}
  1346. */ get utf8() {
  1347. Object.defineProperty(this, "utf8", {
  1348. enumerable: true,
  1349. writable: false,
  1350. configurable: false,
  1351. value: utf8Encode(this.bytes)
  1352. });
  1353. return this.utf8;
  1354. }
  1355. /**
  1356. * Base32 string representation of secret key.
  1357. * @type {string}
  1358. */ get base32() {
  1359. Object.defineProperty(this, "base32", {
  1360. enumerable: true,
  1361. writable: false,
  1362. configurable: false,
  1363. value: base32Encode(this.bytes)
  1364. });
  1365. return this.base32;
  1366. }
  1367. /**
  1368. * Hexadecimal string representation of secret key.
  1369. * @type {string}
  1370. */ get hex() {
  1371. Object.defineProperty(this, "hex", {
  1372. enumerable: true,
  1373. writable: false,
  1374. configurable: false,
  1375. value: hexEncode(this.bytes)
  1376. });
  1377. return this.hex;
  1378. }
  1379. /**
  1380. * Creates a secret key object.
  1381. * @param {Object} [config] Configuration options.
  1382. * @param {ArrayBufferLike} [config.buffer] Secret key buffer.
  1383. * @param {number} [config.size=20] Number of random bytes to generate, ignored if 'buffer' is provided.
  1384. */ constructor({ buffer, size = 20 } = {}){
  1385. /**
  1386. * Secret key.
  1387. * @type {Uint8Array}
  1388. * @readonly
  1389. */ this.bytes = typeof buffer === "undefined" ? randomBytes(size) : new Uint8Array(buffer);
  1390. // Prevent the "bytes" property from being modified.
  1391. Object.defineProperty(this, "bytes", {
  1392. enumerable: true,
  1393. writable: false,
  1394. configurable: false,
  1395. value: this.bytes
  1396. });
  1397. }
  1398. }
  1399. /**
  1400. * Returns true if a is equal to b, without leaking timing information that would allow an attacker to guess one of the values.
  1401. * @param {string} a String a.
  1402. * @param {string} b String b.
  1403. * @returns {boolean} Equality result.
  1404. */ const timingSafeEqual = (a, b)=>{
  1405. {
  1406. if (a.length !== b.length) {
  1407. throw new TypeError("Input strings must have the same length");
  1408. }
  1409. let i = -1;
  1410. let out = 0;
  1411. while(++i < a.length){
  1412. out |= a.charCodeAt(i) ^ b.charCodeAt(i);
  1413. }
  1414. return out === 0;
  1415. }
  1416. };
  1417. /**
  1418. * HOTP: An HMAC-based One-time Password Algorithm.
  1419. * @see [RFC 4226](https://tools.ietf.org/html/rfc4226)
  1420. */ class HOTP {
  1421. /**
  1422. * Default configuration.
  1423. * @type {{
  1424. * issuer: string,
  1425. * label: string,
  1426. * issuerInLabel: boolean,
  1427. * algorithm: string,
  1428. * digits: number,
  1429. * counter: number
  1430. * window: number
  1431. * }}
  1432. */ static get defaults() {
  1433. return {
  1434. issuer: "",
  1435. label: "OTPAuth",
  1436. issuerInLabel: true,
  1437. algorithm: "SHA1",
  1438. digits: 6,
  1439. counter: 0,
  1440. window: 1
  1441. };
  1442. }
  1443. /**
  1444. * Generates an HOTP token.
  1445. * @param {Object} config Configuration options.
  1446. * @param {Secret} config.secret Secret key.
  1447. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
  1448. * @param {number} [config.digits=6] Token length.
  1449. * @param {number} [config.counter=0] Counter value.
  1450. * @returns {string} Token.
  1451. */ static generate({ secret, algorithm = HOTP.defaults.algorithm, digits = HOTP.defaults.digits, counter = HOTP.defaults.counter }) {
  1452. const digest = hmacDigest(algorithm, secret.bytes, uintDecode(counter));
  1453. const offset = digest[digest.byteLength - 1] & 15;
  1454. const otp = ((digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255) % 10 ** digits;
  1455. return otp.toString().padStart(digits, "0");
  1456. }
  1457. /**
  1458. * Generates an HOTP token.
  1459. * @param {Object} [config] Configuration options.
  1460. * @param {number} [config.counter=this.counter++] Counter value.
  1461. * @returns {string} Token.
  1462. */ generate({ counter = this.counter++ } = {}) {
  1463. return HOTP.generate({
  1464. secret: this.secret,
  1465. algorithm: this.algorithm,
  1466. digits: this.digits,
  1467. counter
  1468. });
  1469. }
  1470. /**
  1471. * Validates an HOTP token.
  1472. * @param {Object} config Configuration options.
  1473. * @param {string} config.token Token value.
  1474. * @param {Secret} config.secret Secret key.
  1475. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
  1476. * @param {number} config.digits Token length.
  1477. * @param {number} [config.counter=0] Counter value.
  1478. * @param {number} [config.window=1] Window of counter values to test.
  1479. * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
  1480. */ static validate({ token, secret, algorithm, digits, counter = HOTP.defaults.counter, window = HOTP.defaults.window }) {
  1481. // Return early if the token length does not match the digit number.
  1482. if (token.length !== digits) return null;
  1483. let delta = null;
  1484. const check = (/** @type {number} */ i)=>{
  1485. const generatedToken = HOTP.generate({
  1486. secret,
  1487. algorithm,
  1488. digits,
  1489. counter: i
  1490. });
  1491. if (timingSafeEqual(token, generatedToken)) {
  1492. delta = i - counter;
  1493. }
  1494. };
  1495. check(counter);
  1496. for(let i = 1; i <= window && delta === null; ++i){
  1497. check(counter - i);
  1498. if (delta !== null) break;
  1499. check(counter + i);
  1500. if (delta !== null) break;
  1501. }
  1502. return delta;
  1503. }
  1504. /**
  1505. * Validates an HOTP token.
  1506. * @param {Object} config Configuration options.
  1507. * @param {string} config.token Token value.
  1508. * @param {number} [config.counter=this.counter] Counter value.
  1509. * @param {number} [config.window=1] Window of counter values to test.
  1510. * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
  1511. */ validate({ token, counter = this.counter, window }) {
  1512. return HOTP.validate({
  1513. token,
  1514. secret: this.secret,
  1515. algorithm: this.algorithm,
  1516. digits: this.digits,
  1517. counter,
  1518. window
  1519. });
  1520. }
  1521. /**
  1522. * Returns a Google Authenticator key URI.
  1523. * @returns {string} URI.
  1524. */ toString() {
  1525. const e = encodeURIComponent;
  1526. return "otpauth://hotp/" + `${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}` + `secret=${e(this.secret.base32)}&` + `algorithm=${e(this.algorithm)}&` + `digits=${e(this.digits)}&` + `counter=${e(this.counter)}`;
  1527. }
  1528. /**
  1529. * Creates an HOTP object.
  1530. * @param {Object} [config] Configuration options.
  1531. * @param {string} [config.issuer=''] Account provider.
  1532. * @param {string} [config.label='OTPAuth'] Account label.
  1533. * @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
  1534. * @param {Secret|string} [config.secret=Secret] Secret key.
  1535. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
  1536. * @param {number} [config.digits=6] Token length.
  1537. * @param {number} [config.counter=0] Initial counter value.
  1538. */ constructor({ issuer = HOTP.defaults.issuer, label = HOTP.defaults.label, issuerInLabel = HOTP.defaults.issuerInLabel, secret = new Secret(), algorithm = HOTP.defaults.algorithm, digits = HOTP.defaults.digits, counter = HOTP.defaults.counter } = {}){
  1539. /**
  1540. * Account provider.
  1541. * @type {string}
  1542. */ this.issuer = issuer;
  1543. /**
  1544. * Account label.
  1545. * @type {string}
  1546. */ this.label = label;
  1547. /**
  1548. * Include issuer prefix in label.
  1549. * @type {boolean}
  1550. */ this.issuerInLabel = issuerInLabel;
  1551. /**
  1552. * Secret key.
  1553. * @type {Secret}
  1554. */ this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
  1555. /**
  1556. * HMAC hashing algorithm.
  1557. * @type {string}
  1558. */ this.algorithm = algorithm.toUpperCase();
  1559. /**
  1560. * Token length.
  1561. * @type {number}
  1562. */ this.digits = digits;
  1563. /**
  1564. * Initial counter value.
  1565. * @type {number}
  1566. */ this.counter = counter;
  1567. }
  1568. }
  1569. /**
  1570. * TOTP: Time-Based One-Time Password Algorithm.
  1571. * @see [RFC 6238](https://tools.ietf.org/html/rfc6238)
  1572. */ class TOTP {
  1573. /**
  1574. * Default configuration.
  1575. * @type {{
  1576. * issuer: string,
  1577. * label: string,
  1578. * issuerInLabel: boolean,
  1579. * algorithm: string,
  1580. * digits: number,
  1581. * period: number
  1582. * window: number
  1583. * }}
  1584. */ static get defaults() {
  1585. return {
  1586. issuer: "",
  1587. label: "OTPAuth",
  1588. issuerInLabel: true,
  1589. algorithm: "SHA1",
  1590. digits: 6,
  1591. period: 30,
  1592. window: 1
  1593. };
  1594. }
  1595. /**
  1596. * Generates a TOTP token.
  1597. * @param {Object} config Configuration options.
  1598. * @param {Secret} config.secret Secret key.
  1599. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
  1600. * @param {number} [config.digits=6] Token length.
  1601. * @param {number} [config.period=30] Token time-step duration.
  1602. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
  1603. * @returns {string} Token.
  1604. */ static generate({ secret, algorithm, digits, period = TOTP.defaults.period, timestamp = Date.now() }) {
  1605. return HOTP.generate({
  1606. secret,
  1607. algorithm,
  1608. digits,
  1609. counter: Math.floor(timestamp / 1000 / period)
  1610. });
  1611. }
  1612. /**
  1613. * Generates a TOTP token.
  1614. * @param {Object} [config] Configuration options.
  1615. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
  1616. * @returns {string} Token.
  1617. */ generate({ timestamp = Date.now() } = {}) {
  1618. return TOTP.generate({
  1619. secret: this.secret,
  1620. algorithm: this.algorithm,
  1621. digits: this.digits,
  1622. period: this.period,
  1623. timestamp
  1624. });
  1625. }
  1626. /**
  1627. * Validates a TOTP token.
  1628. * @param {Object} config Configuration options.
  1629. * @param {string} config.token Token value.
  1630. * @param {Secret} config.secret Secret key.
  1631. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
  1632. * @param {number} config.digits Token length.
  1633. * @param {number} [config.period=30] Token time-step duration.
  1634. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
  1635. * @param {number} [config.window=1] Window of counter values to test.
  1636. * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
  1637. */ static validate({ token, secret, algorithm, digits, period = TOTP.defaults.period, timestamp = Date.now(), window }) {
  1638. return HOTP.validate({
  1639. token,
  1640. secret,
  1641. algorithm,
  1642. digits,
  1643. counter: Math.floor(timestamp / 1000 / period),
  1644. window
  1645. });
  1646. }
  1647. /**
  1648. * Validates a TOTP token.
  1649. * @param {Object} config Configuration options.
  1650. * @param {string} config.token Token value.
  1651. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
  1652. * @param {number} [config.window=1] Window of counter values to test.
  1653. * @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
  1654. */ validate({ token, timestamp, window }) {
  1655. return TOTP.validate({
  1656. token,
  1657. secret: this.secret,
  1658. algorithm: this.algorithm,
  1659. digits: this.digits,
  1660. period: this.period,
  1661. timestamp,
  1662. window
  1663. });
  1664. }
  1665. /**
  1666. * Returns a Google Authenticator key URI.
  1667. * @returns {string} URI.
  1668. */ toString() {
  1669. const e = encodeURIComponent;
  1670. return "otpauth://totp/" + `${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}` + `secret=${e(this.secret.base32)}&` + `algorithm=${e(this.algorithm)}&` + `digits=${e(this.digits)}&` + `period=${e(this.period)}`;
  1671. }
  1672. /**
  1673. * Creates a TOTP object.
  1674. * @param {Object} [config] Configuration options.
  1675. * @param {string} [config.issuer=''] Account provider.
  1676. * @param {string} [config.label='OTPAuth'] Account label.
  1677. * @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
  1678. * @param {Secret|string} [config.secret=Secret] Secret key.
  1679. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
  1680. * @param {number} [config.digits=6] Token length.
  1681. * @param {number} [config.period=30] Token time-step duration.
  1682. */ constructor({ issuer = TOTP.defaults.issuer, label = TOTP.defaults.label, issuerInLabel = TOTP.defaults.issuerInLabel, secret = new Secret(), algorithm = TOTP.defaults.algorithm, digits = TOTP.defaults.digits, period = TOTP.defaults.period } = {}){
  1683. /**
  1684. * Account provider.
  1685. * @type {string}
  1686. */ this.issuer = issuer;
  1687. /**
  1688. * Account label.
  1689. * @type {string}
  1690. */ this.label = label;
  1691. /**
  1692. * Include issuer prefix in label.
  1693. * @type {boolean}
  1694. */ this.issuerInLabel = issuerInLabel;
  1695. /**
  1696. * Secret key.
  1697. * @type {Secret}
  1698. */ this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
  1699. /**
  1700. * HMAC hashing algorithm.
  1701. * @type {string}
  1702. */ this.algorithm = algorithm.toUpperCase();
  1703. /**
  1704. * Token length.
  1705. * @type {number}
  1706. */ this.digits = digits;
  1707. /**
  1708. * Token time-step duration.
  1709. * @type {number}
  1710. */ this.period = period;
  1711. }
  1712. }
  1713. /**
  1714. * Key URI regex (otpauth://TYPE/[ISSUER:]LABEL?PARAMETERS).
  1715. * @type {RegExp}
  1716. */ const OTPURI_REGEX = /^otpauth:\/\/([ht]otp)\/(.+)\?([A-Z0-9.~_-]+=[^?&]*(?:&[A-Z0-9.~_-]+=[^?&]*)*)$/i;
  1717. /**
  1718. * RFC 4648 base32 alphabet with pad.
  1719. * @type {RegExp}
  1720. */ const SECRET_REGEX = /^[2-7A-Z]+=*$/i;
  1721. /**
  1722. * Regex for supported algorithms.
  1723. * @type {RegExp}
  1724. */ const ALGORITHM_REGEX = /^SHA(?:1|224|256|384|512|3-224|3-256|3-384|3-512)$/i;
  1725. /**
  1726. * Integer regex.
  1727. * @type {RegExp}
  1728. */ const INTEGER_REGEX = /^[+-]?\d+$/;
  1729. /**
  1730. * Positive integer regex.
  1731. * @type {RegExp}
  1732. */ const POSITIVE_INTEGER_REGEX = /^\+?[1-9]\d*$/;
  1733. /**
  1734. * HOTP/TOTP object/string conversion.
  1735. * @see [Key URI Format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format)
  1736. */ class URI {
  1737. /**
  1738. * Parses a Google Authenticator key URI and returns an HOTP/TOTP object.
  1739. * @param {string} uri Google Authenticator Key URI.
  1740. * @returns {HOTP|TOTP} HOTP/TOTP object.
  1741. */ static parse(uri) {
  1742. let uriGroups;
  1743. try {
  1744. uriGroups = uri.match(OTPURI_REGEX);
  1745. // eslint-disable-next-line no-unused-vars
  1746. } catch (_) {
  1747. /* Handled below */ }
  1748. if (!Array.isArray(uriGroups)) {
  1749. throw new URIError("Invalid URI format");
  1750. }
  1751. // Extract URI groups.
  1752. const uriType = uriGroups[1].toLowerCase();
  1753. const uriLabel = uriGroups[2].split(/(?::|%3A) *(.+)/i, 2).map(decodeURIComponent);
  1754. /** @type {Object.<string, string>} */ const uriParams = uriGroups[3].split("&").reduce((acc, cur)=>{
  1755. const pairArr = cur.split(/=(.*)/, 2).map(decodeURIComponent);
  1756. const pairKey = pairArr[0].toLowerCase();
  1757. const pairVal = pairArr[1];
  1758. /** @type {Object.<string, string>} */ const pairAcc = acc;
  1759. pairAcc[pairKey] = pairVal;
  1760. return pairAcc;
  1761. }, {});
  1762. // 'OTP' will be instantiated with 'config' argument.
  1763. let OTP;
  1764. const config = {};
  1765. if (uriType === "hotp") {
  1766. OTP = HOTP;
  1767. // Counter: required
  1768. if (typeof uriParams.counter !== "undefined" && INTEGER_REGEX.test(uriParams.counter)) {
  1769. config.counter = parseInt(uriParams.counter, 10);
  1770. } else {
  1771. throw new TypeError("Missing or invalid 'counter' parameter");
  1772. }
  1773. } else if (uriType === "totp") {
  1774. OTP = TOTP;
  1775. // Period: optional
  1776. if (typeof uriParams.period !== "undefined") {
  1777. if (POSITIVE_INTEGER_REGEX.test(uriParams.period)) {
  1778. config.period = parseInt(uriParams.period, 10);
  1779. } else {
  1780. throw new TypeError("Invalid 'period' parameter");
  1781. }
  1782. }
  1783. } else {
  1784. throw new TypeError("Unknown OTP type");
  1785. }
  1786. // Label: required
  1787. // Issuer: optional
  1788. if (typeof uriParams.issuer !== "undefined") {
  1789. config.issuer = uriParams.issuer;
  1790. }
  1791. if (uriLabel.length === 2) {
  1792. config.label = uriLabel[1];
  1793. if (typeof config.issuer === "undefined" || config.issuer === "") {
  1794. config.issuer = uriLabel[0];
  1795. } else if (uriLabel[0] === "") {
  1796. config.issuerInLabel = false;
  1797. }
  1798. } else {
  1799. config.label = uriLabel[0];
  1800. if (typeof config.issuer !== "undefined" && config.issuer !== "") {
  1801. config.issuerInLabel = false;
  1802. }
  1803. }
  1804. // Secret: required
  1805. if (typeof uriParams.secret !== "undefined" && SECRET_REGEX.test(uriParams.secret)) {
  1806. config.secret = uriParams.secret;
  1807. } else {
  1808. throw new TypeError("Missing or invalid 'secret' parameter");
  1809. }
  1810. // Algorithm: optional
  1811. if (typeof uriParams.algorithm !== "undefined") {
  1812. if (ALGORITHM_REGEX.test(uriParams.algorithm)) {
  1813. config.algorithm = uriParams.algorithm;
  1814. } else {
  1815. throw new TypeError("Invalid 'algorithm' parameter");
  1816. }
  1817. }
  1818. // Digits: optional
  1819. if (typeof uriParams.digits !== "undefined") {
  1820. if (POSITIVE_INTEGER_REGEX.test(uriParams.digits)) {
  1821. config.digits = parseInt(uriParams.digits, 10);
  1822. } else {
  1823. throw new TypeError("Invalid 'digits' parameter");
  1824. }
  1825. }
  1826. return new OTP(config);
  1827. }
  1828. /**
  1829. * Converts an HOTP/TOTP object to a Google Authenticator key URI.
  1830. * @param {HOTP|TOTP} otp HOTP/TOTP object.
  1831. * @returns {string} Google Authenticator Key URI.
  1832. */ static stringify(otp) {
  1833. if (otp instanceof HOTP || otp instanceof TOTP) {
  1834. return otp.toString();
  1835. }
  1836. throw new TypeError("Invalid 'HOTP/TOTP' object");
  1837. }
  1838. }
  1839. /**
  1840. * Library version.
  1841. * @type {string}
  1842. */ const version = "9.3.1";
  1843. export { HOTP, Secret, TOTP, URI, version };