tiny-essentials 1.1.1 โ†’ 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/README.md +3 -1
  2. package/dist/TinyBasicsEs.js +2821 -0
  3. package/dist/TinyBasicsEs.min.js +2 -0
  4. package/dist/TinyBasicsEs.min.js.LICENSE.txt +8 -0
  5. package/dist/TinyCertCrypto.js +31364 -0
  6. package/dist/TinyCertCrypto.min.js +2 -0
  7. package/dist/TinyCertCrypto.min.js.LICENSE.txt +8 -0
  8. package/dist/TinyCrypto.js +48138 -0
  9. package/dist/TinyCrypto.min.js +2 -0
  10. package/dist/TinyCrypto.min.js.LICENSE.txt +10 -0
  11. package/dist/TinyEssentials.js +77695 -0
  12. package/dist/TinyEssentials.min.js +2 -1
  13. package/dist/TinyEssentials.min.js.LICENSE.txt +10 -0
  14. package/dist/TinyLevelUp.js +173 -0
  15. package/dist/TinyLevelUp.min.js +1 -0
  16. package/dist/legacy/crypto/decrypt.cjs +1 -0
  17. package/dist/legacy/crypto/decrypt.mjs +1 -0
  18. package/dist/legacy/crypto/default.cjs +2 -0
  19. package/dist/legacy/crypto/default.mjs +1 -0
  20. package/dist/legacy/crypto/encrypt.cjs +2 -1
  21. package/dist/legacy/crypto/encrypt.mjs +1 -0
  22. package/dist/legacy/crypto/index.cjs +1 -1
  23. package/dist/legacy/crypto/index.mjs +1 -0
  24. package/dist/legacy/firebase/cookieSession.cjs +2 -0
  25. package/dist/legacy/firebase/cookieSession.mjs +1 -0
  26. package/dist/legacy/firebase/database/index.cjs +3 -0
  27. package/dist/legacy/firebase/database/index.mjs +1 -0
  28. package/dist/legacy/firebase/database/presence.cjs +3 -0
  29. package/dist/legacy/firebase/database/presence.mjs +1 -0
  30. package/dist/legacy/firebase/database/saveAsync.cjs +2 -0
  31. package/dist/legacy/firebase/database/saveAsync.mjs +1 -0
  32. package/dist/legacy/firebase/databaseEscape.cjs +3 -0
  33. package/dist/legacy/firebase/databaseEscape.mjs +1 -0
  34. package/dist/legacy/firebase/databaseLogger.cjs +3 -0
  35. package/dist/legacy/firebase/databaseLogger.mjs +1 -0
  36. package/dist/legacy/firebase/discord/api/addGuildMember.cjs +3 -0
  37. package/dist/legacy/firebase/discord/api/addGuildMember.mjs +1 -0
  38. package/dist/legacy/firebase/discord/api/getGuildWidget.cjs +3 -0
  39. package/dist/legacy/firebase/discord/api/getGuildWidget.mjs +1 -0
  40. package/dist/legacy/firebase/discord/api/getToken.cjs +3 -0
  41. package/dist/legacy/firebase/discord/api/getToken.mjs +1 -0
  42. package/dist/legacy/firebase/discord/api/getUser.cjs +3 -0
  43. package/dist/legacy/firebase/discord/api/getUser.mjs +1 -0
  44. package/dist/legacy/firebase/discord/api/getUserConnections.cjs +3 -0
  45. package/dist/legacy/firebase/discord/api/getUserConnections.mjs +1 -0
  46. package/dist/legacy/firebase/discord/api/getUserGuilds.cjs +3 -0
  47. package/dist/legacy/firebase/discord/api/getUserGuilds.mjs +1 -0
  48. package/dist/legacy/firebase/discord/api/index.cjs +3 -0
  49. package/dist/legacy/firebase/discord/api/index.mjs +1 -0
  50. package/dist/legacy/firebase/discord/api/refreshToken.cjs +3 -0
  51. package/dist/legacy/firebase/discord/api/refreshToken.mjs +1 -0
  52. package/dist/legacy/firebase/discord/api/revokeToken.cjs +3 -0
  53. package/dist/legacy/firebase/discord/api/revokeToken.mjs +1 -0
  54. package/dist/legacy/firebase/discord/config.cjs +2 -0
  55. package/dist/legacy/firebase/discord/config.mjs +1 -0
  56. package/dist/legacy/firebase/discord/firebase_redirect/index.cjs +3 -0
  57. package/dist/legacy/firebase/discord/firebase_redirect/index.mjs +1 -0
  58. package/dist/legacy/firebase/discord/firebase_redirect/login.cjs +2 -0
  59. package/dist/legacy/firebase/discord/firebase_redirect/login.mjs +1 -0
  60. package/dist/legacy/firebase/discord/firebase_redirect/logout.cjs +2 -0
  61. package/dist/legacy/firebase/discord/firebase_redirect/logout.mjs +1 -0
  62. package/dist/legacy/firebase/discord/get/authURLGenerator.cjs +3 -0
  63. package/dist/legacy/firebase/discord/get/authURLGenerator.mjs +1 -0
  64. package/dist/legacy/firebase/discord/get/cookie-session.cjs +3 -0
  65. package/dist/legacy/firebase/discord/get/cookie-session.mjs +1 -0
  66. package/dist/legacy/firebase/discord/get/credentials.cjs +2 -0
  67. package/dist/legacy/firebase/discord/get/credentials.mjs +1 -0
  68. package/dist/legacy/firebase/discord/get/errorValidator.cjs +3 -0
  69. package/dist/legacy/firebase/discord/get/errorValidator.mjs +1 -0
  70. package/dist/legacy/firebase/discord/get/index.cjs +3 -0
  71. package/dist/legacy/firebase/discord/get/index.mjs +1 -0
  72. package/dist/legacy/firebase/discord/get/randomAvatar.cjs +3 -0
  73. package/dist/legacy/firebase/discord/get/randomAvatar.mjs +1 -0
  74. package/dist/legacy/firebase/discord/http/index.cjs +3 -0
  75. package/dist/legacy/firebase/discord/http/index.mjs +1 -0
  76. package/dist/legacy/firebase/discord/http/login.cjs +3 -0
  77. package/dist/legacy/firebase/discord/http/login.mjs +1 -0
  78. package/dist/legacy/firebase/discord/http/logout.cjs +3 -0
  79. package/dist/legacy/firebase/discord/http/logout.mjs +1 -0
  80. package/dist/legacy/firebase/discord/http/redirect.cjs +3 -0
  81. package/dist/legacy/firebase/discord/http/redirect.mjs +1 -0
  82. package/dist/legacy/firebase/discord/http/refreshToken.cjs +3 -0
  83. package/dist/legacy/firebase/discord/http/refreshToken.mjs +1 -0
  84. package/dist/legacy/firebase/discord/index.cjs +3 -0
  85. package/dist/legacy/firebase/discord/index.mjs +1 -0
  86. package/dist/legacy/firebase/discord/template/cookie-session.cjs +3 -0
  87. package/dist/legacy/firebase/discord/template/cookie-session.mjs +1 -0
  88. package/dist/legacy/firebase/domainRedirect.cjs +2 -0
  89. package/dist/legacy/firebase/domainRedirect.mjs +1 -0
  90. package/dist/legacy/firebase/escape.cjs +2 -0
  91. package/dist/legacy/firebase/escape.mjs +1 -0
  92. package/dist/legacy/firebase/getDBAsync.cjs +2 -0
  93. package/dist/legacy/firebase/getDBAsync.mjs +1 -0
  94. package/dist/legacy/firebase/getDBData.cjs +3 -0
  95. package/dist/legacy/firebase/getDBData.mjs +1 -0
  96. package/dist/legacy/firebase/getDBValue.cjs +2 -0
  97. package/dist/legacy/firebase/getDBValue.mjs +1 -0
  98. package/dist/legacy/firebase/index.cjs +3 -0
  99. package/dist/legacy/firebase/index.mjs +1 -0
  100. package/dist/legacy/firebase/isEmulator.cjs +2 -0
  101. package/dist/legacy/firebase/isEmulator.mjs +1 -0
  102. package/dist/legacy/firebase/logger.cjs +3 -0
  103. package/dist/legacy/firebase/logger.mjs +1 -0
  104. package/dist/legacy/firebase/mySQL.cjs +3 -0
  105. package/dist/legacy/firebase/mySQL.mjs +1 -0
  106. package/dist/legacy/firebase/mysqlConnector/create.cjs +2 -0
  107. package/dist/legacy/firebase/mysqlConnector/create.mjs +1 -0
  108. package/dist/legacy/firebase/mysqlConnector/index.cjs +3 -0
  109. package/dist/legacy/firebase/mysqlConnector/index.mjs +1 -0
  110. package/dist/legacy/firebase/mysqlConnector/nextPrev.cjs +2 -0
  111. package/dist/legacy/firebase/mysqlConnector/nextPrev.mjs +1 -0
  112. package/dist/legacy/firebase/mysqlConnector/pagination.cjs +2 -0
  113. package/dist/legacy/firebase/mysqlConnector/pagination.mjs +1 -0
  114. package/dist/legacy/firebase/mysqlConnector/sameUser.cjs +3 -0
  115. package/dist/legacy/firebase/mysqlConnector/sameUser.mjs +1 -0
  116. package/dist/legacy/firebase/transactionDBAsync.cjs +2 -0
  117. package/dist/legacy/firebase/transactionDBAsync.mjs +1 -0
  118. package/dist/legacy/get/countObj.cjs +3 -0
  119. package/dist/legacy/get/countObj.mjs +1 -0
  120. package/dist/legacy/get/decimalColor.cjs +3 -0
  121. package/dist/legacy/get/decimalColor.mjs +1 -0
  122. package/dist/legacy/get/objType.cjs +2 -0
  123. package/dist/legacy/get/objType.mjs +1 -0
  124. package/dist/legacy/get/pagination.cjs +3 -0
  125. package/dist/legacy/get/pagination.mjs +1 -0
  126. package/dist/legacy/get/queryUrlByName.cjs +2 -0
  127. package/dist/legacy/get/queryUrlByName.mjs +1 -0
  128. package/dist/legacy/get/queryUrlJSON.cjs +2 -0
  129. package/dist/legacy/get/queryUrlJSON.mjs +1 -0
  130. package/dist/legacy/get/super_string_filter.cjs +3 -0
  131. package/dist/legacy/get/super_string_filter.mjs +1 -0
  132. package/dist/legacy/get/versionCheck.cjs +2 -1
  133. package/dist/legacy/get/versionCheck.mjs +1 -0
  134. package/dist/legacy/http/HTTP-1.0.cjs +2 -0
  135. package/dist/legacy/http/HTTP-1.0.mjs +1 -0
  136. package/dist/legacy/http/auth.cjs +2 -0
  137. package/dist/legacy/http/auth.mjs +1 -0
  138. package/dist/legacy/http/check_domain.cjs +2 -0
  139. package/dist/legacy/http/check_domain.mjs +1 -0
  140. package/dist/legacy/http/csrfTokenAnalyze.cjs +2 -0
  141. package/dist/legacy/http/csrfTokenAnalyze.mjs +1 -0
  142. package/dist/legacy/http/domainValidator.cjs +3 -0
  143. package/dist/legacy/http/domainValidator.mjs +1 -0
  144. package/dist/legacy/http/errorsCallback.cjs +2 -0
  145. package/dist/legacy/http/errorsCallback.mjs +1 -0
  146. package/dist/legacy/http/fetch/json.cjs +3 -0
  147. package/dist/legacy/http/fetch/json.mjs +1 -0
  148. package/dist/legacy/http/fetch/text.cjs +3 -0
  149. package/dist/legacy/http/fetch/text.mjs +1 -0
  150. package/dist/legacy/http/fileCache.cjs +3 -0
  151. package/dist/legacy/http/fileCache.mjs +1 -0
  152. package/dist/legacy/http/getDomainURL.cjs +3 -0
  153. package/dist/legacy/http/getDomainURL.mjs +1 -0
  154. package/dist/legacy/http/userIP.cjs +3 -0
  155. package/dist/legacy/http/userIP.mjs +1 -0
  156. package/dist/legacy/index.cjs +3 -0
  157. package/dist/legacy/index.mjs +1 -0
  158. package/dist/legacy/libs/arraySortPositions.cjs +2 -0
  159. package/dist/legacy/libs/arraySortPositions.mjs +1 -0
  160. package/dist/legacy/libs/capitalize.cjs +2 -0
  161. package/dist/legacy/libs/capitalize.mjs +1 -0
  162. package/dist/legacy/libs/convertBytes.cjs +2 -0
  163. package/dist/legacy/libs/convertBytes.mjs +1 -0
  164. package/dist/legacy/libs/custom_module_loader.cjs +3 -0
  165. package/dist/legacy/libs/custom_module_loader.mjs +1 -0
  166. package/dist/legacy/libs/dice.cjs +2 -0
  167. package/dist/legacy/libs/dice.mjs +1 -0
  168. package/dist/legacy/libs/markdown.cjs +2 -0
  169. package/dist/legacy/libs/markdown.mjs +1 -0
  170. package/dist/legacy/libs/percentage.cjs +2 -0
  171. package/dist/legacy/libs/percentage.mjs +1 -0
  172. package/dist/legacy/libs/regex/getLetter.cjs +2 -0
  173. package/dist/legacy/libs/regex/getLetter.mjs +1 -0
  174. package/dist/legacy/libs/replaceAsync.cjs +3 -0
  175. package/dist/legacy/libs/replaceAsync.mjs +3 -0
  176. package/dist/legacy/libs/rule3.cjs +2 -0
  177. package/dist/legacy/libs/rule3.mjs +1 -0
  178. package/dist/legacy/libs/userLevel.cjs +9 -9
  179. package/dist/legacy/libs/userLevel.d.mts +39 -16
  180. package/dist/legacy/libs/userLevel.mjs +9 -9
  181. package/dist/legacy/momentjs/getAge.cjs +3 -0
  182. package/dist/legacy/momentjs/getAge.mjs +1 -0
  183. package/dist/legacy/momentjs/index.cjs +1 -1
  184. package/dist/legacy/momentjs/index.mjs +1 -0
  185. package/dist/legacy/momentjs/timeDuration.cjs +3 -0
  186. package/dist/legacy/momentjs/timeDuration.mjs +1 -0
  187. package/dist/legacy/socket.io/antiFlood/index.cjs +1 -1
  188. package/dist/legacy/socket.io/antiFlood/index.mjs +1 -0
  189. package/dist/legacy/socket.io/antiFlood/install.cjs +3 -0
  190. package/dist/legacy/socket.io/antiFlood/install.mjs +1 -0
  191. package/dist/legacy/socket.io/antiFlood/verify.cjs +3 -0
  192. package/dist/legacy/socket.io/antiFlood/verify.mjs +1 -0
  193. package/dist/legacy/socket.io/cookie-session.cjs +2 -0
  194. package/dist/legacy/socket.io/cookie-session.mjs +1 -0
  195. package/dist/legacy/socket.io/discord.cjs +3 -0
  196. package/dist/legacy/socket.io/discord.mjs +1 -0
  197. package/dist/legacy/socket.io/index.cjs +3 -0
  198. package/dist/legacy/socket.io/index.mjs +1 -0
  199. package/dist/v1/basics/clock.cjs +43 -13
  200. package/dist/v1/basics/clock.mjs +31 -13
  201. package/dist/v1/basics/index.cjs +27 -0
  202. package/dist/v1/basics/index.d.mts +17 -0
  203. package/dist/v1/basics/index.mjs +7 -0
  204. package/dist/v1/basics/objFilter.cjs +7 -1
  205. package/dist/v1/basics/objFilter.mjs +4 -0
  206. package/dist/v1/basics/simpleMath.cjs +1 -1
  207. package/dist/v1/basics/simpleMath.mjs +1 -1
  208. package/dist/v1/build/TinyCertCrypto.cjs +7 -0
  209. package/dist/v1/build/TinyCertCrypto.d.mts +2 -0
  210. package/dist/v1/build/TinyCertCrypto.mjs +2 -0
  211. package/dist/v1/build/TinyCrypto.cjs +7 -0
  212. package/dist/v1/build/TinyCrypto.d.mts +2 -0
  213. package/dist/v1/build/TinyCrypto.mjs +2 -0
  214. package/dist/v1/build/TinyLevelUp.cjs +7 -0
  215. package/dist/v1/build/TinyLevelUp.d.mts +2 -0
  216. package/dist/v1/build/TinyLevelUp.mjs +2 -0
  217. package/dist/v1/index.cjs +2 -0
  218. package/dist/v1/index.d.mts +2 -1
  219. package/dist/v1/index.mjs +2 -1
  220. package/dist/v1/libs/TinyCertCrypto.cjs +573 -0
  221. package/dist/v1/libs/TinyCertCrypto.d.mts +193 -0
  222. package/dist/v1/libs/TinyCertCrypto.mjs +481 -0
  223. package/dist/v1/libs/TinyCrypto.cjs +91 -45
  224. package/dist/v1/libs/TinyCrypto.d.mts +65 -26
  225. package/dist/v1/libs/TinyCrypto.mjs +64 -39
  226. package/docs/README.md +2 -0
  227. package/docs/libs/TinyCertCrypto.md +202 -0
  228. package/package.json +11 -6
