@alwatr/crypto 4.0.0 → 4.2.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 +14 -0
- package/dist/main.cjs +2 -2
- package/dist/main.cjs.map +2 -2
- package/dist/main.d.ts.map +1 -1
- package/dist/main.mjs +2 -2
- package/dist/main.mjs.map +2 -2
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,20 @@
|
|
|
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.2.0](https://github.com/Alwatr/nanotron/compare/v4.1.0...v4.2.0) (2024-09-23)
|
|
7
|
+
|
|
8
|
+
### Dependencies update
|
|
9
|
+
|
|
10
|
+
* bump the alwatr-dependencies group with 6 updates ([1c8a8ec](https://github.com/Alwatr/nanotron/commit/1c8a8ec468aa31c79de45f0e897cc45578242981)) by @dependabot[bot]
|
|
11
|
+
* bump the development-dependencies group with 2 updates ([e3bc7f7](https://github.com/Alwatr/nanotron/commit/e3bc7f7dcbf1779a3fdf8fbe18c4f8b4095cc222)) by @dependabot[bot]
|
|
12
|
+
* update ([d9f8d57](https://github.com/Alwatr/nanotron/commit/d9f8d577b058b4e945db7dfc1c5c68da78c4112f)) by @AliMD
|
|
13
|
+
|
|
14
|
+
## [4.0.2](https://github.com/Alwatr/nanotron/compare/v4.0.1...v4.0.2) (2024-09-14)
|
|
15
|
+
|
|
16
|
+
### Bug Fixes
|
|
17
|
+
|
|
18
|
+
* definePackage ([a2edcc1](https://github.com/Alwatr/nanotron/commit/a2edcc1b3a4822371cefa4a28ff62a7c6754287e)) by @AliMD
|
|
19
|
+
|
|
6
20
|
## [4.0.0](https://github.com/Alwatr/nanotron/compare/v4.0.0-alpha.3...v4.0.0) (2024-09-14)
|
|
7
21
|
|
|
8
22
|
**Note:** Version bump only for package @alwatr/crypto
|
package/dist/main.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/* @alwatr/crypto v4.
|
|
2
|
-
"use strict";var c=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var
|
|
1
|
+
/* @alwatr/crypto v4.2.0 */
|
|
2
|
+
"use strict";var c=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var x=(t,e)=>{for(var r in e)c(t,r,{get:e[r],enumerable:!0})},v=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of C(e))!_.call(t,o)&&o!==r&&c(t,o,{get:()=>e[o],enumerable:!(n=y(e,o))||n.enumerable});return t};var k=t=>v(c({},"__esModule",{value:!0}),t);var G={};x(G,{AlwatrCryptoFactory:()=>m,AlwatrHashGenerator:()=>i,AlwatrTokenGenerator:()=>s,deviceIdGeneratorRecommendedConfig:()=>d,secretGeneratorRecommendedConfig:()=>f,userIdGeneratorRecommendedConfig:()=>g,userTokenGeneratorRecommendedConfig:()=>p});module.exports=k(G);var a=require("node:crypto"),i=class{constructor(e){this.config=e}generateRandom(){return this.generate((0,a.randomBytes)(16))}generateRandomSelfValidate(){return this.generateSelfValidate((0,a.randomBytes)(16))}generate(e){return this.config.prefix+(0,a.createHash)(this.config.algorithm).update(e).digest(this.config.encoding)}generateCrc(e){let r=(0,a.createHash)("sha1").update(e).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?r:r.slice(0,this.config.crcLength)}generateSelfValidate(e){let r=this.generate(e),n=this.generateCrc(r);return r+n}verify(e,r){return r===this.generate(e)}verifySelfValidate(e){let r=e.length-this.config.crcLength,n=e.slice(0,r);return e.slice(r)===this.generateCrc(n)}};var h=require("node:crypto"),u=require("@alwatr/parse-duration"),s=class{constructor(e){this.config=e;this._duration=e.duration=="infinite"?0:(0,u.parseDuration)(e.duration)}get _epoch(){return this._duration==0?0:Math.floor(Date.now()/this._duration)}generate(e){return this._generate(e,this._epoch)}verify(e,r){let n=this._epoch;return r===this._generate(e,n)?"valid":this._duration==0?"invalid":r===this._generate(e,n-1)?"expired":"invalid"}_generate(e,r){return this.config.prefix+(0,h.createHmac)(this.config.algorithm,e).update(e+r).digest(this.config.encoding)}};var g={prefix:"u",algorithm:"sha1",encoding:"base64url",crcLength:4},d={...g,prefix:"d"},f={prefix:"s",algorithm:"sha384",encoding:"base64url",crcLength:4},p={prefix:"t",algorithm:"sha224",encoding:"base64url"};var m=class{constructor(e){this._generators={secret:new i(f),deviceId:new i(d),userId:new i(g),token:new s({...p,...e})}}generateUserId(){return this._generators.userId.generateRandomSelfValidate()}verifyUserId(e){return this._generators.userId.verifySelfValidate(e)}generateToken(e){return this._generators.token.generate(e.join())}verifyToken(e,r){return this._generators.token.verify(e.join(),r)}generateSecret(){return this._generators.secret.generateRandomSelfValidate()}verifySecret(e){return this._generators.secret.verifySelfValidate(e)}generateDeviceId(){return this._generators.deviceId.generateRandomSelfValidate()}verifyDeviceId(e){return this._generators.deviceId.verifySelfValidate(e)}};var l=require("@alwatr/logger");(0,l.definePackage)("@alwatr/crypto","4.2.0");0&&(module.exports={AlwatrCryptoFactory,AlwatrHashGenerator,AlwatrTokenGenerator,deviceIdGeneratorRecommendedConfig,secretGeneratorRecommendedConfig,userIdGeneratorRecommendedConfig,userTokenGeneratorRecommendedConfig});
|
|
3
3
|
//# sourceMappingURL=main.cjs.map
|
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/pre-config.ts", "../src/api.ts"],
|
|
4
|
-
"sourcesContent": ["import {definePackage} from '@alwatr/logger';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('crypto', '3.x');\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 DurationString} from '@alwatr/parse-duration';\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: DurationString | '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 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", "import {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\nimport type {DurationString} from '@alwatr/parse-duration';\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: DurationString | '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"],
|
|
5
|
-
"mappings": ";yaAAA,IAAAA,EAAA,GAAAC,EAAAD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AAmCC,EAA8B,CAC3E,OAAO,KAAK,YAAY,MAAM,OAAOD,EAAa,KAAK,EAAGC,CAAK,CACjE,CAaA,gBAAyB,CACvB,OAAO,KAAK,YAAY,OAAO,2BAA2B,CAC5D,CAaA,aAAaC,EAAyB,CACpC,OAAO,KAAK,YAAY,OAAO,mBAAmBA,CAAM,CAC1D,CAUA,kBAA2B,CACzB,OAAO,KAAK,YAAY,SAAS,2BAA2B,CAC9D,CAiBA,eAAeC,EAA2B,CACxC,OAAO,KAAK,YAAY,SAAS,mBAAmBA,CAAQ,CAC9D,CACF,EJvKA,IAAAC,EAA4B,
|
|
4
|
+
"sourcesContent": ["import {definePackage} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('@alwatr/crypto', __package_version__);\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 DurationString} from '@alwatr/parse-duration';\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: DurationString | '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 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", "import {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\nimport type {DurationString} from '@alwatr/parse-duration';\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: DurationString | '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"],
|
|
5
|
+
"mappings": ";yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,yBAAAE,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,uCAAAC,EAAA,qCAAAC,EAAA,qCAAAC,EAAA,wCAAAC,IAAA,eAAAC,EAAAT,GCAA,IAAAU,EAAuD,uBAgC1CC,EAAN,KAA0B,CAK/B,YAAmBC,EAA6B,CAA7B,YAAAA,CAA8B,CAUjD,gBAAyB,CACvB,OAAO,KAAK,YAAS,eAAY,EAAE,CAAC,CACtC,CAUA,4BAAqC,CACnC,OAAO,KAAK,wBAAqB,eAAY,EAAE,CAAC,CAClD,CAWA,SAASC,EAA0B,CACjC,OAAO,KAAK,OAAO,UAAS,cAAW,KAAK,OAAO,SAAS,EAAE,OAAOA,CAAI,EAAE,OAAO,KAAK,OAAO,QAAQ,CACxG,CAOA,YAAYA,EAA0B,CACpC,IAAMC,KAAM,cAAW,MAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,KAAK,OAAO,QAAQ,EACvE,OAAO,KAAK,OAAO,WAAa,MAAQ,KAAK,OAAO,UAAY,EAAIC,EAA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KaE,EAAwD,CACnE,OAAQ,IACR,UAAW,SACX,SAAU,YACV,UAAW,CACb,EAKaC,EAAyF,CACpG,OAAQ,IACR,UAAW,SACX,SAAU,WACZ,ECTO,IAAMC,EAAN,KAA0B,CAO/B,YAAYC,EAA6B,CACvC,KAAK,YAAc,CACjB,OAAQ,IAAIC,EAAoBC,CAAgC,EAChE,SAAU,IAAID,EAAoBE,CAAkC,EACpE,OAAQ,IAAIF,EAAoBG,CAAgC,EAChE,MAAO,IAAIC,EAAqB,CAC9B,GAAGC,EACH,GAAGN,CACL,CAAC,CACH,CACF,CAaA,gBAAyB,CACvB,OAAO,KAAK,YAAY,OAAO,2BAA2B,CAC5D,CAaA,aAAaO,EAAyB,CACpC,OAAO,KAAK,YAAY,OAAO,mBAAmBA,CAAM,CAC1D,CAWA,cAAcC,EAA2C,CACvD,OAAO,KAAK,YAAY,MAAM,SAASA,EAAa,KAAK,CAAC,CAC5D,CAcA,YAAYA,EAAmCC,EAA8B,CAC3E,OAAO,KAAK,YAAY,MAAM,OAAOD,EAAa,KAAK,EAAGC,CAAK,CACjE,CAaA,gBAAyB,CACvB,OAAO,KAAK,YAAY,OAAO,2BAA2B,CAC5D,CAaA,aAAaC,EAAyB,CACpC,OAAO,KAAK,YAAY,OAAO,mBAAmBA,CAAM,CAC1D,CAUA,kBAA2B,CACzB,OAAO,KAAK,YAAY,SAAS,2BAA2B,CAC9D,CAiBA,eAAeC,EAA2B,CACxC,OAAO,KAAK,YAAY,SAAS,mBAAmBA,CAAQ,CAC9D,CACF,EJvKA,IAAAC,EAA4B,6BAU5B,iBAAc,iBAAkB,OAAmB",
|
|
6
6
|
"names": ["main_exports", "__export", "AlwatrCryptoFactory", "AlwatrHashGenerator", "AlwatrTokenGenerator", "deviceIdGeneratorRecommendedConfig", "secretGeneratorRecommendedConfig", "userIdGeneratorRecommendedConfig", "userTokenGeneratorRecommendedConfig", "__toCommonJS", "import_node_crypto", "AlwatrHashGenerator", "config", "data", "crc", "mainHash", "crcHash", "hash", "gapPos", "import_node_crypto", "import_parse_duration", "AlwatrTokenGenerator", "config", "data", "token", "epoch", "userIdGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "secretGeneratorRecommendedConfig", "userTokenGeneratorRecommendedConfig", "AlwatrCryptoFactory", "config", "AlwatrHashGenerator", "secretGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "userIdGeneratorRecommendedConfig", "AlwatrTokenGenerator", "userTokenGeneratorRecommendedConfig", "userId", "uniquelyList", "token", "secret", "deviceId", "import_logger"]
|
|
7
7
|
}
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAIA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC"}
|
package/dist/main.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/* @alwatr/crypto v4.
|
|
2
|
-
import{createHash as s,randomBytes as g}from"node:crypto";var n=class{constructor(e){this.config=e}generateRandom(){return this.generate(g(16))}generateRandomSelfValidate(){return this.generateSelfValidate(g(16))}generate(e){return this.config.prefix+s(this.config.algorithm).update(e).digest(this.config.encoding)}generateCrc(e){let r=s("sha1").update(e).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?r:r.slice(0,this.config.crcLength)}generateSelfValidate(e){let r=this.generate(e),t=this.generateCrc(r);return r+t}verify(e,r){return r===this.generate(e)}verifySelfValidate(e){let r=e.length-this.config.crcLength,t=e.slice(0,r);return e.slice(r)===this.generateCrc(t)}};import{createHmac as
|
|
1
|
+
/* @alwatr/crypto v4.2.0 */
|
|
2
|
+
import{createHash as s,randomBytes as g}from"node:crypto";var n=class{constructor(e){this.config=e}generateRandom(){return this.generate(g(16))}generateRandomSelfValidate(){return this.generateSelfValidate(g(16))}generate(e){return this.config.prefix+s(this.config.algorithm).update(e).digest(this.config.encoding)}generateCrc(e){let r=s("sha1").update(e).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?r:r.slice(0,this.config.crcLength)}generateSelfValidate(e){let r=this.generate(e),t=this.generateCrc(r);return r+t}verify(e,r){return r===this.generate(e)}verifySelfValidate(e){let r=e.length-this.config.crcLength,t=e.slice(0,r);return e.slice(r)===this.generateCrc(t)}};import{createHmac as m}from"node:crypto";import{parseDuration as h}from"@alwatr/parse-duration";var i=class{constructor(e){this.config=e;this._duration=e.duration=="infinite"?0:h(e.duration)}get _epoch(){return this._duration==0?0:Math.floor(Date.now()/this._duration)}generate(e){return this._generate(e,this._epoch)}verify(e,r){let t=this._epoch;return r===this._generate(e,t)?"valid":this._duration==0?"invalid":r===this._generate(e,t-1)?"expired":"invalid"}_generate(e,r){return this.config.prefix+m(this.config.algorithm,e).update(e+r).digest(this.config.encoding)}};var o={prefix:"u",algorithm:"sha1",encoding:"base64url",crcLength:4},c={...o,prefix:"d"},d={prefix:"s",algorithm:"sha384",encoding:"base64url",crcLength:4},f={prefix:"t",algorithm:"sha224",encoding:"base64url"};var p=class{constructor(e){this._generators={secret:new n(d),deviceId:new n(c),userId:new n(o),token:new i({...f,...e})}}generateUserId(){return this._generators.userId.generateRandomSelfValidate()}verifyUserId(e){return this._generators.userId.verifySelfValidate(e)}generateToken(e){return this._generators.token.generate(e.join())}verifyToken(e,r){return this._generators.token.verify(e.join(),r)}generateSecret(){return this._generators.secret.generateRandomSelfValidate()}verifySecret(e){return this._generators.secret.verifySelfValidate(e)}generateDeviceId(){return this._generators.deviceId.generateRandomSelfValidate()}verifyDeviceId(e){return this._generators.deviceId.verifySelfValidate(e)}};import{definePackage as u}from"@alwatr/logger";u("@alwatr/crypto","4.2.0");export{p as AlwatrCryptoFactory,n as AlwatrHashGenerator,i as AlwatrTokenGenerator,c as deviceIdGeneratorRecommendedConfig,d as secretGeneratorRecommendedConfig,o as userIdGeneratorRecommendedConfig,f as userTokenGeneratorRecommendedConfig};
|
|
3
3
|
//# sourceMappingURL=main.mjs.map
|
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/pre-config.ts", "../src/api.ts", "../src/main.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 DurationString} from '@alwatr/parse-duration';\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: DurationString | '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 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", "import {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\nimport type {DurationString} from '@alwatr/parse-duration';\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: DurationString | '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 {definePackage} from '@alwatr/logger';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('crypto', '3.x');\n"],
|
|
5
|
-
"mappings": ";AAAA,OAAQ,cAAAA,EAAY,eAAAC,MAAmC,cAgChD,IAAMC,EAAN,KAA0B,CAK/B,YAAmBC,EAA6B,CAA7B,YAAAA,CAA8B,CAUjD,gBAAyB,CACvB,OAAO,KAAK,SAASF,EAAY,EAAE,CAAC,CACtC,CAUA,4BAAqC,CACnC,OAAO,KAAK,qBAAqBA,EAAY,EAAE,CAAC,CAClD,CAWA,SAASG,EAA0B,CACjC,OAAO,KAAK,OAAO,OAASJ,EAAW,KAAK,OAAO,SAAS,EAAE,OAAOI,CAAI,EAAE,OAAO,KAAK,OAAO,QAAQ,CACxG,CAOA,YAAYA,EAA0B,CACpC,IAAMC,EAAML,EAAW,MAAM,EAAE,OAAOI,CAAI,EAAE,OAAO,KAAK,OAAO,QAAQ,EACvE,OAAO,KAAK,OAAO,WAAa,MAAQ,KAAK,OAAO,UAAY,EAAIC,EAAMA,EAAI,MAAM,EAAG,KAAK,OAAO,SAAS,CAC9G,CAWA,qBAAqBD,EAA0B,CAC7C,IAAME,EAAW,KAAK,SAASF,CAAI,EAC7BG,EAAU,KAAK,YAAYD,CAAQ,EACzC,OAAOA,EAAWC,CACpB,CAcA,OAAOH,EAAkBI,EAAuB,CAC9C,OAAOA,IAAS,KAAK,SAAS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IC,EAAoBC,CAAgC,EAChE,SAAU,IAAID,EAAoBE,CAAkC,EACpE,OAAQ,IAAIF,EAAoBG,CAAgC,EAChE,MAAO,IAAIC,EAAqB,CAC9B,GAAGC,EACH,GAAGN,CACL,CAAC,CACH,CACF,CAaA,gBAAyB,CACvB,OAAO,KAAK,YAAY,OAAO,2BAA2B,CAC5D,CAaA,aAAaO,EAAyB,CACpC,OAAO,KAAK,YAAY,OAAO,mBAAmBA,CAAM,CAC1D,CAWA,cAAcC,EAA2C,CACvD,OAAO,KAAK,YAAY,MAAM,SAASA,EAAa,KAAK,CAAC,CAC5D,CAcA,YAAYA,EAAmCC,EAA8B,CAC3E,OAAO,KAAK,YAAY,MAAM,OAAOD,EAAa,KAAK,EAAGC,CAAK,CACjE,CAaA,gBAAyB,CACvB,OAAO,KAAK,YAAY,OAAO,2BAA2B,CAC5D,CAaA,aAAaC,EAAyB,CACpC,OAAO,KAAK,YAAY,OAAO,mBAAmBA,CAAM,CAC1D,CAUA,kBAA2B,CACzB,OAAO,KAAK,YAAY,SAAS,2BAA2B,CAC9D,CAiBA,eAAeC,EAA2B,CACxC,OAAO,KAAK,YAAY,SAAS,mBAAmBA,CAAQ,CAC9D,CACF,ECvKA,OAAQ,iBAAAC,MAAoB,
|
|
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 DurationString} from '@alwatr/parse-duration';\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: DurationString | '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 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", "import {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\nimport type {DurationString} from '@alwatr/parse-duration';\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: DurationString | '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 {definePackage} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('@alwatr/crypto', __package_version__);\n"],
|
|
5
|
+
"mappings": ";AAAA,OAAQ,cAAAA,EAAY,eAAAC,MAAmC,cAgChD,IAAMC,EAAN,KAA0B,CAK/B,YAAmBC,EAA6B,CAA7B,YAAAA,CAA8B,CAUjD,gBAAyB,CACvB,OAAO,KAAK,SAASF,EAAY,EAAE,CAAC,CACtC,CAUA,4BAAqC,CACnC,OAAO,KAAK,qBAAqBA,EAAY,EAAE,CAAC,CAClD,CAWA,SAASG,EAA0B,CACjC,OAA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AQ,CAC9D,CACF,ECvKA,OAAQ,iBAAAC,MAAoB,iBAU5BA,EAAc,iBAAkB,OAAmB",
|
|
6
6
|
"names": ["createHash", "randomBytes", "AlwatrHashGenerator", "config", "data", "crc", "mainHash", "crcHash", "hash", "gapPos", "createHmac", "parseDuration", "AlwatrTokenGenerator", "config", "data", "token", "epoch", "userIdGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "secretGeneratorRecommendedConfig", "userTokenGeneratorRecommendedConfig", "AlwatrCryptoFactory", "config", "AlwatrHashGenerator", "secretGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "userIdGeneratorRecommendedConfig", "AlwatrTokenGenerator", "userTokenGeneratorRecommendedConfig", "userId", "uniquelyList", "token", "secret", "deviceId", "definePackage"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/crypto",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.2.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,17 +66,17 @@
|
|
|
66
66
|
"clean": "rm -rfv dist *.tsbuildinfo"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@alwatr/logger": "^3.2.
|
|
70
|
-
"@alwatr/parse-duration": "^1.0.
|
|
69
|
+
"@alwatr/logger": "^3.2.14",
|
|
70
|
+
"@alwatr/parse-duration": "^1.0.11"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
|
-
"@alwatr/nano-build": "^1.3.
|
|
73
|
+
"@alwatr/nano-build": "^1.3.10",
|
|
74
74
|
"@alwatr/prettier-config": "^1.0.4",
|
|
75
75
|
"@alwatr/tsconfig-base": "^1.2.0",
|
|
76
|
-
"@alwatr/type-helper": "^1.2.
|
|
77
|
-
"@types/node": "^22.5.
|
|
76
|
+
"@alwatr/type-helper": "^1.2.6",
|
|
77
|
+
"@types/node": "^22.5.5",
|
|
78
78
|
"jest": "^29.7.0",
|
|
79
79
|
"typescript": "^5.6.2"
|
|
80
80
|
},
|
|
81
|
-
"gitHead": "
|
|
81
|
+
"gitHead": "34e75bad9206fc2b5c6b787cd030707003bd3c2a"
|
|
82
82
|
}
|