tiny-essentials 1.2.0 → 1.3.0

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 (222) hide show
  1. package/README.md +3 -3
  2. package/dist/TinyBasicsEs.js +51 -14
  3. package/dist/TinyBasicsEs.min.js +1 -1
  4. package/dist/TinyEssentials.js +2372 -77014
  5. package/dist/TinyEssentials.min.js +1 -1
  6. package/dist/TinyEssentials.min.js.LICENSE.txt +0 -2
  7. package/dist/TinyLevelUp.js +9 -9
  8. package/dist/legacy/crypto/decrypt.cjs +1 -0
  9. package/dist/legacy/crypto/decrypt.mjs +1 -0
  10. package/dist/legacy/crypto/default.cjs +2 -0
  11. package/dist/legacy/crypto/default.mjs +1 -0
  12. package/dist/legacy/crypto/encrypt.cjs +2 -1
  13. package/dist/legacy/crypto/encrypt.mjs +1 -0
  14. package/dist/legacy/crypto/index.cjs +1 -1
  15. package/dist/legacy/crypto/index.mjs +1 -0
  16. package/dist/legacy/firebase/cookieSession.cjs +2 -0
  17. package/dist/legacy/firebase/cookieSession.mjs +1 -0
  18. package/dist/legacy/firebase/database/index.cjs +3 -0
  19. package/dist/legacy/firebase/database/index.mjs +1 -0
  20. package/dist/legacy/firebase/database/presence.cjs +3 -0
  21. package/dist/legacy/firebase/database/presence.mjs +1 -0
  22. package/dist/legacy/firebase/database/saveAsync.cjs +2 -0
  23. package/dist/legacy/firebase/database/saveAsync.mjs +1 -0
  24. package/dist/legacy/firebase/databaseEscape.cjs +3 -0
  25. package/dist/legacy/firebase/databaseEscape.mjs +1 -0
  26. package/dist/legacy/firebase/databaseLogger.cjs +3 -0
  27. package/dist/legacy/firebase/databaseLogger.mjs +1 -0
  28. package/dist/legacy/firebase/discord/api/addGuildMember.cjs +3 -0
  29. package/dist/legacy/firebase/discord/api/addGuildMember.mjs +1 -0
  30. package/dist/legacy/firebase/discord/api/getGuildWidget.cjs +3 -0
  31. package/dist/legacy/firebase/discord/api/getGuildWidget.mjs +1 -0
  32. package/dist/legacy/firebase/discord/api/getToken.cjs +3 -0
  33. package/dist/legacy/firebase/discord/api/getToken.mjs +1 -0
  34. package/dist/legacy/firebase/discord/api/getUser.cjs +3 -0
  35. package/dist/legacy/firebase/discord/api/getUser.mjs +1 -0
  36. package/dist/legacy/firebase/discord/api/getUserConnections.cjs +3 -0
  37. package/dist/legacy/firebase/discord/api/getUserConnections.mjs +1 -0
  38. package/dist/legacy/firebase/discord/api/getUserGuilds.cjs +3 -0
  39. package/dist/legacy/firebase/discord/api/getUserGuilds.mjs +1 -0
  40. package/dist/legacy/firebase/discord/api/index.cjs +3 -0
  41. package/dist/legacy/firebase/discord/api/index.mjs +1 -0
  42. package/dist/legacy/firebase/discord/api/refreshToken.cjs +3 -0
  43. package/dist/legacy/firebase/discord/api/refreshToken.mjs +1 -0
  44. package/dist/legacy/firebase/discord/api/revokeToken.cjs +3 -0
  45. package/dist/legacy/firebase/discord/api/revokeToken.mjs +1 -0
  46. package/dist/legacy/firebase/discord/config.cjs +2 -0
  47. package/dist/legacy/firebase/discord/config.mjs +1 -0
  48. package/dist/legacy/firebase/discord/firebase_redirect/index.cjs +3 -0
  49. package/dist/legacy/firebase/discord/firebase_redirect/index.mjs +1 -0
  50. package/dist/legacy/firebase/discord/firebase_redirect/login.cjs +2 -0
  51. package/dist/legacy/firebase/discord/firebase_redirect/login.mjs +1 -0
  52. package/dist/legacy/firebase/discord/firebase_redirect/logout.cjs +2 -0
  53. package/dist/legacy/firebase/discord/firebase_redirect/logout.mjs +1 -0
  54. package/dist/legacy/firebase/discord/get/authURLGenerator.cjs +3 -0
  55. package/dist/legacy/firebase/discord/get/authURLGenerator.mjs +1 -0
  56. package/dist/legacy/firebase/discord/get/cookie-session.cjs +3 -0
  57. package/dist/legacy/firebase/discord/get/cookie-session.mjs +1 -0
  58. package/dist/legacy/firebase/discord/get/credentials.cjs +2 -0
  59. package/dist/legacy/firebase/discord/get/credentials.mjs +1 -0
  60. package/dist/legacy/firebase/discord/get/errorValidator.cjs +3 -0
  61. package/dist/legacy/firebase/discord/get/errorValidator.mjs +1 -0
  62. package/dist/legacy/firebase/discord/get/index.cjs +3 -0
  63. package/dist/legacy/firebase/discord/get/index.mjs +1 -0
  64. package/dist/legacy/firebase/discord/get/randomAvatar.cjs +3 -0
  65. package/dist/legacy/firebase/discord/get/randomAvatar.mjs +1 -0
  66. package/dist/legacy/firebase/discord/http/index.cjs +3 -0
  67. package/dist/legacy/firebase/discord/http/index.mjs +1 -0
  68. package/dist/legacy/firebase/discord/http/login.cjs +3 -0
  69. package/dist/legacy/firebase/discord/http/login.mjs +1 -0
  70. package/dist/legacy/firebase/discord/http/logout.cjs +3 -0
  71. package/dist/legacy/firebase/discord/http/logout.mjs +1 -0
  72. package/dist/legacy/firebase/discord/http/redirect.cjs +3 -0
  73. package/dist/legacy/firebase/discord/http/redirect.mjs +1 -0
  74. package/dist/legacy/firebase/discord/http/refreshToken.cjs +3 -0
  75. package/dist/legacy/firebase/discord/http/refreshToken.mjs +1 -0
  76. package/dist/legacy/firebase/discord/index.cjs +3 -0
  77. package/dist/legacy/firebase/discord/index.mjs +1 -0
  78. package/dist/legacy/firebase/discord/template/cookie-session.cjs +3 -0
  79. package/dist/legacy/firebase/discord/template/cookie-session.mjs +1 -0
  80. package/dist/legacy/firebase/domainRedirect.cjs +2 -0
  81. package/dist/legacy/firebase/domainRedirect.mjs +1 -0
  82. package/dist/legacy/firebase/escape.cjs +2 -0
  83. package/dist/legacy/firebase/escape.mjs +1 -0
  84. package/dist/legacy/firebase/getDBAsync.cjs +2 -0
  85. package/dist/legacy/firebase/getDBAsync.mjs +1 -0
  86. package/dist/legacy/firebase/getDBData.cjs +3 -0
  87. package/dist/legacy/firebase/getDBData.mjs +1 -0
  88. package/dist/legacy/firebase/getDBValue.cjs +2 -0
  89. package/dist/legacy/firebase/getDBValue.mjs +1 -0
  90. package/dist/legacy/firebase/index.cjs +3 -0
  91. package/dist/legacy/firebase/index.mjs +1 -0
  92. package/dist/legacy/firebase/isEmulator.cjs +2 -0
  93. package/dist/legacy/firebase/isEmulator.mjs +1 -0
  94. package/dist/legacy/firebase/logger.cjs +3 -0
  95. package/dist/legacy/firebase/logger.mjs +1 -0
  96. package/dist/legacy/firebase/mySQL.cjs +3 -0
  97. package/dist/legacy/firebase/mySQL.mjs +1 -0
  98. package/dist/legacy/firebase/mysqlConnector/create.cjs +2 -0
  99. package/dist/legacy/firebase/mysqlConnector/create.mjs +1 -0
  100. package/dist/legacy/firebase/mysqlConnector/index.cjs +3 -0
  101. package/dist/legacy/firebase/mysqlConnector/index.mjs +1 -0
  102. package/dist/legacy/firebase/mysqlConnector/nextPrev.cjs +2 -0
  103. package/dist/legacy/firebase/mysqlConnector/nextPrev.mjs +1 -0
  104. package/dist/legacy/firebase/mysqlConnector/pagination.cjs +2 -0
  105. package/dist/legacy/firebase/mysqlConnector/pagination.mjs +1 -0
  106. package/dist/legacy/firebase/mysqlConnector/sameUser.cjs +3 -0
  107. package/dist/legacy/firebase/mysqlConnector/sameUser.mjs +1 -0
  108. package/dist/legacy/firebase/transactionDBAsync.cjs +2 -0
  109. package/dist/legacy/firebase/transactionDBAsync.mjs +1 -0
  110. package/dist/legacy/get/countObj.cjs +3 -0
  111. package/dist/legacy/get/countObj.mjs +1 -0
  112. package/dist/legacy/get/decimalColor.cjs +3 -0
  113. package/dist/legacy/get/decimalColor.mjs +1 -0
  114. package/dist/legacy/get/objType.cjs +2 -0
  115. package/dist/legacy/get/objType.mjs +1 -0
  116. package/dist/legacy/get/pagination.cjs +3 -0
  117. package/dist/legacy/get/pagination.mjs +1 -0
  118. package/dist/legacy/get/queryUrlByName.cjs +2 -0
  119. package/dist/legacy/get/queryUrlByName.mjs +1 -0
  120. package/dist/legacy/get/queryUrlJSON.cjs +2 -0
  121. package/dist/legacy/get/queryUrlJSON.mjs +1 -0
  122. package/dist/legacy/get/super_string_filter.cjs +3 -0
  123. package/dist/legacy/get/super_string_filter.mjs +1 -0
  124. package/dist/legacy/get/versionCheck.cjs +2 -1
  125. package/dist/legacy/get/versionCheck.mjs +1 -0
  126. package/dist/legacy/http/HTTP-1.0.cjs +2 -0
  127. package/dist/legacy/http/HTTP-1.0.mjs +1 -0
  128. package/dist/legacy/http/auth.cjs +2 -0
  129. package/dist/legacy/http/auth.mjs +1 -0
  130. package/dist/legacy/http/check_domain.cjs +2 -0
  131. package/dist/legacy/http/check_domain.mjs +1 -0
  132. package/dist/legacy/http/csrfTokenAnalyze.cjs +2 -0
  133. package/dist/legacy/http/csrfTokenAnalyze.mjs +1 -0
  134. package/dist/legacy/http/domainValidator.cjs +3 -0
  135. package/dist/legacy/http/domainValidator.mjs +1 -0
  136. package/dist/legacy/http/errorsCallback.cjs +2 -0
  137. package/dist/legacy/http/errorsCallback.mjs +1 -0
  138. package/dist/legacy/http/fetch/json.cjs +3 -0
  139. package/dist/legacy/http/fetch/json.mjs +1 -0
  140. package/dist/legacy/http/fetch/text.cjs +3 -0
  141. package/dist/legacy/http/fetch/text.mjs +1 -0
  142. package/dist/legacy/http/fileCache.cjs +3 -0
  143. package/dist/legacy/http/fileCache.mjs +1 -0
  144. package/dist/legacy/http/getDomainURL.cjs +3 -0
  145. package/dist/legacy/http/getDomainURL.mjs +1 -0
  146. package/dist/legacy/http/userIP.cjs +3 -0
  147. package/dist/legacy/http/userIP.mjs +1 -0
  148. package/dist/legacy/index.cjs +3 -0
  149. package/dist/legacy/index.mjs +1 -0
  150. package/dist/legacy/libs/arraySortPositions.cjs +2 -0
  151. package/dist/legacy/libs/arraySortPositions.mjs +1 -0
  152. package/dist/legacy/libs/capitalize.cjs +2 -0
  153. package/dist/legacy/libs/capitalize.mjs +1 -0
  154. package/dist/legacy/libs/convertBytes.cjs +2 -0
  155. package/dist/legacy/libs/convertBytes.mjs +1 -0
  156. package/dist/legacy/libs/custom_module_loader.cjs +3 -0
  157. package/dist/legacy/libs/custom_module_loader.mjs +1 -0
  158. package/dist/legacy/libs/dice.cjs +2 -0
  159. package/dist/legacy/libs/dice.mjs +1 -0
  160. package/dist/legacy/libs/markdown.cjs +2 -0
  161. package/dist/legacy/libs/markdown.mjs +1 -0
  162. package/dist/legacy/libs/percentage.cjs +2 -0
  163. package/dist/legacy/libs/percentage.mjs +1 -0
  164. package/dist/legacy/libs/regex/getLetter.cjs +2 -0
  165. package/dist/legacy/libs/regex/getLetter.mjs +1 -0
  166. package/dist/legacy/libs/replaceAsync.cjs +3 -0
  167. package/dist/legacy/libs/replaceAsync.mjs +3 -0
  168. package/dist/legacy/libs/rule3.cjs +2 -0
  169. package/dist/legacy/libs/rule3.mjs +1 -0
  170. package/dist/legacy/libs/userLevel.cjs +9 -9
  171. package/dist/legacy/libs/userLevel.d.mts +39 -16
  172. package/dist/legacy/libs/userLevel.mjs +9 -9
  173. package/dist/legacy/momentjs/getAge.cjs +3 -0
  174. package/dist/legacy/momentjs/getAge.mjs +1 -0
  175. package/dist/legacy/momentjs/index.cjs +1 -1
  176. package/dist/legacy/momentjs/index.mjs +1 -0
  177. package/dist/legacy/momentjs/timeDuration.cjs +3 -0
  178. package/dist/legacy/momentjs/timeDuration.mjs +1 -0
  179. package/dist/legacy/socket.io/antiFlood/index.cjs +1 -1
  180. package/dist/legacy/socket.io/antiFlood/index.mjs +1 -0
  181. package/dist/legacy/socket.io/antiFlood/install.cjs +3 -0
  182. package/dist/legacy/socket.io/antiFlood/install.mjs +1 -0
  183. package/dist/legacy/socket.io/antiFlood/verify.cjs +3 -0
  184. package/dist/legacy/socket.io/antiFlood/verify.mjs +1 -0
  185. package/dist/legacy/socket.io/cookie-session.cjs +2 -0
  186. package/dist/legacy/socket.io/cookie-session.mjs +1 -0
  187. package/dist/legacy/socket.io/discord.cjs +3 -0
  188. package/dist/legacy/socket.io/discord.mjs +1 -0
  189. package/dist/legacy/socket.io/index.cjs +3 -0
  190. package/dist/legacy/socket.io/index.mjs +1 -0
  191. package/dist/v1/basics/clock.cjs +43 -13
  192. package/dist/v1/basics/clock.mjs +31 -13
  193. package/dist/v1/basics/objFilter.cjs +4 -0
  194. package/dist/v1/basics/objFilter.mjs +3 -0
  195. package/dist/v1/basics/simpleMath.cjs +1 -1
  196. package/dist/v1/basics/simpleMath.mjs +1 -1
  197. package/dist/v1/index.cjs +0 -4
  198. package/dist/v1/index.d.mts +1 -3
  199. package/dist/v1/index.mjs +1 -3
  200. package/docs/README.md +1 -11
  201. package/package.json +2 -5
  202. package/dist/TinyCertCrypto.js +0 -76229
  203. package/dist/TinyCertCrypto.min.js +0 -2
  204. package/dist/TinyCertCrypto.min.js.LICENSE.txt +0 -10
  205. package/dist/TinyCrypto.js +0 -48115
  206. package/dist/TinyCrypto.min.js +0 -2
  207. package/dist/TinyCrypto.min.js.LICENSE.txt +0 -10
  208. package/dist/v1/build/TinyCertCrypto.cjs +0 -7
  209. package/dist/v1/build/TinyCertCrypto.d.mts +0 -2
  210. package/dist/v1/build/TinyCertCrypto.mjs +0 -2
  211. package/dist/v1/build/TinyCrypto.cjs +0 -7
  212. package/dist/v1/build/TinyCrypto.d.mts +0 -2
  213. package/dist/v1/build/TinyCrypto.mjs +0 -2
  214. package/dist/v1/libs/TinyCertCrypto.cjs +0 -514
  215. package/dist/v1/libs/TinyCertCrypto.d.mts +0 -191
  216. package/dist/v1/libs/TinyCertCrypto.mjs +0 -450
  217. package/dist/v1/libs/TinyCrypto.cjs +0 -603
  218. package/dist/v1/libs/TinyCrypto.d.mts +0 -268
  219. package/dist/v1/libs/TinyCrypto.mjs +0 -581
  220. package/docs/libs/TinyCertCrypto.md +0 -202
  221. package/docs/libs/TinyCrypto.md +0 -177
  222. package/webpack.config.mjs +0 -69