@@ -1,7 +1,16 @@
1
- import crypto from 'crypto';
2
- import fs from 'fs';
1
+ import { randomBytes, createDecipheriv, createCipheriv } from 'crypto';
2
+ import * as fs from 'fs';
3
+ import { Buffer } from 'buffer';
3
4
  import { objType } from '../../v1/basics/objFilter.mjs';
4
- // Detecta se estamos no browser
5
+ /**
6
+ * Determines if the environment is a browser.
7
+ *
8
+ * This constant checks if the code is running in a browser environment by verifying if
9
+ * the `window` object and the `window.document` object are available. It will return `true`
10
+ * if the environment is a browser, and `false` otherwise (e.g., in a Node.js environment).
11
+ *
12
+ * @constant {boolean}
13
+ */
5
14
  const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
6
15
  /**
7
16
  * TinyCrypto is a utility class that provides methods for secure key generation,
@@ -17,8 +26,8 @@ class TinyCrypto {
17
26
  *
18
27
  * @param {Object} [options={}] - Configuration options for encryption and decryption.
19
28
  * @param {string} [options.algorithm='aes-256-gcm'] - The encryption algorithm to use. Recommended: 'aes-256-gcm' for authenticated encryption.
20
- * @param {string} [options.outputEncoding='hex'] - The encoding used when returning encrypted data (e.g., 'hex', 'base64').
21
- * @param {string} [options.inputEncoding='utf8'] - The encoding used for plaintext inputs (e.g., 'utf8').
29
+ * @param {BufferEncoding} [options.outputEncoding='hex'] - The encoding used when returning encrypted data (e.g., 'hex', 'base64').
30
+ * @param {BufferEncoding} [options.inputEncoding='utf8'] - The encoding used for plaintext inputs (e.g., 'utf8').
22
31
  * @param {number} [options.authTagLength=16] - The length of the authentication tag used in GCM mode. Usually 16 for AES-256-GCM.
23
32
  * @param {Buffer} [options.key] - Optional 32-byte cryptographic key. If not provided, a random key is generated.
24
33
  *
@@ -28,15 +37,17 @@ class TinyCrypto {
28
37
  * const crypto = new CryptoManager({
29
38
  * algorithm: 'aes-256-gcm',
30
39
  * outputEncoding: 'base64',
31
- * key: crypto.randomBytes(32),
40
+ * key: randomBytes(32),
32
41
  * });
33
42
  */
