tiny-essentials 1.2.0 → 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 (207) hide show
  1. package/dist/TinyBasicsEs.js +51 -14
  2. package/dist/TinyBasicsEs.min.js +1 -1
  3. package/dist/TinyCertCrypto.js +26497 -71362
  4. package/dist/TinyCertCrypto.min.js +1 -1
  5. package/dist/TinyCertCrypto.min.js.LICENSE.txt +0 -2
  6. package/dist/TinyCrypto.js +93 -70
  7. package/dist/TinyCrypto.min.js +1 -1
  8. package/dist/TinyEssentials.js +232 -136
  9. package/dist/TinyEssentials.min.js +1 -1
  10. package/dist/TinyLevelUp.js +9 -9
  11. package/dist/legacy/crypto/decrypt.cjs +1 -0
  12. package/dist/legacy/crypto/decrypt.mjs +1 -0
  13. package/dist/legacy/crypto/default.cjs +2 -0
  14. package/dist/legacy/crypto/default.mjs +1 -0
  15. package/dist/legacy/crypto/encrypt.cjs +2 -1
  16. package/dist/legacy/crypto/encrypt.mjs +1 -0
  17. package/dist/legacy/crypto/index.cjs +1 -1
  18. package/dist/legacy/crypto/index.mjs +1 -0
  19. package/dist/legacy/firebase/cookieSession.cjs +2 -0
  20. package/dist/legacy/firebase/cookieSession.mjs +1 -0
  21. package/dist/legacy/firebase/database/index.cjs +3 -0
  22. package/dist/legacy/firebase/database/index.mjs +1 -0
  23. package/dist/legacy/firebase/database/presence.cjs +3 -0
  24. package/dist/legacy/firebase/database/presence.mjs +1 -0
  25. package/dist/legacy/firebase/database/saveAsync.cjs +2 -0
  26. package/dist/legacy/firebase/database/saveAsync.mjs +1 -0
  27. package/dist/legacy/firebase/databaseEscape.cjs +3 -0
  28. package/dist/legacy/firebase/databaseEscape.mjs +1 -0
  29. package/dist/legacy/firebase/databaseLogger.cjs +3 -0
  30. package/dist/legacy/firebase/databaseLogger.mjs +1 -0
  31. package/dist/legacy/firebase/discord/api/addGuildMember.cjs +3 -0
  32. package/dist/legacy/firebase/discord/api/addGuildMember.mjs +1 -0
  33. package/dist/legacy/firebase/discord/api/getGuildWidget.cjs +3 -0
  34. package/dist/legacy/firebase/discord/api/getGuildWidget.mjs +1 -0
  35. package/dist/legacy/firebase/discord/api/getToken.cjs +3 -0
  36. package/dist/legacy/firebase/discord/api/getToken.mjs +1 -0
  37. package/dist/legacy/firebase/discord/api/getUser.cjs +3 -0
  38. package/dist/legacy/firebase/discord/api/getUser.mjs +1 -0
  39. package/dist/legacy/firebase/discord/api/getUserConnections.cjs +3 -0
  40. package/dist/legacy/firebase/discord/api/getUserConnections.mjs +1 -0
  41. package/dist/legacy/firebase/discord/api/getUserGuilds.cjs +3 -0
  42. package/dist/legacy/firebase/discord/api/getUserGuilds.mjs +1 -0
  43. package/dist/legacy/firebase/discord/api/index.cjs +3 -0
  44. package/dist/legacy/firebase/discord/api/index.mjs +1 -0
  45. package/dist/legacy/firebase/discord/api/refreshToken.cjs +3 -0
  46. package/dist/legacy/firebase/discord/api/refreshToken.mjs +1 -0
  47. package/dist/legacy/firebase/discord/api/revokeToken.cjs +3 -0
  48. package/dist/legacy/firebase/discord/api/revokeToken.mjs +1 -0
  49. package/dist/legacy/firebase/discord/config.cjs +2 -0
  50. package/dist/legacy/firebase/discord/config.mjs +1 -0
  51. package/dist/legacy/firebase/discord/firebase_redirect/index.cjs +3 -0
  52. package/dist/legacy/firebase/discord/firebase_redirect/index.mjs +1 -0
  53. package/dist/legacy/firebase/discord/firebase_redirect/login.cjs +2 -0
  54. package/dist/legacy/firebase/discord/firebase_redirect/login.mjs +1 -0
  55. package/dist/legacy/firebase/discord/firebase_redirect/logout.cjs +2 -0
  56. package/dist/legacy/firebase/discord/firebase_redirect/logout.mjs +1 -0
  57. package/dist/legacy/firebase/discord/get/authURLGenerator.cjs +3 -0
  58. package/dist/legacy/firebase/discord/get/authURLGenerator.mjs +1 -0
  59. package/dist/legacy/firebase/discord/get/cookie-session.cjs +3 -0
  60. package/dist/legacy/firebase/discord/get/cookie-session.mjs +1 -0
  61. package/dist/legacy/firebase/discord/get/credentials.cjs +2 -0
  62. package/dist/legacy/firebase/discord/get/credentials.mjs +1 -0
  63. package/dist/legacy/firebase/discord/get/errorValidator.cjs +3 -0
  64. package/dist/legacy/firebase/discord/get/errorValidator.mjs +1 -0
  65. package/dist/legacy/firebase/discord/get/index.cjs +3 -0
  66. package/dist/legacy/firebase/discord/get/index.mjs +1 -0
  67. package/dist/legacy/firebase/discord/get/randomAvatar.cjs +3 -0
  68. package/dist/legacy/firebase/discord/get/randomAvatar.mjs +1 -0
  69. package/dist/legacy/firebase/discord/http/index.cjs +3 -0
  70. package/dist/legacy/firebase/discord/http/index.mjs +1 -0
  71. package/dist/legacy/firebase/discord/http/login.cjs +3 -0
  72. package/dist/legacy/firebase/discord/http/login.mjs +1 -0
  73. package/dist/legacy/firebase/discord/http/logout.cjs +3 -0
  74. package/dist/legacy/firebase/discord/http/logout.mjs +1 -0
  75. package/dist/legacy/firebase/discord/http/redirect.cjs +3 -0
  76. package/dist/legacy/firebase/discord/http/redirect.mjs +1 -0
  77. package/dist/legacy/firebase/discord/http/refreshToken.cjs +3 -0
  78. package/dist/legacy/firebase/discord/http/refreshToken.mjs +1 -0
  79. package/dist/legacy/firebase/discord/index.cjs +3 -0
  80. package/dist/legacy/firebase/discord/index.mjs +1 -0
  81. package/dist/legacy/firebase/discord/template/cookie-session.cjs +3 -0
  82. package/dist/legacy/firebase/discord/template/cookie-session.mjs +1 -0
  83. package/dist/legacy/firebase/domainRedirect.cjs +2 -0
  84. package/dist/legacy/firebase/domainRedirect.mjs +1 -0
  85. package/dist/legacy/firebase/escape.cjs +2 -0
  86. package/dist/legacy/firebase/escape.mjs +1 -0
  87. package/dist/legacy/firebase/getDBAsync.cjs +2 -0
  88. package/dist/legacy/firebase/getDBAsync.mjs +1 -0
  89. package/dist/legacy/firebase/getDBData.cjs +3 -0
  90. package/dist/legacy/firebase/getDBData.mjs +1 -0
  91. package/dist/legacy/firebase/getDBValue.cjs +2 -0
  92. package/dist/legacy/firebase/getDBValue.mjs +1 -0
  93. package/dist/legacy/firebase/index.cjs +3 -0
  94. package/dist/legacy/firebase/index.mjs +1 -0
  95. package/dist/legacy/firebase/isEmulator.cjs +2 -0
  96. package/dist/legacy/firebase/isEmulator.mjs +1 -0
  97. package/dist/legacy/firebase/logger.cjs +3 -0
  98. package/dist/legacy/firebase/logger.mjs +1 -0
  99. package/dist/legacy/firebase/mySQL.cjs +3 -0
  100. package/dist/legacy/firebase/mySQL.mjs +1 -0
  101. package/dist/legacy/firebase/mysqlConnector/create.cjs +2 -0
  102. package/dist/legacy/firebase/mysqlConnector/create.mjs +1 -0
  103. package/dist/legacy/firebase/mysqlConnector/index.cjs +3 -0
  104. package/dist/legacy/firebase/mysqlConnector/index.mjs +1 -0
  105. package/dist/legacy/firebase/mysqlConnector/nextPrev.cjs +2 -0
  106. package/dist/legacy/firebase/mysqlConnector/nextPrev.mjs +1 -0
  107. package/dist/legacy/firebase/mysqlConnector/pagination.cjs +2 -0
  108. package/dist/legacy/firebase/mysqlConnector/pagination.mjs +1 -0
  109. package/dist/legacy/firebase/mysqlConnector/sameUser.cjs +3 -0
  110. package/dist/legacy/firebase/mysqlConnector/sameUser.mjs +1 -0
  111. package/dist/legacy/firebase/transactionDBAsync.cjs +2 -0
  112. package/dist/legacy/firebase/transactionDBAsync.mjs +1 -0
  113. package/dist/legacy/get/countObj.cjs +3 -0
  114. package/dist/legacy/get/countObj.mjs +1 -0
  115. package/dist/legacy/get/decimalColor.cjs +3 -0
  116. package/dist/legacy/get/decimalColor.mjs +1 -0
  117. package/dist/legacy/get/objType.cjs +2 -0
  118. package/dist/legacy/get/objType.mjs +1 -0
  119. package/dist/legacy/get/pagination.cjs +3 -0
  120. package/dist/legacy/get/pagination.mjs +1 -0
  121. package/dist/legacy/get/queryUrlByName.cjs +2 -0
  122. package/dist/legacy/get/queryUrlByName.mjs +1 -0
  123. package/dist/legacy/get/queryUrlJSON.cjs +2 -0
  124. package/dist/legacy/get/queryUrlJSON.mjs +1 -0
  125. package/dist/legacy/get/super_string_filter.cjs +3 -0
  126. package/dist/legacy/get/super_string_filter.mjs +1 -0
  127. package/dist/legacy/get/versionCheck.cjs +2 -1
  128. package/dist/legacy/get/versionCheck.mjs +1 -0
  129. package/dist/legacy/http/HTTP-1.0.cjs +2 -0
  130. package/dist/legacy/http/HTTP-1.0.mjs +1 -0
  131. package/dist/legacy/http/auth.cjs +2 -0
  132. package/dist/legacy/http/auth.mjs +1 -0
  133. package/dist/legacy/http/check_domain.cjs +2 -0
  134. package/dist/legacy/http/check_domain.mjs +1 -0
  135. package/dist/legacy/http/csrfTokenAnalyze.cjs +2 -0
  136. package/dist/legacy/http/csrfTokenAnalyze.mjs +1 -0
  137. package/dist/legacy/http/domainValidator.cjs +3 -0
  138. package/dist/legacy/http/domainValidator.mjs +1 -0
  139. package/dist/legacy/http/errorsCallback.cjs +2 -0
  140. package/dist/legacy/http/errorsCallback.mjs +1 -0
  141. package/dist/legacy/http/fetch/json.cjs +3 -0
  142. package/dist/legacy/http/fetch/json.mjs +1 -0
  143. package/dist/legacy/http/fetch/text.cjs +3 -0
  144. package/dist/legacy/http/fetch/text.mjs +1 -0
  145. package/dist/legacy/http/fileCache.cjs +3 -0
  146. package/dist/legacy/http/fileCache.mjs +1 -0
  147. package/dist/legacy/http/getDomainURL.cjs +3 -0
  148. package/dist/legacy/http/getDomainURL.mjs +1 -0
  149. package/dist/legacy/http/userIP.cjs +3 -0
  150. package/dist/legacy/http/userIP.mjs +1 -0
  151. package/dist/legacy/index.cjs +3 -0
  152. package/dist/legacy/index.mjs +1 -0
  153. package/dist/legacy/libs/arraySortPositions.cjs +2 -0
  154. package/dist/legacy/libs/arraySortPositions.mjs +1 -0
  155. package/dist/legacy/libs/capitalize.cjs +2 -0
  156. package/dist/legacy/libs/capitalize.mjs +1 -0
  157. package/dist/legacy/libs/convertBytes.cjs +2 -0
  158. package/dist/legacy/libs/convertBytes.mjs +1 -0
  159. package/dist/legacy/libs/custom_module_loader.cjs +3 -0
  160. package/dist/legacy/libs/custom_module_loader.mjs +1 -0
  161. package/dist/legacy/libs/dice.cjs +2 -0
  162. package/dist/legacy/libs/dice.mjs +1 -0
  163. package/dist/legacy/libs/markdown.cjs +2 -0
  164. package/dist/legacy/libs/markdown.mjs +1 -0
  165. package/dist/legacy/libs/percentage.cjs +2 -0
  166. package/dist/legacy/libs/percentage.mjs +1 -0
  167. package/dist/legacy/libs/regex/getLetter.cjs +2 -0
  168. package/dist/legacy/libs/regex/getLetter.mjs +1 -0
  169. package/dist/legacy/libs/replaceAsync.cjs +3 -0
  170. package/dist/legacy/libs/replaceAsync.mjs +3 -0
  171. package/dist/legacy/libs/rule3.cjs +2 -0
  172. package/dist/legacy/libs/rule3.mjs +1 -0
  173. package/dist/legacy/libs/userLevel.cjs +9 -9
  174. package/dist/legacy/libs/userLevel.d.mts +39 -16
  175. package/dist/legacy/libs/userLevel.mjs +9 -9
  176. package/dist/legacy/momentjs/getAge.cjs +3 -0
  177. package/dist/legacy/momentjs/getAge.mjs +1 -0
  178. package/dist/legacy/momentjs/index.cjs +1 -1
  179. package/dist/legacy/momentjs/index.mjs +1 -0
  180. package/dist/legacy/momentjs/timeDuration.cjs +3 -0
  181. package/dist/legacy/momentjs/timeDuration.mjs +1 -0
  182. package/dist/legacy/socket.io/antiFlood/index.cjs +1 -1
  183. package/dist/legacy/socket.io/antiFlood/index.mjs +1 -0
  184. package/dist/legacy/socket.io/antiFlood/install.cjs +3 -0
  185. package/dist/legacy/socket.io/antiFlood/install.mjs +1 -0
  186. package/dist/legacy/socket.io/antiFlood/verify.cjs +3 -0
  187. package/dist/legacy/socket.io/antiFlood/verify.mjs +1 -0
  188. package/dist/legacy/socket.io/cookie-session.cjs +2 -0
  189. package/dist/legacy/socket.io/cookie-session.mjs +1 -0
  190. package/dist/legacy/socket.io/discord.cjs +3 -0
  191. package/dist/legacy/socket.io/discord.mjs +1 -0
  192. package/dist/legacy/socket.io/index.cjs +3 -0
  193. package/dist/legacy/socket.io/index.mjs +1 -0
  194. package/dist/v1/basics/clock.cjs +43 -13
  195. package/dist/v1/basics/clock.mjs +31 -13
  196. package/dist/v1/basics/objFilter.cjs +4 -0
  197. package/dist/v1/basics/objFilter.mjs +3 -0
  198. package/dist/v1/basics/simpleMath.cjs +1 -1
  199. package/dist/v1/basics/simpleMath.mjs +1 -1
  200. package/dist/v1/libs/TinyCertCrypto.cjs +104 -45
  201. package/dist/v1/libs/TinyCertCrypto.d.mts +18 -16
  202. package/dist/v1/libs/TinyCertCrypto.mjs +68 -37
  203. package/dist/v1/libs/TinyCrypto.cjs +70 -33
  204. package/dist/v1/libs/TinyCrypto.d.mts +64 -26
  205. package/dist/v1/libs/TinyCrypto.mjs +54 -38
  206. package/package.json +1 -1
  207. package/webpack.config.mjs +0 -69