@@ -1,191 +0,0 @@
1
- export default TinyCertCrypto;
2
- /**
3
- * Class representing a certificate and key management utility.
4
- *
5
- * This class provides functionality to load, initialize, and manage X.509 certificates and RSA keys.
6
- * It supports encryption and decryption operations using RSA keys, and also includes utility methods
7
- * for certificate handling and metadata extraction.
8
- *
9
- * @class
10
- */
11
- declare class TinyCertCrypto {
12
- /**
13
- * Constructs a new instance of TinyCertCrypto.
14
- *
15
- * This class provides cross-platform (Node.js and browser) support
16
- * for handling X.509 certificates and performing RSA-based encryption and decryption.
17
- *
18
- * The constructor accepts optional paths or PEM buffers for the public certificate and private key.
19
- * If used in a browser environment, either `publicCertPath` or `publicCertBuffer` is required.
20
- *
21
- * @param {Object} [options={}] - Initialization options.
22
- * @param {string|null} [options.publicCertPath=null] - Path or URL to the public certificate in PEM format.
23
- * @param {string|null} [options.privateKeyPath=null] - Path or URL to the private key in PEM format.
24
- * @param {string|Buffer|null} [options.publicCertBuffer=null] - The public certificate as a PEM string or Buffer.
25
- * @param {string|Buffer|null} [options.privateKeyBuffer=null] - The private key as a PEM string or Buffer.
26
- * @param {string} [options.cryptoType='RSA-OAEP'] - The algorithm identifier used with Crypto API.
27
- *
28
- * @throws {Error} If in a browser and neither `publicCertPath` nor `publicCertBuffer` is provided.
29
- * @throws {TypeError} If provided buffers are not strings or Buffers.
30
- */
31
- constructor({ publicCertPath, privateKeyPath, publicCertBuffer, privateKeyBuffer, cryptoType, }?: {
32
- publicCertPath?: string | null | undefined;
33
- privateKeyPath?: string | null | undefined;
34
- publicCertBuffer?: string | Buffer<ArrayBufferLike> | null | undefined;
35
- privateKeyBuffer?: string | Buffer<ArrayBufferLike> | null | undefined;
36
- cryptoType?: string | undefined;
37
- });
38
- source: string | null;
39
- cryptoType: string;
40
- publicCertPath: string | null;
41
- privateKeyPath: string | null;
42
- publicCertBuffer: string | Buffer<ArrayBufferLike> | null;
43
- privateKeyBuffer: string | Buffer<ArrayBufferLike> | null;
44
- publicKey: any;
45
- privateKey: any;
46
- publicCert: any;
47
- metadata: {
48
- subject?: undefined;
49
- issuer?: undefined;
50
- serialNumber?: undefined;
51
- validFrom?: undefined;
52
- validTo?: undefined;
53
- } | {
54
- subject: {
55
- names: {};
56
- shortNames: {};
57
- raw: any;
58
- };
59
- issuer: {
60
- names: {};
61
- shortNames: {};
62
- raw: any;
63
- };
64
- serialNumber: any;
65
- validFrom: any;
66
- validTo: any;
67
- } | null;
68
- forge: any;
69
- /**
70
- * Public wrapper for fetching the `node-forge` module.
71
- * Useful for on-demand loading in environments like browsers.
72
- *
73
- * @returns {Promise<Object>} The loaded `node-forge` module.
74
- */
75
- fetchNodeForge(): Promise<Object>;
76
- /**
77
- * Public wrapper for accessing the `node-forge` instance.
78
- *
79
- * @returns {Object} The `node-forge` module.
80
- */
81
- getNodeForge(): Object;
82
- /**
83
- * Generates a new X.509 certificate along with a public/private RSA key pair.
84
- *
85
- * This method can only be used in Node.js environments. It throws an error if a certificate
86
- * or key is already loaded into the instance.
87
- *
88
- * @param {Object} subjectFields - An object representing the subject fields of the certificate (e.g., CN, O, C).
89
- * @param {Object} [options={}] - Optional configuration for key and certificate generation.
90
- * @param {number} [options.modulusLength=2048] - Length of the RSA key in bits.
91
- * @param {Object} [options.publicKeyEncoding={ type: 'spki', format: 'pem' }] - Options for public key encoding.
92
- * @param {Object} [options.privateKeyEncoding={ type: 'pkcs8', format: 'pem' }] - Options for private key encoding.
93
- * @param {string} [options.publicKeyType] - Overrides `publicKeyEncoding.type` if provided.
94
- * @param {string} [options.privateKeyType] - Overrides `privateKeyEncoding.type` if provided.
95
- * @param {number} [options.validityInYears=1] - Number of years the certificate will be valid.
96
- * @param {number} [options.randomBytesLength=16] - Number of random bytes to use for serial number generation.
97
- *
98
- * @returns {Promise<{publicKey: string, privateKey: string, cert: string}>} The generated keys and certificate in PEM format.
99
- * @throws {Error} If running in a browser or if a cert/key is already loaded.
100
- */
101
- generateX509Cert(subjectFields: Object, options?: {
102
- modulusLength?: number | undefined;
103
- publicKeyEncoding?: Object | undefined;
104
- privateKeyEncoding?: Object | undefined;
105
- publicKeyType?: string | undefined;
106
- privateKeyType?: string | undefined;
107
- validityInYears?: number | undefined;
108
- randomBytesLength?: number | undefined;
109
- }): Promise<{
110
- publicKey: string;
111
- privateKey: string;
112
- cert: string;
113
- }>;
114
- /**
115
- * Initializes the instance by loading the public certificate and, optionally, the private key.
116
- *
117
- * This method must be called before using cryptographic operations that depend on a loaded certificate.
118
- * It supports both Node.js and browser environments.
119
- *
120
- * In Node.js:
121
- * - It loads PEM data from provided file paths or buffers.
122
- *
123
- * In browsers:
124
- * - It loads PEM data from provided URLs or ArrayBuffers.
125
- *
126
- * @async
127
- * @throws {Error} If a certificate is already loaded.
128
- * @throws {Error} If no public certificate is provided.
129
- * @throws {Error} If the PEM type cannot be determined or is invalid.
130
- */
131
- init(): Promise<void>;
132
- /**
133
- * Extracts the metadata of the loaded X.509 certificate.
134
- *
135
- * Returns an object containing the certificate's metadata such as the subject, issuer,
136
- * serial number, and validity period. If no certificate is loaded, an empty object is returned.
137
- *
138
- * @returns {Object} The metadata of the certificate, or an empty object if no certificate is loaded.
139
- */
140
- extractCertMetadata(): Object;
141
- /**
142
- * Encrypts a JSON object using the initialized public key.
143
- *
144
- * This method serializes the provided JSON object to a string and encrypts it using the
145
- * public key in PEM format. The encryption is done using the algorithm defined in the
146
- * `cryptoType` property (e.g., 'RSA-OAEP').
147
- *
148
- * @param {Object} jsonObject - The JSON object to be encrypted.
149
- * @returns {string} The encrypted JSON object, encoded in Base64 format.
150
- * @throws {Error} If the public key is not initialized (i.e., if `init()` or `generateKeyPair()` has not been called).
151
- */
152
- encryptJson(jsonObject: Object): string;
153
- /**
154
- * Decrypts a Base64-encoded encrypted JSON string using the initialized private key.
155
- *
156
- * This method takes the encrypted Base64 string, decodes it, and decrypts it using the
157
- * private key in PEM format. It then parses the decrypted string back into a JSON object.
158
- *
159
- * @param {string} encryptedBase64 - The encrypted JSON string in Base64 format to be decrypted.
160
- * @returns {Object} The decrypted JSON object.
161
- * @throws {Error} If the private key is not initialized.
162
- */
163
- decryptToJson(encryptedBase64: string): Object;
164
- /**
165
- * Checks if both the public and private keys are initialized.
166
- *
167
- * This method verifies if both the public key and private key have been initialized
168
- * in the instance. It returns `true` if both keys are present, otherwise `false`.
169
- *
170
- * @returns {boolean} `true` if both public and private keys are initialized, `false` otherwise.
171
- */
172
- hasKeys(): boolean;
173
- /**
174
- * Checks if a public certificate is initialized.
175
- *
176
- * This method checks if the public certificate has been loaded or initialized in the instance.
177
- * It returns `true` if the public certificate is available, otherwise `false`.
178
- *
179
- * @returns {boolean} `true` if the public certificate is initialized, `false` otherwise.
180
- */
181
- hasCert(): boolean;
182
- /**
183
- * Resets the instance by clearing the keys and certificate data.
184
- *
185
- * This method sets the public and private keys, the public certificate, metadata, and
186
- * the source to `null`, effectively resetting the instance to its initial state.
187
- */
188
- reset(): void;
189
- #private;
190
- }
191
- import { Buffer } from 'buffer';
@@ -1,450 +0,0 @@
1
- import fs from 'fs';
2
- import crypto from 'crypto';
3
- import { Buffer } from 'buffer';
4
- /**
5
- * Determines if the environment is a browser.
6
- *
7
- * This constant checks if the code is running in a browser environment by verifying if
8
- * the `window` object and the `window.document` object are available. It will return `true`
9
- * if the environment is a browser, and `false` otherwise (e.g., in a Node.js environment).
10
- *
11
- * @constant {boolean}
12
- */
13
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
14
- /**
15
- * Class representing a certificate and key management utility.
16
- *
17
- * This class provides functionality to load, initialize, and manage X.509 certificates and RSA keys.
18
- * It supports encryption and decryption operations using RSA keys, and also includes utility methods
19
- * for certificate handling and metadata extraction.
20
- *
21
- * @class
22
- */
23
- class TinyCertCrypto {
24
- /**
25
- * Regular expression for matching X.509 PEM certificates.
26
- *
27
- * This pattern captures the base64-encoded body of a certificate
28
- * enclosed between `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----`.
29
- * It supports multi-line content.
30
- *
31
- * @type {RegExp}
32
- * @private
33
- */
34
- #certRegex = /-----BEGIN CERTIFICATE-----([\s\S]+?)-----END CERTIFICATE-----/;
35
- /**
36
- * Regular expression for matching RSA PEM keys.
37
- *
38
- * This pattern captures both RSA public and private keys, supporting
39
- * the standard PEM formatting:
40
- * `-----BEGIN [RSA] PUBLIC|PRIVATE KEY-----` to `-----END ... KEY-----`.
41
- * It captures the key type (PUBLIC|PRIVATE) and the base64 content.
42
- *
43
- * @type {RegExp}
44
- * @private
45
- */
46
- #keyRegex = /-----BEGIN\s+(?:RSA\s+)?(PUBLIC|PRIVATE)\s+KEY-----([\s\S]+?)-----END\s+(?:RSA\s+)?\1\s+KEY-----/;
47
- /**
48
- * Constructs a new instance of TinyCertCrypto.
49
- *
50
- * This class provides cross-platform (Node.js and browser) support
51
- * for handling X.509 certificates and performing RSA-based encryption and decryption.
52
- *
53
- * The constructor accepts optional paths or PEM buffers for the public certificate and private key.
54
- * If used in a browser environment, either `publicCertPath` or `publicCertBuffer` is required.
55
- *
56
- * @param {Object} [options={}] - Initialization options.
57
- * @param {string|null} [options.publicCertPath=null] - Path or URL to the public certificate in PEM format.
58
- * @param {string|null} [options.privateKeyPath=null] - Path or URL to the private key in PEM format.
59
- * @param {string|Buffer|null} [options.publicCertBuffer=null] - The public certificate as a PEM string or Buffer.
60
- * @param {string|Buffer|null} [options.privateKeyBuffer=null] - The private key as a PEM string or Buffer.
61
- * @param {string} [options.cryptoType='RSA-OAEP'] - The algorithm identifier used with Crypto API.
62
- *
63
- * @throws {Error} If in a browser and neither `publicCertPath` nor `publicCertBuffer` is provided.
64
- * @throws {TypeError} If provided buffers are not strings or Buffers.
65
- */
66
- constructor({ publicCertPath = null, privateKeyPath = null, publicCertBuffer = null, privateKeyBuffer = null, cryptoType = 'RSA-OAEP', } = {}) {
67
- if (!publicCertPath && !publicCertBuffer && isBrowser)
68
- throw new Error('In browser, publicCertPath or publicCertBuffer must be provided');
69
- if (publicCertBuffer &&
70
- typeof publicCertBuffer !== 'string' &&
71
- !Buffer.isBuffer(publicCertBuffer))
72
- throw new TypeError('publicCertBuffer must be a string or Buffer');
73
- if (privateKeyBuffer &&
74
- typeof privateKeyBuffer !== 'string' &&
75
- !Buffer.isBuffer(privateKeyBuffer))
76
- throw new TypeError('privateKeyBuffer must be a string or Buffer');
77
- this.source = null;
78
- this.cryptoType = cryptoType;
79
- this.publicCertPath = publicCertPath;
80
- this.privateKeyPath = privateKeyPath;
81
- this.publicCertBuffer = publicCertBuffer;
82
- this.privateKeyBuffer = privateKeyBuffer;
83
- this.publicKey = null;
84
- this.privateKey = null;
85
- this.publicCert = null;
86
- this.metadata = null;
87
- this.forge = null;
88
- }
89
- /**
90
- * Dynamically imports the `node-forge` module and stores it in the instance.
91
- * Ensures the module is loaded only once (lazy singleton).
92
- *
93
- * This method is private and should not be called directly from outside.
94
- *
95
- * @returns {Promise<Object>} The loaded `node-forge` module.
96
- * @private
97
- */
98
- async #fetchNodeForge() {
99
- if (!this.forge) {
100
- const forge = await import(/* webpackMode: "eager" */ 'node-forge');
101
- this.forge = forge.default;
102
- }
103
- return this.#getNodeForge();
104
- }
105
- /**
106
- * Public wrapper for fetching the `node-forge` module.
107
- * Useful for on-demand loading in environments like browsers.
108
- *
109
- * @returns {Promise<Object>} The loaded `node-forge` module.
110
- */
111
- async fetchNodeForge() {
112
- return this.#fetchNodeForge();
113
- }
114
- /**
115
- * Returns the previously loaded `node-forge` instance.
116
- * Assumes the module has already been loaded.
117
- *
118
- * @returns {Object} The `node-forge` module.
119
- * @private
120
- */
121
- #getNodeForge() {
122
- return this.forge;
123
- }
124
- /**
125
- * Public wrapper for accessing the `node-forge` instance.
126
- *
127
- * @returns {Object} The `node-forge` module.
128
- */
129
- getNodeForge() {
130
- return this.#getNodeForge();
131
- }
132
- /**
133
- * Detects the type of a PEM-formatted string.
134
- *
135
- * Recognizes X.509 certificates and RSA keys (public/private).
136
- * Returns a string describing the type, such as `'certificate'`, `'public_key'`, `'private_key'`,
137
- * or `'unknown'` if the format is not recognized.
138
- *
139
- * @param {string} pemString - The PEM string to inspect.
140
- * @returns {'certificate' | 'public_key' | 'private_key' | 'unknown'} The detected PEM type.
141
- * @private
142
- */
143
- #detectPemType(pemString) {
144
- if (this.#certRegex.test(pemString))
145
- return 'certificate';
146
- const keyMatch = this.#keyRegex.exec(pemString);
147
- if (keyMatch)
148
- return keyMatch[1].toLowerCase() + '_key'; // "public_key" or "private_key"
149
- return 'unknown';
150
- }
151
- /**
152
- * Generates a new X.509 certificate along with a public/private RSA key pair.
153
- *
154
- * This method can only be used in Node.js environments. It throws an error if a certificate
155
- * or key is already loaded into the instance.
156
- *
157
- * @param {Object} subjectFields - An object representing the subject fields of the certificate (e.g., CN, O, C).
158
- * @param {Object} [options={}] - Optional configuration for key and certificate generation.
159
- * @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
- * @param {number} [options.validityInYears=1] - Number of years the certificate will be valid.
165
- * @param {number} [options.randomBytesLength=16] - Number of random bytes to use for serial number generation.
166
- *
167
- * @returns {Promise<{publicKey: string, privateKey: string, cert: string}>} The generated keys and certificate in PEM format.
168
- * @throws {Error} If running in a browser or if a cert/key is already loaded.
169
- */
170
- async generateX509Cert(subjectFields, options = {}) {
171
- // Errors
172
- if (this.publicKey || this.privateKey || this.publicCert)
173
- throw new Error('A certificate is already loaded into the instance.');
174
- // Prepare cert
175
- 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');
183
- // Generate keys
184
- const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
185
- modulusLength,
186
- publicKeyEncoding: { ...publicKeyEncoding, type: publicKeyType },
187
- privateKeyEncoding: { ...privateKeyEncoding, type: privateKeyType },
188
- });
189
- // Get pem files
190
- const { cert, publicPem, privatePem } = this.#generateCertificate(subjectFields, publicKey, privateKey, validityInYears, randomBytesLength);
191
- // Insert data
192
- this.publicKey = publicPem;
193
- this.privateKey = privatePem;
194
- this.publicCertPath = 'MEMORY';
195
- this.privateKeyPath = 'MEMORY';
196
- this.source = 'memory';
197
- this.publicCertBuffer = publicKey;
198
- this.privateKeyBuffer = privateKey;
199
- this.#loadX509Certificate(cert);
200
- return { publicKey, privateKey, cert };
201
- }
202
- /**
203
- * Generates a self-signed X.509 certificate using the given public and private RSA keys.
204
- *
205
- * This method creates a certificate, assigns the subject and issuer fields,
206
- * sets the validity period, and signs it with the private key.
207
- *
208
- * @param {Object} subject - An object representing the subject/issuer fields (e.g., { CN: 'example.com' }).
209
- * @param {string} publicKey - The public key in PEM format.
210
- * @param {string} privateKey - The private key in PEM format.
211
- * @param {number} validityInYears - Number of years the certificate will remain valid.
212
- * @param {number} randomBytesLength - Number of random bytes used to generate the serial number.
213
- *
214
- * @returns {Object} An object containing:
215
- * - {string} cert: The generated certificate in PEM format.
216
- * - {Object} publicPem: The parsed public key object (from node-forge).
217
- * - {Object} privatePem: The parsed private key object (from node-forge).
218
- */
219
- #generateCertificate(subject, publicKey, privateKey, validityInYears, randomBytesLength) {
220
- const { pki } = this.forge;
221
- const cert = pki.createCertificate();
222
- const publicPem = pki.publicKeyFromPem(publicKey);
223
- const privatePem = pki.privateKeyFromPem(privateKey);
224
- cert.publicKey = publicPem;
225
- cert.serialNumber = Buffer.from(crypto.randomBytes(randomBytesLength)).toString('hex');
226
- cert.validity.notBefore = new Date();
227
- cert.validity.notAfter = new Date();
228
- cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + validityInYears);
229
- const attrs = [];
230
- for (const name in subject)
231
- attrs.push({ name, value: subject[name] });
232
- cert.setSubject(attrs);
233
- cert.setIssuer(attrs);
234
- cert.sign(privatePem);
235
- return { cert: pki.certificateToPem(cert), publicPem, privatePem };
236
- }
237
- /**
238
- * Initializes the instance by loading the public certificate and, optionally, the private key.
239
- *
240
- * This method must be called before using cryptographic operations that depend on a loaded certificate.
241
- * It supports both Node.js and browser environments.
242
- *
243
- * In Node.js:
244
- * - It loads PEM data from provided file paths or buffers.
245
- *
246
- * In browsers:
247
- * - It loads PEM data from provided URLs or ArrayBuffers.
248
- *
249
- * @async
250
- * @throws {Error} If a certificate is already loaded.
251
- * @throws {Error} If no public certificate is provided.
252
- * @throws {Error} If the PEM type cannot be determined or is invalid.
253
- */
254
- async init() {
255
- // Errors
256
- if (this.publicKey || this.privateKey || this.publicCert)
257
- throw new Error('A certificate is already loaded into the instance.');
258
- if (!this.publicCertPath && !this.publicCertBuffer)
259
- throw new Error('Public certificate is required to initialize');
260
- // Load public key
261
- this.metadata = {};
262
- const { pki } = await this.#fetchNodeForge();
263
- const loadPublicKey = (publicPem) => {
264
- // File type
265
- const fileType = this.#detectPemType(publicPem);
266
- // Cert
267
- if (fileType === 'certificate') {
268
- const cert = pki.certificateFromPem(publicPem);
269
- this.publicKey = cert.publicKey;
270
- this.#loadX509Certificate(cert);
271
- }
272
- // Public key
273
- else if (fileType === 'public_key')
274
- this.publicKey = pki.publicKeyFromPem(publicPem);
275
- else
276
- throw new Error('Public key is required to initialize');
277
- };
278
- const loadPrivateKey = (privatePem) => {
279
- const fileType = this.#detectPemType(privatePem);
280
- if (fileType === 'private_key')
281
- this.privateKey = pki.privateKeyFromPem(privatePem);
282
- else
283
- throw new Error('Private key is required to initialize');
284
- };
285
- // Nodejs
286
- if (!isBrowser) {
287
- const usedPublicBuffer = !!this.publicCertBuffer;
288
- const usedPrivateBuffer = !!this.privateKeyBuffer;
289
- // Public key
290
- const publicPem = usedPublicBuffer
291
- ? typeof this.publicCertBuffer === 'string'
292
- ? this.publicCertBuffer
293
- : this.publicCertBuffer.toString('utf-8')
294
- : fs.readFileSync(this.publicCertPath, 'utf-8');
295
- loadPublicKey(publicPem);
296
- // Private Key
297
- if (this.privateKeyPath || this.privateKeyBuffer) {
298
- const privatePem = usedPrivateBuffer
299
- ? typeof this.privateKeyBuffer === 'string'
300
- ? this.privateKeyBuffer
301
- : this.privateKeyBuffer.toString('utf-8')
302
- : fs.readFileSync(this.privateKeyPath, 'utf-8');
303
- loadPrivateKey(privatePem);
304
- }
305
- // Insert source
306
- this.source = this.publicCertBuffer || this.privateKeyBuffer ? 'memory' : 'file';
307
- }
308
- // Browser
309
- else {
310
- // Public key
311
- const publicPem = this.publicCertBuffer
312
- ? typeof this.publicCertBuffer === 'string'
313
- ? this.publicCertBuffer
314
- : new TextDecoder().decode(this.publicCertBuffer)
315
- : await fetch(this.publicCertPath).then((r) => r.text());
316
- loadPublicKey(publicPem);
317
- // Private key
318
- if (this.privateKeyPath || this.privateKeyBuffer) {
319
- const privatePem = this.privateKeyBuffer
320
- ? typeof this.privateKeyBuffer === 'string'
321
- ? this.privateKeyBuffer
322
- : new TextDecoder().decode(this.privateKeyBuffer)
323
- : await fetch(this.privateKeyPath).then((r) => r.text());
324
- loadPrivateKey(privatePem);
325
- }
326
- // Insert key
327
- this.source = 'url';
328
- }
329
- }
330
- /**
331
- * Parses and stores an X.509 certificate in the instance, extracting metadata such as
332
- * subject, issuer, serial number, and validity period.
333
- *
334
- * This method supports both PEM strings and already-parsed Forge certificate objects.
335
- * The parsed certificate is saved to `this.publicCert` and its metadata is extracted to `this.metadata`.
336
- *
337
- * @private
338
- * @param {string|object} certPem - A PEM-encoded certificate string or a `forge.pki.Certificate` object.
339
- * @throws {Error} If the certificate cannot be parsed or processed.
340
- */
341
- #loadX509Certificate(certPem) {
342
- try {
343
- const { pki } = this.forge;
344
- const cert = typeof certPem === 'string' ? pki.certificateFromPem(certPem) : certPem;
345
- this.publicCert = cert;
346
- const insertData = (attributes) => {
347
- const names = {};
348
- const shortNames = {};
349
- const raw = attributes.map((attr) => `${attr.shortName}=${attr.value}`).join(',');
350
- for (const item of attributes) {
351
- names[item.name] = item.value;
352
- shortNames[item.shortName] = item.value;
353
- }
354
- return { names, shortNames, raw };
355
- };
356
- this.metadata = {
357
- subject: insertData(cert.subject.attributes),
358
- issuer: insertData(cert.issuer.attributes),
359
- serialNumber: cert.serialNumber,
360
- validFrom: cert.validity.notBefore,
361
- validTo: cert.validity.notAfter,
362
- };
363
- }
364
- catch (err) {
365
- throw new Error('Failed to parse X.509 certificate in browser: ' + err.message);
366
- }
367
- }
368
- /**
369
- * Extracts the metadata of the loaded X.509 certificate.
370
- *
371
- * Returns an object containing the certificate's metadata such as the subject, issuer,
372
- * serial number, and validity period. If no certificate is loaded, an empty object is returned.
373
- *
374
- * @returns {Object} The metadata of the certificate, or an empty object if no certificate is loaded.
375
- */
376
- extractCertMetadata() {
377
- return this.metadata || {};
378
- }
379
- /**
380
- * Encrypts a JSON object using the initialized public key.
381
- *
382
- * This method serializes the provided JSON object to a string and encrypts it using the
383
- * public key in PEM format. The encryption is done using the algorithm defined in the
384
- * `cryptoType` property (e.g., 'RSA-OAEP').
385
- *
386
- * @param {Object} jsonObject - The JSON object to be encrypted.
387
- * @returns {string} The encrypted JSON object, encoded in Base64 format.
388
- * @throws {Error} If the public key is not initialized (i.e., if `init()` or `generateKeyPair()` has not been called).
389
- */
390
- encryptJson(jsonObject) {
391
- if (!this.publicKey)
392
- throw new Error('Public key is not initialized. Call init() or generateKeyPair() first.');
393
- const jsonString = JSON.stringify(jsonObject);
394
- const encrypted = this.publicKey.encrypt(jsonString, this.cryptoType);
395
- return this.forge.util.encode64(encrypted);
396
- }
397
- /**
398
- * Decrypts a Base64-encoded encrypted JSON string using the initialized private key.
399
- *
400
- * This method takes the encrypted Base64 string, decodes it, and decrypts it using the
401
- * private key in PEM format. It then parses the decrypted string back into a JSON object.
402
- *
403
- * @param {string} encryptedBase64 - The encrypted JSON string in Base64 format to be decrypted.
404
- * @returns {Object} The decrypted JSON object.
405
- * @throws {Error} If the private key is not initialized.
406
- */
407
- decryptToJson(encryptedBase64) {
408
- if (!this.privateKey)
409
- throw new Error('Private key is required for decryption');
410
- const data = this.forge.util.decode64(encryptedBase64);
411
- const decrypted = this.privateKey.decrypt(data, this.cryptoType);
412
- return JSON.parse(decrypted);
413
- }
414
- /**
415
- * Checks if both the public and private keys are initialized.
416
- *
417
- * This method verifies if both the public key and private key have been initialized
418
- * in the instance. It returns `true` if both keys are present, otherwise `false`.
419
- *
420
- * @returns {boolean} `true` if both public and private keys are initialized, `false` otherwise.
421
- */
422
- hasKeys() {
423
- return this.publicKey !== null && this.privateKey !== null;
424
- }
425
- /**
426
- * Checks if a public certificate is initialized.
427
- *
428
- * This method checks if the public certificate has been loaded or initialized in the instance.
429
- * It returns `true` if the public certificate is available, otherwise `false`.
430
- *
431
- * @returns {boolean} `true` if the public certificate is initialized, `false` otherwise.
432
- */
433
- hasCert() {
434
- return this.publicCert !== null;
435
- }
436
- /**
437
- * Resets the instance by clearing the keys and certificate data.
438
- *
439
- * This method sets the public and private keys, the public certificate, metadata, and
440
- * the source to `null`, effectively resetting the instance to its initial state.
441
- */
442
- reset() {
443
- this.publicKey = null;
444
- this.privateKey = null;
445
- this.publicCert = null;
446
- this.metadata = null;
447
- this.source = null;
448
- }
449
- }
450
- export default TinyCertCrypto;