34
43
  constructor(options = {}) {
35
44
  this.algorithm = options.algorithm || 'aes-256-gcm';
36
- this.outputEncoding = options.outputEncoding || 'hex';
37
- this.inputEncoding = options.inputEncoding || 'utf8';
38
45
  this.authTagLength = options.authTagLength || 16;
39
46
  this.key = options.key || this.generateKey();
47
+ /** @type {BufferEncoding} */
48
+ this.outputEncoding = options.outputEncoding || 'hex';
49
+ /** @type {BufferEncoding} */
50
+ this.inputEncoding = options.inputEncoding || 'utf8';
40
51
  }
41
52
  /**
42
53
  * Generates a secure random cryptographic key.
@@ -49,7 +60,7 @@ class TinyCrypto {
49
60
  * const customKey = cryptoManager.generateKey(16); // Generates a 16-byte key (e.g. for AES-128)
50
61
  */
51
62
  generateKey(value = 32) {
52
- return crypto.randomBytes(value); // 256-bit
63
+ return randomBytes(value); // 256-bit
53
64
  }
54
65
  /**
55
66
  * Generates a secure random Initialization Vector (IV).
@@ -62,7 +73,7 @@ class TinyCrypto {
62
73
  * const customIV = cryptoManager.generateIV(16); // Generates a 16-byte IV if needed for other algorithms
63
74
  */