@@ -1,5 +1,4 @@
1
- import fs from 'fs';
2
- import crypto from 'crypto';
1
+ import * as fs from 'fs';
3
2
  import { Buffer } from 'buffer';
4
3
  /**
5
4
  * Determines if the environment is a browser.
@@ -29,7 +28,6 @@ class TinyCertCrypto {
29
28
  * It supports multi-line content.
30
29
  *
31
30
  * @type {RegExp}
32
- * @private
33
31
  */
34
32
  #certRegex = /-----BEGIN CERTIFICATE-----([\s\S]+?)-----END CERTIFICATE-----/;
35
33
  /**
@@ -41,7 +39,6 @@ class TinyCertCrypto {
41
39
  * It captures the key type (PUBLIC|PRIVATE) and the base64 content.
42
40
  *
43
41
  * @type {RegExp}
44
- * @private
45
42
  */
46
43
  #keyRegex = /-----BEGIN\s+(?:RSA\s+)?(PUBLIC|PRIVATE)\s+KEY-----([\s\S]+?)-----END\s+(?:RSA\s+)?\1\s+KEY-----/;
47
44
  /**
@@ -93,10 +90,10 @@ class TinyCertCrypto {
93
90
  * This method is private and should not be called directly from outside.
94
91
  *
95
92
  * @returns {Promise<Object>} The loaded `node-forge` module.
96
- * @private
97
93
  */
