@alwatr/crypto 4.3.0 → 4.5.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,23 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [4.5.0](https://github.com/Alwatr/nanotron/compare/v4.4.1...v4.5.0) (2024-10-28)
7
+
8
+ ### Bug Fixes
9
+
10
+ * **crypto:** remove side effects ([852e035](https://github.com/Alwatr/nanotron/commit/852e035d6ffceec32f7b4d2197140a27b4afb330)) by @AliMD
11
+
12
+ ### Dependencies update
13
+
14
+ * bump the development-dependencies group across 1 directory with 2 updates ([8b3e101](https://github.com/Alwatr/nanotron/commit/8b3e10128af769ef95a2e7b2ed788e843eb47414)) by @dependabot[bot]
15
+ * update nanolib v1.4.0 and other deps ([b8e7be7](https://github.com/Alwatr/nanotron/commit/b8e7be7b6c58d4f1cbc12593b2d6124f3d19b377)) by @
16
+
17
+ ## [4.4.1](https://github.com/Alwatr/nanotron/compare/v4.4.0...v4.4.1) (2024-10-16)
18
+
19
+ ### Dependencies update
20
+
21
+ * update ([8917c2e](https://github.com/Alwatr/nanotron/commit/8917c2e637781fe219c5031f414de3dea82cf371)) by @
22
+
6
23
  ## [4.3.0](https://github.com/Alwatr/nanotron/compare/v4.2.2...v4.3.0) (2024-10-11)
7
24
 
8
25
  ### Features
package/dist/main.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /* @alwatr/crypto v4.3.0 */
1
+ /* @alwatr/crypto v4.5.0 */
2
2
  "use strict";
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -217,7 +217,7 @@ var userTokenGeneratorRecommendedConfig = {
217
217
  };
218
218
 
219
219
  // src/api.ts
220
- __dev_mode__: import_nanolib2.packageTracer.add("@alwatr/crypto", "4.3.0");
220
+ __dev_mode__: import_nanolib2.packageTracer.add("@alwatr/crypto", "4.5.0");
221
221
  var AlwatrCryptoFactory = class {
222
222
  /**
223
223
  * Creates a new instance of crypto factory.
package/dist/main.cjs.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/main.ts", "../src/hash.ts", "../src/token.ts", "../src/api.ts", "../src/pre-config.ts"],
4
- "sourcesContent": ["export * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n", "import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type Duration} from '@alwatr/nanolib';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import {packageTracer, type Duration} from '@alwatr/nanolib';\n\nimport {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAuD;AAgChD,IAAM,sBAAN,MAA0B;AAAA;AAAA;AAAA;AAAA;AAAA,EAK/B,YAAmB,QAA6B;AAA7B;AAAA,EAA8B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUjD,iBAAyB;AACvB,WAAO,KAAK,aAAS,gCAAY,EAAE,CAAC;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,6BAAqC;AACnC,WAAO,KAAK,yBAAqB,gCAAY,EAAE,CAAC;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,SAAS,MAA0B;AACjC,WAAO,KAAK,OAAO,aAAS,+BAAW,KAAK,OAAO,SAAS,EAAE,OAAO,IAAI,EAAE,OAAO,KAAK,OAAO,QAAQ;AAAA,EACxG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAY,MAA0B;AACpC,UAAM,UAAM,+BAAW,MAAM,EAAE,OAAO,IAAI,EAAE,OAAO,KAAK,OAAO,QAAQ;AACvE,WAAO,KAAK,OAAO,aAAa,QAAQ,KAAK,OAAO,YAAY,IAAI,MAAM,IAAI,MAAM,GA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2B;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,aAAa,QAAyB;AACpC,WAAO,KAAK,YAAY,OAAO,mBAAmB,MAAM;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,cAAc,cAA2C;AACvD,WAAO,KAAK,YAAY,MAAM,SAAS,aAAa,KAAK,CAAC;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,YAAY,cAAmC,OAA8B;AAC3E,WAAO,KAAK,YAAY,MAAM,OAAO,aAAa,KAAK,GAAG,KAAK;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,iBAAyB;AACvB,WAAO,KAAK,YAAY,OAAO,2BAA2B;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,aAAa,QAAyB;AACpC,WAAO,KAAK,YAAY,OAAO,mBAAmB,MAAM;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,mBAA2B;AACzB,WAAO,KAAK,YAAY,SAAS,2BAA2B;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,eAAe,UAA2B;AACxC,WAAO,KAAK,YAAY,SAAS,mBAAmB,QAAQ;AAAA,EAC9D;AACF;",
4
+ "sourcesContent": ["export * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n", "import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type Duration} from '@alwatr/nanolib';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import {packageTracer, type Duration} from '@alwatr/nanolib';\n\nimport {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = /* #__PURE__ */ {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,YAAY,cAAmC,OAA8B;AAC3E,WAAO,KAAK,YAAY,MAAM,OAAO,aAAa,KAAK,GAAG,KAAK;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,iBAAyB;AACvB,WAAO,KAAK,YAAY,OAAO,2BAA2B;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,aAAa,QAAyB;AACpC,WAAO,KAAK,YAAY,OAAO,mBAAmB,MAAM;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,mBAA2B;AACzB,WAAO,KAAK,YAAY,SAAS,2BAA2B;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,eAAe,UAA2B;AACxC,WAAO,KAAK,YAAY,SAAS,mBAAmB,QAAQ;AAAA,EAC9D;AACF;",
6
6
  "names": ["import_node_crypto", "import_nanolib"]
7
7
  }
package/dist/main.mjs CHANGED
@@ -1,4 +1,4 @@
1
- /* @alwatr/crypto v4.3.0 */
1
+ /* @alwatr/crypto v4.5.0 */
2
2
 
3
3
  // src/hash.ts
4
4
  import { createHash, randomBytes } from "node:crypto";
@@ -186,7 +186,7 @@ var userTokenGeneratorRecommendedConfig = {
186
186
  };
187
187
 
188
188
  // src/api.ts
189
- __dev_mode__: packageTracer.add("@alwatr/crypto", "4.3.0");
189
+ __dev_mode__: packageTracer.add("@alwatr/crypto", "4.5.0");
190
190
  var AlwatrCryptoFactory = class {
191
191
  /**
192
192
  * Creates a new instance of crypto factory.
package/dist/main.mjs.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/hash.ts", "../src/token.ts", "../src/api.ts", "../src/pre-config.ts"],
4
- "sourcesContent": ["import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type Duration} from '@alwatr/nanolib';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import {packageTracer, type Duration} from '@alwatr/nanolib';\n\nimport {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,YAAY,cAAmC,OAA8B;AAC3E,WAAO,KAAK,YAAY,MAAM,OAAO,aAAa,KAAK,GAAG,KAAK;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,iBAAyB;AACvB,WAAO,KAAK,YAAY,OAAO,2BAA2B;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,aAAa,QAAyB;AACpC,WAAO,KAAK,YAAY,OAAO,mBAAmB,MAAM;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,mBAA2B;AACzB,WAAO,KAAK,YAAY,SAAS,2BAA2B;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,eAAe,UAA2B;AACxC,WAAO,KAAK,YAAY,SAAS,mBAAmB,QAAQ;AAAA,EAC9D;AACF;",
4
+ "sourcesContent": ["import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type Duration} from '@alwatr/nanolib';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import {packageTracer, type Duration} from '@alwatr/nanolib';\n\nimport {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = /* #__PURE__ */ {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n"],
5
+ "mappings": ";;;AAAA,SAAQ,YAAY,mBAAmC;AAgChD,IAAM,sBAAN,MAA0B;AAAA;AAAA;AAAA;AAAA;AAAA,EAK/B,YAAmB,QAA6B;AAA7B;AAAA,EAA8B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUjD,iBAAyB;AACvB,WAAO,KAAK,SAAS,YAAY,EAAE,CAAC;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,6BAAqC;AACnC,WAAO,KAAK,qBAAqB,YAAY,EAAE,CAAC;AAAA,EAClD;AAAA;AAAA;AAAA;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UA,mBAA2B;AACzB,WAAO,KAAK,YAAY,SAAS,2BAA2B;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,eAAe,UAA2B;AACxC,WAAO,KAAK,YAAY,SAAS,mBAAmB,QAAQ;AAAA,EAC9D;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alwatr/crypto",
3
- "version": "4.3.0",
3
+ "version": "4.5.0",
4
4
  "description": "A robust generator of secure authentication HOTP tokens, employing the HMAC-based One-Time Password algorithm, accompanied by a suite of cryptographic utilities, all encapsulated within a compact TypeScript module.",
5
5
  "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
6
  "keywords": [
@@ -66,16 +66,16 @@
66
66
  "clean": "rm -rfv dist *.tsbuildinfo"
67
67
  },
68
68
  "dependencies": {
69
- "@alwatr/nanolib": "^1.2.0"
69
+ "@alwatr/nanolib": "^1.4.0"
70
70
  },
71
71
  "devDependencies": {
72
- "@alwatr/nano-build": "^2.0.1",
72
+ "@alwatr/nano-build": "^2.0.3",
73
73
  "@alwatr/prettier-config": "^1.0.6",
74
- "@alwatr/tsconfig-base": "^1.3.2",
75
- "@alwatr/type-helper": "^2.0.2",
76
- "@types/node": "^22.7.5",
74
+ "@alwatr/tsconfig-base": "^1.3.3",
75
+ "@alwatr/type-helper": "^2.0.3",
76
+ "@types/node": "^22.8.1",
77
77
  "jest": "^29.7.0",
78
78
  "typescript": "^5.6.3"
79
79
  },
80
- "gitHead": "5dd04b482d18bc8160ead9003f1d518512a62a8e"
80
+ "gitHead": "935f351bb504b7e09661a30d365363369e4609d8"
81
81
  }