64
75
  generateIV(value = 12) {
65
- return crypto.randomBytes(value); // 96-bit padrรฃo para GCM
76
+ return randomBytes(value); // 96-bit padrรฃo para GCM
66
77
  }
67
78
  /**
68
79
  * Encrypts a given value (string, number, object, etc.)
@@ -71,10 +82,7 @@ class TinyCrypto {
71
82
  *
72
83
  * @param {*} data - The data to encrypt. Can be of any supported type (string, number, boolean, Date, JSON, etc.).
73
84
  * @param {Buffer} [iv=this.generateIV()] - Optional Initialization Vector (IV). If not provided, a secure random IV is generated.
74
- * @returns {Object} An object containing:
75
- * - `iv` {string} - The IV used, encoded with the output encoding.
76
- * - `encrypted` {string} - The encrypted payload.
77
- * - `authTag` {string} - The authentication tag used to verify the integrity of the ciphertext.
85
+ * @returns {EncryptedDataParams} An object containing the encrypted data.
78
86
  *
79
87
  * @example
80
88
  * const result = cryptoManager.encrypt('Hello, world!');
@@ -86,28 +94,37 @@ class TinyCrypto {
86
94
  */
87
95
  encrypt(data, iv = this.generateIV()) {
88
96
  const plainText = this.#serialize(data);
89
- const cipher = crypto.createCipheriv(this.algorithm, this.key, iv, {
97
+ const cipher = createCipheriv(this.algorithm, this.key, iv, {
98
+ // @ts-ignore
90
99
  authTagLength: this.authTagLength,
91
100
  });
101
+ // @ts-ignore
92
102
  let encrypted = cipher.update(plainText, this.inputEncoding);
103
+ // @ts-ignore
93
104
  encrypted = Buffer.concat([encrypted, cipher.final()]);
94
105
  const authTag = cipher.getAuthTag();
95
106
  return {
107
+ // @ts-ignore
96
108
  iv: iv.toString(this.outputEncoding),
109
+ // @ts-ignore
97
110
  encrypted: encrypted.toString(this.outputEncoding),
111
+ // @ts-ignore
98
112
  authTag: authTag.toString(this.outputEncoding),
99
113
  };
100
114
  }
115
+ /**
116
+ * @typedef {Object} EncryptedDataParams
117
+ * @property {string} iv - The Initialization Vector (IV) used in encryption, encoded with the output encoding.
118
+ * @property {string} encrypted - The encrypted data to decrypt, encoded with the output encoding.
119
+ * @property {string} authTag - The authentication tag used to verify the integrity of the encrypted data.
120
+ */
101
121
  /**
102
122
  * Decrypts a previously encrypted value.
103
123
  *
104
124
  * The method checks the integrity of the data using the authentication tag (`authTag`) and ensures the data is properly decrypted.
105
125
  * After decryption, it automatically deserializes the data back to its original type.
106
126
  *
107
- * @param {Object} params - An object containing the encrypted data:
108
- * - `iv` {string} - The Initialization Vector (IV) used in encryption, encoded with the output encoding.
109
- * - `encrypted` {string} - The encrypted data to decrypt, encoded with the output encoding.
110
- * - `authTag` {string} - The authentication tag used to verify the integrity of the encrypted data.
127
+ * @param {EncryptedDataParams} params - An object containing the encrypted data.
111
128
  * @param {string|null} [expectedType=null] - Optionally specify the expected type of the decrypted data. If provided, the method will validate the type of the deserialized value.
112
129
  * @returns {*} The decrypted value, which will be the original type of the data before encryption.
113
130
  * @throws {Error} Throws if the authentication tag doesn't match or the data has been tampered with.
@@ -126,11 +143,15 @@ class TinyCrypto {
126
143
  const ivBuffer = Buffer.from(iv, this.outputEncoding);
127
144
  const encryptedBuffer = Buffer.from(encrypted, this.outputEncoding);
128
145
  const authTagBuffer = Buffer.from(authTag, this.outputEncoding);
129
- const decipher = crypto.createDecipheriv(this.algorithm, this.key, ivBuffer, {
146
+ const decipher = createDecipheriv(this.algorithm, this.key, ivBuffer, {
147
+ // @ts-ignore
130
148
  authTagLength: this.authTagLength,
131
149
  });
132
150
  decipher.setAuthTag(authTagBuffer);
151
+ /** @type {string} */
152
+ // @ts-ignore
133
153
  let decrypted = decipher.update(encryptedBuffer, null, this.inputEncoding);
154
+ // @ts-ignore
134
155
  decrypted += decipher.final(this.inputEncoding);
135
156
  const { value, type } = this.#deserialize(decrypted);
136
157
  if (expectedType)
@@ -143,10 +164,7 @@ class TinyCrypto {
143
164
  * This method decrypts the encrypted data and extracts its type information without fully deserializing the value.
144
165
  * It is useful when you need to verify the type of the encrypted data before fully decrypting it.
145
166
  *
146
- * @param {Object} params - An object containing the encrypted data:
147
- * - `iv` {string} - The Initialization Vector (IV) used in encryption, encoded with the output encoding.
148
- * - `encrypted` {string} - The encrypted data to decrypt, encoded with the output encoding.
149
- * - `authTag` {string} - The authentication tag used to verify the integrity of the encrypted data.
167
+ * @param {EncryptedDataParams} params - An object containing the encrypted data.
150
168
  * @returns {string} The type of the original data (e.g., 'string', 'number', 'date', etc.).
151
169
  *
152
170
  * @example
@@ -162,11 +180,14 @@ class TinyCrypto {
162
180
  const ivBuffer = Buffer.from(iv, this.outputEncoding);
163
181
  const encryptedBuffer = Buffer.from(encrypted, this.outputEncoding);
164
182
  const authTagBuffer = Buffer.from(authTag, this.outputEncoding);
165
- const decipher = crypto.createDecipheriv(this.algorithm, this.key, ivBuffer, {
183
+ const decipher = createDecipheriv(this.algorithm, this.key, ivBuffer, {
184
+ // @ts-ignore
166
185
  authTagLength: this.authTagLength,
167
186
  });
168
187
  decipher.setAuthTag(authTagBuffer);
188
+ // @ts-ignore
169
189
  let decrypted = decipher.update(encryptedBuffer, null, this.inputEncoding);
190
+ // @ts-ignore
170
191
  decrypted += decipher.final(this.inputEncoding);
171
192
  const { type } = this.#deserialize(decrypted);
172
193
  return typeof type === 'string' ? type : 'unknown';
@@ -256,10 +277,12 @@ class TinyCrypto {
256
277
  async loadConfigFromFile(file) {
257
278
  if (isBrowser) {
258
279
  return new Promise((resolve, reject) => {
280
+ if (!(file instanceof File))
281
+ return reject(new Error('In browser, the file must be a File object'));
259
282
  const reader = new FileReader();
260
283
  reader.onload = () => {
261
284
  try {
262
- const config = JSON.parse(reader.result);
285
+ const config = typeof reader.result === 'string' ? JSON.parse(reader.result) : {};
263
286
  resolve(this.importConfig(config));
264
287
  }
265
288
  catch (err) {
@@ -271,7 +294,7 @@ class TinyCrypto {
271
294
  });
272
295
  }
273
296
  else {
274
- const raw = fs.readFileSync(file, 'utf8');
297
+ const raw = fs.readFileSync(/** @type {string} */ (file), 'utf8');
275
298
  const config = JSON.parse(raw);
276
299
  return this.importConfig(config);
277
300
  }
@@ -302,9 +325,11 @@ class TinyCrypto {
302
325
  async loadKeyFromFile(file) {
303
326
  if (isBrowser) {
304
327
  return new Promise((resolve, reject) => {
328
+ if (!(file instanceof File))
329
+ return reject(new Error('In browser, the file must be a File object'));
305
330
  const reader = new FileReader();
306
331
  reader.onload = () => {
307
- const hexKey = reader.result.trim();
332
+ const hexKey = typeof reader.result === 'string' ? reader.result.trim() : '';
308
333
  const keyBuffer = Buffer.from(hexKey, 'hex');
309
334
  this.key = keyBuffer;
310
335
  resolve(keyBuffer);
@@ -314,7 +339,7 @@ class TinyCrypto {
314
339
  });
315
340
  }
316
341
  else {
317
- const hexKey = fs.readFileSync(file, 'utf8');
342
+ const hexKey = fs.readFileSync(/** @type {string} */ (file), 'utf8');
318
343
  const keyBuffer = Buffer.from(hexKey, 'hex');
319
344
  this.key = keyBuffer;
320
345
  return keyBuffer;
@@ -358,8 +383,8 @@ class TinyCrypto {
358
383
  *
359
384
  * @param {Object} config - The configuration object to import.
360
385
  * @param {string} config.algorithm - The encryption algorithm (e.g., 'aes-256-gcm').
361
- * @param {string} config.outputEncoding - The output encoding format (e.g., 'hex').
362
- * @param {string} config.inputEncoding - The input encoding format (e.g., 'utf8').
386
+ * @param {BufferEncoding} config.outputEncoding - The output encoding format (e.g., 'hex').
387
+ * @param {BufferEncoding} config.inputEncoding - The input encoding format (e.g., 'utf8').
363
388
  * @param {number} config.authTagLength - The authentication tag length (e.g., 16).
364
389
  * @param {string} config.key - The cryptographic key in hexadecimal string format.
365
390
  *
@@ -406,7 +431,7 @@ class TinyCrypto {
406
431
  * Each key corresponds to a specific data type (e.g., 'number', 'date', 'buffer', etc.),
407
432
  * and the value is a function that serializes the data to a specific format.
408
433
  *
409
- * @type {Object}
434
+ * @type {Record<string, (data: any) => string>}
410
435
  * @property {Function} weakmap - Throws an error as WeakMap cannot be serialized.
411
436
  * @property {Function} weakset - Throws an error as WeakSet cannot be serialized.
412
437
  * @property {Function} promise - Throws an error as Promise cannot be serialized.
@@ -447,8 +472,8 @@ class TinyCrypto {
447
472
  number: (data) => JSON.stringify({ __type: 'number', value: data }),
448
473
  boolean: (data) => JSON.stringify({ __type: 'boolean', value: data }),
449
474
  string: (data) => JSON.stringify({ __type: 'string', value: data }),
450
- null: (data) => JSON.stringify({ __type: 'null' }),
451
- undefined: (data) => JSON.stringify({ __type: 'undefined' }),
475
+ null: () => JSON.stringify({ __type: 'null' }),
476
+ undefined: () => JSON.stringify({ __type: 'undefined' }),
452
477
  map: (data) => JSON.stringify({
453
478
  __type: 'map',
454
479
  value: Array.from(data.entries()),
@@ -470,7 +495,7 @@ class TinyCrypto {
470
495
  * Each key corresponds to a specific data type (e.g., 'Date', 'BigInt', 'Buffer', etc.),
471
496
  * and the value is a function that deserializes the value to its original format.
472
497
  *
473
- * @type {Object}
498
+ * @type {Record<string, (data: any) => any>}
474
499
  * @property {Function} regexp - Deserializes a regular expression from its string representation (e.g., `/pattern/flags`).
475
500
  * @property {Function} htmlelement - Deserializes an HTML element from its serialized outerHTML string (only works in browser environments).
476
501
  * @property {Function} date - Deserializes a date from its ISO string representation.
@@ -497,14 +522,14 @@ class TinyCrypto {
497
522
  throw new Error('HTMLElement deserialization is only supported in browsers');
498
523
  const div = document.createElement('div');
499
524
  div.innerHTML = value;
500
- return div.firstElementChild;
525
+ return div;
501
526
  },
502
527
  date: (value) => new Date(value),
503
528
  bigint: (value) => BigInt(value),
504
529
  number: (value) => Number(value),
505
530
  boolean: (value) => Boolean(value),
506
- null: (value) => null,
507
- undefined: (value) => undefined,
531
+ null: () => null,
532
+ undefined: () => undefined,
508
533
  map: (value) => new Map(value),
509
534
  set: (value) => new Set(value),
510
535
  symbol: (value) => Symbol(value),
@@ -524,7 +549,7 @@ class TinyCrypto {
524
549
  */
525
550
  #serialize(data) {
526
551
  const type = objType(data) || 'undefined';
527
- if (this.#valueConvertTypes[type])
552
+ if (typeof type === 'string' && this.#valueConvertTypes[type])
528
553
  return this.#valueConvertTypes[type](data);
529
554
  throw new Error(`Unsupported data type for encryption: ${type}`);
530
555
  }
package/docs/README.md CHANGED
@@ -14,6 +14,8 @@ This folder contains external libraries and utility modules that are designed to
14
14
 
15
15
  - ๐Ÿ” **[TinyCrypto.md](./libs/TinyCrypto.md)** โ€” A flexible and browser-compatible AES-256-GCM encryption utility with support for complex JavaScript types like `Date`, `RegExp`, `Buffer`, and even DOM elements (in the browser).
16
16
 
17
+ - ๐Ÿ“„ **[TinyCertCrypto.md](./libs/TinyCertCrypto.md)** โ€” A lightweight tool for managing RSA key pairs and X.509 certificates with support for generation, PEM parsing, encryption/decryption of JSON, and certificate metadata extraction. Works in both Node.js and browser environments (with limitations in browser).
18
+
17
19
  ---
18
20
 
19
21
  ### 2. **`basics/`**
@@ -0,0 +1,202 @@
1
+ # โœจ Tiny Cert Crypto
2
+
3
+ A lightweight ๐Ÿ” utility for managing, generating, and handling **X.509 certificates** and **RSA key pairs**.
4
+ Built with flexibility in mind โ€” runs seamlessly in both **Node.js** and **browser** environments! ๐ŸŒ
5
+
6
+ ---
7
+
8
+ ## ๐Ÿ“ฆ Features
9
+
10
+ - ๐Ÿ› ๏ธ RSA key pair generation (**Node.js only**)
11
+ - ๐Ÿงพ Self-signed X.509 certificate creation
12
+ - ๐Ÿงฌ Support for PEM-based ๐Ÿ”‘ public/private keys and certificates
13
+ - ๐ŸงŠ JSON encryption & decryption using Base64 encoding
14
+ - ๐Ÿ•ต๏ธ Metadata extraction from certificates (issuer, subject, validity, etc.)
15
+ - ๐Ÿ“ Flexible key loading: from memory, local files (Node.js), or URLs (browser)
16
+
17
+ ---
18
+
19
+ ## ๐Ÿš€ Getting Started
20
+
21
+ ### ๐Ÿ“š Constructor
22
+
23
+ ```js
24
+ const instance = new TinyCertCrypto({
25
+ publicCertPath: 'cert.pem', // Path to public cert (Node.js)
26
+ privateKeyPath: 'key.pem', // Path to private key (Node.js)
27
+ publicCertBuffer: null, // String or Buffer in memory (Node.js/browser)
28
+ privateKeyBuffer: null, // String or Buffer in memory (Node.js/browser)
29
+ cryptoType: 'RSA-OAEP', // Encryption algorithm (default: 'RSA-OAEP')
30
+ });
31
+ ```
32
+
33
+ > ๐Ÿ” In **browser environments**, at least `publicCertPath` or `publicCertBuffer` must be provided.
34
+
35
+ ---
36
+
37
+ ## ๐Ÿงช Core Methods
38
+
39
+ ### ๐Ÿ”ง `async init()`
40
+ Initializes the certificate and key system from files, memory buffers, or URLs.
41
+
42
+ - Loads the public certificate/key.
43
+ - Optionally loads the private key.
44
+ - Detects whether youโ€™re running in Node.js or the browser and adjusts behavior accordingly.
45
+
46
+ ---
47
+
48
+ ### ๐Ÿ“‘ `extractCertMetadata()`
49
+ Returns parsed metadata from the loaded certificate.
50
+
51
+ ```js
52
+ {
53
+ subject: { names: {}, shortNames: {}, raw: "CN=example.com,O=MyOrg" },
54
+ issuer: { names: {}, shortNames: {}, raw: "CN=example.com,O=MyOrg" },
55
+ serialNumber: '...',
56
+ validFrom: Date,
57
+ validTo: Date
58
+ }
59
+ ```
60
+
61
+ ---
62
+
63
+ ### ๐Ÿ›ก๏ธ `encryptJson(jsonObject)`
64
+ Encrypts a JavaScript object using the loaded **public key**, returning a **Base64-encoded string**.
65
+
66
+ ```js
67
+ const encrypted = instance.encryptJson({ hello: "world" });
68
+ ```
69
+
70
+ ---
71
+
72
+ ### ๐Ÿ”“ `decryptToJson(base64String)`
73
+ Decrypts a Base64 string using the **private key**, returning the original JSON object.
74
+
75
+ ```js
76
+ const json = instance.decryptToJson(encrypted);
77
+ ```
78
+
79
+ ---
80
+
81
+ ### ๐Ÿ” `hasKeys()`
82
+ Returns `true` if both `publicKey` and `privateKey` are loaded.
83
+
84
+ ---
85
+
86
+ ### ๐Ÿ“œ `hasCert()`
87
+ Returns `true` if a certificate (`publicCert`) is loaded.
88
+
89
+ ---
90
+
91
+ ### โ™ป๏ธ `reset()`
92
+ Resets the internal state, clearing:
93
+ - `publicKey`
94
+ - `privateKey`
95
+ - `publicCert`
96
+ - `metadata`
97
+ - `source`
98
+
99
+ ---
100
+
101
+ ### ๐Ÿ“ฆ `fetchNodeForge()` & `getNodeForge()`
102
+ Handles lazy-loading and reuse of the `node-forge` module.
103
+
104
+ Use if you want to access Forge directly without importing it yourself:
105
+
106
+ ```js
107
+ const forge = await instance.fetchNodeForge();
108
+ ```
109
+
110
+ ---
111
+
112
+ ## ๐Ÿง  Internals & Design
113
+
114
+ - ๐Ÿ” Uses regular expressions to detect PEM types (`CERTIFICATE`, `PUBLIC KEY`, `PRIVATE KEY`)
115
+ - ๐Ÿงช Automatically parses PEM buffers and files depending on the runtime
116
+ - ๐Ÿ” Encrypts data with the selected algorithm (`RSA-OAEP`, etc.)
117
+ - ๐Ÿงฌ X.509 certificate metadata extraction is done via `node-forge`
118
+
119
+ ---
120
+
121
+ ## ๐Ÿงฐ Requirements
122
+
123
+ | Environment | Requirement |
124
+ |-------------|--------------------|
125
+ | Node.js | `node-forge` |
126
+ | Browser | Works with native `fetch()` and `TextDecoder` |
127
+
128
+ ---
129
+
130
+ ## ๐Ÿ˜บ Example Use Case
131
+
132
+ ```js
133
+ const crypto = new TinyCertCrypto({ publicCertPath: 'cert.pem', privateKeyPath: 'key.pem' });
134
+ await crypto.init();
135
+
136
+ const data = { secret: 'I love ponies' };
137
+ const encrypted = crypto.encryptJson(data);
138
+ const decrypted = crypto.decryptToJson(encrypted);
139
+
140
+ console.log(decrypted); // { secret: 'I love ponies' }
141
+ ```
142
+
143
+ ---
144
+
145
+ ### ๐Ÿงพ `async generateX509Cert(subjectFields, options = {})`
146
+ Generates a new **RSA key pair** and a **self-signed X.509 certificate** using the provided subject information.
147
+
148
+ ๐Ÿ” This is ideal for internal services, development environments, or cryptographic testing tools where a trusted CA is not required.
149
+
150
+ ---
151
+
152
+ **๐Ÿงฌ Parameters:**
153
+
154
+ - `subjectFields` (`Object`) โ€“ Describes the identity fields that will be embedded into the certificate's subject and issuer:
155
+ - Common fields include:
156
+ - `CN`: Common Name (e.g. domain or hostname)
157
+ - `O`: Organization Name
158
+ - `OU`: Organizational Unit
159
+ - `L`: Locality (City)
160
+ - `ST`: State or Province
161
+ - `C`: Country (2-letter code)
162
+ - `emailAddress`: Optional email field
163
+
164
+ - `options` (`Object`) โ€“ Optional configuration:
165
+ - `keySize` (`number`) โ€“ RSA key size in bits (default: `2048`)
166
+ - `validityInYears` (`number`) โ€“ Certificate validity period (default: `1`)
167
+ - `randomBytesLength` (`number`) โ€“ Length of the serial number (default: `16`)
168
+ - `digestAlgorithm` (`string`) โ€“ Digest algorithm used to sign the certificate (default: `'sha256'`)
169
+ - `forgeInstance` (`object`) โ€“ Optionally inject a specific instance of `node-forge`
170
+ - `cryptoType` (`string`) โ€“ Encryption scheme used for later operations (e.g., `'RSA-OAEP'`, `'RSAES-PKCS1-V1_5'`)
171
+
172
+ ---
173
+
174
+ **โœ… Returns:**
175
+
176
+ An object containing all the generated artifacts:
177
+
178
+ ```js
179
+ {
180
+ publicKey: '-----BEGIN PUBLIC KEY-----...',
181
+ privateKey: '-----BEGIN PRIVATE KEY-----...',
182
+ cert: '-----BEGIN CERTIFICATE-----...'
183
+ }
184
+ ```
185
+
186
+ - `publicKey`: The newly generated **PEM-encoded RSA public key**
187
+ - `privateKey`: The corresponding **PEM-encoded RSA private key**
188
+ - `cert`: A **PEM-encoded X.509 certificate** that is **self-signed** with the private key and matches the provided subject
189
+
190
+ ---
191
+
192
+ **๐Ÿ“Œ Notes:**
193
+
194
+ - ๐Ÿ”„ The `subject` and `issuer` of the certificate are the same (self-signed).
195
+ - โณ The certificate `validFrom` is set to the current date, and `validTo` is based on the `validityInYears` option.
196
+ - ๐Ÿ”ข A secure random `serialNumber` is generated using `crypto.randomBytes`.
197
+
198
+ ---
199
+
200
+ **โš ๏ธ Availability:**
201
+
202
+ > This method is only available in **Node.js environments** due to its dependency on the native `crypto` module and synchronous file access via `fs`.
package/package.json CHANGED
@@ -1,15 +1,19 @@
1
1
  {
2
2
  "name": "tiny-essentials",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "description": "Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.",
5
5
  "scripts": {
6
6
  "test": "npm run test:mjs && npm run test:cjs && npm run test:js",
7
7
  "test:js": "npx babel-node test/index.js",
8
8
  "test:mjs": "node test/index.mjs",
9
9
  "test:cjs": "node test/index.cjs",
10
- "fix:prettier": "prettier --write ./src/* && prettier --write ./test/*",
10
+ "fix:prettier": "npm run fix:prettier:src && npm run fix:prettier:test && npm run fix:prettier:rollup.config && npm run fix:prettier:webpack.config",
11
+ "fix:prettier:src": "prettier --write ./src/*",
12
+ "fix:prettier:test": "prettier --write ./test/*",
13
+ "fix:prettier:rollup.config": "prettier --write ./rollup.config.mjs",
14
+ "fix:prettier:webpack.config": "prettier --write ./webpack.config.mjs",
11
15
  "auto-build": "npm run build",
12
- "build": "tsc -p tsconfig.json && rollup -c",
16
+ "build": "tsc -p tsconfig.json && rollup -c && webpack --mode production",
13
17
  "build-clean": "npm run clean && npm run build",
14
18
  "build-dist": "npm run build",
15
19
  "build-browserify": "npx browserify build/browserify.js -p esmify > dist/TinyAiApi.web.js",
@@ -58,7 +62,6 @@
58
62
  "@rollup/plugin-commonjs": "^28.0.3",
59
63
  "@rollup/plugin-json": "^6.1.0",
60
64
  "@rollup/plugin-node-resolve": "^16.0.1",
61
- "@rollup/plugin-terser": "^0.4.4",
62
65
  "@rollup/plugin-typescript": "^12.1.2",
63
66
  "babel-preset-es2015": "^6.24.1",
64
67
  "byte-length": "^1.0.2",
@@ -72,15 +75,17 @@
72
75
  "moment-timezone": "^0.5.48",
73
76
  "mysql": "^2.18.1",
74
77
  "node-fetch": "2.7.0",
78
+ "node-forge": "^1.3.1",
79
+ "node-polyfill-webpack-plugin": "^4.1.0",
75
80
  "object-hash": "^3.0.0",
76
81
  "prettier": "3.5.3",
77
82
  "rollup": "^4.40.0",
78
- "rollup-plugin-polyfill-node": "^0.13.0",
79
83
  "rollup-preserve-directives": "^1.1.3",
80
84
  "tinycolor2": "^1.6.0",
81
85
  "tslib": "^2.8.1",
82
86
  "type-fest": "^4.40.0",
83
87
  "typescript": "^5.8.3",
84
- "util": "^0.12.5"
88
+ "webpack": "^5.99.6",
89
+ "webpack-cli": "^6.0.1"
85
90
  }
86
91
  }