98
94
  async #fetchNodeForge() {
99
95
  if (!this.forge) {
96
+ // @ts-ignore
100
97
  const forge = await import(/* webpackMode: "eager" */ 'node-forge');
101
98
  this.forge = forge.default;
102
99
  }
@@ -116,7 +113,6 @@ class TinyCertCrypto {
116
113
  * Assumes the module has already been loaded.
117
114
  *
118
115
  * @returns {Object} The `node-forge` module.
119
- * @private
120
116
  */
121
117
  #getNodeForge() {
122
118
  return this.forge;
@@ -137,14 +133,13 @@ class TinyCertCrypto {
137
133
  * or `'unknown'` if the format is not recognized.
138
134
  *
139
135
  * @param {string} pemString - The PEM string to inspect.
140
- * @returns {'certificate' | 'public_key' | 'private_key' | 'unknown'} The detected PEM type.
141
- * @private
136
+ * @returns {string} The detected PEM type.
142
137
  */
143
138
  #detectPemType(pemString) {
144
139
  if (this.#certRegex.test(pemString))
145
140
  return 'certificate';
146
141
  const keyMatch = this.#keyRegex.exec(pemString);
147
- if (keyMatch)
142
+ if (keyMatch && typeof keyMatch[1] === 'string')
148
143
  return keyMatch[1].toLowerCase() + '_key'; // "public_key" or "private_key"
149
144
  return 'unknown';
150
145
  }
@@ -154,13 +149,9 @@ class TinyCertCrypto {
154
149
  * This method can only be used in Node.js environments. It throws an error if a certificate
155
150
  * or key is already loaded into the instance.
156
151
  *
157
- * @param {Object} subjectFields - An object representing the subject fields of the certificate (e.g., CN, O, C).
152
+ * @param {Object<string, string>} subjectFields - An object representing the subject fields of the certificate (e.g., CN, O, C).
158
153
  * @param {Object} [options={}] - Optional configuration for key and certificate generation.
159
154
  * @param {number} [options.modulusLength=2048] - Length of the RSA key in bits.
160
- * @param {Object} [options.publicKeyEncoding={ type: 'spki', format: 'pem' }] - Options for public key encoding.
161
- * @param {Object} [options.privateKeyEncoding={ type: 'pkcs8', format: 'pem' }] - Options for private key encoding.
162
- * @param {string} [options.publicKeyType] - Overrides `publicKeyEncoding.type` if provided.
163
- * @param {string} [options.privateKeyType] - Overrides `privateKeyEncoding.type` if provided.
164
155
  * @param {number} [options.validityInYears=1] - Number of years the certificate will be valid.
165
156
  * @param {number} [options.randomBytesLength=16] - Number of random bytes to use for serial number generation.
166
157
  *
@@ -172,46 +163,50 @@ class TinyCertCrypto {
172
163
  if (this.publicKey || this.privateKey || this.publicCert)
173
164
  throw new Error('A certificate is already loaded into the instance.');
174
165
  // Prepare cert
166
+ /** @type {any} */
175
167
  const { pki } = await this.#fetchNodeForge();
176
- const { modulusLength = 2048, publicKeyEncoding = { type: 'spki', format: 'pem' }, privateKeyEncoding = { type: 'pkcs8', format: 'pem' }, validityInYears = 1, randomBytesLength = 16, } = options;
177
- // Value types
178
- const publicKeyType = options.publicKeyType || publicKeyEncoding.type;
179
- const privateKeyType = options.privateKeyType || privateKeyEncoding.type;
180
- // Validator
181
- if (isBrowser)
182
- throw new Error('generateKeyPair can only be used in Node.js environments');
168
+ /**
169
+ * @property {number} [modulusLength=2048] - The length of the RSA modulus (in bits). Default is 2048.
170
+ * @property {number} [validityInYears=1] - The validity period of the key pair in years. Default is 1 year.
171
+ * @property {number} [randomBytesLength=16] - The length of random bytes used in key generation. Default is 16 bytes.
172
+ */
173
+ const { modulusLength = 2048, validityInYears = 1, randomBytesLength = 16 } = options;
183
174
  // Generate keys
184
- const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
185
- modulusLength,
186
- publicKeyEncoding: { ...publicKeyEncoding, type: publicKeyType },
187
- privateKeyEncoding: { ...privateKeyEncoding, type: privateKeyType },
188
- });
175
+ const { publicKey, privateKey } = pki.rsa.generateKeyPair(modulusLength);
176
+ const encodedPublicKey = pki.publicKeyToPem(publicKey);
177
+ const encodedPrivateKey = pki.privateKeyToPem(privateKey);
189
178
  // Get pem files
190
- const { cert, publicPem, privatePem } = this.#generateCertificate(subjectFields, publicKey, privateKey, validityInYears, randomBytesLength);
179
+ const { cert, publicPem, privatePem } = this.#generateCertificate(subjectFields, encodedPublicKey, encodedPrivateKey, validityInYears, randomBytesLength);
191
180
  // Insert data
192
181
  this.publicKey = publicPem;
193
182
  this.privateKey = privatePem;
194
183
  this.publicCertPath = 'MEMORY';
195
184
  this.privateKeyPath = 'MEMORY';
196
185
  this.source = 'memory';
197
- this.publicCertBuffer = publicKey;
198
- this.privateKeyBuffer = privateKey;
186
+ this.publicCertBuffer = Buffer.from(encodedPublicKey);
187
+ this.privateKeyBuffer = Buffer.from(encodedPrivateKey);
199
188
  this.#loadX509Certificate(cert);
200
- return { publicKey, privateKey, cert };
189
+ return { publicKey: encodedPublicKey, privateKey: encodedPrivateKey, cert };
201
190
  }
191
+ /**
192
+ * @typedef {Object} CertificateDetails
193
+ * @property {string} cert - The certificate in PEM format.
194
+ * @property {string} publicPem - The public key in PEM format.
195
+ * @property {string} privatePem - The private key in PEM format.
196
+ */
202
197
  /**
203
198
  * Generates a self-signed X.509 certificate using the given public and private RSA keys.
204
199
  *
205
200
  * This method creates a certificate, assigns the subject and issuer fields,
206
201
  * sets the validity period, and signs it with the private key.
207
202
  *
208
- * @param {Object} subject - An object representing the subject/issuer fields (e.g., { CN: 'example.com' }).
203
+ * @param {Object<string, string>} subject - An object representing the subject/issuer fields (e.g., { CN: 'example.com' }).
209
204
  * @param {string} publicKey - The public key in PEM format.
210
205
  * @param {string} privateKey - The private key in PEM format.
211
206
  * @param {number} validityInYears - Number of years the certificate will remain valid.
212
207
  * @param {number} randomBytesLength - Number of random bytes used to generate the serial number.
213
208
  *
214
- * @returns {Object} An object containing:
209
+ * @returns {CertificateDetails} An object containing:
215
210
  * - {string} cert: The generated certificate in PEM format.
216
211
  * - {Object} publicPem: The parsed public key object (from node-forge).
217
212
  * - {Object} privatePem: The parsed private key object (from node-forge).
@@ -222,7 +217,7 @@ class TinyCertCrypto {
222
217
  const publicPem = pki.publicKeyFromPem(publicKey);
223
218
  const privatePem = pki.privateKeyFromPem(privateKey);
224
219
  cert.publicKey = publicPem;
225
- cert.serialNumber = Buffer.from(crypto.randomBytes(randomBytesLength)).toString('hex');
220
+ cert.serialNumber = Buffer.from(this.forge.random.getBytesSync(randomBytesLength)).toString('hex');
226
221
  cert.validity.notBefore = new Date();
227
222
  cert.validity.notAfter = new Date();
228
223
  cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + validityInYears);
@@ -259,8 +254,17 @@ class TinyCertCrypto {
259
254
  throw new Error('Public certificate is required to initialize');
260
255
  // Load public key
261
256
  this.metadata = {};
257
+ /** @type {any} */
262
258
  const { pki } = await this.#fetchNodeForge();
259
+ /**
260
+ * Loads the public key from a PEM-encoded certificate or public key.
261
+ *
262
+ * @param {string|null} publicPem - The PEM-encoded public key or certificate.
263
+ * @throws {Error} If the PEM string is not recognized or if the key cannot be parsed.
264
+ */
263
265
  const loadPublicKey = (publicPem) => {
266
+ if (typeof publicPem !== 'string')
267
+ throw new Error('Expected publicPem to be a string containing a PEM-encoded key or certificate.');
264
268
  // File type
265
269
  const fileType = this.#detectPemType(publicPem);
266
270
  // Cert
@@ -275,13 +279,25 @@ class TinyCertCrypto {
275
279
  else
276
280
  throw new Error('Public key is required to initialize');
277
281
  };
282
+ /**
283
+ * Loads the private key from a PEM-encoded private key.
284
+ *
285
+ * @param {string|null} privatePem - The PEM-encoded private key.
286
+ * @throws {Error} If the PEM string is not recognized or if the key cannot be parsed.
287
+ */
278
288
  const loadPrivateKey = (privatePem) => {
289
+ if (typeof privatePem !== 'string')
290
+ throw new Error('Expected privatePem to be a string containing a PEM-encoded private key.');
279
291
  const fileType = this.#detectPemType(privatePem);
280
292
  if (fileType === 'private_key')
281
293
  this.privateKey = pki.privateKeyFromPem(privatePem);
282
294
  else
283
295
  throw new Error('Private key is required to initialize');
284
296
  };
297
+ if (typeof this.publicCertPath !== 'string')
298
+ throw new TypeError(`Expected 'publicCertPath' to be a string, but got ${typeof this.publicCertPath}`);
299
+ if (typeof this.privateKeyPath !== 'string')
300
+ throw new TypeError(`Expected 'privateKeyPath' to be a string, but got ${typeof this.privateKeyPath}`);
285
301
  // Nodejs
286
302
  if (!isBrowser) {
287
303
  const usedPublicBuffer = !!this.publicCertBuffer;
@@ -290,7 +306,9 @@ class TinyCertCrypto {
290
306
  const publicPem = usedPublicBuffer
291
307
  ? typeof this.publicCertBuffer === 'string'
292
308
  ? this.publicCertBuffer
293
- : this.publicCertBuffer.toString('utf-8')
309
+ : Buffer.isBuffer(this.publicCertBuffer)
310
+ ? this.publicCertBuffer.toString('utf-8')
311
+ : null
294
312
  : fs.readFileSync(this.publicCertPath, 'utf-8');
295
313
  loadPublicKey(publicPem);
296
314
  // Private Key
@@ -298,7 +316,9 @@ class TinyCertCrypto {
298
316
  const privatePem = usedPrivateBuffer
299
317
  ? typeof this.privateKeyBuffer === 'string'
300
318
  ? this.privateKeyBuffer
301
- : this.privateKeyBuffer.toString('utf-8')
319
+ : Buffer.isBuffer(this.privateKeyBuffer)
320
+ ? this.privateKeyBuffer.toString('utf-8')
321
+ : null
302
322
  : fs.readFileSync(this.privateKeyPath, 'utf-8');
303
323
  loadPrivateKey(privatePem);
304
324
  }
@@ -334,7 +354,6 @@ class TinyCertCrypto {
334
354
  * This method supports both PEM strings and already-parsed Forge certificate objects.
335
355
  * The parsed certificate is saved to `this.publicCert` and its metadata is extracted to `this.metadata`.
336
356
  *
337
- * @private
338
357
  * @param {string|object} certPem - A PEM-encoded certificate string or a `forge.pki.Certificate` object.
339
358
  * @throws {Error} If the certificate cannot be parsed or processed.
340
359
  */
@@ -343,8 +362,20 @@ class TinyCertCrypto {
343
362
  const { pki } = this.forge;
344
363
  const cert = typeof certPem === 'string' ? pki.certificateFromPem(certPem) : certPem;
345
364
  this.publicCert = cert;
365
+ /**
366
+ * @typedef {Object} Attribute
367
+ * @property {string} name - The name of the attribute.
368
+ * @property {string} shortName - The short name of the attribute.
369
+ * @property {string} value - The value of the attribute.
370
+ */
371
+ /**
372
+ * @param {Array<Attribute>} attributes - The list of attributes, each containing `name`, `shortName`, and `value`.
373
+ * @returns {{names: { [key: string]: string }, shortNames: { [key: string]: string }, raw: string}} The processed data containing the organized attributes.
374
+ */
346
375
  const insertData = (attributes) => {
376
+ /** @type {{[key: string]: string}} */
347
377
  const names = {};
378
+ /** @type {{[key: string]: string}} */
348
379
  const shortNames = {};
349
380
  const raw = attributes.map((attr) => `${attr.shortName}=${attr.value}`).join(',');
350
381
  for (const item of attributes) {
@@ -362,7 +393,7 @@ class TinyCertCrypto {
362
393
  };
363
394
  }
364
395
  catch (err) {
365
- throw new Error('Failed to parse X.509 certificate in browser: ' + err.message);
396
+ throw new Error(`Failed to parse X.509 certificate in browser: ${err instanceof Error && typeof err.message === 'string' ? err.message : 'Unknown error'}`);
366
397
  }
367
398
  }
368
399
  /**
@@ -5,6 +5,25 @@ var fs = require('fs');
5
5
  var buffer = require('buffer');
6
6
  var objFilter = require('../basics/objFilter.cjs');
7
7
 
8
+ function _interopNamespaceDefault(e) {
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n.default = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
26
+
8
27
  /**
9
28
  * Determines if the environment is a browser.
10
29
  *
@@ -30,8 +49,8 @@ class TinyCrypto {
30
49
  *
31
50
  * @param {Object} [options={}] - Configuration options for encryption and decryption.
32
51
  * @param {string} [options.algorithm='aes-256-gcm'] - The encryption algorithm to use. Recommended: 'aes-256-gcm' for authenticated encryption.
33
- * @param {string} [options.outputEncoding='hex'] - The encoding used when returning encrypted data (e.g., 'hex', 'base64').
34
- * @param {string} [options.inputEncoding='utf8'] - The encoding used for plaintext inputs (e.g., 'utf8').
52
+ * @param {BufferEncoding} [options.outputEncoding='hex'] - The encoding used when returning encrypted data (e.g., 'hex', 'base64').
53
+ * @param {BufferEncoding} [options.inputEncoding='utf8'] - The encoding used for plaintext inputs (e.g., 'utf8').
35
54
  * @param {number} [options.authTagLength=16] - The length of the authentication tag used in GCM mode. Usually 16 for AES-256-GCM.
36
55
  * @param {Buffer} [options.key] - Optional 32-byte cryptographic key. If not provided, a random key is generated.
37
56
  *
@@ -41,15 +60,17 @@ class TinyCrypto {
41
60
  * const crypto = new CryptoManager({
42
61
  * algorithm: 'aes-256-gcm',
43
62
  * outputEncoding: 'base64',
44
- * key: crypto.randomBytes(32),
63
+ * key: randomBytes(32),
45
64
  * });
46
65
  */
47
66
  constructor(options = {}) {
48
67
  this.algorithm = options.algorithm || 'aes-256-gcm';
49
- this.outputEncoding = options.outputEncoding || 'hex';
50
- this.inputEncoding = options.inputEncoding || 'utf8';
51
68
  this.authTagLength = options.authTagLength || 16;
52
69
  this.key = options.key || this.generateKey();
70
+ /** @type {BufferEncoding} */
71
+ this.outputEncoding = options.outputEncoding || 'hex';
72
+ /** @type {BufferEncoding} */
73
+ this.inputEncoding = options.inputEncoding || 'utf8';
53
74
  }
54
75
 
55
76
  /**
@@ -87,10 +108,7 @@ class TinyCrypto {
87
108
  *
88
109
  * @param {*} data - The data to encrypt. Can be of any supported type (string, number, boolean, Date, JSON, etc.).
89
110
  * @param {Buffer} [iv=this.generateIV()] - Optional Initialization Vector (IV). If not provided, a secure random IV is generated.
90
- * @returns {Object} An object containing:
91
- * - `iv` {string} - The IV used, encoded with the output encoding.
92
- * - `encrypted` {string} - The encrypted payload.
93
- * - `authTag` {string} - The authentication tag used to verify the integrity of the ciphertext.
111
+ * @returns {EncryptedDataParams} An object containing the encrypted data.
94
112
  *
95
113
  * @example
96
114
  * const result = cryptoManager.encrypt('Hello, world!');
@@ -104,30 +122,40 @@ class TinyCrypto {
104
122
  const plainText = this.#serialize(data);
105
123
 
106
124
  const cipher = crypto.createCipheriv(this.algorithm, this.key, iv, {
125
+ // @ts-ignore
107
126
  authTagLength: this.authTagLength,
108
127
  });
109
128
 
129
+ // @ts-ignore
110
130
  let encrypted = cipher.update(plainText, this.inputEncoding);
131
+ // @ts-ignore
111
132
  encrypted = buffer.Buffer.concat([encrypted, cipher.final()]);
112
133
  const authTag = cipher.getAuthTag();
113
134
 
114
135
  return {
136
+ // @ts-ignore
115
137
  iv: iv.toString(this.outputEncoding),
138
+ // @ts-ignore
116
139
  encrypted: encrypted.toString(this.outputEncoding),
140
+ // @ts-ignore
117
141
  authTag: authTag.toString(this.outputEncoding),
118
142
  };
119
143
  }
120
144
 
145
+ /**
146
+ * @typedef {Object} EncryptedDataParams
147
+ * @property {string} iv - The Initialization Vector (IV) used in encryption, encoded with the output encoding.
148
+ * @property {string} encrypted - The encrypted data to decrypt, encoded with the output encoding.
149
+ * @property {string} authTag - The authentication tag used to verify the integrity of the encrypted data.
150
+ */
151
+
121
152
  /**
122
153
  * Decrypts a previously encrypted value.
123
154
  *
124
155
  * The method checks the integrity of the data using the authentication tag (`authTag`) and ensures the data is properly decrypted.
125
156
  * After decryption, it automatically deserializes the data back to its original type.
126
157
  *
127
- * @param {Object} params - An object containing the encrypted data:
128
- * - `iv` {string} - The Initialization Vector (IV) used in encryption, encoded with the output encoding.
129
- * - `encrypted` {string} - The encrypted data to decrypt, encoded with the output encoding.
130
- * - `authTag` {string} - The authentication tag used to verify the integrity of the encrypted data.
158
+ * @param {EncryptedDataParams} params - An object containing the encrypted data.
131
159
  * @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.
132
160
  * @returns {*} The decrypted value, which will be the original type of the data before encryption.
133
161
  * @throws {Error} Throws if the authentication tag doesn't match or the data has been tampered with.
@@ -148,12 +176,16 @@ class TinyCrypto {
148
176
  const authTagBuffer = buffer.Buffer.from(authTag, this.outputEncoding);
149
177
 
150
178
  const decipher = crypto.createDecipheriv(this.algorithm, this.key, ivBuffer, {
179
+ // @ts-ignore
151
180
  authTagLength: this.authTagLength,
152
181
  });
153
182
 
154
183
  decipher.setAuthTag(authTagBuffer);
155
184
 
185
+ /** @type {string} */
186
+ // @ts-ignore
156
187
  let decrypted = decipher.update(encryptedBuffer, null, this.inputEncoding);
188
+ // @ts-ignore
157
189
  decrypted += decipher.final(this.inputEncoding);
158
190
  const { value, type } = this.#deserialize(decrypted);
159
191
 
@@ -167,10 +199,7 @@ class TinyCrypto {
167
199
  * This method decrypts the encrypted data and extracts its type information without fully deserializing the value.
168
200
  * It is useful when you need to verify the type of the encrypted data before fully decrypting it.
169
201
  *
170
- * @param {Object} params - An object containing the encrypted data:
171
- * - `iv` {string} - The Initialization Vector (IV) used in encryption, encoded with the output encoding.
172
- * - `encrypted` {string} - The encrypted data to decrypt, encoded with the output encoding.
173
- * - `authTag` {string} - The authentication tag used to verify the integrity of the encrypted data.
202
+ * @param {EncryptedDataParams} params - An object containing the encrypted data.
174
203
  * @returns {string} The type of the original data (e.g., 'string', 'number', 'date', etc.).
175
204
  *
176
205
  * @example
@@ -188,12 +217,15 @@ class TinyCrypto {
188
217
  const authTagBuffer = buffer.Buffer.from(authTag, this.outputEncoding);
189
218
 
190
219
  const decipher = crypto.createDecipheriv(this.algorithm, this.key, ivBuffer, {
220
+ // @ts-ignore
191
221
  authTagLength: this.authTagLength,
192
222
  });
193
223
 
194
224
  decipher.setAuthTag(authTagBuffer);
195
225
 
226
+ // @ts-ignore
196
227
  let decrypted = decipher.update(encryptedBuffer, null, this.inputEncoding);
228
+ // @ts-ignore
197
229
  decrypted += decipher.final(this.inputEncoding);
198
230
 
199
231
  const { type } = this.#deserialize(decrypted);
@@ -226,7 +258,7 @@ class TinyCrypto {
226
258
  a.download = filename;
227
259
  a.click();
228
260
  URL.revokeObjectURL(url);
229
- } else fs.writeFileSync(filename, data);
261
+ } else fs__namespace.writeFileSync(filename, data);
230
262
  }
231
263
 
232
264
  /**
@@ -255,7 +287,7 @@ class TinyCrypto {
255
287
  a.download = filename;
256
288
  a.click();
257
289
  URL.revokeObjectURL(url);
258
- } else fs.writeFileSync(filename, configData);
290
+ } else fs__namespace.writeFileSync(filename, configData);
259
291
  }
260
292
 
261
293
  /**
@@ -283,10 +315,12 @@ class TinyCrypto {
283
315
  async loadConfigFromFile(file) {
284
316
  if (isBrowser) {
285
317
  return new Promise((resolve, reject) => {
318
+ if (!(file instanceof File))
319
+ return reject(new Error('In browser, the file must be a File object'));
286
320
  const reader = new FileReader();
287
321
  reader.onload = () => {
288
322
  try {
289
- const config = JSON.parse(reader.result);
323
+ const config = typeof reader.result === 'string' ? JSON.parse(reader.result) : {};
290
324
  resolve(this.importConfig(config));
291
325
  } catch (err) {
292
326
  reject(new Error('Invalid config JSON file'));
@@ -296,7 +330,7 @@ class TinyCrypto {
296
330
  reader.readAsText(file);
297
331
  });
298
332
  } else {
299
- const raw = fs.readFileSync(file, 'utf8');
333
+ const raw = fs__namespace.readFileSync(/** @type {string} */ (file), 'utf8');
300
334
  const config = JSON.parse(raw);
301
335
  return this.importConfig(config);
302
336
  }
@@ -328,9 +362,11 @@ class TinyCrypto {
328
362
  async loadKeyFromFile(file) {
329
363
  if (isBrowser) {
330
364
  return new Promise((resolve, reject) => {
365
+ if (!(file instanceof File))
366
+ return reject(new Error('In browser, the file must be a File object'));
331
367
  const reader = new FileReader();
332
368
  reader.onload = () => {
333
- const hexKey = reader.result.trim();
369
+ const hexKey = typeof reader.result === 'string' ? reader.result.trim() : '';
334
370
  const keyBuffer = buffer.Buffer.from(hexKey, 'hex');
335
371
  this.key = keyBuffer;
336
372
  resolve(keyBuffer);
@@ -339,7 +375,7 @@ class TinyCrypto {
339
375
  reader.readAsText(file);
340
376
  });
341
377
  } else {
342
- const hexKey = fs.readFileSync(file, 'utf8');
378
+ const hexKey = fs__namespace.readFileSync(/** @type {string} */ (file), 'utf8');
343
379
  const keyBuffer = buffer.Buffer.from(hexKey, 'hex');
344
380
  this.key = keyBuffer;
345
381
  return keyBuffer;
@@ -385,8 +421,8 @@ class TinyCrypto {
385
421
  *
386
422
  * @param {Object} config - The configuration object to import.
387
423
  * @param {string} config.algorithm - The encryption algorithm (e.g., 'aes-256-gcm').
388
- * @param {string} config.outputEncoding - The output encoding format (e.g., 'hex').
389
- * @param {string} config.inputEncoding - The input encoding format (e.g., 'utf8').
424
+ * @param {BufferEncoding} config.outputEncoding - The output encoding format (e.g., 'hex').
425
+ * @param {BufferEncoding} config.inputEncoding - The input encoding format (e.g., 'utf8').
390
426
  * @param {number} config.authTagLength - The authentication tag length (e.g., 16).
391
427
  * @param {string} config.key - The cryptographic key in hexadecimal string format.
392
428
  *
@@ -433,7 +469,7 @@ class TinyCrypto {
433
469
  * Each key corresponds to a specific data type (e.g., 'number', 'date', 'buffer', etc.),
434
470
  * and the value is a function that serializes the data to a specific format.
435
471
  *
436
- * @type {Object}
472
+ * @type {Record<string, (data: any) => string>}
437
473
  * @property {Function} weakmap - Throws an error as WeakMap cannot be serialized.
438
474
  * @property {Function} weakset - Throws an error as WeakSet cannot be serialized.
439
475
  * @property {Function} promise - Throws an error as Promise cannot be serialized.
@@ -474,8 +510,8 @@ class TinyCrypto {
474
510
  number: (data) => JSON.stringify({ __type: 'number', value: data }),
475
511
  boolean: (data) => JSON.stringify({ __type: 'boolean', value: data }),
476
512
  string: (data) => JSON.stringify({ __type: 'string', value: data }),
477
- null: (data) => JSON.stringify({ __type: 'null' }),
478
- undefined: (data) => JSON.stringify({ __type: 'undefined' }),
513
+ null: () => JSON.stringify({ __type: 'null' }),
514
+ undefined: () => JSON.stringify({ __type: 'undefined' }),
479
515
  map: (data) =>
480
516
  JSON.stringify({
481
517
  __type: 'map',
@@ -500,7 +536,7 @@ class TinyCrypto {
500
536
  * Each key corresponds to a specific data type (e.g., 'Date', 'BigInt', 'Buffer', etc.),
501
537
  * and the value is a function that deserializes the value to its original format.
502
538
  *
503
- * @type {Object}
539
+ * @type {Record<string, (data: any) => any>}
504
540
  * @property {Function} regexp - Deserializes a regular expression from its string representation (e.g., `/pattern/flags`).
505
541
  * @property {Function} htmlelement - Deserializes an HTML element from its serialized outerHTML string (only works in browser environments).
506
542
  * @property {Function} date - Deserializes a date from its ISO string representation.
@@ -527,14 +563,14 @@ class TinyCrypto {
527
563
  throw new Error('HTMLElement deserialization is only supported in browsers');
528
564
  const div = document.createElement('div');
529
565
  div.innerHTML = value;
530
- return div.firstElementChild;
566
+ return div;
531
567
  },
532
568
  date: (value) => new Date(value),
533
569
  bigint: (value) => BigInt(value),
534
570
  number: (value) => Number(value),
535
571
  boolean: (value) => Boolean(value),
536
- null: (value) => null,
537
- undefined: (value) => undefined,
572
+ null: () => null,
573
+ undefined: () => undefined,
538
574
  map: (value) => new Map(value),
539
575
  set: (value) => new Set(value),
540
576
  symbol: (value) => Symbol(value),
@@ -555,7 +591,8 @@ class TinyCrypto {
555
591
  */
556
592
  #serialize(data) {
557
593
  const type = objFilter.objType(data) || 'undefined';
558
- if (this.#valueConvertTypes[type]) return this.#valueConvertTypes[type](data);
594
+ if (typeof type === 'string' && this.#valueConvertTypes[type])
595
+ return this.#valueConvertTypes[type](data);
559
596
  throw new Error(`Unsupported data type for encryption: ${type}`);
560
597
  }
561
598