Helpers.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. const crypto = require('crypto');
  2. const fs = require("fs").promises;
  3. class Helpers {
  4. /**
  5. * Generates a random long integer (8 bytes), which is optionally signed
  6. * @returns {BigInt}
  7. */
  8. static generateRandomLong(signed) {
  9. let buf = Buffer.from(Helpers.generateRandomBytes(8)); // 0x12345678 = 305419896
  10. if (signed)
  11. return buf.readBigInt64LE(0);
  12. else
  13. return buf.readBigUInt64LE(0);
  14. }
  15. /**
  16. * Generates a random bytes array
  17. * @param count
  18. * @returns {Buffer}
  19. */
  20. static generateRandomBytes(count) {
  21. return crypto.randomBytes(count);
  22. }
  23. /**
  24. * Loads the user settings located under `api/`
  25. * @param path
  26. * @returns {Promise<void>}
  27. */
  28. static async loadSettings(path = "api/settings") {
  29. let settings = {};
  30. let left, right, value_pair;
  31. let data = await fs.readFile(path, 'utf-8');
  32. for (let line of data.toString().split('\n')) {
  33. value_pair = line.split("=");
  34. if (value_pair.length !== 2) {
  35. break;
  36. }
  37. left = value_pair[0].replace(/ \r?\n|\r/g, '');
  38. right = value_pair[1].replace(/ \r?\n|\r/g, '');
  39. if (!isNaN(right)) {
  40. settings[left] = Number.parseInt(right);
  41. } else {
  42. settings[left] = right;
  43. }
  44. }
  45. return settings;
  46. }
  47. /**
  48. * Calculate the key based on Telegram guidelines, specifying whether it's the client or not
  49. * @param shared_key
  50. * @param msg_key
  51. * @param client
  52. * @returns {{iv: Buffer, key: Buffer}}
  53. */
  54. static calcKey(shared_key, msg_key, client) {
  55. let x = client === true ? 0 : 8;
  56. let iv, key, sha1a, sha1b, sha1c, sha1d;
  57. sha1a = Helpers.sha1(Buffer.concat([
  58. msg_key,
  59. shared_key.slice(x, (x + 32))
  60. ]));
  61. sha1b = Helpers.sha1(Buffer.concat([
  62. shared_key.slice(x + 32, x + 48),
  63. msg_key,
  64. shared_key.slice(x + 48, x + 64)
  65. ]));
  66. sha1c = Helpers.sha1(Buffer.concat([
  67. shared_key.slice(x + 64, x + 96),
  68. msg_key
  69. ]));
  70. sha1d = Helpers.sha1(Buffer.concat([
  71. msg_key,
  72. shared_key.slice((x + 96), (x + 128))
  73. ]));
  74. key = Buffer.concat([
  75. sha1a.slice(0, 8),
  76. sha1b.slice(8, 20),
  77. sha1c.slice(4, 16)]);
  78. iv = Buffer.concat([
  79. sha1a.slice(8, 20),
  80. sha1b.slice(0, 8),
  81. sha1c.slice(16, 20),
  82. sha1d.slice(0, 8)]);
  83. return {key, iv}
  84. }
  85. /**
  86. * Calculates the message key from the given data
  87. * @param data
  88. * @returns {Buffer}
  89. */
  90. static calcMsgKey(data) {
  91. return Helpers.sha1(data).slice(4, 20);
  92. }
  93. /**
  94. * Generates the key data corresponding to the given nonces
  95. * @param serverNonce
  96. * @param newNonce
  97. * @returns {{ivBuffer: Buffer, keyBuffer: Buffer}}
  98. */
  99. static generateKeyDataFromNonces(serverNonce, newNonce) {
  100. let hash1 = Helpers.sha1(Buffer.concat([newNonce, serverNonce]));
  101. let hash2 = Helpers.sha1(Buffer.concat([serverNonce, newNonce]));
  102. let hash3 = Helpers.sha1(Buffer.concat([newNonce, newNonce]));
  103. let keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);
  104. let ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);
  105. return {keyBuffer: keyBuffer, ivBuffer: ivBuffer}
  106. }
  107. /**
  108. * Calculates the SHA1 digest for the given data
  109. * @param data
  110. * @returns {Buffer}
  111. */
  112. static sha1(data) {
  113. let shaSum = crypto.createHash('sha1');
  114. shaSum.update(data);
  115. return shaSum.digest();
  116. }
  117. /**
  118. * Reads a Telegram-encoded string
  119. * @param buffer {Buffer}
  120. * @param offset {number}
  121. * @returns {{string: string, offset: number}}
  122. */
  123. static tgReadString(buffer, offset) {
  124. let res = Helpers.tgReadByte(buffer, offset);
  125. offset = res.offset;
  126. let string = res.data.toString("utf8");
  127. return {string, offset}
  128. }
  129. /**
  130. *
  131. * @param reader {Buffer}
  132. * @param offset {number}
  133. */
  134. static tgReadObject(reader, offset) {
  135. let constructorId = reader.readUInt32LE(offset);
  136. offset += 4;
  137. let clazz = tlobjects[constructorId];
  138. if (clazz === undefined) {
  139. /**
  140. * The class was None, but there's still a
  141. * chance of it being a manually parsed value like bool!
  142. */
  143. if (constructorId === 0x997275b5) {
  144. return true
  145. } else if (constructorId === 0xbc799737) {
  146. return false
  147. }
  148. throw Error("type not found "+ constructorId);
  149. }
  150. return undefined;
  151. }
  152. /**
  153. *
  154. * @param buffer {Buffer}
  155. * @param offset {Number}
  156. * @returns {{data: Buffer, offset: Number}}
  157. */
  158. static tgReadByte(buffer, offset) {
  159. let firstByte = buffer[offset];
  160. offset += 1;
  161. let padding, length;
  162. if (firstByte === 254) {
  163. length = buffer.readInt8(offset) | (buffer.readInt8(offset + 1) << 8) | (buffer.readInt8(offset + 2) << 16);
  164. offset += 3;
  165. padding = length % 4;
  166. } else {
  167. length = firstByte;
  168. padding = (length + 1) % 4;
  169. }
  170. let data = buffer.slice(offset, offset + length);
  171. offset += length;
  172. if (padding > 0) {
  173. padding = 4 - padding;
  174. offset += padding;
  175. }
  176. return {data: data, offset: offset}
  177. }
  178. static tgWriteString(string) {
  179. return Helpers.tgWriteBytes(Buffer.from(string, "utf8"));
  180. }
  181. static tgWriteBytes(data) {
  182. let buffer;
  183. let padding;
  184. if (data.length < 254) {
  185. padding = (data.length + 1) % 4;
  186. if (padding !== 0) {
  187. padding = 4 - padding;
  188. }
  189. buffer = Buffer.concat([Buffer.from([data.length]), data]);
  190. } else {
  191. padding = data.length % 4;
  192. if (padding !== 0) {
  193. padding = 4 - padding;
  194. }
  195. buffer = Buffer.concat([
  196. Buffer.from([254]),
  197. Buffer.from([data.length % 256]),
  198. Buffer.from([(data.length >> 8) % 256]),
  199. Buffer.from([(data.length >> 16) % 256]),
  200. data,
  201. ]);
  202. }
  203. return Buffer.concat([buffer, Buffer.alloc(padding).fill(0)]);
  204. }
  205. /**
  206. * Fast mod pow for RSA calculation. a^b % n
  207. * @param a
  208. * @param b
  209. * @param n
  210. * @returns {bigint}
  211. */
  212. static modExp(a, b, n) {
  213. a = a % n;
  214. let result = 1n;
  215. let x = a;
  216. while (b > 0) {
  217. let leastSignificantBit = b % 2n;
  218. b = b / 2n;
  219. if (leastSignificantBit === 1n) {
  220. result = result * x;
  221. result = result % n;
  222. }
  223. x = x * x;
  224. x = x % n;
  225. }
  226. return result;
  227. };
  228. /**
  229. * returns a random int from min (inclusive) and max (inclusive)
  230. * @param min
  231. * @param max
  232. * @returns {number}
  233. */
  234. static getRandomInt(min, max) {
  235. min = Math.ceil(min);
  236. max = Math.floor(max);
  237. return Math.floor(Math.random() * (max - min + 1)) + min;
  238. }
  239. /**
  240. * Sleeps a specified amount of time
  241. * @param ms time in milliseconds
  242. * @returns {Promise}
  243. */
  244. static sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
  245. }
  246. module.exports = Helpers;