@alwatr/crypto 3.0.4 → 4.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,64 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## 4.0.0-alpha.0 (2024-09-10)
7
+
8
+ ### ⚠ BREAKING CHANGES
9
+
10
+ * **crypto:** new api
11
+ * **crypto/api:** rename AlwatrUserGenerator to AlwatrCryptoFactory and change config
12
+ * **crypto/user:** methods name updated
13
+ * **crypto/token:** methods name updated
14
+ * **crypto/hash:** methods name updated
15
+
16
+ ### Features
17
+
18
+ * **crypto/api:** AlwatrCryptoFactory with secret and device id ([2d754a1](https://github.com/Alwatr/nanotron/commit/2d754a19b2f04f64d0828e31ba004fc192f466d3)) by @
19
+ * **crypto/api:** device id generator preconfig ([71e80d6](https://github.com/Alwatr/nanotron/commit/71e80d63743579505a6be17d014c364e9f6cf55c)) by @
20
+ * **crypto/hash:** review and update all methods and documents ([14acd26](https://github.com/Alwatr/nanotron/commit/14acd265a19b1b67bd32f725468fe66985464fe6)) by @
21
+ * **crypto/preConfig:** update prefix and secret algorithm ([0cfff12](https://github.com/Alwatr/nanotron/commit/0cfff124e692d02aad0b5c97908df63bc692f896)) by @
22
+ * **crypto/token:** review and update all methods and documents ([dc943f8](https://github.com/Alwatr/nanotron/commit/dc943f8a007567b58e9e3b7f9cada556ac76ae9b)) by @
23
+ * **crypto/user:** review and update all methods and documents ([bb79fa8](https://github.com/Alwatr/nanotron/commit/bb79fa81f8632d5fe75cac813238b04094d0bb6a)) by @
24
+ * **crypto:** complete rewrite with new api ([3d56861](https://github.com/Alwatr/nanotron/commit/3d56861a2857e760c7cd5f03be98f003738fc7a9)) by @
25
+ * **crypto:** prefix option ([6be5c90](https://github.com/Alwatr/nanotron/commit/6be5c90dad4674e8ae3e27611a13dcf1e08ce11a)) by @
26
+ * **crypto:** rename user file to api ([52343ea](https://github.com/Alwatr/nanotron/commit/52343ead04c23f50bedac2caa01f46bf489ab318)) by @
27
+ * **yarn:** pnp ([b6a562c](https://github.com/Alwatr/nanotron/commit/b6a562c909a35b3e626442e5c325da3fce448e1b)) by @
28
+
29
+ ### Bug Fixes
30
+
31
+ * build issue after update package.json ([9df6a58](https://github.com/Alwatr/nanotron/commit/9df6a5866d2b5542e89788f1cf2a1bea5cc369d3)) by @njfamirm
32
+ * **crypto:** compatible with new logger api ([f867317](https://github.com/Alwatr/nanotron/commit/f8673178d18f14276e13dcb35a7d973f301a722b)) by @
33
+ * **crypto:** use import type ([30e3bac](https://github.com/Alwatr/nanotron/commit/30e3bacb187d58417cb62e2a1511de4ade3f80c0)) by @
34
+ * move repo urls ([719aa3e](https://github.com/Alwatr/nanotron/commit/719aa3e7462d3c9c6272958fc93f89fda6793fb1)) by @
35
+ * package repo urls ([466cbe9](https://github.com/Alwatr/nanotron/commit/466cbe9188f24e1a1bc36d879a95b52538a58f16)) by @
36
+
37
+ ### Code Refactoring
38
+
39
+ * change build config and remove tslib ([81eabfa](https://github.com/Alwatr/nanotron/commit/81eabfa7ba4db432333f11f854e054304e80e922)) by @
40
+ * rename core ro packages ([680604f](https://github.com/Alwatr/nanotron/commit/680604fb6af49273e5ad0745194b7186cb818faa)) by @
41
+ * Update import paths for duration parsing ([97dd8aa](https://github.com/Alwatr/nanotron/commit/97dd8aa68e050127e444ef268e48246b6b7318c6)) by @AliMD
42
+ * 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
43
+
44
+ ### Miscellaneous Chores
45
+
46
+ * add required deps ([32b8ade](https://github.com/Alwatr/nanotron/commit/32b8adeba96dbd68879d004fe44f2f2c88b2b624)) by @njfamirm
47
+ * **crypto:** define package version ([cd54226](https://github.com/Alwatr/nanotron/commit/cd5422634edf7f29f19fb7fccc880397c02c18c0)) by @
48
+ * **deps-dev:** bump the development-dependencies group with 1 update ([97fcdb3](https://github.com/Alwatr/nanotron/commit/97fcdb3487be289c3c6a718335fea9ba441bfef9)) by @
49
+ * **deps-dev:** bump the development-dependencies group with 1 update ([0e580fa](https://github.com/Alwatr/nanotron/commit/0e580fa23274e6ddc626512b00ba5b7612ad9ed4)) by @
50
+ * **deps-dev:** bump the development-dependencies group with 12 updates ([c908185](https://github.com/Alwatr/nanotron/commit/c908185df0bdd4acf361382ec6c1cfbcf6667256)) by @
51
+ * **deps-dev:** bump the development-dependencies group with 4 updates ([0334169](https://github.com/Alwatr/nanotron/commit/033416915a9b8a6d62ce5d1831c31ff953f6c54c)) by @
52
+ * **deps-dev:** bump the development-dependencies group with 5 updates ([64f796d](https://github.com/Alwatr/nanotron/commit/64f796ddfb8b1073da586cfdf526172b20b70903)) by @
53
+ * **deps-dev:** bump the development-dependencies group with 9 updates ([4d50729](https://github.com/Alwatr/nanotron/commit/4d50729cdc8d0fdb6d5a9c0c3b98e3d9ad057a1b)) by @
54
+ * **deps-dev:** bump the development-dependencies group with 9 updates ([e0f9bde](https://github.com/Alwatr/nanotron/commit/e0f9bdeb13fae513334c56d8e6414caca0611fab)) by @
55
+ * rename project ([3f54d28](https://github.com/Alwatr/nanotron/commit/3f54d289c004ee1454f4906ad46baca7e3060d16)) by @
56
+ * update package.json of each package from nanolib ([b8a7c8a](https://github.com/Alwatr/nanotron/commit/b8a7c8af9f88d36ac3c1ab6324b78890dc2023b3)) by @njfamirm
57
+ * update repository url ([3d96754](https://github.com/Alwatr/nanotron/commit/3d96754b11740b18c02e4f11f6a559f90b09d726)) by @
58
+ * **yarn:** fix packages version ([aaf3818](https://github.com/Alwatr/nanotron/commit/aaf381844ac253e9b0e5ffaf2e039a33edee0668)) by @
59
+
60
+ ### Dependencies update
61
+
62
+ * update ([f95134f](https://github.com/Alwatr/nanotron/commit/f95134fe5a4b61ee01eb84450807efb9ef099010)) by @AliMD
63
+
6
64
  ## [3.0.4](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@3.0.3...@alwatr/crypto@3.0.4) (2023-12-19)
7
65
 
8
66
  **Note:** Version bump only for package @alwatr/crypto
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Alwatr Crypto - `@alwatr/crypto`
1
+ # Crypto
2
2
 
3
3
  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
4
 
@@ -1,6 +1,6 @@
1
- import { DurationString } from '@alwatr/math';
2
1
  import { AlwatrHashGenerator } from './hash.js';
3
2
  import { AlwatrTokenGenerator, type TokenValidity } from './token.js';
3
+ import type { DurationString } from '@alwatr/parse-duration';
4
4
  /**
5
5
  * Configuration options for the CryptoFactory.
6
6
  */
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,mBAAmB,EAAC,MAAM,WAAW,CAAC;AAO9C,OAAO,EAAC,oBAAoB,EAAE,KAAK,aAAa,EAAC,MAAM,YAAY,CAAC;AAEpE,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,wBAAwB,CAAC;AAE3D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,QAAQ,EAAE,cAAc,GAAG,UAAU,CAAC;CACvC;AAED;;GAEG;AACH,qBAAa,mBAAmB;IAC9B,SAAS,CAAC,WAAW;;;;;MAAC;IAEtB;;;OAGG;gBACS,MAAM,EAAE,mBAAmB;IAYvC;;;;;;;;;;OAUG;IACH,cAAc,IAAI,MAAM;IAIxB;;;;;;;;;;OAUG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAIrC;;;;;;;;OAQG;IACH,aAAa,CAAC,YAAY,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG,MAAM;IAIxD;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,YAAY,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,aAAa;IAI5E;;;;;;;;;;OAUG;IACH,cAAc,IAAI,MAAM;IAIxB;;;;;;;;;;OAUG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAIrC;;;;;;;OAOG;IACH,gBAAgB,IAAI,MAAM;IAI1B;;;;;;;;;;;;;;OAcG;IACH,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAG1C"}
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { type BinaryLike } from 'node:crypto';
3
2
  import type { CryptoAlgorithm, CryptoEncoding } from './type.js';
4
3
  /**
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../src/hash.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,UAAU,EAAC,MAAM,aAAa,CAAC;AAErE,OAAO,KAAK,EAAC,eAAe,EAAE,cAAc,EAAC,MAAM,WAAW,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,SAAS,EAAE,eAAe,CAAC;IAE3B;;OAEG;IACH,QAAQ,EAAE,cAAc,CAAC;IAEzB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,qBAAa,mBAAmB;IAKX,MAAM,EAAE,mBAAmB;IAJ9C;;;OAGG;gBACgB,MAAM,EAAE,mBAAmB;IAE9C;;;;;;;OAOG;IACH,cAAc,IAAI,MAAM;IAIxB;;;;;;;OAOG;IACH,0BAA0B,IAAI,MAAM;IAIpC;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM;IAIlC;;;;OAIG;IACH,WAAW,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM;IAKrC;;;;;;;;OAQG;IACH,oBAAoB,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM;IAM9C;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO;IAI/C;;;;;;;;;;OAUG;IACH,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;CAM1C"}
package/dist/main.cjs ADDED
@@ -0,0 +1,3 @@
1
+ /* @alwatr/crypto v4.0.0-alpha.0 */
2
+ "use strict";var c=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var v=(t,e)=>{for(var r in e)c(t,r,{get:e[r],enumerable:!0})},_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of C(e))!x.call(t,o)&&o!==r&&c(t,o,{get:()=>e[o],enumerable:!(n=y(e,o))||n.enumerable});return t};var k=t=>_(c({},"__esModule",{value:!0}),t);var G={};v(G,{AlwatrCryptoFactory:()=>h,AlwatrHashGenerator:()=>i,AlwatrTokenGenerator:()=>s,deviceIdGeneratorRecommendedConfig:()=>d,secretGeneratorRecommendedConfig:()=>f,userIdGeneratorRecommendedConfig:()=>g,userTokenGeneratorRecommendedConfig:()=>p});module.exports=k(G);var a=require("node:crypto"),i=class{constructor(e){this.config=e}generateRandom(){return this.generate((0,a.randomBytes)(16))}generateRandomSelfValidate(){return this.generateSelfValidate((0,a.randomBytes)(16))}generate(e){return this.config.prefix+(0,a.createHash)(this.config.algorithm).update(e).digest(this.config.encoding)}generateCrc(e){let r=(0,a.createHash)("sha1").update(e).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?r:r.slice(0,this.config.crcLength)}generateSelfValidate(e){let r=this.generate(e),n=this.generateCrc(r);return r+n}verify(e,r){return r===this.generate(e)}verifySelfValidate(e){let r=e.length-this.config.crcLength,n=e.slice(0,r);return e.slice(r)===this.generateCrc(n)}};var m=require("node:crypto"),u=require("@alwatr/parse-duration"),s=class{constructor(e){this.config=e;this._duration=e.duration=="infinite"?0:(0,u.parseDuration)(e.duration)}get _epoch(){return this._duration==0?0:Math.floor(Date.now()/this._duration)}generate(e){return this._generate(e,this._epoch)}verify(e,r){let n=this._epoch;return r===this._generate(e,n)?"valid":this._duration==0?"invalid":r===this._generate(e,n-1)?"expired":"invalid"}_generate(e,r){return this.config.prefix+(0,m.createHmac)(this.config.algorithm,e).update(e+r).digest(this.config.encoding)}};var g={prefix:"u",algorithm:"sha1",encoding:"base64url",crcLength:4},d={...g,prefix:"d"},f={prefix:"s",algorithm:"sha384",encoding:"base64url",crcLength:4},p={prefix:"t",algorithm:"sha224",encoding:"base64url"};var h=class{constructor(e){this._generators={secret:new i(f),deviceId:new i(d),userId:new i(g),token:new s({...p,...e})}}generateUserId(){return this._generators.userId.generateRandomSelfValidate()}verifyUserId(e){return this._generators.userId.verifySelfValidate(e)}generateToken(e){return this._generators.token.generate(e.join())}verifyToken(e,r){return this._generators.token.verify(e.join(),r)}generateSecret(){return this._generators.secret.generateRandomSelfValidate()}verifySecret(e){return this._generators.secret.verifySelfValidate(e)}generateDeviceId(){return this._generators.deviceId.generateRandomSelfValidate()}verifyDeviceId(e){return this._generators.deviceId.verifySelfValidate(e)}};var l=require("@alwatr/logger");(0,l.definePackage)("crypto","3.x");0&&(module.exports={AlwatrCryptoFactory,AlwatrHashGenerator,AlwatrTokenGenerator,deviceIdGeneratorRecommendedConfig,secretGeneratorRecommendedConfig,userIdGeneratorRecommendedConfig,userTokenGeneratorRecommendedConfig});
3
+ //# sourceMappingURL=main.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/main.ts", "../src/hash.ts", "../src/token.ts", "../src/pre-config.ts", "../src/api.ts"],
4
+ "sourcesContent": ["import {definePackage} from '@alwatr/logger';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('crypto', '3.x');\n", "import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type DurationString} from '@alwatr/parse-duration';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n", "import {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\nimport type {DurationString} from '@alwatr/parse-duration';\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n"],
5
+ "mappings": "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",
6
+ "names": ["main_exports", "__export", "AlwatrCryptoFactory", "AlwatrHashGenerator", "AlwatrTokenGenerator", "deviceIdGeneratorRecommendedConfig", "secretGeneratorRecommendedConfig", "userIdGeneratorRecommendedConfig", "userTokenGeneratorRecommendedConfig", "__toCommonJS", "import_node_crypto", "AlwatrHashGenerator", "config", "data", "crc", "mainHash", "crcHash", "hash", "gapPos", "import_node_crypto", "import_parse_duration", "AlwatrTokenGenerator", "config", "data", "token", "epoch", "userIdGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "secretGeneratorRecommendedConfig", "userTokenGeneratorRecommendedConfig", "AlwatrCryptoFactory", "config", "AlwatrHashGenerator", "secretGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "userIdGeneratorRecommendedConfig", "AlwatrTokenGenerator", "userTokenGeneratorRecommendedConfig", "userId", "uniquelyList", "token", "secret", "deviceId", "import_logger"]
7
+ }
@@ -3,4 +3,4 @@ export * from './token.js';
3
3
  export * from './api.js';
4
4
  export * from './type.js';
5
5
  export * from './pre-config.js';
6
- //# sourceMappingURL=index.d.ts.map
6
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAEA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC"}
package/dist/main.mjs ADDED
@@ -0,0 +1,3 @@
1
+ /* @alwatr/crypto v4.0.0-alpha.0 */
2
+ import{createHash as s,randomBytes as g}from"node:crypto";var n=class{constructor(e){this.config=e}generateRandom(){return this.generate(g(16))}generateRandomSelfValidate(){return this.generateSelfValidate(g(16))}generate(e){return this.config.prefix+s(this.config.algorithm).update(e).digest(this.config.encoding)}generateCrc(e){let r=s("sha1").update(e).digest(this.config.encoding);return this.config.crcLength==null||this.config.crcLength<1?r:r.slice(0,this.config.crcLength)}generateSelfValidate(e){let r=this.generate(e),t=this.generateCrc(r);return r+t}verify(e,r){return r===this.generate(e)}verifySelfValidate(e){let r=e.length-this.config.crcLength,t=e.slice(0,r);return e.slice(r)===this.generateCrc(t)}};import{createHmac as h}from"node:crypto";import{parseDuration as m}from"@alwatr/parse-duration";var i=class{constructor(e){this.config=e;this._duration=e.duration=="infinite"?0:m(e.duration)}get _epoch(){return this._duration==0?0:Math.floor(Date.now()/this._duration)}generate(e){return this._generate(e,this._epoch)}verify(e,r){let t=this._epoch;return r===this._generate(e,t)?"valid":this._duration==0?"invalid":r===this._generate(e,t-1)?"expired":"invalid"}_generate(e,r){return this.config.prefix+h(this.config.algorithm,e).update(e+r).digest(this.config.encoding)}};var o={prefix:"u",algorithm:"sha1",encoding:"base64url",crcLength:4},c={...o,prefix:"d"},d={prefix:"s",algorithm:"sha384",encoding:"base64url",crcLength:4},f={prefix:"t",algorithm:"sha224",encoding:"base64url"};var p=class{constructor(e){this._generators={secret:new n(d),deviceId:new n(c),userId:new n(o),token:new i({...f,...e})}}generateUserId(){return this._generators.userId.generateRandomSelfValidate()}verifyUserId(e){return this._generators.userId.verifySelfValidate(e)}generateToken(e){return this._generators.token.generate(e.join())}verifyToken(e,r){return this._generators.token.verify(e.join(),r)}generateSecret(){return this._generators.secret.generateRandomSelfValidate()}verifySecret(e){return this._generators.secret.verifySelfValidate(e)}generateDeviceId(){return this._generators.deviceId.generateRandomSelfValidate()}verifyDeviceId(e){return this._generators.deviceId.verifySelfValidate(e)}};import{definePackage as u}from"@alwatr/logger";u("crypto","3.x");export{p as AlwatrCryptoFactory,n as AlwatrHashGenerator,i as AlwatrTokenGenerator,c as deviceIdGeneratorRecommendedConfig,d as secretGeneratorRecommendedConfig,o as userIdGeneratorRecommendedConfig,f as userTokenGeneratorRecommendedConfig};
3
+ //# sourceMappingURL=main.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hash.ts", "../src/token.ts", "../src/pre-config.ts", "../src/api.ts", "../src/main.ts"],
4
+ "sourcesContent": ["import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type DurationString} from '@alwatr/parse-duration';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n", "import {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\nimport type {DurationString} from '@alwatr/parse-duration';\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n", "import {definePackage} from '@alwatr/logger';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('crypto', '3.x');\n"],
5
+ "mappings": "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",
6
+ "names": ["createHash", "randomBytes", "AlwatrHashGenerator", "config", "data", "crc", "mainHash", "crcHash", "hash", "gapPos", "createHmac", "parseDuration", "AlwatrTokenGenerator", "config", "data", "token", "epoch", "userIdGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "secretGeneratorRecommendedConfig", "userTokenGeneratorRecommendedConfig", "AlwatrCryptoFactory", "config", "AlwatrHashGenerator", "secretGeneratorRecommendedConfig", "deviceIdGeneratorRecommendedConfig", "userIdGeneratorRecommendedConfig", "AlwatrTokenGenerator", "userTokenGeneratorRecommendedConfig", "userId", "uniquelyList", "token", "secret", "deviceId", "definePackage"]
7
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pre-config.d.ts","sourceRoot":"","sources":["../src/pre-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,WAAW,CAAC;AACnD,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,YAAY,CAAC;AAErD;;GAEG;AACH,eAAO,MAAM,gCAAgC,EAAE,mBAK9C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kCAAkC,EAAE,mBAGhD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,gCAAgC,EAAE,mBAK9C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,mCAAmC,EAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,GAAG,UAAU,CAIjG,CAAC"}
@@ -1,4 +1,4 @@
1
- import { DurationString } from '@alwatr/math';
1
+ import { type DurationString } from '@alwatr/parse-duration';
2
2
  import type { CryptoAlgorithm, CryptoEncoding } from './type.js';
3
3
  export type TokenValidity = 'valid' | 'invalid' | 'expired';
4
4
  /**
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../src/token.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgB,KAAK,cAAc,EAAC,MAAM,wBAAwB,CAAC;AAE1E,OAAO,KAAK,EAAC,eAAe,EAAE,cAAc,EAAC,MAAM,WAAW,CAAC;AAE/D,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,SAAS,GAAG,SAAS,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,SAAS,EAAE,eAAe,CAAC;IAE3B;;OAEG;IACH,QAAQ,EAAE,cAAc,CAAC;IAEzB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,QAAQ,EAAE,cAAc,GAAG,UAAU,CAAC;CACvC;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAcZ,MAAM,EAAE,oBAAoB;IAb/C,OAAO,CAAC,SAAS,CAAS;IAE1B;;OAEG;IACH,SAAS,KAAK,MAAM,IAAI,MAAM,CAE7B;IAED;;;OAGG;gBACgB,MAAM,EAAE,oBAAoB;IAI/C;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAI9B;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,aAAa;IAQlD;;;;;OAKG;IACH,SAAS,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM;CAQzD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAEzF;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,WAAW,GAAG,KAAK,GAAG,QAAQ,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@alwatr/crypto",
3
- "version": "3.0.4",
3
+ "version": "4.0.0-alpha.0",
4
4
  "description": "A robust generator of secure authentication HOTP tokens, employing the HMAC-based One-Time Password algorithm, accompanied by a suite of cryptographic utilities, all encapsulated within a compact TypeScript module.",
5
+ "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
5
6
  "keywords": [
6
7
  "crypto",
7
8
  "hash",
@@ -19,33 +20,63 @@
19
20
  "esm",
20
21
  "alwatr"
21
22
  ],
22
- "main": "index.js",
23
23
  "type": "module",
24
- "types": "index.d.ts",
25
- "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
24
+ "main": "./dist/main.cjs",
25
+ "module": "./dist/main.mjs",
26
+ "types": "./dist/main.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/main.d.ts",
30
+ "import": "./dist/main.mjs",
31
+ "require": "./dist/main.cjs"
32
+ }
33
+ },
26
34
  "license": "MIT",
27
35
  "files": [
28
- "**/*.{d.ts.map,d.ts,js.map,js,html,md}"
36
+ "**/*.{js,mjs,cjs,map,d.ts,html,md}",
37
+ "!demo/**/*"
29
38
  ],
30
39
  "publishConfig": {
31
40
  "access": "public"
32
41
  },
33
42
  "repository": {
34
43
  "type": "git",
35
- "url": "https://github.com/Alwatr/alwatr-es-sdk",
44
+ "url": "https://github.com/Alwatr/nanotron",
36
45
  "directory": "packages/crypto"
37
46
  },
38
- "homepage": "https://github.com/Alwatr/alwatr-es-sdk/tree/next/packages/crypto#readme",
47
+ "homepage": "https://github.com/Alwatr/nanotron/tree/next/packages/crypto#readme",
39
48
  "bugs": {
40
- "url": "https://github.com/Alwatr/alwatr-es-sdk/issues"
49
+ "url": "https://github.com/Alwatr/nanotron/issues"
50
+ },
51
+ "prettier": "@alwatr/prettier-config",
52
+ "scripts": {
53
+ "b": "yarn run build",
54
+ "t": "yarn run test",
55
+ "w": "yarn run watch",
56
+ "c": "yarn run clean",
57
+ "cb": "yarn run clean && yarn run build",
58
+ "d": "yarn run build:es && yarn node --enable-source-maps --trace-warnings",
59
+ "build": "yarn run build:ts & yarn run build:es",
60
+ "build:es": "nano-build --preset=module",
61
+ "build:ts": "tsc --build",
62
+ "test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" jest",
63
+ "watch": "yarn run watch:ts & yarn run watch:es",
64
+ "watch:es": "yarn run build:es --watch",
65
+ "watch:ts": "yarn run build:ts --watch --preserveWatchOutput",
66
+ "clean": "rm -rfv dist *.tsbuildinfo"
41
67
  },
42
68
  "dependencies": {
43
- "@alwatr/logger": "^2.4.1",
44
- "@alwatr/math": "^1.3.1",
45
- "@alwatr/util": "^1.4.1"
69
+ "@alwatr/logger": "^3.2.12",
70
+ "@alwatr/parse-duration": "^1.0.9"
46
71
  },
47
72
  "devDependencies": {
48
- "@types/node": "^20.10.5"
73
+ "@alwatr/nano-build": "^1.3.8",
74
+ "@alwatr/prettier-config": "^1.0.4",
75
+ "@alwatr/tsconfig-base": "^1.2.0",
76
+ "@alwatr/type-helper": "^1.2.5",
77
+ "@types/node": "^22.5.4",
78
+ "jest": "^29.7.0",
79
+ "typescript": "^5.6.2"
49
80
  },
50
- "gitHead": "8df92c67b69527b5474e8741a8633e0e67b5d09a"
81
+ "gitHead": "98c507c61c76e83f1559fd1df4f7ef6510cfc70a"
51
82
  }
package/api.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,cAAc,EAAC,MAAM,cAAc,CAAC;AAE5C,OAAO,EAAC,mBAAmB,EAAC,MAAM,WAAW,CAAC;AAO9C,OAAO,EAAC,oBAAoB,EAAE,KAAK,aAAa,EAAC,MAAM,YAAY,CAAC;AAEpE;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,QAAQ,EAAE,cAAc,GAAG,UAAU,CAAC;CACvC;AAED;;GAEG;AACH,qBAAa,mBAAmB;IAC9B,SAAS,CAAC,WAAW;;;;;MAAC;IAEtB;;;OAGG;gBACS,MAAM,EAAE,mBAAmB;IAYvC;;;;;;;;;;OAUG;IACH,cAAc,IAAI,MAAM;IAIxB;;;;;;;;;;OAUG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAIrC;;;;;;;;OAQG;IACH,aAAa,CAAC,YAAY,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG,MAAM;IAIxD;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,YAAY,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,aAAa;IAI5E;;;;;;;;;;OAUG;IACH,cAAc,IAAI,MAAM;IAIxB;;;;;;;;;;OAUG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAIrC;;;;;;;OAOG;IACH,gBAAgB,IAAI,MAAM;IAI1B;;;;;;;;;;;;;;OAcG;IACH,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAG1C"}
package/api.js DELETED
@@ -1,136 +0,0 @@
1
- import { AlwatrHashGenerator } from './hash.js';
2
- import { deviceIdGeneratorRecommendedConfig, secretGeneratorRecommendedConfig, userIdGeneratorRecommendedConfig, userTokenGeneratorRecommendedConfig, } from './pre-config.js';
3
- import { AlwatrTokenGenerator } from './token.js';
4
- /**
5
- * Crypto factory for generating self-validate user-id, user-token, secret, device-id.
6
- */
7
- export class AlwatrCryptoFactory {
8
- /**
9
- * Creates a new instance of crypto factory.
10
- * @param config The configuration used to create the crypto factory.
11
- */
12
- constructor(config) {
13
- this._generators = {
14
- secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),
15
- deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),
16
- userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),
17
- token: new AlwatrTokenGenerator({
18
- ...userTokenGeneratorRecommendedConfig,
19
- ...config,
20
- }),
21
- };
22
- }
23
- /**
24
- * Generate self-verifiable user ID.
25
- * @returns The generated user ID.
26
- * @example
27
- * ```typescript
28
- * const newUser = {
29
- * id: cryptoFactory.generateUserId(),
30
- * ...
31
- * }
32
- * ```
33
- */
34
- generateUserId() {
35
- return this._generators.userId.generateRandomSelfValidate();
36
- }
37
- /**
38
- * Verify a user ID without token.
39
- * @param userId The user ID to verify.
40
- * @returns A boolean indicating whether the user ID is valid.
41
- * @example
42
- * ```typescript
43
- * if (!cryptoFactory.verifyUserId(user.id)) {
44
- * throw new Error('invalid_user');
45
- * }
46
- * ```
47
- */
48
- verifyUserId(userId) {
49
- return this._generators.userId.verifySelfValidate(userId);
50
- }
51
- /**
52
- * Generate authentication token.
53
- * @param uniquelyList The list of uniq values to generate the token from.
54
- * @returns The generated user token.
55
- * @example
56
- * ```typescript
57
- * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);
58
- * ```
59
- */
60
- generateToken(uniquelyList) {
61
- return this._generators.token.generate(uniquelyList.join());
62
- }
63
- /**
64
- * Verify a authentication token.
65
- * @param uniquelyList The list of uniq values used to generate the token.
66
- * @param token The user token to verify.
67
- * @returns The validity of the token.
68
- * @example
69
- * ```typescript
70
- * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {
71
- * throw new Error('invalid_token');
72
- * }
73
- * ```
74
- */
75
- verifyToken(uniquelyList, token) {
76
- return this._generators.token.verify(uniquelyList.join(), token);
77
- }
78
- /**
79
- * Generate self-verifiable secret.
80
- * @returns The generated secret.
81
- * @example
82
- * ```typescript
83
- * const config = {
84
- * storageToken: cryptoFactory.generateSecret(),
85
- * ...
86
- * }
87
- * ```
88
- */
89
- generateSecret() {
90
- return this._generators.secret.generateRandomSelfValidate();
91
- }
92
- /**
93
- * Verify a secret.
94
- * @param secret The secret to verify.
95
- * @returns A boolean indicating whether the secret is valid.
96
- * @example
97
- * ```typescript
98
- * if (!cryptoFactory.verifySecret(config.storageToken)) {
99
- * throw new Error('invalid_secret');
100
- * }
101
- * ```
102
- */
103
- verifySecret(secret) {
104
- return this._generators.secret.verifySelfValidate(secret);
105
- }
106
- /**
107
- * Generate self-verifiable device ID.
108
- * @returns The generated device ID.
109
- * @example
110
- * ```typescript
111
- * const deviceId = deviceFactory.generateDeviceId();
112
- * ```
113
- */
114
- generateDeviceId() {
115
- return this._generators.deviceId.generateRandomSelfValidate();
116
- }
117
- /**
118
- * Verify a device ID.
119
- * @param deviceId The device ID to verify.
120
- * @returns A boolean indicating whether the device ID is valid.
121
- * @example
122
- * ```typescript
123
- * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {
124
- * throw {
125
- * ok: false,
126
- * status: 400,
127
- * error: 'invalid_device_id',
128
- * }
129
- * }
130
- * ```
131
- */
132
- verifyDeviceId(deviceId) {
133
- return this._generators.deviceId.verifySelfValidate(deviceId);
134
- }
135
- }
136
- //# sourceMappingURL=api.js.map
package/api.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["src/api.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,mBAAmB,EAAC,MAAM,WAAW,CAAC;AAC9C,OAAO,EACL,kCAAkC,EAClC,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,GACpC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAC,oBAAoB,EAAqB,MAAM,YAAY,CAAC;AAiBpE;;GAEG;AACH,MAAM,OAAO,mBAAmB;IAG9B;;;OAGG;IACH,YAAY,MAA2B;QACrC,IAAI,CAAC,WAAW,GAAG;YACjB,MAAM,EAAE,IAAI,mBAAmB,CAAC,gCAAgC,CAAC;YACjE,QAAQ,EAAE,IAAI,mBAAmB,CAAC,kCAAkC,CAAC;YACrE,MAAM,EAAE,IAAI,mBAAmB,CAAC,gCAAgC,CAAC;YACjE,KAAK,EAAE,IAAI,oBAAoB,CAAC;gBAC9B,GAAG,mCAAmC;gBACtC,GAAG,MAAM;aACV,CAAC;SACM,CAAC;IACb,CAAC;IAED;;;;;;;;;;OAUG;IACH,cAAc;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,0BAA0B,EAAE,CAAC;IAC9D,CAAC;IAED;;;;;;;;;;OAUG;IACH,YAAY,CAAC,MAAc;QACzB,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAC5D,CAAC;IAED;;;;;;;;OAQG;IACH,aAAa,CAAC,YAAiC;QAC7C,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC;IAC9D,CAAC;IAED;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,YAAiC,EAAE,KAAa;QAC1D,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;IACnE,CAAC;IAED;;;;;;;;;;OAUG;IACH,cAAc;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,0BAA0B,EAAE,CAAC;IAC9D,CAAC;IAED;;;;;;;;;;OAUG;IACH,YAAY,CAAC,MAAc;QACzB,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAC5D,CAAC;IAED;;;;;;;OAOG;IACH,gBAAgB;QACd,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,0BAA0B,EAAE,CAAC;IAChE,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,cAAc,CAAC,QAAgB;QAC7B,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAChE,CAAC;CACF","sourcesContent":["import {DurationString} from '@alwatr/math';\n\nimport {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n"]}
package/hash.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["src/hash.ts"],"names":[],"mappings":";AAAA,OAAO,EAA0B,KAAK,UAAU,EAAC,MAAM,aAAa,CAAC;AAErE,OAAO,KAAK,EAAC,eAAe,EAAE,cAAc,EAAC,MAAM,WAAW,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,SAAS,EAAE,eAAe,CAAC;IAE3B;;OAEG;IACH,QAAQ,EAAE,cAAc,CAAC;IAEzB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,qBAAa,mBAAmB;IAKX,MAAM,EAAE,mBAAmB;IAJ9C;;;OAGG;gBACgB,MAAM,EAAE,mBAAmB;IAE9C;;;;;;;OAOG;IACH,cAAc,IAAI,MAAM;IAIxB;;;;;;;OAOG;IACH,0BAA0B,IAAI,MAAM;IAIpC;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM;IAIlC;;;;OAIG;IACH,WAAW,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM;IAKrC;;;;;;;;OAQG;IACH,oBAAoB,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM;IAM9C;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO;IAI/C;;;;;;;;;;OAUG;IACH,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;CAM1C"}
package/hash.js DELETED
@@ -1,103 +0,0 @@
1
- import { createHash, randomBytes } from 'node:crypto';
2
- /**
3
- * Secure **self-validate** hash generator.
4
- */
5
- export class AlwatrHashGenerator {
6
- /**
7
- * Creates a new instance of the AlwatrHashGenerator class.
8
- * @param config The configuration for the hash generator.
9
- */
10
- constructor(config) {
11
- this.config = config;
12
- }
13
- /**
14
- * Generate a random hash.
15
- * @returns The generated hash.
16
- * @example
17
- * ```typescript
18
- * const clientId = hashGenerator.generateRandom();
19
- * ```
20
- */
21
- generateRandom() {
22
- return this.generate(randomBytes(16));
23
- }
24
- /**
25
- * Generate a **self-validate** random hash.
26
- * @returns The generated self-validated hash.
27
- * @example
28
- * ```typescript
29
- * const userId = hashGenerator.generateRandomSelfValidate();
30
- * ```
31
- */
32
- generateRandomSelfValidate() {
33
- return this.generateSelfValidate(randomBytes(16));
34
- }
35
- /**
36
- * Generate a hash from data.
37
- * @param data - The data to generate the hash from.
38
- * @returns The generated hash.
39
- * @example
40
- * ```typescript
41
- * const crcHash = hashGenerator.generate(data);
42
- * ```
43
- */
44
- generate(data) {
45
- return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);
46
- }
47
- /**
48
- * Generate a crc hash.
49
- * @param data - The data to generate the crc hash from.
50
- * @returns The generated crc hash.
51
- */
52
- generateCrc(data) {
53
- const crc = createHash('sha1').update(data).digest(this.config.encoding);
54
- return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);
55
- }
56
- /**
57
- * Generate a **self-validate** hash from data.
58
- * @param data - The data to generate the self-validated hash from.
59
- * @returns The generated self-validated hash.
60
- * @example
61
- * ```typescript
62
- * const userId = hashGenerator.generateSelfValidate(data);
63
- * ```
64
- */
65
- generateSelfValidate(data) {
66
- const mainHash = this.generate(data);
67
- const crcHash = this.generateCrc(mainHash);
68
- return mainHash + crcHash;
69
- }
70
- /**
71
- * Verify if the generated hash matches the provided hash.
72
- * @param data - The data to verify.
73
- * @param hash - The hash to compare against.
74
- * @returns `true` if the hash is verified, `false` otherwise.
75
- * @example
76
- * ```typescript
77
- * if (!hashGenerator.verify(data, hash)) {
78
- * new Error('data_corrupted');
79
- * }
80
- * ```
81
- */
82
- verify(data, hash) {
83
- return hash === this.generate(data);
84
- }
85
- /**
86
- * Verify a **self-validate** hash to check if it was generated by this class (with the same options).
87
- * @param hash - The self-validated hash to verify.
88
- * @returns `true` if the hash is verified, `false` otherwise.
89
- * @example
90
- * ```typescript
91
- * if (!hashGenerator.verifySelfValidate(hash)) {
92
- * new Error('invalid_hash');
93
- * }
94
- * ```
95
- */
96
- verifySelfValidate(hash) {
97
- const gapPos = hash.length - this.config.crcLength;
98
- const mainHash = hash.slice(0, gapPos);
99
- const crcHash = hash.slice(gapPos);
100
- return crcHash === this.generateCrc(mainHash);
101
- }
102
- }
103
- //# sourceMappingURL=hash.js.map
package/hash.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"hash.js","sourceRoot":"","sources":["src/hash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAE,WAAW,EAAkB,MAAM,aAAa,CAAC;AA6BrE;;GAEG;AACH,MAAM,OAAO,mBAAmB;IAC9B;;;OAGG;IACH,YAAmB,MAA2B;QAA3B,WAAM,GAAN,MAAM,CAAqB;IAAG,CAAC;IAElD;;;;;;;OAOG;IACH,cAAc;QACZ,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;IACxC,CAAC;IAED;;;;;;;OAOG;IACH,0BAA0B;QACxB,OAAO,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;IACpD,CAAC;IAED;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAgB;QACvB,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC1G,CAAC;IAED;;;;OAIG;IACH,WAAW,CAAC,IAAgB;QAC1B,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACzE,OAAO,IAAI,CAAC,MAAM,CAAC,SAAS,IAAI,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAChH,CAAC;IAED;;;;;;;;OAQG;IACH,oBAAoB,CAAC,IAAgB;QACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC3C,OAAO,QAAQ,GAAG,OAAO,CAAC;IAC5B,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,IAAgB,EAAE,IAAY;QACnC,OAAO,IAAI,KAAK,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACtC,CAAC;IAED;;;;;;;;;;OAUG;IACH,kBAAkB,CAAC,IAAY;QAC7B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC;QACnD,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACvC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QACnC,OAAO,OAAO,KAAK,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n"]}
package/index.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAEA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC"}
package/index.js DELETED
@@ -1,8 +0,0 @@
1
- import { definePackage } from '@alwatr/logger';
2
- export * from './hash.js';
3
- export * from './token.js';
4
- export * from './api.js';
5
- export * from './type.js';
6
- export * from './pre-config.js';
7
- definePackage('crypto', '3.x');
8
- //# sourceMappingURL=index.js.map
package/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,gBAAgB,CAAC;AAE7C,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC;AAEhC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC","sourcesContent":["import {definePackage} from '@alwatr/logger';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('crypto', '3.x');\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pre-config.d.ts","sourceRoot":"","sources":["src/pre-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,WAAW,CAAC;AACnD,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,YAAY,CAAC;AAErD;;GAEG;AACH,eAAO,MAAM,gCAAgC,EAAE,mBAK9C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kCAAkC,EAAE,mBAGhD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,gCAAgC,EAAE,mBAK9C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,mCAAmC,EAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,GAAG,UAAU,CAIjG,CAAC"}
package/pre-config.js DELETED
@@ -1,34 +0,0 @@
1
- /**
2
- * Alwatr hash generator recommended configuration for making random self-validate **user-id**.
3
- */
4
- export const userIdGeneratorRecommendedConfig = {
5
- prefix: 'u',
6
- algorithm: 'sha1',
7
- encoding: 'base64url',
8
- crcLength: 4,
9
- };
10
- /**
11
- * Hash generator recommended configuration for making random self-validate **device-id**.
12
- */
13
- export const deviceIdGeneratorRecommendedConfig = {
14
- ...userIdGeneratorRecommendedConfig,
15
- prefix: 'd',
16
- };
17
- /**
18
- * Hash generator pre configuration for making random self-validate **secrets**.
19
- */
20
- export const secretGeneratorRecommendedConfig = {
21
- prefix: 's',
22
- algorithm: 'sha384',
23
- encoding: 'base64url',
24
- crcLength: 4,
25
- };
26
- /**
27
- * Token generator recommended configuration for making secure self-validate **user-token**.
28
- */
29
- export const userTokenGeneratorRecommendedConfig = {
30
- prefix: 't',
31
- algorithm: 'sha224',
32
- encoding: 'base64url',
33
- };
34
- //# sourceMappingURL=pre-config.js.map
package/pre-config.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"pre-config.js","sourceRoot":"","sources":["src/pre-config.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAwB;IACnE,MAAM,EAAE,GAAG;IACX,SAAS,EAAE,MAAM;IACjB,QAAQ,EAAE,WAAW;IACrB,SAAS,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAwB;IACrE,GAAG,gCAAgC;IACnC,MAAM,EAAE,GAAG;CACZ,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAwB;IACnE,MAAM,EAAE,GAAG;IACX,SAAS,EAAE,QAAQ;IACnB,QAAQ,EAAE,WAAW;IACrB,SAAS,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAsD;IACpG,MAAM,EAAE,GAAG;IACX,SAAS,EAAE,QAAQ;IACnB,QAAQ,EAAE,WAAW;CACtB,CAAC","sourcesContent":["import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n"]}
package/token.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["src/token.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,cAAc,EAAgB,MAAM,cAAc,CAAC;AAE3D,OAAO,KAAK,EAAC,eAAe,EAAE,cAAc,EAAC,MAAM,WAAW,CAAC;AAE/D,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,SAAS,GAAG,SAAS,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,SAAS,EAAE,eAAe,CAAC;IAE3B;;OAEG;IACH,QAAQ,EAAE,cAAc,CAAC;IAEzB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,QAAQ,EAAE,cAAc,GAAG,UAAU,CAAC;CACvC;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAcZ,MAAM,EAAE,oBAAoB;IAb/C,OAAO,CAAC,SAAS,CAAS;IAE1B;;OAEG;IACH,SAAS,KAAK,MAAM,IAAI,MAAM,CAE7B;IAED;;;OAGG;gBACgB,MAAM,EAAE,oBAAoB;IAI/C;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAI9B;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,aAAa;IAQlD;;;;;OAKG;IACH,SAAS,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM;CAQzD"}
package/token.js DELETED
@@ -1,66 +0,0 @@
1
- import { createHmac } from 'node:crypto';
2
- import { parseDuration } from '@alwatr/math';
3
- /**
4
- * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).
5
- */
6
- export class AlwatrTokenGenerator {
7
- /**
8
- * The current epoch based on the configured duration.
9
- */
10
- get _epoch() {
11
- return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);
12
- }
13
- /**
14
- * Creates a new instance of AlwatrTokenGenerator.
15
- * @param config The configuration for the token generator.
16
- */
17
- constructor(config) {
18
- this.config = config;
19
- this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);
20
- }
21
- /**
22
- * Generates a HOTP token based on the provided data for special duration.
23
- * @param data The data to generate the token from.
24
- * @returns The generated token.
25
- * @example
26
- * ```typescript
27
- * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);
28
- * ```
29
- */
30
- generate(data) {
31
- return this._generate(data, this._epoch);
32
- }
33
- /**
34
- * Verifies if a token is valid.
35
- * @param data The data used to generate the token.
36
- * @param token The token to verify.
37
- * @returns The validity of the token.
38
- * @example
39
- * ```typescript
40
- * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);
41
- * ```
42
- */
43
- verify(data, token) {
44
- const epoch = this._epoch;
45
- if (token === this._generate(data, epoch))
46
- return 'valid';
47
- if (this._duration == 0)
48
- return 'invalid';
49
- if (token === this._generate(data, epoch - 1))
50
- return 'expired';
51
- return 'invalid';
52
- }
53
- /**
54
- * Generates a cryptographic token based on the provided data and epoch.
55
- * @param data - The data to be used in the token generation.
56
- * @param epoch - The epoch value to be used in the token generation.
57
- * @returns The generated cryptographic token.
58
- */
59
- _generate(data, epoch) {
60
- return (this.config.prefix +
61
- createHmac(this.config.algorithm, data)
62
- .update(data + epoch)
63
- .digest(this.config.encoding));
64
- }
65
- }
66
- //# sourceMappingURL=token.js.map
package/token.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"token.js","sourceRoot":"","sources":["src/token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAiB,aAAa,EAAC,MAAM,cAAc,CAAC;AAoC3D;;GAEG;AACH,MAAM,OAAO,oBAAoB;IAG/B;;OAEG;IACH,IAAc,MAAM;QAClB,OAAO,IAAI,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;IAC3E,CAAC;IAED;;;OAGG;IACH,YAAmB,MAA4B;QAA5B,WAAM,GAAN,MAAM,CAAsB;QAC7C,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACtF,CAAC;IAED;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAY;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAY,EAAE,KAAa;QAChC,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;YAAE,OAAO,OAAO,CAAC;QAC1D,IAAI,IAAI,CAAC,SAAS,IAAI,CAAC;YAAE,OAAO,SAAS,CAAC;QAC1C,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,CAAC;YAAE,OAAO,SAAS,CAAC;QAChE,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,IAAY,EAAE,KAAa;QAC7C,OAAO,CACL,IAAI,CAAC,MAAM,CAAC,MAAM;YAClB,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC;iBACpC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC;iBACpB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAChC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {createHmac} from 'node:crypto';\n\nimport {DurationString, parseDuration} from '@alwatr/math';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n"]}
package/type.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAEzF;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,WAAW,GAAG,KAAK,GAAG,QAAQ,CAAC"}
package/type.js DELETED
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=type.js.map
package/type.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"type.js","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Represents a cryptographic algorithm.\n * Supported algorithms include: 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'.\n */\nexport type CryptoAlgorithm = 'md5' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512';\n\n/**\n * Represents the encoding options for cryptographic operations.\n * The encoding can be one of the following: 'base64', 'base64url', 'hex', or 'binary'.\n */\nexport type CryptoEncoding = 'base64' | 'base64url' | 'hex' | 'binary';\n"]}
File without changes
File without changes