@alwatr/crypto 4.10.1 → 9.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +5 -0
- package/dist/main.js.map +13 -0
- package/package.json +48 -52
- package/src/api.ts +168 -0
- package/src/hash.ts +135 -0
- package/src/main.ts +5 -0
- package/src/pre-config.ts +39 -0
- package/src/token.ts +105 -0
- package/src/type.ts +5 -0
- package/CHANGELOG.md +0 -449
- package/dist/main.cjs +0 -4
- package/dist/main.cjs.map +0 -7
- package/dist/main.mjs +0 -4
- package/dist/main.mjs.map +0 -7
package/dist/main.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/* 📦 @alwatr/crypto v9.1.1 */
|
|
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=230B2514A9C168F864756E2164756E21
|
|
5
|
+
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
ADDED
|
@@ -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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
|
|
13
|
+
}
|
package/package.json
CHANGED
|
@@ -1,33 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/crypto",
|
|
3
|
+
"version": "9.1.1",
|
|
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
|
-
"
|
|
5
|
-
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
|
|
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/next/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.
|
|
23
|
-
"
|
|
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.1"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@alwatr/nano-build": "9.1.1",
|
|
28
|
+
"@alwatr/tsconfig-base": "9.1.1",
|
|
29
|
+
"@alwatr/type-helper": "9.1.1",
|
|
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
|
-
"
|
|
28
|
-
"
|
|
50
|
+
"dist",
|
|
51
|
+
"src/**/*.ts",
|
|
52
|
+
"!src/**/*.test.ts",
|
|
53
|
+
"README.md",
|
|
54
|
+
"LICENSE"
|
|
29
55
|
],
|
|
30
|
-
"
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
},
|
|
31
59
|
"keywords": [
|
|
32
60
|
"access",
|
|
33
61
|
"alwatr",
|
|
@@ -42,39 +70,7 @@
|
|
|
42
70
|
"otp-token",
|
|
43
71
|
"time",
|
|
44
72
|
"token",
|
|
45
|
-
"token",
|
|
46
73
|
"typescript"
|
|
47
74
|
],
|
|
48
|
-
"
|
|
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
|
-
"sideEffects": false,
|
|
77
|
-
"type": "module",
|
|
78
|
-
"types": "./dist/main.d.ts",
|
|
79
|
-
"gitHead": "e077211736b90023d4842a23b252dc5284d0445a"
|
|
75
|
+
"gitHead": "38fb79dd8b6cf48108ae6492ecd7a285c7633e9b"
|
|
80
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,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
package/CHANGELOG.md
DELETED
|
@@ -1,449 +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.1](https://github.com/Alwatr/nanotron/compare/v4.10.0...v4.10.1) (2025-09-21)
|
|
7
|
-
|
|
8
|
-
### 🧹 Miscellaneous Chores
|
|
9
|
-
|
|
10
|
-
* add "sideEffects": false to package.json files for better tree-shaking ([2aae07b](https://github.com/Alwatr/nanotron/commit/2aae07b0e1757b6035ea0ca8c1b0eda64a13dfcc))
|
|
11
|
-
|
|
12
|
-
## [4.10.0](https://github.com/Alwatr/nanotron/compare/v4.9.4...v4.10.0) (2025-09-21)
|
|
13
|
-
|
|
14
|
-
### 🐛 Bug Fixes
|
|
15
|
-
|
|
16
|
-
* make generate and verify methods public in AlwatrTokenGenerator class ([637666f](https://github.com/Alwatr/nanotron/commit/637666f8326e8696c6bdb2400ea207fe05d6cc40))
|
|
17
|
-
* update import for Duration type from '@alwatr/parse-duration' ([a365b18](https://github.com/Alwatr/nanotron/commit/a365b18577124d7f4f62ed48c8d639554362d530))
|
|
18
|
-
* update import path for parseDuration from nanolib to parse-duration ([5c390a2](https://github.com/Alwatr/nanotron/commit/5c390a2bd3299a82789b125458016c93ff9b47d5))
|
|
19
|
-
|
|
20
|
-
### 🔨 Code Refactoring
|
|
21
|
-
|
|
22
|
-
* add public access modifiers to methods in AlwatrHashGenerator ([e54d186](https://github.com/Alwatr/nanotron/commit/e54d1863a05339cf23b75305f809f2b11e0087c2))
|
|
23
|
-
* update access modifiers to public for methods in AlwatrCryptoFactory ([2dd01fd](https://github.com/Alwatr/nanotron/commit/2dd01fd3465ad1f8c26980a809333c7036abed6b))
|
|
24
|
-
|
|
25
|
-
### 🧹 Miscellaneous Chores
|
|
26
|
-
|
|
27
|
-
* remove Exir Studio sponsorship logo from multiple README files ([af3fd5d](https://github.com/Alwatr/nanotron/commit/af3fd5dda9b57d0948003db1feb0dc2dad4883d7))
|
|
28
|
-
* remove unused types from compiler options in tsconfig.json ([a65a484](https://github.com/Alwatr/nanotron/commit/a65a484cbf96ae4e36a395620b2940e3bcc221c0))
|
|
29
|
-
* 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))
|
|
30
|
-
* update @alwatr/nanolib and related dependencies to version 6.x ([d824f0d](https://github.com/Alwatr/nanotron/commit/d824f0d5b8e008ec758842997a6e2ee6f7d078d5))
|
|
31
|
-
* update licenses from AGPL-3.0 to MPL-2.0 ([a84513e](https://github.com/Alwatr/nanotron/commit/a84513efbe12b9570c7550c887f2cdfbf67fc82b))
|
|
32
|
-
|
|
33
|
-
### 🔗 Dependencies update
|
|
34
|
-
|
|
35
|
-
* replace @alwatr/nanolib with @alwatr/parse-duration in package.json ([b7d3841](https://github.com/Alwatr/nanotron/commit/b7d38412d1bc72c682c13c576640161d8a231ebc))
|
|
36
|
-
|
|
37
|
-
## [4.9.4](https://github.com/Alwatr/nanotron/compare/v4.9.3...v4.9.4) (2025-08-23)
|
|
38
|
-
|
|
39
|
-
### 🔨 Code Refactoring
|
|
40
|
-
|
|
41
|
-
* reorganize package.json files for consistency and clarity ([bde116e](https://github.com/Alwatr/nanotron/commit/bde116e21f9d9bd6084940e257438916d2c3d312)) by @alimd
|
|
42
|
-
|
|
43
|
-
### 🔗 Dependencies update
|
|
44
|
-
|
|
45
|
-
* downgrade @types/node version to 22.17.2 in all package.json files ([4f01e14](https://github.com/Alwatr/nanotron/commit/4f01e1408d8d0954865eb9d20f90178f13e98719)) by @alimd
|
|
46
|
-
* update dependencies for eslint-config, lerna-lite, typescript, and nanolib ([de16a71](https://github.com/Alwatr/nanotron/commit/de16a718bb1c0fa569d39c824ec39a1e67ef8dfe)) by @alimd
|
|
47
|
-
|
|
48
|
-
## [4.9.3](https://github.com/Alwatr/nanotron/compare/v4.9.2...v4.9.3) (2025-07-23)
|
|
49
|
-
|
|
50
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
51
|
-
|
|
52
|
-
## [4.9.2](https://github.com/Alwatr/nanotron/compare/v4.9.1...v4.9.2) (2025-07-23)
|
|
53
|
-
|
|
54
|
-
### Dependencies update
|
|
55
|
-
|
|
56
|
-
* update dependencies to latest versions ([353d048](https://github.com/Alwatr/nanotron/commit/353d0485a5c21ab219d84cd0a6c35f62b46c2da9)) by @alimd
|
|
57
|
-
|
|
58
|
-
## [4.9.1](https://github.com/Alwatr/nanotron/compare/v4.9.0...v4.9.1) (2025-03-06)
|
|
59
|
-
|
|
60
|
-
### Dependencies update
|
|
61
|
-
|
|
62
|
-
* **deps-dev:** bump the dependencies group with 5 updates ([e6a00eb](https://github.com/Alwatr/nanotron/commit/e6a00eb139f70f2396ecf12b68103b40aa785521)) by @dependabot[bot]
|
|
63
|
-
* 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 @
|
|
64
|
-
|
|
65
|
-
## [4.9.0](https://github.com/Alwatr/nanotron/compare/v4.8.1...v4.9.0) (2025-02-26)
|
|
66
|
-
|
|
67
|
-
### Features
|
|
68
|
-
|
|
69
|
-
* **crypto:** add 'ascii' and 'utf8' to CryptoEncoding type ([aa2720f](https://github.com/Alwatr/nanotron/commit/aa2720f6f7b128a572d8591dc7a75ac15ed6d2d6)) by @alimd
|
|
70
|
-
|
|
71
|
-
### Code Refactoring
|
|
72
|
-
|
|
73
|
-
* **crypto:** replace CryptoEncoding with BinaryToTextEncoding in hash and token configurations ([8e356cd](https://github.com/Alwatr/nanotron/commit/8e356cd60ee438d1f2d2ab688468944d8b6bd99e)) by @alimd
|
|
74
|
-
|
|
75
|
-
### Dependencies update
|
|
76
|
-
|
|
77
|
-
* 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
|
|
78
|
-
|
|
79
|
-
## [4.8.1](https://github.com/Alwatr/nanotron/compare/v4.8.0...v4.8.1) (2025-02-18)
|
|
80
|
-
|
|
81
|
-
### Dependencies update
|
|
82
|
-
|
|
83
|
-
* **deps-dev:** bump the dependencies group across 1 directory with 11 updates ([9257e08](https://github.com/Alwatr/nanotron/commit/9257e08b96f5661a7e13e153b9c71d9dbc08fd18)) by @dependabot[bot]
|
|
84
|
-
* update TypeScript, Prettier, and various dependencies to latest versions ([5c0f752](https://github.com/Alwatr/nanotron/commit/5c0f7521851acaabb2466e459754c130d7ebf31b)) by @
|
|
85
|
-
|
|
86
|
-
## [4.6.0](https://github.com/Alwatr/nanotron/compare/v4.5.2...v4.6.0) (2024-11-07)
|
|
87
|
-
|
|
88
|
-
### Dependencies update
|
|
89
|
-
|
|
90
|
-
* **deps-dev:** bump @types/node in the dependencies group ([9901819](https://github.com/Alwatr/nanotron/commit/9901819d0a7fef85736951f354bc1846294bb7fe)) by @dependabot[bot]
|
|
91
|
-
* **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]
|
|
92
|
-
|
|
93
|
-
## [4.5.2](https://github.com/Alwatr/nanotron/compare/v4.5.1...v4.5.2) (2024-11-02)
|
|
94
|
-
|
|
95
|
-
### Dependencies update
|
|
96
|
-
|
|
97
|
-
* **deps:** bump the alwatr group with 6 updates ([6636bb3](https://github.com/Alwatr/nanotron/commit/6636bb307401e28863eb27288d5abbaab2d67e18)) by @dependabot[bot]
|
|
98
|
-
* update ([86fbeb6](https://github.com/Alwatr/nanotron/commit/86fbeb663d94452f3596d0894ec19d4c6bed3099)) by @
|
|
99
|
-
|
|
100
|
-
## [4.5.0](https://github.com/Alwatr/nanotron/compare/v4.4.1...v4.5.0) (2024-10-28)
|
|
101
|
-
|
|
102
|
-
### Bug Fixes
|
|
103
|
-
|
|
104
|
-
* **crypto:** remove side effects ([852e035](https://github.com/Alwatr/nanotron/commit/852e035d6ffceec32f7b4d2197140a27b4afb330)) by @AliMD
|
|
105
|
-
|
|
106
|
-
### Dependencies update
|
|
107
|
-
|
|
108
|
-
* bump the development-dependencies group across 1 directory with 2 updates ([8b3e101](https://github.com/Alwatr/nanotron/commit/8b3e10128af769ef95a2e7b2ed788e843eb47414)) by @dependabot[bot]
|
|
109
|
-
* update nanolib v1.4.0 and other deps ([b8e7be7](https://github.com/Alwatr/nanotron/commit/b8e7be7b6c58d4f1cbc12593b2d6124f3d19b377)) by @
|
|
110
|
-
|
|
111
|
-
## [4.4.1](https://github.com/Alwatr/nanotron/compare/v4.4.0...v4.4.1) (2024-10-16)
|
|
112
|
-
|
|
113
|
-
### Dependencies update
|
|
114
|
-
|
|
115
|
-
* update ([8917c2e](https://github.com/Alwatr/nanotron/commit/8917c2e637781fe219c5031f414de3dea82cf371)) by @
|
|
116
|
-
|
|
117
|
-
## [4.3.0](https://github.com/Alwatr/nanotron/compare/v4.2.2...v4.3.0) (2024-10-11)
|
|
118
|
-
|
|
119
|
-
### Features
|
|
120
|
-
|
|
121
|
-
* 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
|
|
122
|
-
|
|
123
|
-
### Bug Fixes
|
|
124
|
-
|
|
125
|
-
* **crypto:** update types & `logger` & use `packageTracer` based on last changes of `nanolib` ([cf1a480](https://github.com/Alwatr/nanotron/commit/cf1a48071fe745226f6aed2afdf11038da5065e2)) by @mohammadhonarvar
|
|
126
|
-
|
|
127
|
-
### Code Refactoring
|
|
128
|
-
|
|
129
|
-
* update `import`s & packages based on the latest changes of `nanolib` ([7652b5d](https://github.com/Alwatr/nanotron/commit/7652b5d9cc69218f2ff28bda3d0d8f52f147c6f6)) by @mohammadhonarvar
|
|
130
|
-
|
|
131
|
-
### Miscellaneous Chores
|
|
132
|
-
|
|
133
|
-
* edited README ([d707d38](https://github.com/Alwatr/nanotron/commit/d707d389e085dd320402521cb23af5805013d777)) by @ArmanAsadian
|
|
134
|
-
|
|
135
|
-
### Dependencies update
|
|
136
|
-
|
|
137
|
-
* update ([834ffcc](https://github.com/Alwatr/nanotron/commit/834ffcc8f6de96cc11a1a6fa933f948b7813cde6)) by @mohammadhonarvar
|
|
138
|
-
|
|
139
|
-
## [4.2.2](https://github.com/Alwatr/nanotron/compare/v4.2.1...v4.2.2) (2024-09-29)
|
|
140
|
-
|
|
141
|
-
### Miscellaneous Chores
|
|
142
|
-
|
|
143
|
-
* **crypto:** change the license to AGPL-3.0 ([a37fb50](https://github.com/Alwatr/nanotron/commit/a37fb50898bb0bc909746f44bc34d14bcf255a61)) by @ArmanAsadian
|
|
144
|
-
|
|
145
|
-
### Dependencies update
|
|
146
|
-
|
|
147
|
-
* bump @types/node in the development-dependencies group ([9c8d7d5](https://github.com/Alwatr/nanotron/commit/9c8d7d518d9a5da2ea57ac2b210a8697267e6d3d)) by @dependabot[bot]
|
|
148
|
-
* update ([1c4ef63](https://github.com/Alwatr/nanotron/commit/1c4ef635fc969d4abd416aea2b954de674748da8)) by @AliMD
|
|
149
|
-
|
|
150
|
-
## [4.2.1](https://github.com/Alwatr/nanotron/compare/v4.2.0...v4.2.1) (2024-09-24)
|
|
151
|
-
|
|
152
|
-
### Dependencies update
|
|
153
|
-
|
|
154
|
-
* update ([e698199](https://github.com/Alwatr/nanotron/commit/e698199e4a41532de8e9c799db96b9bde2a647f6)) by @AliMD
|
|
155
|
-
|
|
156
|
-
## [4.2.0](https://github.com/Alwatr/nanotron/compare/v4.1.0...v4.2.0) (2024-09-23)
|
|
157
|
-
|
|
158
|
-
### Dependencies update
|
|
159
|
-
|
|
160
|
-
* bump the alwatr-dependencies group with 6 updates ([1c8a8ec](https://github.com/Alwatr/nanotron/commit/1c8a8ec468aa31c79de45f0e897cc45578242981)) by @dependabot[bot]
|
|
161
|
-
* bump the development-dependencies group with 2 updates ([e3bc7f7](https://github.com/Alwatr/nanotron/commit/e3bc7f7dcbf1779a3fdf8fbe18c4f8b4095cc222)) by @dependabot[bot]
|
|
162
|
-
* update ([d9f8d57](https://github.com/Alwatr/nanotron/commit/d9f8d577b058b4e945db7dfc1c5c68da78c4112f)) by @AliMD
|
|
163
|
-
|
|
164
|
-
## [4.0.2](https://github.com/Alwatr/nanotron/compare/v4.0.1...v4.0.2) (2024-09-14)
|
|
165
|
-
|
|
166
|
-
### Bug Fixes
|
|
167
|
-
|
|
168
|
-
* definePackage ([a2edcc1](https://github.com/Alwatr/nanotron/commit/a2edcc1b3a4822371cefa4a28ff62a7c6754287e)) by @AliMD
|
|
169
|
-
|
|
170
|
-
## [4.0.0](https://github.com/Alwatr/nanotron/compare/v4.0.0-alpha.3...v4.0.0) (2024-09-14)
|
|
171
|
-
|
|
172
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
173
|
-
|
|
174
|
-
## [4.0.0-alpha.0](https://github.com/Alwatr/nanotron/compare/v1.2.7...v4.0.0-alpha.0) (2024-09-10)
|
|
175
|
-
|
|
176
|
-
### Bug Fixes
|
|
177
|
-
|
|
178
|
-
* build issue after update package.json ([9df6a58](https://github.com/Alwatr/nanotron/commit/9df6a5866d2b5542e89788f1cf2a1bea5cc369d3)) by @njfamirm
|
|
179
|
-
|
|
180
|
-
### Code Refactoring
|
|
181
|
-
|
|
182
|
-
* Update import paths for duration parsing ([97dd8aa](https://github.com/Alwatr/nanotron/commit/97dd8aa68e050127e444ef268e48246b6b7318c6)) by @AliMD
|
|
183
|
-
* 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
|
|
184
|
-
|
|
185
|
-
### Miscellaneous Chores
|
|
186
|
-
|
|
187
|
-
* add required deps ([32b8ade](https://github.com/Alwatr/nanotron/commit/32b8adeba96dbd68879d004fe44f2f2c88b2b624)) by @njfamirm
|
|
188
|
-
* update package.json of each package from nanolib ([b8a7c8a](https://github.com/Alwatr/nanotron/commit/b8a7c8af9f88d36ac3c1ab6324b78890dc2023b3)) by @njfamirm
|
|
189
|
-
|
|
190
|
-
### Dependencies update
|
|
191
|
-
|
|
192
|
-
* update ([f95134f](https://github.com/Alwatr/nanotron/commit/f95134fe5a4b61ee01eb84450807efb9ef099010)) by @AliMD
|
|
193
|
-
|
|
194
|
-
## [3.0.4](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.3...@alwatr/crypto@3.0.4) (2023-12-19)
|
|
195
|
-
|
|
196
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
197
|
-
|
|
198
|
-
## [3.0.3](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.2...@alwatr/crypto@3.0.3) (2023-12-19)
|
|
199
|
-
|
|
200
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
201
|
-
|
|
202
|
-
## [3.0.2](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.1...@alwatr/crypto@3.0.2) (2023-12-11)
|
|
203
|
-
|
|
204
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
205
|
-
|
|
206
|
-
## [3.0.1](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.0...@alwatr/crypto@3.0.1) (2023-12-11)
|
|
207
|
-
|
|
208
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
209
|
-
|
|
210
|
-
# [3.0.0](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@2.0.0...@alwatr/crypto@3.0.0) (2023-12-09)
|
|
211
|
-
|
|
212
|
-
### Bug Fixes
|
|
213
|
-
|
|
214
|
-
* **crypto:** use import type ([30e3bac](https://github.com/Alwatr/alwatr-es-sdk/commit/30e3bacb187d58417cb62e2a1511de4ade3f80c0)) by @njfamirm
|
|
215
|
-
|
|
216
|
-
### Features
|
|
217
|
-
|
|
218
|
-
* **crypto/api:** AlwatrCryptoFactory with secret and device id ([2d754a1](https://github.com/Alwatr/alwatr-es-sdk/commit/2d754a19b2f04f64d0828e31ba004fc192f466d3)) by @njfamirm
|
|
219
|
-
* **crypto/api:** device id generator preconfig ([71e80d6](https://github.com/Alwatr/alwatr-es-sdk/commit/71e80d63743579505a6be17d014c364e9f6cf55c)) by @njfamirm
|
|
220
|
-
* **crypto:** complete rewrite with new api ([3d56861](https://github.com/Alwatr/alwatr-es-sdk/commit/3d56861a2857e760c7cd5f03be98f003738fc7a9)) by @AliMD
|
|
221
|
-
* **crypto:** rename user file to api ([52343ea](https://github.com/Alwatr/alwatr-es-sdk/commit/52343ead04c23f50bedac2caa01f46bf489ab318)) by @njfamirm
|
|
222
|
-
|
|
223
|
-
### BREAKING CHANGES
|
|
224
|
-
|
|
225
|
-
* **crypto:** new api
|
|
226
|
-
* **crypto/api:** rename AlwatrUserGenerator to AlwatrCryptoFactory and change config
|
|
227
|
-
|
|
228
|
-
# [2.0.0](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.2.1...@alwatr/crypto@2.0.0) (2023-11-29)
|
|
229
|
-
|
|
230
|
-
### Features
|
|
231
|
-
|
|
232
|
-
* **crypto/hash:** review and update all methods and documents ([14acd26](https://github.com/Alwatr/eslib/commit/14acd265a19b1b67bd32f725468fe66985464fe6)) by @AliMD
|
|
233
|
-
* **crypto/preConfig:** update prefix and secret algorithm ([0cfff12](https://github.com/Alwatr/eslib/commit/0cfff124e692d02aad0b5c97908df63bc692f896)) by @AliMD
|
|
234
|
-
* **crypto/token:** review and update all methods and documents ([dc943f8](https://github.com/Alwatr/eslib/commit/dc943f8a007567b58e9e3b7f9cada556ac76ae9b)) by @AliMD
|
|
235
|
-
* **crypto/user:** review and update all methods and documents ([bb79fa8](https://github.com/Alwatr/eslib/commit/bb79fa81f8632d5fe75cac813238b04094d0bb6a)) by @AliMD
|
|
236
|
-
* **crypto:** prefix option ([6be5c90](https://github.com/Alwatr/eslib/commit/6be5c90dad4674e8ae3e27611a13dcf1e08ce11a)) by @AliMD
|
|
237
|
-
|
|
238
|
-
### BREAKING CHANGES
|
|
239
|
-
|
|
240
|
-
* **crypto/user:** methods name updated
|
|
241
|
-
* **crypto/token:** methods name updated
|
|
242
|
-
* **crypto/hash:** methods name updated
|
|
243
|
-
|
|
244
|
-
## [1.2.1](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.2.0...@alwatr/crypto@1.2.1) (2023-11-23)
|
|
245
|
-
|
|
246
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
247
|
-
|
|
248
|
-
# [1.2.0](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.12...@alwatr/crypto@1.2.0) (2023-11-14)
|
|
249
|
-
|
|
250
|
-
### Features
|
|
251
|
-
|
|
252
|
-
* **yarn:** pnp ([b6a562c](https://github.com/Alwatr/eslib/commit/b6a562c909a35b3e626442e5c325da3fce448e1b)) by @AliMD
|
|
253
|
-
|
|
254
|
-
## [1.1.12](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.11...@alwatr/crypto@1.1.12) (2023-11-08)
|
|
255
|
-
|
|
256
|
-
### Bug Fixes
|
|
257
|
-
|
|
258
|
-
* move repo urls ([719aa3e](https://github.com/Alwatr/eslib/commit/719aa3e7462d3c9c6272958fc93f89fda6793fb1)) by @AliMD
|
|
259
|
-
|
|
260
|
-
## [1.1.11](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.10...@alwatr/crypto@1.1.11) (2023-11-01)
|
|
261
|
-
|
|
262
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
263
|
-
|
|
264
|
-
## [1.1.10](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.9...@alwatr/crypto@1.1.10) (2023-10-23)
|
|
265
|
-
|
|
266
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
267
|
-
|
|
268
|
-
## [1.1.9](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.8...@alwatr/crypto@1.1.9) (2023-10-23)
|
|
269
|
-
|
|
270
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
271
|
-
|
|
272
|
-
## [1.1.8](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.7...@alwatr/crypto@1.1.8) (2023-10-23)
|
|
273
|
-
|
|
274
|
-
### Bug Fixes
|
|
275
|
-
|
|
276
|
-
* **crypto:** compatible with new logger api ([f867317](https://github.com/Alwatr/eslib/commit/f8673178d18f14276e13dcb35a7d973f301a722b)) by @AliMD
|
|
277
|
-
|
|
278
|
-
## [1.1.7](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.6...@alwatr/crypto@1.1.7) (2023-10-23)
|
|
279
|
-
|
|
280
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
281
|
-
|
|
282
|
-
## [1.1.6](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.5...@alwatr/crypto@1.1.6) (2023-10-23)
|
|
283
|
-
|
|
284
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
285
|
-
|
|
286
|
-
## [1.1.5](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.4...@alwatr/crypto@1.1.5) (2023-09-19)
|
|
287
|
-
|
|
288
|
-
### Bug Fixes
|
|
289
|
-
|
|
290
|
-
- package repo urls ([466cbe9](https://github.com/Alwatr/eslib/commit/466cbe9188f24e1a1bc36d879a95b52538a58f16)) by @AliMD
|
|
291
|
-
|
|
292
|
-
## [1.1.4](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.3...@alwatr/crypto@1.1.4) (2023-09-19)
|
|
293
|
-
|
|
294
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
295
|
-
|
|
296
|
-
## 1.1.3 (2023-09-19)
|
|
297
|
-
|
|
298
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
299
|
-
|
|
300
|
-
## [1.1.2](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.1...@alwatr/crypto@1.1.2) (2023-09-12)
|
|
301
|
-
|
|
302
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
303
|
-
|
|
304
|
-
## [1.1.1](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.1.0...@alwatr/crypto@1.1.1) (2023-09-12)
|
|
305
|
-
|
|
306
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
307
|
-
|
|
308
|
-
# 1.1.0 (2023-09-12)
|
|
309
|
-
|
|
310
|
-
# 1.0.0 (2023-06-14)
|
|
311
|
-
|
|
312
|
-
# 0.32.0 (2023-05-27)
|
|
313
|
-
|
|
314
|
-
### Features
|
|
315
|
-
|
|
316
|
-
- **crypto:** add some pre config ([4b960c5](https://github.com/Alwatr/eslib/commit/4b960c5cb3f7495c0689adcb65c62a1032ae2650))
|
|
317
|
-
|
|
318
|
-
### Performance Improvements
|
|
319
|
-
|
|
320
|
-
- **crypto/hash:** enhance crc generator ([ba8c4bc](https://github.com/Alwatr/eslib/commit/ba8c4bcf8f9ec9767b0bd3b6c3fd5c4f503a84dd))
|
|
321
|
-
|
|
322
|
-
# 0.31.0 (2023-05-08)
|
|
323
|
-
|
|
324
|
-
### Bug Fixes
|
|
325
|
-
|
|
326
|
-
- **crypto:** package ([866c5f4](https://github.com/Alwatr/eslib/commit/866c5f490ea2eaa75bf177f35b3f4711931e13d2))
|
|
327
|
-
|
|
328
|
-
### Features
|
|
329
|
-
|
|
330
|
-
- **crypto:** make prefix for userId ([5baa00a](https://github.com/Alwatr/eslib/commit/5baa00aafb16a4c6ed1d77913edddd090f732dad))
|
|
331
|
-
|
|
332
|
-
# [1.0.0](https://github.com/Alwatr/eslib/compare/v0.32.0...v1.0.0) (2023-06-14)
|
|
333
|
-
|
|
334
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
335
|
-
|
|
336
|
-
# [0.32.0](https://github.com/Alwatr/eslib/compare/v0.31.0...v0.32.0) (2023-05-27)
|
|
337
|
-
|
|
338
|
-
### Features
|
|
339
|
-
|
|
340
|
-
- **crypto:** add some pre config ([4b960c5](https://github.com/Alwatr/eslib/commit/4b960c5cb3f7495c0689adcb65c62a1032ae2650))
|
|
341
|
-
|
|
342
|
-
### Performance Improvements
|
|
343
|
-
|
|
344
|
-
- **crypto/hash:** enhance crc generator ([ba8c4bc](https://github.com/Alwatr/eslib/commit/ba8c4bcf8f9ec9767b0bd3b6c3fd5c4f503a84dd))
|
|
345
|
-
|
|
346
|
-
# [0.31.0](https://github.com/Alwatr/eslib/compare/v0.30.0...v0.31.0) (2023-05-08)
|
|
347
|
-
|
|
348
|
-
### Bug Fixes
|
|
349
|
-
|
|
350
|
-
- **crypto:** package ([866c5f4](https://github.com/Alwatr/eslib/commit/866c5f490ea2eaa75bf177f35b3f4711931e13d2))
|
|
351
|
-
|
|
352
|
-
### Features
|
|
353
|
-
|
|
354
|
-
- **crypto:** make prefix for userId ([5baa00a](https://github.com/Alwatr/eslib/commit/5baa00aafb16a4c6ed1d77913edddd090f732dad))
|
|
355
|
-
|
|
356
|
-
# [0.30.0](https://github.com/Alwatr/eslib/compare/v0.29.0...v0.30.0) (2023-03-06)
|
|
357
|
-
|
|
358
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
359
|
-
|
|
360
|
-
# [0.29.0](https://github.com/Alwatr/eslib/compare/v0.28.0...v0.29.0) (2023-02-10)
|
|
361
|
-
|
|
362
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
363
|
-
|
|
364
|
-
# [0.28.0](https://github.com/Alwatr/eslib/compare/v0.27.0...v0.28.0) (2023-01-20)
|
|
365
|
-
|
|
366
|
-
### Bug Fixes
|
|
367
|
-
|
|
368
|
-
- **token:** types ([a7da60e](https://github.com/Alwatr/eslib/commit/a7da60e720ac83b8d2d2ed5c0b811dea1952a2b9))
|
|
369
|
-
|
|
370
|
-
### Features
|
|
371
|
-
|
|
372
|
-
- **token:** generate and verify token without expiration time ([6db78f0](https://github.com/Alwatr/eslib/commit/6db78f0644e076c3401a263173d7139838bbbf0c))
|
|
373
|
-
- **type:** define math types ([8c19f40](https://github.com/Alwatr/eslib/commit/8c19f4058d4361b7d3f4f714595e34cb6fa21109))
|
|
374
|
-
|
|
375
|
-
# [0.27.0](https://github.com/Alwatr/eslib/compare/v0.26.0...v0.27.0) (2022-12-29)
|
|
376
|
-
|
|
377
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
378
|
-
|
|
379
|
-
# [0.26.0](https://github.com/Alwatr/eslib/compare/v0.25.0...v0.26.0) (2022-12-22)
|
|
380
|
-
|
|
381
|
-
### Bug Fixes
|
|
382
|
-
|
|
383
|
-
- set correct path ([d01ce6f](https://github.com/Alwatr/eslib/commit/d01ce6ffa749a5e3e0e11e35b4ed61d75d61fec9))
|
|
384
|
-
- tsconfig ([e96dcd3](https://github.com/Alwatr/eslib/commit/e96dcd30774a9f06f7d051e0504192cbbe019e35))
|
|
385
|
-
|
|
386
|
-
# [0.25.0](https://github.com/Alwatr/eslib/compare/v0.24.1...v0.25.0) (2022-12-07)
|
|
387
|
-
|
|
388
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
389
|
-
|
|
390
|
-
## [0.24.1](https://github.com/Alwatr/eslib/compare/v0.24.0...v0.24.1) (2022-12-01)
|
|
391
|
-
|
|
392
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
393
|
-
|
|
394
|
-
# [0.24.0](https://github.com/Alwatr/eslib/compare/v0.23.0...v0.24.0) (2022-11-28)
|
|
395
|
-
|
|
396
|
-
### Bug Fixes
|
|
397
|
-
|
|
398
|
-
- use ~ for package version ([4e027ff](https://github.com/Alwatr/eslib/commit/4e027ff63875e03b088ebcdc1bdf2495f4494eec))
|
|
399
|
-
|
|
400
|
-
# [0.23.0](https://github.com/Alwatr/eslib/compare/v0.22.1...v0.23.0) (2022-11-23)
|
|
401
|
-
|
|
402
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
403
|
-
|
|
404
|
-
## [0.22.1](https://github.com/Alwatr/eslib/compare/v0.22.0...v0.22.1) (2022-11-21)
|
|
405
|
-
|
|
406
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
407
|
-
|
|
408
|
-
# [0.22.0](https://github.com/Alwatr/eslib/compare/v0.21.0...v0.22.0) (2022-11-20)
|
|
409
|
-
|
|
410
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
411
|
-
|
|
412
|
-
# [0.21.0](https://github.com/Alwatr/eslib/compare/v0.20.0...v0.21.0) (2022-11-13)
|
|
413
|
-
|
|
414
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
415
|
-
|
|
416
|
-
# [0.20.0](https://github.com/Alwatr/eslib/compare/v0.19.0...v0.20.0) (2022-11-05)
|
|
417
|
-
|
|
418
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
419
|
-
|
|
420
|
-
# [0.19.0](https://github.com/Alwatr/eslib/compare/v0.18.0...v0.19.0) (2022-11-01)
|
|
421
|
-
|
|
422
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
423
|
-
|
|
424
|
-
# [0.18.0](https://github.com/Alwatr/eslib/compare/v0.17.0...v0.18.0) (2022-10-22)
|
|
425
|
-
|
|
426
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
427
|
-
|
|
428
|
-
# [0.17.0](https://github.com/Alwatr/eslib/compare/v0.16.1...v0.17.0) (2022-10-21)
|
|
429
|
-
|
|
430
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
431
|
-
|
|
432
|
-
# [0.16.0](https://github.com/Alwatr/eslib/compare/v0.15.0...v0.16.0) (2022-09-08)
|
|
433
|
-
|
|
434
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
435
|
-
|
|
436
|
-
# [0.15.0](https://github.com/Alwatr/eslib/compare/v0.14.0...v0.15.0) (2022-09-01)
|
|
437
|
-
|
|
438
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
439
|
-
|
|
440
|
-
# [0.14.0](https://github.com/Alwatr/eslib/compare/v0.13.0...v0.14.0) (2022-08-19)
|
|
441
|
-
|
|
442
|
-
**Note:** Version bump only for package @alwatr/crypto
|
|
443
|
-
|
|
444
|
-
# [0.13.0](https://github.com/Alwatr/eslib/compare/v0.12.0...v0.13.0) (2022-08-06)
|
|
445
|
-
|
|
446
|
-
### Features
|
|
447
|
-
|
|
448
|
-
- **token:** generate and verify HOTP tpkens ([d0372f8](https://github.com/Alwatr/eslib/commit/d0372f805a45d6fd6571b50821529068cec7d424))
|
|
449
|
-
- **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.1 */
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/crypto v4.10.1");
|
|
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": ";;qqBAAA,+fCAA,uBAAkF,uBAgC3E,IAAM,oBAAN,KAA0B,CAK/B,YAAmB,OAA6B,CAA7B,kBAA8B,CAU1C,gBAAyB,CAC9B,OAAO,KAAK,YAAS,gCAAY,EAAE,CAAC,CACtC,CAUO,4BAAqC,CAC1C,OAAO,KAAK,wBAAqB,gCAAY,EAAE,CAAC,CAClD,CAWO,SAAS,KAA0B,CACx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AAmB,QAAQ,CAC9D,CACF",
|
|
6
|
-
"names": ["import_node_crypto"]
|
|
7
|
-
}
|
package/dist/main.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/** 📦 @alwatr/crypto v4.10.1 */
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/crypto v4.10.1");
|
|
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": ";;AAAA,OAAQ,WAAY,gBAA8D,cAgC3E,IAAM,oBAAN,KAA0B,CAK/B,YAAmB,OAA6B,CAA7B,kBAA8B,CAU1C,gBAAyB,CAC9B,OAAO,KAAK,SAAS,YAAY,EAAE,CAAC,CACtC,CAUO,4BAAqC,CAC1C,OAAO,KAAK,qBAAqB,YAAY,EAAE,CAAC,CAClD,CAWO,SAAS,KAA0B,CAC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