@alwatr/crypto 4.10.0 → 9.1.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/dist/main.js ADDED
@@ -0,0 +1,5 @@
1
+ /* 📦 @alwatr/crypto v9.1.0 */
2
+ import{createHash as K,randomBytes as M}from"node:crypto";class A{config;constructor(x){this.config=x}generateRandom(){return this.generate(M(16))}generateRandomSelfValidate(){return this.generateSelfValidate(M(16))}generate(x){return this.config.prefix+K(this.config.algorithm).update(x).digest(this.config.encoding)}generateCrc(x){let j=K("sha1").update(x).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?j:j.slice(0,this.config.crcLength)}generateSelfValidate(x){let j=this.generate(x),z=this.generateCrc(j);return j+z}verify(x,j){return j===this.generate(x)}verifySelfValidate(x){let j=x.length-this.config.crcLength,z=x.slice(0,j);return x.slice(j)===this.generateCrc(z)}}import{createHmac as U}from"node:crypto";import{parseDuration as W}from"@alwatr/parse-duration";class F{config;_duration;get _epoch(){return this._duration==0?0:Math.floor(Date.now()/this._duration)}constructor(x){this.config=x;this._duration=x.duration=="infinite"?0:W(x.duration)}generate(x){return this._generate(x,this._epoch)}verify(x,j){let z=this._epoch;if(j===this._generate(x,z))return"valid";if(this._duration==0)return"invalid";if(j===this._generate(x,z-1))return"expired";return"invalid"}_generate(x,j){return this.config.prefix+U(this.config.algorithm,x).update(x+j).digest(this.config.encoding)}}var J={prefix:"u",algorithm:"sha1",encoding:"base64url",crcLength:4},N={...J,prefix:"d"},O={prefix:"s",algorithm:"sha384",encoding:"base64url",crcLength:4},Q={prefix:"t",algorithm:"sha224",encoding:"base64url"};class X{_generators;constructor(x){this._generators={secret:new A(O),deviceId:new A(N),userId:new A(J),token:new F({...Q,...x})}}generateUserId(){return this._generators.userId.generateRandomSelfValidate()}verifyUserId(x){return this._generators.userId.verifySelfValidate(x)}generateToken(x){return this._generators.token.generate(x.join())}verifyToken(x,j){return this._generators.token.verify(x.join(),j)}generateSecret(){return this._generators.secret.generateRandomSelfValidate()}verifySecret(x){return this._generators.secret.verifySelfValidate(x)}generateDeviceId(){return this._generators.deviceId.generateRandomSelfValidate()}verifyDeviceId(x){return this._generators.deviceId.verifySelfValidate(x)}}export{Q as userTokenGeneratorRecommendedConfig,J as userIdGeneratorRecommendedConfig,O as secretGeneratorRecommendedConfig,N as deviceIdGeneratorRecommendedConfig,F as AlwatrTokenGenerator,A as AlwatrHashGenerator,X as AlwatrCryptoFactory};
3
+
4
+ //# debugId=BC83A2377A9A925F64756E2164756E21
5
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hash.ts", "../src/token.ts", "../src/pre-config.ts", "../src/api.ts"],
4
+ "sourcesContent": [
5
+ "import {createHash, randomBytes, type BinaryLike, type BinaryToTextEncoding} from 'node:crypto';\n\nimport type {CryptoAlgorithm} 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: BinaryToTextEncoding;\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 public 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 public 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 public 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 public 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 public 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 public 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 public 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",
6
+ "import {createHmac, type BinaryToTextEncoding} from 'node:crypto';\n\nimport {parseDuration, type Duration} from '@alwatr/parse-duration';\n\nimport type {CryptoAlgorithm} 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: BinaryToTextEncoding;\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 public 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 public 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",
7
+ "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",
8
+ "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 {Duration} 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: 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n"
9
+ ],
10
+ "mappings": ";AAAA,qBAAQ,iBAAY,oBAgCb,MAAM,CAAoB,CAKZ,OAAnB,WAAW,CAAQ,EAA6B,CAA7B,cAUZ,cAAc,EAAW,CAC9B,OAAO,KAAK,SAAS,EAAY,EAAE,CAAC,EAW/B,0BAA0B,EAAW,CAC1C,OAAO,KAAK,qBAAqB,EAAY,EAAE,CAAC,EAY3C,QAAQ,CAAC,EAA0B,CACxC,OAAO,KAAK,OAAO,OAAS,EAAW,KAAK,OAAO,SAAS,EAAE,OAAO,CAAI,EAAE,OAAO,KAAK,OAAO,QAAQ,EAQjG,WAAW,CAAC,EAA0B,CAC3C,IAAM,EAAM,EAAW,MAAM,EAAE,OAAO,CAAI,EAAE,OAAO,KAAK,OAAO,QAAQ,EACvE,OAAO,KAAK,OAAO,WAAa,MAAQ,KAAK,OAAO,UAAY,EAAI,EAAM,EAAI,MAAM,EAAG,KAAK,OAAO,SAAS,EAYvG,oBAAoB,CAAC,EAA0B,CACpD,IAAM,EAAW,KAAK,SAAS,CAAI,EAC7B,EAAU,KAAK,YAAY,CAAQ,EACzC,OAAO,EAAW,EAeb,MAAM,CAAC,EAAkB,EAAuB,CACrD,OAAO,IAAS,KAAK,SAAS,CAAI,EAc7B,kBAAkB,CAAC,EAAuB,CAC/C,IAAM,EAAS,EAAK,OAAS,KAAK,OAAO,UACnC,EAAW,EAAK,MAAM,EAAG,CAAM,EAErC,OADgB,EAAK,MAAM,CAAM,IACd,KAAK,YAAY,CAAQ,EAEhD,CCtIA,qBAAQ,oBAER,wBAAQ,+BAuCD,MAAM,CAAqB,CAcb,OAbX,aAKM,OAAM,EAAW,CAC7B,OAAO,KAAK,WAAa,EAAI,EAAI,KAAK,MAAM,KAAK,IAAI,EAAI,KAAK,SAAS,EAOzE,WAAW,CAAQ,EAA8B,CAA9B,cACjB,KAAK,UAAY,EAAO,UAAY,WAAa,EAAI,EAAc,EAAO,QAAQ,EAY7E,QAAQ,CAAC,EAAsB,CACpC,OAAO,KAAK,UAAU,EAAM,KAAK,MAAM,EAalC,MAAM,CAAC,EAAc,EAA8B,CACxD,IAAM,EAAQ,KAAK,OACnB,GAAI,IAAU,KAAK,UAAU,EAAM,CAAK,EAAG,MAAO,QAClD,GAAI,KAAK,WAAa,EAAG,MAAO,UAChC,GAAI,IAAU,KAAK,UAAU,EAAM,EAAQ,CAAC,EAAG,MAAO,UACtD,MAAO,UASC,SAAS,CAAC,EAAc,EAAuB,CACvD,OACE,KAAK,OAAO,OACZ,EAAW,KAAK,OAAO,UAAW,CAAI,EACnC,OAAO,EAAO,CAAK,EACnB,OAAO,KAAK,OAAO,QAAQ,EAGpC,CClGO,IAAM,EAAwE,CACnF,OAAQ,IACR,UAAW,OACX,SAAU,YACV,UAAW,CACb,EAKa,EAA0E,IAClF,EACH,OAAQ,GACV,EAKa,EAAwE,CACnF,OAAQ,IACR,UAAW,SACX,SAAU,YACV,UAAW,CACb,EAKa,EAAyG,CACpH,OAAQ,IACR,UAAW,SACX,SAAU,WACZ,ECTO,MAAM,CAAoB,CACrB,YAMV,WAAW,CAAC,EAA6B,CACvC,KAAK,YAAc,CACjB,OAAQ,IAAI,EAAoB,CAAgC,EAChE,SAAU,IAAI,EAAoB,CAAkC,EACpE,OAAQ,IAAI,EAAoB,CAAgC,EAChE,MAAO,IAAI,EAAqB,IAC3B,KACA,CACL,CAAC,CACH,EAcK,cAAc,EAAW,CAC9B,OAAO,KAAK,YAAY,OAAO,2BAA2B,EAcrD,YAAY,CAAC,EAAyB,CAC3C,OAAO,KAAK,YAAY,OAAO,mBAAmB,CAAM,EAYnD,aAAa,CAAC,EAA2C,CAC9D,OAAO,KAAK,YAAY,MAAM,SAAS,EAAa,KAAK,CAAC,EAerD,WAAW,CAAC,EAAmC,EAA8B,CAClF,OAAO,KAAK,YAAY,MAAM,OAAO,EAAa,KAAK,EAAG,CAAK,EAc1D,cAAc,EAAW,CAC9B,OAAO,KAAK,YAAY,OAAO,2BAA2B,EAcrD,YAAY,CAAC,EAAyB,CAC3C,OAAO,KAAK,YAAY,OAAO,mBAAmB,CAAM,EAWnD,gBAAgB,EAAW,CAChC,OAAO,KAAK,YAAY,SAAS,2BAA2B,EAkBvD,cAAc,CAAC,EAA2B,CAC/C,OAAO,KAAK,YAAY,SAAS,mBAAmB,CAAQ,EAEhE",
11
+ "debugId": "BC83A2377A9A925F64756E2164756E21",
12
+ "names": []
13
+ }
package/package.json CHANGED
@@ -1,33 +1,61 @@
1
1
  {
2
2
  "name": "@alwatr/crypto",
3
+ "version": "9.1.0",
3
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.",
4
- "version": "4.10.0",
5
- "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
- "bugs": "https://github.com/Alwatr/nanotron/issues",
7
- "dependencies": {
8
- "@alwatr/parse-duration": "^5.5.17"
9
- },
10
- "devDependencies": {
11
- "@alwatr/nano-build": "^6.3.1",
12
- "@alwatr/prettier-config": "^5.0.4",
13
- "@alwatr/tsconfig-base": "^6.0.2",
14
- "@alwatr/type-helper": "^6.1.1",
15
- "@types/node": "^22.18.6",
16
- "jest": "^30.1.3",
17
- "typescript": "^5.9.2"
5
+ "license": "MPL-2.0",
6
+ "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
7
+ "type": "module",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Alwatr/alwatr",
11
+ "directory": "pkg/nanolib/crypto"
18
12
  },
13
+ "homepage": "https://github.com/Alwatr/alwatr/tree/main/pkg/nanolib/crypto#readme",
14
+ "bugs": "https://github.com/Alwatr/alwatr/issues",
19
15
  "exports": {
20
16
  ".": {
21
17
  "types": "./dist/main.d.ts",
22
- "import": "./dist/main.mjs",
23
- "require": "./dist/main.cjs"
18
+ "import": "./dist/main.js",
19
+ "default": "./dist/main.js"
24
20
  }
25
21
  },
22
+ "sideEffects": false,
23
+ "dependencies": {
24
+ "@alwatr/parse-duration": "9.1.0"
25
+ },
26
+ "devDependencies": {
27
+ "@alwatr/nano-build": "9.1.0",
28
+ "@alwatr/tsconfig-base": "9.1.0",
29
+ "@alwatr/type-helper": "9.1.0",
30
+ "@types/node": "^25.5.0",
31
+ "typescript": "^6.0.2"
32
+ },
33
+ "scripts": {
34
+ "b": "bun run build",
35
+ "build": "bun run build:ts && bun run build:es",
36
+ "build:es": "nano-build --preset=module src/main.ts",
37
+ "build:ts": "tsc --build",
38
+ "cl": "bun run clean",
39
+ "clean": "rm -rfv dist *.tsbuildinfo",
40
+ "format": "prettier --write \"src/**/*.ts\"",
41
+ "lint": "eslint src/ --ext .ts",
42
+ "t": "bun run test",
43
+ "test": "ALWATR_DEBUG=0 bun test",
44
+ "w": "bun run watch",
45
+ "watch": "bun run watch:ts & bun run watch:es",
46
+ "watch:es": "bun run build:es --watch",
47
+ "watch:ts": "bun run build:ts --watch --preserveWatchOutput"
48
+ },
26
49
  "files": [
27
- "**/*.{js,mjs,cjs,map,d.ts,html,md}",
28
- "!demo/**/*"
50
+ "dist",
51
+ "src/**/*.ts",
52
+ "!src/**/*.test.ts",
53
+ "README.md",
54
+ "LICENSE"
29
55
  ],
30
- "homepage": "https://github.com/Alwatr/nanotron/tree/next/packages/crypto#readme",
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
31
59
  "keywords": [
32
60
  "access",
33
61
  "alwatr",
@@ -42,38 +70,7 @@
42
70
  "otp-token",
43
71
  "time",
44
72
  "token",
45
- "token",
46
73
  "typescript"
47
74
  ],
48
- "license": "MPL-2.0",
49
- "main": "./dist/main.cjs",
50
- "module": "./dist/main.mjs",
51
- "prettier": "@alwatr/prettier-config",
52
- "publishConfig": {
53
- "access": "public"
54
- },
55
- "repository": {
56
- "type": "git",
57
- "url": "https://github.com/Alwatr/nanotron",
58
- "directory": "packages/crypto"
59
- },
60
- "scripts": {
61
- "b": "yarn run build",
62
- "build": "yarn run build:ts & yarn run build:es",
63
- "build:es": "nano-build --preset=module",
64
- "build:ts": "tsc --build",
65
- "c": "yarn run clean",
66
- "cb": "yarn run clean && yarn run build",
67
- "clean": "rm -rfv dist *.tsbuildinfo",
68
- "d": "yarn run build:es && yarn node --enable-source-maps --trace-warnings",
69
- "t": "yarn run test",
70
- "test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" jest",
71
- "w": "yarn run watch",
72
- "watch": "yarn run watch:ts & yarn run watch:es",
73
- "watch:es": "yarn run build:es --watch",
74
- "watch:ts": "yarn run build:ts --watch --preserveWatchOutput"
75
- },
76
- "type": "module",
77
- "types": "./dist/main.d.ts",
78
- "gitHead": "234113e16cdec26d18c5687219d5f5c29829e045"
75
+ "gitHead": "4a25cd3e0499cf61dd761e87d3711abf9b0cd208"
79
76
  }
package/src/api.ts ADDED
@@ -0,0 +1,168 @@
1
+ import {AlwatrHashGenerator} from './hash.js';
2
+ import {
3
+ deviceIdGeneratorRecommendedConfig,
4
+ secretGeneratorRecommendedConfig,
5
+ userIdGeneratorRecommendedConfig,
6
+ userTokenGeneratorRecommendedConfig,
7
+ } from './pre-config.js';
8
+ import {AlwatrTokenGenerator, type TokenValidity} from './token.js';
9
+
10
+ import type {Duration} from '@alwatr/parse-duration';
11
+
12
+ /**
13
+ * Configuration options for the CryptoFactory.
14
+ */
15
+ export interface CryptoFactoryConfig {
16
+ /**
17
+ * The secret used for encryption and decryption tokens.
18
+ */
19
+ secret: string;
20
+
21
+ /**
22
+ * The duration for which the token is valid.
23
+ */
24
+ duration: Duration | 'infinite';
25
+ }
26
+
27
+ /**
28
+ * Crypto factory for generating self-validate user-id, user-token, secret, device-id.
29
+ */
30
+ export class AlwatrCryptoFactory {
31
+ protected _generators;
32
+
33
+ /**
34
+ * Creates a new instance of crypto factory.
35
+ * @param config The configuration used to create the crypto factory.
36
+ */
37
+ constructor(config: CryptoFactoryConfig) {
38
+ this._generators = {
39
+ secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),
40
+ deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),
41
+ userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),
42
+ token: new AlwatrTokenGenerator({
43
+ ...userTokenGeneratorRecommendedConfig,
44
+ ...config,
45
+ }),
46
+ } as const;
47
+ }
48
+
49
+ /**
50
+ * Generate self-verifiable user ID.
51
+ * @returns The generated user ID.
52
+ * @example
53
+ * ```typescript
54
+ * const newUser = {
55
+ * id: cryptoFactory.generateUserId(),
56
+ * ...
57
+ * }
58
+ * ```
59
+ */
60
+ public generateUserId(): string {
61
+ return this._generators.userId.generateRandomSelfValidate();
62
+ }
63
+
64
+ /**
65
+ * Verify a user ID without token.
66
+ * @param userId The user ID to verify.
67
+ * @returns A boolean indicating whether the user ID is valid.
68
+ * @example
69
+ * ```typescript
70
+ * if (!cryptoFactory.verifyUserId(user.id)) {
71
+ * throw new Error('invalid_user');
72
+ * }
73
+ * ```
74
+ */
75
+ public verifyUserId(userId: string): boolean {
76
+ return this._generators.userId.verifySelfValidate(userId);
77
+ }
78
+
79
+ /**
80
+ * Generate authentication token.
81
+ * @param uniquelyList The list of uniq values to generate the token from.
82
+ * @returns The generated user token.
83
+ * @example
84
+ * ```typescript
85
+ * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);
86
+ * ```
87
+ */
88
+ public generateToken(uniquelyList: (string | number)[]): string {
89
+ return this._generators.token.generate(uniquelyList.join());
90
+ }
91
+
92
+ /**
93
+ * Verify a authentication token.
94
+ * @param uniquelyList The list of uniq values used to generate the token.
95
+ * @param token The user token to verify.
96
+ * @returns The validity of the token.
97
+ * @example
98
+ * ```typescript
99
+ * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {
100
+ * throw new Error('invalid_token');
101
+ * }
102
+ * ```
103
+ */
104
+ public verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {
105
+ return this._generators.token.verify(uniquelyList.join(), token);
106
+ }
107
+
108
+ /**
109
+ * Generate self-verifiable secret.
110
+ * @returns The generated secret.
111
+ * @example
112
+ * ```typescript
113
+ * const config = {
114
+ * storageToken: cryptoFactory.generateSecret(),
115
+ * ...
116
+ * }
117
+ * ```
118
+ */
119
+ public generateSecret(): string {
120
+ return this._generators.secret.generateRandomSelfValidate();
121
+ }
122
+
123
+ /**
124
+ * Verify a secret.
125
+ * @param secret The secret to verify.
126
+ * @returns A boolean indicating whether the secret is valid.
127
+ * @example
128
+ * ```typescript
129
+ * if (!cryptoFactory.verifySecret(config.storageToken)) {
130
+ * throw new Error('invalid_secret');
131
+ * }
132
+ * ```
133
+ */
134
+ public verifySecret(secret: string): boolean {
135
+ return this._generators.secret.verifySelfValidate(secret);
136
+ }
137
+
138
+ /**
139
+ * Generate self-verifiable device ID.
140
+ * @returns The generated device ID.
141
+ * @example
142
+ * ```typescript
143
+ * const deviceId = deviceFactory.generateDeviceId();
144
+ * ```
145
+ */
146
+ public generateDeviceId(): string {
147
+ return this._generators.deviceId.generateRandomSelfValidate();
148
+ }
149
+
150
+ /**
151
+ * Verify a device ID.
152
+ * @param deviceId The device ID to verify.
153
+ * @returns A boolean indicating whether the device ID is valid.
154
+ * @example
155
+ * ```typescript
156
+ * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {
157
+ * throw {
158
+ * ok: false,
159
+ * status: 400,
160
+ * error: 'invalid_device_id',
161
+ * }
162
+ * }
163
+ * ```
164
+ */
165
+ public verifyDeviceId(deviceId: string): boolean {
166
+ return this._generators.deviceId.verifySelfValidate(deviceId);
167
+ }
168
+ }
package/src/hash.ts ADDED
@@ -0,0 +1,135 @@
1
+ import {createHash, randomBytes, type BinaryLike, type BinaryToTextEncoding} from 'node:crypto';
2
+
3
+ import type {CryptoAlgorithm} from './type.js';
4
+
5
+ /**
6
+ * Represents the configuration for a hash generator.
7
+ */
8
+ export interface HashGeneratorConfig {
9
+ /**
10
+ * The prefix to be added to the generated hash.
11
+ */
12
+ prefix: string;
13
+
14
+ /**
15
+ * The algorithm used for hashing.
16
+ */
17
+ algorithm: CryptoAlgorithm;
18
+
19
+ /**
20
+ * The encoding used for the generated hash.
21
+ */
22
+ encoding: BinaryToTextEncoding;
23
+
24
+ /**
25
+ * The length of the CRC (Cyclic Redundancy Check) value.
26
+ */
27
+ crcLength: number;
28
+ }
29
+
30
+ /**
31
+ * Secure **self-validate** hash generator.
32
+ */
33
+ export class AlwatrHashGenerator {
34
+ /**
35
+ * Creates a new instance of the AlwatrHashGenerator class.
36
+ * @param config The configuration for the hash generator.
37
+ */
38
+ constructor(public config: HashGeneratorConfig) {}
39
+
40
+ /**
41
+ * Generate a random hash.
42
+ * @returns The generated hash.
43
+ * @example
44
+ * ```typescript
45
+ * const clientId = hashGenerator.generateRandom();
46
+ * ```
47
+ */
48
+ public generateRandom(): string {
49
+ return this.generate(randomBytes(16));
50
+ }
51
+
52
+ /**
53
+ * Generate a **self-validate** random hash.
54
+ * @returns The generated self-validated hash.
55
+ * @example
56
+ * ```typescript
57
+ * const userId = hashGenerator.generateRandomSelfValidate();
58
+ * ```
59
+ */
60
+ public generateRandomSelfValidate(): string {
61
+ return this.generateSelfValidate(randomBytes(16));
62
+ }
63
+
64
+ /**
65
+ * Generate a hash from data.
66
+ * @param data - The data to generate the hash from.
67
+ * @returns The generated hash.
68
+ * @example
69
+ * ```typescript
70
+ * const crcHash = hashGenerator.generate(data);
71
+ * ```
72
+ */
73
+ public generate(data: BinaryLike): string {
74
+ return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);
75
+ }
76
+
77
+ /**
78
+ * Generate a crc hash.
79
+ * @param data - The data to generate the crc hash from.
80
+ * @returns The generated crc hash.
81
+ */
82
+ public generateCrc(data: BinaryLike): string {
83
+ const crc = createHash('sha1').update(data).digest(this.config.encoding);
84
+ return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);
85
+ }
86
+
87
+ /**
88
+ * Generate a **self-validate** hash from data.
89
+ * @param data - The data to generate the self-validated hash from.
90
+ * @returns The generated self-validated hash.
91
+ * @example
92
+ * ```typescript
93
+ * const userId = hashGenerator.generateSelfValidate(data);
94
+ * ```
95
+ */
96
+ public generateSelfValidate(data: BinaryLike): string {
97
+ const mainHash = this.generate(data);
98
+ const crcHash = this.generateCrc(mainHash);
99
+ return mainHash + crcHash;
100
+ }
101
+
102
+ /**
103
+ * Verify if the generated hash matches the provided hash.
104
+ * @param data - The data to verify.
105
+ * @param hash - The hash to compare against.
106
+ * @returns `true` if the hash is verified, `false` otherwise.
107
+ * @example
108
+ * ```typescript
109
+ * if (!hashGenerator.verify(data, hash)) {
110
+ * new Error('data_corrupted');
111
+ * }
112
+ * ```
113
+ */
114
+ public verify(data: BinaryLike, hash: string): boolean {
115
+ return hash === this.generate(data);
116
+ }
117
+
118
+ /**
119
+ * Verify a **self-validate** hash to check if it was generated by this class (with the same options).
120
+ * @param hash - The self-validated hash to verify.
121
+ * @returns `true` if the hash is verified, `false` otherwise.
122
+ * @example
123
+ * ```typescript
124
+ * if (!hashGenerator.verifySelfValidate(hash)) {
125
+ * new Error('invalid_hash');
126
+ * }
127
+ * ```
128
+ */
129
+ public verifySelfValidate(hash: string): boolean {
130
+ const gapPos = hash.length - this.config.crcLength;
131
+ const mainHash = hash.slice(0, gapPos);
132
+ const crcHash = hash.slice(gapPos);
133
+ return crcHash === this.generateCrc(mainHash);
134
+ }
135
+ }
package/src/main.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './hash.js';
2
+ export * from './token.js';
3
+ export * from './api.js';
4
+ export * from './type.js';
5
+ export * from './pre-config.js';
@@ -0,0 +1,39 @@
1
+ import type {HashGeneratorConfig} from './hash.js';
2
+ import type {TokenGeneratorConfig} from './token.js';
3
+
4
+ /**
5
+ * Alwatr hash generator recommended configuration for making random self-validate **user-id**.
6
+ */
7
+ export const userIdGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {
8
+ prefix: 'u',
9
+ algorithm: 'sha1',
10
+ encoding: 'base64url',
11
+ crcLength: 4,
12
+ };
13
+
14
+ /**
15
+ * Hash generator recommended configuration for making random self-validate **device-id**.
16
+ */
17
+ export const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {
18
+ ...userIdGeneratorRecommendedConfig,
19
+ prefix: 'd',
20
+ };
21
+
22
+ /**
23
+ * Hash generator pre configuration for making random self-validate **secrets**.
24
+ */
25
+ export const secretGeneratorRecommendedConfig: HashGeneratorConfig = /* #__PURE__ */ {
26
+ prefix: 's',
27
+ algorithm: 'sha384',
28
+ encoding: 'base64url',
29
+ crcLength: 4,
30
+ };
31
+
32
+ /**
33
+ * Token generator recommended configuration for making secure self-validate **user-token**.
34
+ */
35
+ export const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = /* #__PURE__ */ {
36
+ prefix: 't',
37
+ algorithm: 'sha224',
38
+ encoding: 'base64url',
39
+ };
package/src/token.ts ADDED
@@ -0,0 +1,105 @@
1
+ import {createHmac, type BinaryToTextEncoding} from 'node:crypto';
2
+
3
+ import {parseDuration, type Duration} from '@alwatr/parse-duration';
4
+
5
+ import type {CryptoAlgorithm} from './type.js';
6
+
7
+ export type TokenValidity = 'valid' | 'invalid' | 'expired';
8
+
9
+ /**
10
+ * Represents the configuration for a token generator.
11
+ */
12
+ export interface TokenGeneratorConfig {
13
+ /**
14
+ * The prefix to be added to the generated hash.
15
+ */
16
+ prefix: string;
17
+
18
+ /**
19
+ * The algorithm used for hashing.
20
+ */
21
+ algorithm: CryptoAlgorithm;
22
+
23
+ /**
24
+ * The encoding used for the generated hash.
25
+ */
26
+ encoding: BinaryToTextEncoding;
27
+
28
+ /**
29
+ * The secret used for encryption and decryption tokens.
30
+ */
31
+ secret: string;
32
+
33
+ /**
34
+ * The duration for which the token is valid.
35
+ */
36
+ duration: Duration | 'infinite';
37
+ }
38
+
39
+ /**
40
+ * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).
41
+ */
42
+ export class AlwatrTokenGenerator {
43
+ private _duration: number;
44
+
45
+ /**
46
+ * The current epoch based on the configured duration.
47
+ */
48
+ protected get _epoch(): number {
49
+ return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);
50
+ }
51
+
52
+ /**
53
+ * Creates a new instance of AlwatrTokenGenerator.
54
+ * @param config The configuration for the token generator.
55
+ */
56
+ constructor(public config: TokenGeneratorConfig) {
57
+ this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);
58
+ }
59
+
60
+ /**
61
+ * Generates a HOTP token based on the provided data for special duration.
62
+ * @param data The data to generate the token from.
63
+ * @returns The generated token.
64
+ * @example
65
+ * ```typescript
66
+ * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);
67
+ * ```
68
+ */
69
+ public generate(data: string): string {
70
+ return this._generate(data, this._epoch);
71
+ }
72
+
73
+ /**
74
+ * Verifies if a token is valid.
75
+ * @param data The data used to generate the token.
76
+ * @param token The token to verify.
77
+ * @returns The validity of the token.
78
+ * @example
79
+ * ```typescript
80
+ * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);
81
+ * ```
82
+ */
83
+ public verify(data: string, token: string): TokenValidity {
84
+ const epoch = this._epoch;
85
+ if (token === this._generate(data, epoch)) return 'valid';
86
+ if (this._duration == 0) return 'invalid';
87
+ if (token === this._generate(data, epoch - 1)) return 'expired';
88
+ return 'invalid';
89
+ }
90
+
91
+ /**
92
+ * Generates a cryptographic token based on the provided data and epoch.
93
+ * @param data - The data to be used in the token generation.
94
+ * @param epoch - The epoch value to be used in the token generation.
95
+ * @returns The generated cryptographic token.
96
+ */
97
+ protected _generate(data: string, epoch: number): string {
98
+ return (
99
+ this.config.prefix +
100
+ createHmac(this.config.algorithm, data)
101
+ .update(data + epoch)
102
+ .digest(this.config.encoding)
103
+ );
104
+ }
105
+ }
package/src/type.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Represents a cryptographic algorithm.
3
+ * Supported algorithms include: 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'.
4
+ */
5
+ export type CryptoAlgorithm = 'md5' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512';
package/CHANGELOG.md DELETED
@@ -1,443 +0,0 @@
1
- # Change Log
2
-
3
- All notable changes to this project will be documented in this file.
4
- See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
-
6
- ## [4.10.0](https://github.com/Alwatr/nanotron/compare/v4.9.4...v4.10.0) (2025-09-21)
7
-
8
- ### 🐛 Bug Fixes
9
-
10
- * make generate and verify methods public in AlwatrTokenGenerator class ([637666f](https://github.com/Alwatr/nanotron/commit/637666f8326e8696c6bdb2400ea207fe05d6cc40))
11
- * update import for Duration type from '@alwatr/parse-duration' ([a365b18](https://github.com/Alwatr/nanotron/commit/a365b18577124d7f4f62ed48c8d639554362d530))
12
- * update import path for parseDuration from nanolib to parse-duration ([5c390a2](https://github.com/Alwatr/nanotron/commit/5c390a2bd3299a82789b125458016c93ff9b47d5))
13
-
14
- ### 🔨 Code Refactoring
15
-
16
- * add public access modifiers to methods in AlwatrHashGenerator ([e54d186](https://github.com/Alwatr/nanotron/commit/e54d1863a05339cf23b75305f809f2b11e0087c2))
17
- * update access modifiers to public for methods in AlwatrCryptoFactory ([2dd01fd](https://github.com/Alwatr/nanotron/commit/2dd01fd3465ad1f8c26980a809333c7036abed6b))
18
-
19
- ### 🧹 Miscellaneous Chores
20
-
21
- * remove Exir Studio sponsorship logo from multiple README files ([af3fd5d](https://github.com/Alwatr/nanotron/commit/af3fd5dda9b57d0948003db1feb0dc2dad4883d7))
22
- * remove unused types from compiler options in tsconfig.json ([a65a484](https://github.com/Alwatr/nanotron/commit/a65a484cbf96ae4e36a395620b2940e3bcc221c0))
23
- * update @alwatr/nanolib and @alwatr/nano-build to version 6.1.1 and 6.3.1 respectively ([81b3d5e](https://github.com/Alwatr/nanotron/commit/81b3d5ebf5ecc1242ee0a010631e4d920af9f3dd))
24
- * update @alwatr/nanolib and related dependencies to version 6.x ([d824f0d](https://github.com/Alwatr/nanotron/commit/d824f0d5b8e008ec758842997a6e2ee6f7d078d5))
25
- * update licenses from AGPL-3.0 to MPL-2.0 ([a84513e](https://github.com/Alwatr/nanotron/commit/a84513efbe12b9570c7550c887f2cdfbf67fc82b))
26
-
27
- ### 🔗 Dependencies update
28
-
29
- * replace @alwatr/nanolib with @alwatr/parse-duration in package.json ([b7d3841](https://github.com/Alwatr/nanotron/commit/b7d38412d1bc72c682c13c576640161d8a231ebc))
30
-
31
- ## [4.9.4](https://github.com/Alwatr/nanotron/compare/v4.9.3...v4.9.4) (2025-08-23)
32
-
33
- ### 🔨 Code Refactoring
34
-
35
- * reorganize package.json files for consistency and clarity ([bde116e](https://github.com/Alwatr/nanotron/commit/bde116e21f9d9bd6084940e257438916d2c3d312)) by @alimd
36
-
37
- ### 🔗 Dependencies update
38
-
39
- * downgrade @types/node version to 22.17.2 in all package.json files ([4f01e14](https://github.com/Alwatr/nanotron/commit/4f01e1408d8d0954865eb9d20f90178f13e98719)) by @alimd
40
- * update dependencies for eslint-config, lerna-lite, typescript, and nanolib ([de16a71](https://github.com/Alwatr/nanotron/commit/de16a718bb1c0fa569d39c824ec39a1e67ef8dfe)) by @alimd
41
-
42
- ## [4.9.3](https://github.com/Alwatr/nanotron/compare/v4.9.2...v4.9.3) (2025-07-23)
43
-
44
- **Note:** Version bump only for package @alwatr/crypto
45
-
46
- ## [4.9.2](https://github.com/Alwatr/nanotron/compare/v4.9.1...v4.9.2) (2025-07-23)
47
-
48
- ### Dependencies update
49
-
50
- * update dependencies to latest versions ([353d048](https://github.com/Alwatr/nanotron/commit/353d0485a5c21ab219d84cd0a6c35f62b46c2da9)) by @alimd
51
-
52
- ## [4.9.1](https://github.com/Alwatr/nanotron/compare/v4.9.0...v4.9.1) (2025-03-06)
53
-
54
- ### Dependencies update
55
-
56
- * **deps-dev:** bump the dependencies group with 5 updates ([e6a00eb](https://github.com/Alwatr/nanotron/commit/e6a00eb139f70f2396ecf12b68103b40aa785521)) by @dependabot[bot]
57
- * update @alwatr/nanolib and @alwatr/nano-build to version 5.5.0; bump @alwatr/type-helper to version 5.4.0 ([1e8b122](https://github.com/Alwatr/nanotron/commit/1e8b1228034af44e0d4914f5100d9e564c05a5a6)) by @
58
-
59
- ## [4.9.0](https://github.com/Alwatr/nanotron/compare/v4.8.1...v4.9.0) (2025-02-26)
60
-
61
- ### Features
62
-
63
- * **crypto:** add 'ascii' and 'utf8' to CryptoEncoding type ([aa2720f](https://github.com/Alwatr/nanotron/commit/aa2720f6f7b128a572d8591dc7a75ac15ed6d2d6)) by @alimd
64
-
65
- ### Code Refactoring
66
-
67
- * **crypto:** replace CryptoEncoding with BinaryToTextEncoding in hash and token configurations ([8e356cd](https://github.com/Alwatr/nanotron/commit/8e356cd60ee438d1f2d2ab688468944d8b6bd99e)) by @alimd
68
-
69
- ### Dependencies update
70
-
71
- * bump @types/node from 22.13.4 to 22.13.5 and prettier from 3.5.1 to 3.5.2 across multiple packages ([3d55c9a](https://github.com/Alwatr/nanotron/commit/3d55c9a4044773fdc8d7c8b635311f2043f48569)) by @alimd
72
-
73
- ## [4.8.1](https://github.com/Alwatr/nanotron/compare/v4.8.0...v4.8.1) (2025-02-18)
74
-
75
- ### Dependencies update
76
-
77
- * **deps-dev:** bump the dependencies group across 1 directory with 11 updates ([9257e08](https://github.com/Alwatr/nanotron/commit/9257e08b96f5661a7e13e153b9c71d9dbc08fd18)) by @dependabot[bot]
78
- * update TypeScript, Prettier, and various dependencies to latest versions ([5c0f752](https://github.com/Alwatr/nanotron/commit/5c0f7521851acaabb2466e459754c130d7ebf31b)) by @
79
-
80
- ## [4.6.0](https://github.com/Alwatr/nanotron/compare/v4.5.2...v4.6.0) (2024-11-07)
81
-
82
- ### Dependencies update
83
-
84
- * **deps-dev:** bump @types/node in the dependencies group ([9901819](https://github.com/Alwatr/nanotron/commit/9901819d0a7fef85736951f354bc1846294bb7fe)) by @dependabot[bot]
85
- * **deps:** bump @alwatr/nanolib from 5.0.0 to 5.2.1 in the alwatr group ([f06afb7](https://github.com/Alwatr/nanotron/commit/f06afb74f363c478ffc5967bafadfa2bc9009129)) by @dependabot[bot]
86
-
87
- ## [4.5.2](https://github.com/Alwatr/nanotron/compare/v4.5.1...v4.5.2) (2024-11-02)
88
-
89
- ### Dependencies update
90
-
91
- * **deps:** bump the alwatr group with 6 updates ([6636bb3](https://github.com/Alwatr/nanotron/commit/6636bb307401e28863eb27288d5abbaab2d67e18)) by @dependabot[bot]
92
- * update ([86fbeb6](https://github.com/Alwatr/nanotron/commit/86fbeb663d94452f3596d0894ec19d4c6bed3099)) by @
93
-
94
- ## [4.5.0](https://github.com/Alwatr/nanotron/compare/v4.4.1...v4.5.0) (2024-10-28)
95
-
96
- ### Bug Fixes
97
-
98
- * **crypto:** remove side effects ([852e035](https://github.com/Alwatr/nanotron/commit/852e035d6ffceec32f7b4d2197140a27b4afb330)) by @AliMD
99
-
100
- ### Dependencies update
101
-
102
- * bump the development-dependencies group across 1 directory with 2 updates ([8b3e101](https://github.com/Alwatr/nanotron/commit/8b3e10128af769ef95a2e7b2ed788e843eb47414)) by @dependabot[bot]
103
- * update nanolib v1.4.0 and other deps ([b8e7be7](https://github.com/Alwatr/nanotron/commit/b8e7be7b6c58d4f1cbc12593b2d6124f3d19b377)) by @
104
-
105
- ## [4.4.1](https://github.com/Alwatr/nanotron/compare/v4.4.0...v4.4.1) (2024-10-16)
106
-
107
- ### Dependencies update
108
-
109
- * update ([8917c2e](https://github.com/Alwatr/nanotron/commit/8917c2e637781fe219c5031f414de3dea82cf371)) by @
110
-
111
- ## [4.3.0](https://github.com/Alwatr/nanotron/compare/v4.2.2...v4.3.0) (2024-10-11)
112
-
113
- ### Features
114
-
115
- * update `import`s & packages based on the latest changes of `nanolib` & prevent `sideeffects` from `build` result ([1d234b8](https://github.com/Alwatr/nanotron/commit/1d234b83152fb246b793476898e9cf026aa52874)) by @mohammadhonarvar
116
-
117
- ### Bug Fixes
118
-
119
- * **crypto:** update types & `logger` & use `packageTracer` based on last changes of `nanolib` ([cf1a480](https://github.com/Alwatr/nanotron/commit/cf1a48071fe745226f6aed2afdf11038da5065e2)) by @mohammadhonarvar
120
-
121
- ### Code Refactoring
122
-
123
- * update `import`s & packages based on the latest changes of `nanolib` ([7652b5d](https://github.com/Alwatr/nanotron/commit/7652b5d9cc69218f2ff28bda3d0d8f52f147c6f6)) by @mohammadhonarvar
124
-
125
- ### Miscellaneous Chores
126
-
127
- * edited README ([d707d38](https://github.com/Alwatr/nanotron/commit/d707d389e085dd320402521cb23af5805013d777)) by @ArmanAsadian
128
-
129
- ### Dependencies update
130
-
131
- * update ([834ffcc](https://github.com/Alwatr/nanotron/commit/834ffcc8f6de96cc11a1a6fa933f948b7813cde6)) by @mohammadhonarvar
132
-
133
- ## [4.2.2](https://github.com/Alwatr/nanotron/compare/v4.2.1...v4.2.2) (2024-09-29)
134
-
135
- ### Miscellaneous Chores
136
-
137
- * **crypto:** change the license to AGPL-3.0 ([a37fb50](https://github.com/Alwatr/nanotron/commit/a37fb50898bb0bc909746f44bc34d14bcf255a61)) by @ArmanAsadian
138
-
139
- ### Dependencies update
140
-
141
- * bump @types/node in the development-dependencies group ([9c8d7d5](https://github.com/Alwatr/nanotron/commit/9c8d7d518d9a5da2ea57ac2b210a8697267e6d3d)) by @dependabot[bot]
142
- * update ([1c4ef63](https://github.com/Alwatr/nanotron/commit/1c4ef635fc969d4abd416aea2b954de674748da8)) by @AliMD
143
-
144
- ## [4.2.1](https://github.com/Alwatr/nanotron/compare/v4.2.0...v4.2.1) (2024-09-24)
145
-
146
- ### Dependencies update
147
-
148
- * update ([e698199](https://github.com/Alwatr/nanotron/commit/e698199e4a41532de8e9c799db96b9bde2a647f6)) by @AliMD
149
-
150
- ## [4.2.0](https://github.com/Alwatr/nanotron/compare/v4.1.0...v4.2.0) (2024-09-23)
151
-
152
- ### Dependencies update
153
-
154
- * bump the alwatr-dependencies group with 6 updates ([1c8a8ec](https://github.com/Alwatr/nanotron/commit/1c8a8ec468aa31c79de45f0e897cc45578242981)) by @dependabot[bot]
155
- * bump the development-dependencies group with 2 updates ([e3bc7f7](https://github.com/Alwatr/nanotron/commit/e3bc7f7dcbf1779a3fdf8fbe18c4f8b4095cc222)) by @dependabot[bot]
156
- * update ([d9f8d57](https://github.com/Alwatr/nanotron/commit/d9f8d577b058b4e945db7dfc1c5c68da78c4112f)) by @AliMD
157
-
158
- ## [4.0.2](https://github.com/Alwatr/nanotron/compare/v4.0.1...v4.0.2) (2024-09-14)
159
-
160
- ### Bug Fixes
161
-
162
- * definePackage ([a2edcc1](https://github.com/Alwatr/nanotron/commit/a2edcc1b3a4822371cefa4a28ff62a7c6754287e)) by @AliMD
163
-
164
- ## [4.0.0](https://github.com/Alwatr/nanotron/compare/v4.0.0-alpha.3...v4.0.0) (2024-09-14)
165
-
166
- **Note:** Version bump only for package @alwatr/crypto
167
-
168
- ## [4.0.0-alpha.0](https://github.com/Alwatr/nanotron/compare/v1.2.7...v4.0.0-alpha.0) (2024-09-10)
169
-
170
- ### Bug Fixes
171
-
172
- * build issue after update package.json ([9df6a58](https://github.com/Alwatr/nanotron/commit/9df6a5866d2b5542e89788f1cf2a1bea5cc369d3)) by @njfamirm
173
-
174
- ### Code Refactoring
175
-
176
- * Update import paths for duration parsing ([97dd8aa](https://github.com/Alwatr/nanotron/commit/97dd8aa68e050127e444ef268e48246b6b7318c6)) by @AliMD
177
- * Update import paths for duration parsing and update typescript SDK version to 5.6.2 ([7d8ea97](https://github.com/Alwatr/nanotron/commit/7d8ea97ed8d7741e26d3a609b30e42992d9fb051)) by @AliMD
178
-
179
- ### Miscellaneous Chores
180
-
181
- * add required deps ([32b8ade](https://github.com/Alwatr/nanotron/commit/32b8adeba96dbd68879d004fe44f2f2c88b2b624)) by @njfamirm
182
- * update package.json of each package from nanolib ([b8a7c8a](https://github.com/Alwatr/nanotron/commit/b8a7c8af9f88d36ac3c1ab6324b78890dc2023b3)) by @njfamirm
183
-
184
- ### Dependencies update
185
-
186
- * update ([f95134f](https://github.com/Alwatr/nanotron/commit/f95134fe5a4b61ee01eb84450807efb9ef099010)) by @AliMD
187
-
188
- ## [3.0.4](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.3...@alwatr/crypto@3.0.4) (2023-12-19)
189
-
190
- **Note:** Version bump only for package @alwatr/crypto
191
-
192
- ## [3.0.3](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.2...@alwatr/crypto@3.0.3) (2023-12-19)
193
-
194
- **Note:** Version bump only for package @alwatr/crypto
195
-
196
- ## [3.0.2](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.1...@alwatr/crypto@3.0.2) (2023-12-11)
197
-
198
- **Note:** Version bump only for package @alwatr/crypto
199
-
200
- ## [3.0.1](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.0...@alwatr/crypto@3.0.1) (2023-12-11)
201
-
202
- **Note:** Version bump only for package @alwatr/crypto
203
-
204
- # [3.0.0](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@2.0.0...@alwatr/crypto@3.0.0) (2023-12-09)
205
-
206
- ### Bug Fixes
207
-
208
- * **crypto:** use import type ([30e3bac](https://github.com/Alwatr/alwatr-es-sdk/commit/30e3bacb187d58417cb62e2a1511de4ade3f80c0)) by @njfamirm
209
-
210
- ### Features
211
-
212
- * **crypto/api:** AlwatrCryptoFactory with secret and device id ([2d754a1](https://github.com/Alwatr/alwatr-es-sdk/commit/2d754a19b2f04f64d0828e31ba004fc192f466d3)) by @njfamirm
213
- * **crypto/api:** device id generator preconfig ([71e80d6](https://github.com/Alwatr/alwatr-es-sdk/commit/71e80d63743579505a6be17d014c364e9f6cf55c)) by @njfamirm
214
- * **crypto:** complete rewrite with new api ([3d56861](https://github.com/Alwatr/alwatr-es-sdk/commit/3d56861a2857e760c7cd5f03be98f003738fc7a9)) by @AliMD
215
- * **crypto:** rename user file to api ([52343ea](https://github.com/Alwatr/alwatr-es-sdk/commit/52343ead04c23f50bedac2caa01f46bf489ab318)) by @njfamirm
216
-
217
- ### BREAKING CHANGES
218
-
219
- * **crypto:** new api
220
- * **crypto/api:** rename AlwatrUserGenerator to AlwatrCryptoFactory and change config
221
-
222
- # [2.0.0](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.2.1...@alwatr/crypto@2.0.0) (2023-11-29)
223
-
224
- ### Features
225
-
226
- * **crypto/hash:** review and update all methods and documents ([14acd26](https://github.com/Alwatr/eslib/commit/14acd265a19b1b67bd32f725468fe66985464fe6)) by @AliMD
227
- * **crypto/preConfig:** update prefix and secret algorithm ([0cfff12](https://github.com/Alwatr/eslib/commit/0cfff124e692d02aad0b5c97908df63bc692f896)) by @AliMD
228
- * **crypto/token:** review and update all methods and documents ([dc943f8](https://github.com/Alwatr/eslib/commit/dc943f8a007567b58e9e3b7f9cada556ac76ae9b)) by @AliMD
229
- * **crypto/user:** review and update all methods and documents ([bb79fa8](https://github.com/Alwatr/eslib/commit/bb79fa81f8632d5fe75cac813238b04094d0bb6a)) by @AliMD
230
- * **crypto:** prefix option ([6be5c90](https://github.com/Alwatr/eslib/commit/6be5c90dad4674e8ae3e27611a13dcf1e08ce11a)) by @AliMD
231
-
232
- ### BREAKING CHANGES
233
-
234
- * **crypto/user:** methods name updated
235
- * **crypto/token:** methods name updated
236
- * **crypto/hash:** methods name updated
237
-
238
- ## [1.2.1](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.2.0...@alwatr/crypto@1.2.1) (2023-11-23)
239
-
240
- **Note:** Version bump only for package @alwatr/crypto
241
-
242
- # [1.2.0](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.12...@alwatr/crypto@1.2.0) (2023-11-14)
243
-
244
- ### Features
245
-
246
- * **yarn:** pnp ([b6a562c](https://github.com/Alwatr/eslib/commit/b6a562c909a35b3e626442e5c325da3fce448e1b)) by @AliMD
247
-
248
- ## [1.1.12](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.11...@alwatr/crypto@1.1.12) (2023-11-08)
249
-
250
- ### Bug Fixes
251
-
252
- * move repo urls ([719aa3e](https://github.com/Alwatr/eslib/commit/719aa3e7462d3c9c6272958fc93f89fda6793fb1)) by @AliMD
253
-
254
- ## [1.1.11](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.10...@alwatr/crypto@1.1.11) (2023-11-01)
255
-
256
- **Note:** Version bump only for package @alwatr/crypto
257
-
258
- ## [1.1.10](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.9...@alwatr/crypto@1.1.10) (2023-10-23)
259
-
260
- **Note:** Version bump only for package @alwatr/crypto
261
-
262
- ## [1.1.9](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.8...@alwatr/crypto@1.1.9) (2023-10-23)
263
-
264
- **Note:** Version bump only for package @alwatr/crypto
265
-
266
- ## [1.1.8](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.7...@alwatr/crypto@1.1.8) (2023-10-23)
267
-
268
- ### Bug Fixes
269
-
270
- * **crypto:** compatible with new logger api ([f867317](https://github.com/Alwatr/eslib/commit/f8673178d18f14276e13dcb35a7d973f301a722b)) by @AliMD
271
-
272
- ## [1.1.7](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.6...@alwatr/crypto@1.1.7) (2023-10-23)
273
-
274
- **Note:** Version bump only for package @alwatr/crypto
275
-
276
- ## [1.1.6](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.5...@alwatr/crypto@1.1.6) (2023-10-23)
277
-
278
- **Note:** Version bump only for package @alwatr/crypto
279
-
280
- ## [1.1.5](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.4...@alwatr/crypto@1.1.5) (2023-09-19)
281
-
282
- ### Bug Fixes
283
-
284
- - package repo urls ([466cbe9](https://github.com/Alwatr/eslib/commit/466cbe9188f24e1a1bc36d879a95b52538a58f16)) by @AliMD
285
-
286
- ## [1.1.4](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.3...@alwatr/crypto@1.1.4) (2023-09-19)
287
-
288
- **Note:** Version bump only for package @alwatr/crypto
289
-
290
- ## 1.1.3 (2023-09-19)
291
-
292
- **Note:** Version bump only for package @alwatr/crypto
293
-
294
- ## [1.1.2](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.1...@alwatr/crypto@1.1.2) (2023-09-12)
295
-
296
- **Note:** Version bump only for package @alwatr/crypto
297
-
298
- ## [1.1.1](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.0...@alwatr/crypto@1.1.1) (2023-09-12)
299
-
300
- **Note:** Version bump only for package @alwatr/crypto
301
-
302
- # 1.1.0 (2023-09-12)
303
-
304
- # 1.0.0 (2023-06-14)
305
-
306
- # 0.32.0 (2023-05-27)
307
-
308
- ### Features
309
-
310
- - **crypto:** add some pre config ([4b960c5](https://github.com/Alwatr/eslib/commit/4b960c5cb3f7495c0689adcb65c62a1032ae2650))
311
-
312
- ### Performance Improvements
313
-
314
- - **crypto/hash:** enhance crc generator ([ba8c4bc](https://github.com/Alwatr/eslib/commit/ba8c4bcf8f9ec9767b0bd3b6c3fd5c4f503a84dd))
315
-
316
- # 0.31.0 (2023-05-08)
317
-
318
- ### Bug Fixes
319
-
320
- - **crypto:** package ([866c5f4](https://github.com/Alwatr/eslib/commit/866c5f490ea2eaa75bf177f35b3f4711931e13d2))
321
-
322
- ### Features
323
-
324
- - **crypto:** make prefix for userId ([5baa00a](https://github.com/Alwatr/eslib/commit/5baa00aafb16a4c6ed1d77913edddd090f732dad))
325
-
326
- # [1.0.0](https://github.com/Alwatr/eslib/compare/v0.32.0...v1.0.0) (2023-06-14)
327
-
328
- **Note:** Version bump only for package @alwatr/crypto
329
-
330
- # [0.32.0](https://github.com/Alwatr/eslib/compare/v0.31.0...v0.32.0) (2023-05-27)
331
-
332
- ### Features
333
-
334
- - **crypto:** add some pre config ([4b960c5](https://github.com/Alwatr/eslib/commit/4b960c5cb3f7495c0689adcb65c62a1032ae2650))
335
-
336
- ### Performance Improvements
337
-
338
- - **crypto/hash:** enhance crc generator ([ba8c4bc](https://github.com/Alwatr/eslib/commit/ba8c4bcf8f9ec9767b0bd3b6c3fd5c4f503a84dd))
339
-
340
- # [0.31.0](https://github.com/Alwatr/eslib/compare/v0.30.0...v0.31.0) (2023-05-08)
341
-
342
- ### Bug Fixes
343
-
344
- - **crypto:** package ([866c5f4](https://github.com/Alwatr/eslib/commit/866c5f490ea2eaa75bf177f35b3f4711931e13d2))
345
-
346
- ### Features
347
-
348
- - **crypto:** make prefix for userId ([5baa00a](https://github.com/Alwatr/eslib/commit/5baa00aafb16a4c6ed1d77913edddd090f732dad))
349
-
350
- # [0.30.0](https://github.com/Alwatr/eslib/compare/v0.29.0...v0.30.0) (2023-03-06)
351
-
352
- **Note:** Version bump only for package @alwatr/crypto
353
-
354
- # [0.29.0](https://github.com/Alwatr/eslib/compare/v0.28.0...v0.29.0) (2023-02-10)
355
-
356
- **Note:** Version bump only for package @alwatr/crypto
357
-
358
- # [0.28.0](https://github.com/Alwatr/eslib/compare/v0.27.0...v0.28.0) (2023-01-20)
359
-
360
- ### Bug Fixes
361
-
362
- - **token:** types ([a7da60e](https://github.com/Alwatr/eslib/commit/a7da60e720ac83b8d2d2ed5c0b811dea1952a2b9))
363
-
364
- ### Features
365
-
366
- - **token:** generate and verify token without expiration time ([6db78f0](https://github.com/Alwatr/eslib/commit/6db78f0644e076c3401a263173d7139838bbbf0c))
367
- - **type:** define math types ([8c19f40](https://github.com/Alwatr/eslib/commit/8c19f4058d4361b7d3f4f714595e34cb6fa21109))
368
-
369
- # [0.27.0](https://github.com/Alwatr/eslib/compare/v0.26.0...v0.27.0) (2022-12-29)
370
-
371
- **Note:** Version bump only for package @alwatr/crypto
372
-
373
- # [0.26.0](https://github.com/Alwatr/eslib/compare/v0.25.0...v0.26.0) (2022-12-22)
374
-
375
- ### Bug Fixes
376
-
377
- - set correct path ([d01ce6f](https://github.com/Alwatr/eslib/commit/d01ce6ffa749a5e3e0e11e35b4ed61d75d61fec9))
378
- - tsconfig ([e96dcd3](https://github.com/Alwatr/eslib/commit/e96dcd30774a9f06f7d051e0504192cbbe019e35))
379
-
380
- # [0.25.0](https://github.com/Alwatr/eslib/compare/v0.24.1...v0.25.0) (2022-12-07)
381
-
382
- **Note:** Version bump only for package @alwatr/crypto
383
-
384
- ## [0.24.1](https://github.com/Alwatr/eslib/compare/v0.24.0...v0.24.1) (2022-12-01)
385
-
386
- **Note:** Version bump only for package @alwatr/crypto
387
-
388
- # [0.24.0](https://github.com/Alwatr/eslib/compare/v0.23.0...v0.24.0) (2022-11-28)
389
-
390
- ### Bug Fixes
391
-
392
- - use ~ for package version ([4e027ff](https://github.com/Alwatr/eslib/commit/4e027ff63875e03b088ebcdc1bdf2495f4494eec))
393
-
394
- # [0.23.0](https://github.com/Alwatr/eslib/compare/v0.22.1...v0.23.0) (2022-11-23)
395
-
396
- **Note:** Version bump only for package @alwatr/crypto
397
-
398
- ## [0.22.1](https://github.com/Alwatr/eslib/compare/v0.22.0...v0.22.1) (2022-11-21)
399
-
400
- **Note:** Version bump only for package @alwatr/crypto
401
-
402
- # [0.22.0](https://github.com/Alwatr/eslib/compare/v0.21.0...v0.22.0) (2022-11-20)
403
-
404
- **Note:** Version bump only for package @alwatr/crypto
405
-
406
- # [0.21.0](https://github.com/Alwatr/eslib/compare/v0.20.0...v0.21.0) (2022-11-13)
407
-
408
- **Note:** Version bump only for package @alwatr/crypto
409
-
410
- # [0.20.0](https://github.com/Alwatr/eslib/compare/v0.19.0...v0.20.0) (2022-11-05)
411
-
412
- **Note:** Version bump only for package @alwatr/crypto
413
-
414
- # [0.19.0](https://github.com/Alwatr/eslib/compare/v0.18.0...v0.19.0) (2022-11-01)
415
-
416
- **Note:** Version bump only for package @alwatr/crypto
417
-
418
- # [0.18.0](https://github.com/Alwatr/eslib/compare/v0.17.0...v0.18.0) (2022-10-22)
419
-
420
- **Note:** Version bump only for package @alwatr/crypto
421
-
422
- # [0.17.0](https://github.com/Alwatr/eslib/compare/v0.16.1...v0.17.0) (2022-10-21)
423
-
424
- **Note:** Version bump only for package @alwatr/crypto
425
-
426
- # [0.16.0](https://github.com/Alwatr/eslib/compare/v0.15.0...v0.16.0) (2022-09-08)
427
-
428
- **Note:** Version bump only for package @alwatr/crypto
429
-
430
- # [0.15.0](https://github.com/Alwatr/eslib/compare/v0.14.0...v0.15.0) (2022-09-01)
431
-
432
- **Note:** Version bump only for package @alwatr/crypto
433
-
434
- # [0.14.0](https://github.com/Alwatr/eslib/compare/v0.13.0...v0.14.0) (2022-08-19)
435
-
436
- **Note:** Version bump only for package @alwatr/crypto
437
-
438
- # [0.13.0](https://github.com/Alwatr/eslib/compare/v0.12.0...v0.13.0) (2022-08-06)
439
-
440
- ### Features
441
-
442
- - **token:** generate and verify HOTP tpkens ([d0372f8](https://github.com/Alwatr/eslib/commit/d0372f805a45d6fd6571b50821529068cec7d424))
443
- - **token:** new package files ([fe620e0](https://github.com/Alwatr/eslib/commit/fe620e0d9f84c4e6d8e0eed47d6b398e218429ad))
package/dist/main.cjs DELETED
@@ -1,4 +0,0 @@
1
- /** 📦 @alwatr/crypto v4.10.0 */
2
- __dev_mode__: console.debug("📦 @alwatr/crypto v4.10.0");
3
- "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{AlwatrCryptoFactory:()=>AlwatrCryptoFactory,AlwatrHashGenerator:()=>AlwatrHashGenerator,AlwatrTokenGenerator:()=>AlwatrTokenGenerator,deviceIdGeneratorRecommendedConfig:()=>deviceIdGeneratorRecommendedConfig,secretGeneratorRecommendedConfig:()=>secretGeneratorRecommendedConfig,userIdGeneratorRecommendedConfig:()=>userIdGeneratorRecommendedConfig,userTokenGeneratorRecommendedConfig:()=>userTokenGeneratorRecommendedConfig});module.exports=__toCommonJS(main_exports);var import_node_crypto=require("node:crypto");var AlwatrHashGenerator=class{constructor(config){this.config=config}generateRandom(){return this.generate((0,import_node_crypto.randomBytes)(16))}generateRandomSelfValidate(){return this.generateSelfValidate((0,import_node_crypto.randomBytes)(16))}generate(data){return this.config.prefix+(0,import_node_crypto.createHash)(this.config.algorithm).update(data).digest(this.config.encoding)}generateCrc(data){const crc=(0,import_node_crypto.createHash)("sha1").update(data).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?crc:crc.slice(0,this.config.crcLength)}generateSelfValidate(data){const mainHash=this.generate(data);const crcHash=this.generateCrc(mainHash);return mainHash+crcHash}verify(data,hash){return hash===this.generate(data)}verifySelfValidate(hash){const gapPos=hash.length-this.config.crcLength;const mainHash=hash.slice(0,gapPos);const crcHash=hash.slice(gapPos);return crcHash===this.generateCrc(mainHash)}};var import_node_crypto2=require("node:crypto");var import_parse_duration=require("@alwatr/parse-duration");var AlwatrTokenGenerator=class{constructor(config){this.config=config;this._duration=config.duration=="infinite"?0:(0,import_parse_duration.parseDuration)(config.duration)}get _epoch(){return this._duration==0?0:Math.floor(Date.now()/this._duration)}generate(data){return this._generate(data,this._epoch)}verify(data,token){const epoch=this._epoch;if(token===this._generate(data,epoch))return"valid";if(this._duration==0)return"invalid";if(token===this._generate(data,epoch-1))return"expired";return"invalid"}_generate(data,epoch){return this.config.prefix+(0,import_node_crypto2.createHmac)(this.config.algorithm,data).update(data+epoch).digest(this.config.encoding)}};var userIdGeneratorRecommendedConfig={prefix:"u",algorithm:"sha1",encoding:"base64url",crcLength:4};var deviceIdGeneratorRecommendedConfig={...userIdGeneratorRecommendedConfig,prefix:"d"};var secretGeneratorRecommendedConfig={prefix:"s",algorithm:"sha384",encoding:"base64url",crcLength:4};var userTokenGeneratorRecommendedConfig={prefix:"t",algorithm:"sha224",encoding:"base64url"};var AlwatrCryptoFactory=class{constructor(config){this._generators={secret:new AlwatrHashGenerator(secretGeneratorRecommendedConfig),deviceId:new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),userId:new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),token:new AlwatrTokenGenerator({...userTokenGeneratorRecommendedConfig,...config})}}generateUserId(){return this._generators.userId.generateRandomSelfValidate()}verifyUserId(userId){return this._generators.userId.verifySelfValidate(userId)}generateToken(uniquelyList){return this._generators.token.generate(uniquelyList.join())}verifyToken(uniquelyList,token){return this._generators.token.verify(uniquelyList.join(),token)}generateSecret(){return this._generators.secret.generateRandomSelfValidate()}verifySecret(secret){return this._generators.secret.verifySelfValidate(secret)}generateDeviceId(){return this._generators.deviceId.generateRandomSelfValidate()}verifyDeviceId(deviceId){return this._generators.deviceId.verifySelfValidate(deviceId)}};0&&(module.exports={AlwatrCryptoFactory,AlwatrHashGenerator,AlwatrTokenGenerator,deviceIdGeneratorRecommendedConfig,secretGeneratorRecommendedConfig,userIdGeneratorRecommendedConfig,userTokenGeneratorRecommendedConfig});
4
- //# sourceMappingURL=main.cjs.map
package/dist/main.cjs.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/main.ts", "../src/hash.ts", "../src/token.ts", "../src/pre-config.ts", "../src/api.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, type BinaryToTextEncoding} from 'node:crypto';\n\nimport type {CryptoAlgorithm} 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: BinaryToTextEncoding;\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 public 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 public 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 public 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 public 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 public 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 public 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 public 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, type BinaryToTextEncoding} from 'node:crypto';\n\nimport {parseDuration, type Duration} from '@alwatr/parse-duration';\n\nimport type {CryptoAlgorithm} 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: BinaryToTextEncoding;\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 public 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 public 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 = /* #__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", "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 {Duration} 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: 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n"],
5
- "mappings": "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",
6
- "names": ["import_node_crypto"]
7
- }
package/dist/main.mjs DELETED
@@ -1,4 +0,0 @@
1
- /** 📦 @alwatr/crypto v4.10.0 */
2
- __dev_mode__: console.debug("📦 @alwatr/crypto v4.10.0");
3
- import{createHash,randomBytes}from"node:crypto";var AlwatrHashGenerator=class{constructor(config){this.config=config}generateRandom(){return this.generate(randomBytes(16))}generateRandomSelfValidate(){return this.generateSelfValidate(randomBytes(16))}generate(data){return this.config.prefix+createHash(this.config.algorithm).update(data).digest(this.config.encoding)}generateCrc(data){const crc=createHash("sha1").update(data).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?crc:crc.slice(0,this.config.crcLength)}generateSelfValidate(data){const mainHash=this.generate(data);const crcHash=this.generateCrc(mainHash);return mainHash+crcHash}verify(data,hash){return hash===this.generate(data)}verifySelfValidate(hash){const gapPos=hash.length-this.config.crcLength;const mainHash=hash.slice(0,gapPos);const crcHash=hash.slice(gapPos);return crcHash===this.generateCrc(mainHash)}};import{createHmac}from"node:crypto";import{parseDuration}from"@alwatr/parse-duration";var AlwatrTokenGenerator=class{constructor(config){this.config=config;this._duration=config.duration=="infinite"?0:parseDuration(config.duration)}get _epoch(){return this._duration==0?0:Math.floor(Date.now()/this._duration)}generate(data){return this._generate(data,this._epoch)}verify(data,token){const epoch=this._epoch;if(token===this._generate(data,epoch))return"valid";if(this._duration==0)return"invalid";if(token===this._generate(data,epoch-1))return"expired";return"invalid"}_generate(data,epoch){return this.config.prefix+createHmac(this.config.algorithm,data).update(data+epoch).digest(this.config.encoding)}};var userIdGeneratorRecommendedConfig={prefix:"u",algorithm:"sha1",encoding:"base64url",crcLength:4};var deviceIdGeneratorRecommendedConfig={...userIdGeneratorRecommendedConfig,prefix:"d"};var secretGeneratorRecommendedConfig={prefix:"s",algorithm:"sha384",encoding:"base64url",crcLength:4};var userTokenGeneratorRecommendedConfig={prefix:"t",algorithm:"sha224",encoding:"base64url"};var AlwatrCryptoFactory=class{constructor(config){this._generators={secret:new AlwatrHashGenerator(secretGeneratorRecommendedConfig),deviceId:new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),userId:new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),token:new AlwatrTokenGenerator({...userTokenGeneratorRecommendedConfig,...config})}}generateUserId(){return this._generators.userId.generateRandomSelfValidate()}verifyUserId(userId){return this._generators.userId.verifySelfValidate(userId)}generateToken(uniquelyList){return this._generators.token.generate(uniquelyList.join())}verifyToken(uniquelyList,token){return this._generators.token.verify(uniquelyList.join(),token)}generateSecret(){return this._generators.secret.generateRandomSelfValidate()}verifySecret(secret){return this._generators.secret.verifySelfValidate(secret)}generateDeviceId(){return this._generators.deviceId.generateRandomSelfValidate()}verifyDeviceId(deviceId){return this._generators.deviceId.verifySelfValidate(deviceId)}};export{AlwatrCryptoFactory,AlwatrHashGenerator,AlwatrTokenGenerator,deviceIdGeneratorRecommendedConfig,secretGeneratorRecommendedConfig,userIdGeneratorRecommendedConfig,userTokenGeneratorRecommendedConfig};
4
- //# sourceMappingURL=main.mjs.map
package/dist/main.mjs.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/hash.ts", "../src/token.ts", "../src/pre-config.ts", "../src/api.ts"],
4
- "sourcesContent": ["import {createHash, randomBytes, type BinaryLike, type BinaryToTextEncoding} from 'node:crypto';\n\nimport type {CryptoAlgorithm} 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: BinaryToTextEncoding;\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 public 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 public 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 public 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 public 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 public 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 public 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 public 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, type BinaryToTextEncoding} from 'node:crypto';\n\nimport {parseDuration, type Duration} from '@alwatr/parse-duration';\n\nimport type {CryptoAlgorithm} 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: BinaryToTextEncoding;\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 public 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 public 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 = /* #__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", "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 {Duration} 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: 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n"],
5
- "mappings": "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",
6
- "names": []
7
- }