@alwatr/crypto 2.0.0 → 3.0.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,24 @@
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
+ # [3.0.0](https://github.com/Alwatr/alwatr-es-sdk/compare/@alwatr/crypto@2.0.0...@alwatr/crypto@3.0.0) (2023-12-09)
7
+
8
+ ### Bug Fixes
9
+
10
+ * **crypto:** use import type ([30e3bac](https://github.com/Alwatr/alwatr-es-sdk/commit/30e3bacb187d58417cb62e2a1511de4ade3f80c0)) by @njfamirm
11
+
12
+ ### Features
13
+
14
+ * **crypto/api:** AlwatrCryptoFactory with secret and device id ([2d754a1](https://github.com/Alwatr/alwatr-es-sdk/commit/2d754a19b2f04f64d0828e31ba004fc192f466d3)) by @njfamirm
15
+ * **crypto/api:** device id generator preconfig ([71e80d6](https://github.com/Alwatr/alwatr-es-sdk/commit/71e80d63743579505a6be17d014c364e9f6cf55c)) by @njfamirm
16
+ * **crypto:** complete rewrite with new api ([3d56861](https://github.com/Alwatr/alwatr-es-sdk/commit/3d56861a2857e760c7cd5f03be98f003738fc7a9)) by @AliMD
17
+ * **crypto:** rename user file to api ([52343ea](https://github.com/Alwatr/alwatr-es-sdk/commit/52343ead04c23f50bedac2caa01f46bf489ab318)) by @njfamirm
18
+
19
+ ### BREAKING CHANGES
20
+
21
+ * **crypto:** new api
22
+ * **crypto/api:** rename AlwatrUserGenerator to AlwatrCryptoFactory and change config
23
+
6
24
  # [2.0.0](https://github.com/Alwatr/eslib/compare/@alwatr/crypto@1.2.1...@alwatr/crypto@2.0.0) (2023-11-29)
7
25
 
8
26
  ### Features
package/api.d.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { DurationString } from '@alwatr/math';
2
+ import { AlwatrHashGenerator } from './hash.js';
3
+ import { AlwatrTokenGenerator, type TokenValidity } from './token.js';
4
+ /**
5
+ * Configuration options for the CryptoFactory.
6
+ */
7
+ export interface CryptoFactoryConfig {
8
+ /**
9
+ * The secret used for encryption and decryption tokens.
10
+ */
11
+ secret: string;
12
+ /**
13
+ * The duration for which the token is valid.
14
+ */
15
+ duration: DurationString | 'infinite';
16
+ }
17
+ /**
18
+ * Crypto factory for generating self-validate user-id, user-token, secret, device-id.
19
+ */
20
+ export declare class AlwatrCryptoFactory {
21
+ protected _generators: {
22
+ readonly secret: AlwatrHashGenerator;
23
+ readonly deviceId: AlwatrHashGenerator;
24
+ readonly userId: AlwatrHashGenerator;
25
+ readonly token: AlwatrTokenGenerator;
26
+ };
27
+ /**
28
+ * Creates a new instance of crypto factory.
29
+ * @param config The configuration used to create the crypto factory.
30
+ */
31
+ constructor(config: CryptoFactoryConfig);
32
+ /**
33
+ * Generate self-verifiable user ID.
34
+ * @returns The generated user ID.
35
+ * @example
36
+ * ```typescript
37
+ * const newUser = {
38
+ * id: cryptoFactory.generateUserId(),
39
+ * ...
40
+ * }
41
+ * ```
42
+ */
43
+ generateUserId(): string;
44
+ /**
45
+ * Verify a user ID without token.
46
+ * @param userId The user ID to verify.
47
+ * @returns A boolean indicating whether the user ID is valid.
48
+ * @example
49
+ * ```typescript
50
+ * if (!cryptoFactory.verifyUserId(user.id)) {
51
+ * throw new Error('invalid_user');
52
+ * }
53
+ * ```
54
+ */
55
+ verifyUserId(userId: string): boolean;
56
+ /**
57
+ * Generate authentication token.
58
+ * @param uniquelyList The list of uniq values to generate the token from.
59
+ * @returns The generated user token.
60
+ * @example
61
+ * ```typescript
62
+ * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);
63
+ * ```
64
+ */
65
+ generateToken(uniquelyList: (string | number)[]): string;
66
+ /**
67
+ * Verify a authentication token.
68
+ * @param uniquelyList The list of uniq values used to generate the token.
69
+ * @param token The user token to verify.
70
+ * @returns The validity of the token.
71
+ * @example
72
+ * ```typescript
73
+ * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {
74
+ * throw new Error('invalid_token');
75
+ * }
76
+ * ```
77
+ */
78
+ verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity;
79
+ /**
80
+ * Generate self-verifiable secret.
81
+ * @returns The generated secret.
82
+ * @example
83
+ * ```typescript
84
+ * const config = {
85
+ * storageToken: cryptoFactory.generateSecret(),
86
+ * ...
87
+ * }
88
+ * ```
89
+ */
90
+ generateSecret(): string;
91
+ /**
92
+ * Verify a secret.
93
+ * @param secret The secret to verify.
94
+ * @returns A boolean indicating whether the secret is valid.
95
+ * @example
96
+ * ```typescript
97
+ * if (!cryptoFactory.verifySecret(config.storageToken)) {
98
+ * throw new Error('invalid_secret');
99
+ * }
100
+ * ```
101
+ */
102
+ verifySecret(secret: string): boolean;
103
+ /**
104
+ * Generate self-verifiable device ID.
105
+ * @returns The generated device ID.
106
+ * @example
107
+ * ```typescript
108
+ * const deviceId = deviceFactory.generateDeviceId();
109
+ * ```
110
+ */
111
+ generateDeviceId(): string;
112
+ /**
113
+ * Verify a device ID.
114
+ * @param deviceId The device ID to verify.
115
+ * @returns A boolean indicating whether the device ID is valid.
116
+ * @example
117
+ * ```typescript
118
+ * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {
119
+ * throw {
120
+ * ok: false,
121
+ * status: 400,
122
+ * error: 'invalid_device_id',
123
+ * }
124
+ * }
125
+ * ```
126
+ */
127
+ verifyDeviceId(deviceId: string): boolean;
128
+ }
129
+ //# sourceMappingURL=api.d.ts.map
package/api.d.ts.map ADDED
@@ -0,0 +1 @@
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 ADDED
@@ -0,0 +1,136 @@
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 ADDED
@@ -0,0 +1 @@
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,M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AA0B,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 CHANGED
@@ -1,6 +1,27 @@
1
1
  /// <reference types="node" />
2
2
  import { type BinaryLike } from 'node:crypto';
3
- import type { HashGeneratorConfig } from './type.js';
3
+ import type { CryptoAlgorithm, CryptoEncoding } from './type.js';
4
+ /**
5
+ * Represents the configuration for a hash generator.
6
+ */
7
+ export interface HashGeneratorConfig {
8
+ /**
9
+ * The prefix to be added to the generated hash.
10
+ */
11
+ prefix: string;
12
+ /**
13
+ * The algorithm used for hashing.
14
+ */
15
+ algorithm: CryptoAlgorithm;
16
+ /**
17
+ * The encoding used for the generated hash.
18
+ */
19
+ encoding: CryptoEncoding;
20
+ /**
21
+ * The length of the CRC (Cyclic Redundancy Check) value.
22
+ */
23
+ crcLength: number;
24
+ }
4
25
  /**
5
26
  * Secure **self-validate** hash generator.
6
27
  */
@@ -75,7 +96,7 @@ export declare class AlwatrHashGenerator {
75
96
  * @example
76
97
  * ```typescript
77
98
  * if (!hashGenerator.verifySelfValidate(hash)) {
78
- * new Error('invalid_user');
99
+ * new Error('invalid_hash');
79
100
  * }
80
101
  * ```
81
102
  */
package/hash.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["src/hash.ts"],"names":[],"mappings":";AAAA,OAAO,EAA2B,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAEvE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAErD;;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;;;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ANGED
@@ -89,14 +89,12 @@ export class AlwatrHashGenerator {
89
89
  * @example
90
90
  * ```typescript
91
91
  * if (!hashGenerator.verifySelfValidate(hash)) {
92
- * new Error('invalid_user');
92
+ * new Error('invalid_hash');
93
93
  * }
94
94
  * ```
95
95
  */
96
96
  verifySelfValidate(hash) {
97
- const gapPos = this.config.crcLength == null || this.config.crcLength < 1
98
- ? hash.length - (hash.length - this.config.prefix.length) / 2
99
- : hash.length - this.config.crcLength;
97
+ const gapPos = hash.length - this.config.crcLength;
100
98
  const mainHash = hash.slice(0, gapPos);
101
99
  const crcHash = hash.slice(gapPos);
102
100
  return crcHash === this.generateCrc(mainHash);
package/hash.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hash.js","sourceRoot":"","sources":["src/hash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAmB,MAAM,aAAa,CAAC;AAIvE;;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,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AC;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 { HashGeneratorConfig } from './type.js';\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_user');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos =\n this.config.crcLength == null || this.config.crcLength < 1\n ? hash.length - (hash.length - this.config.prefix.length) / 2\n : 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"]}
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;IA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ncoding} 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  export * from './hash.js';
2
2
  export * from './token.js';
3
- export * from './user.js';
3
+ export * from './api.js';
4
4
  export * from './type.js';
5
5
  export * from './pre-config.js';
6
6
  //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAEA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC"}
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 CHANGED
@@ -1,8 +1,8 @@
1
1
  import { definePackage } from '@alwatr/logger';
2
2
  export * from './hash.js';
3
3
  export * from './token.js';
4
- export * from './user.js';
4
+ export * from './api.js';
5
5
  export * from './type.js';
6
6
  export * from './pre-config.js';
7
- definePackage('crypto', '1.x');
7
+ definePackage('crypto', '3.x');
8
8
  //# sourceMappingURL=index.js.map
package/index.js.map CHANGED
@@ -1 +1 @@
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,WAAW,CAAC;AAC1B,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 './user.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('crypto', '1.x');\n"]}
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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alwatr/crypto",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "A robust generator of secure authentication HOTP tokens, employing the HMAC-based One-Time Password algorithm, accompanied by a suite of cryptographic utilities, all encapsulated within a compact TypeScript module.",
5
5
  "keywords": [
6
6
  "crypto",
@@ -32,20 +32,20 @@
32
32
  },
33
33
  "repository": {
34
34
  "type": "git",
35
- "url": "https://github.com/Alwatr/eslib",
35
+ "url": "https://github.com/Alwatr/alwatr-es-sdk",
36
36
  "directory": "packages/crypto"
37
37
  },
38
- "homepage": "https://github.com/Alwatr/eslib/tree/next/packages/crypto#readme",
38
+ "homepage": "https://github.com/Alwatr/alwatr-es-sdk/tree/next/packages/crypto#readme",
39
39
  "bugs": {
40
- "url": "https://github.com/Alwatr/eslib/issues"
40
+ "url": "https://github.com/Alwatr/alwatr-es-sdk/issues"
41
41
  },
42
42
  "dependencies": {
43
- "@alwatr/logger": "^2.3.1",
44
- "@alwatr/math": "^1.2.2",
45
- "@alwatr/util": "^1.3.2"
43
+ "@alwatr/logger": "^2.3.2",
44
+ "@alwatr/math": "^1.2.3",
45
+ "@alwatr/util": "^1.3.3"
46
46
  },
47
47
  "devDependencies": {
48
- "@types/node": "^20.10.0"
48
+ "@types/node": "^20.10.4"
49
49
  },
50
- "gitHead": "27cb935580d5ccdc4459f1018c66f23ea0a42ddf"
50
+ "gitHead": "932c439c39ad9aa340cf53e0704cece565d68326"
51
51
  }
package/pre-config.d.ts CHANGED
@@ -1,14 +1,19 @@
1
- import { HashGeneratorConfig, TokenGeneratorConfig } from './type.js';
1
+ import type { HashGeneratorConfig } from './hash.js';
2
+ import type { TokenGeneratorConfig } from './token.js';
2
3
  /**
3
- * Hash generator pre configuration for making random self-validate **secrets**.
4
+ * Alwatr hash generator recommended configuration for making random self-validate **user-id**.
5
+ */
6
+ export declare const userIdGeneratorRecommendedConfig: HashGeneratorConfig;
7
+ /**
8
+ * Hash generator recommended configuration for making random self-validate **device-id**.
4
9
  */
5
- export declare const secretGeneratorPreConfig: HashGeneratorConfig;
10
+ export declare const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig;
6
11
  /**
7
- * Hash generator pre configuration for making random self-validate **user-id**.
12
+ * Hash generator pre configuration for making random self-validate **secrets**.
8
13
  */
9
- export declare const userIdGeneratorPreConfig: HashGeneratorConfig;
14
+ export declare const secretGeneratorRecommendedConfig: HashGeneratorConfig;
10
15
  /**
11
- * Token generator pre configuration for making secure self-validate **user-token**.
16
+ * Token generator recommended configuration for making secure self-validate **user-token**.
12
17
  */
13
- export declare const userTokenGeneratorPreConfig: Pick<TokenGeneratorConfig, 'algorithm' | 'encoding' | 'prefix'>;
18
+ export declare const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'>;
14
19
  //# sourceMappingURL=pre-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pre-config.d.ts","sourceRoot":"","sources":["src/pre-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,mBAAmB,EAAE,oBAAoB,EAAC,MAAM,WAAW,CAAC;AAEpE;;GAEG;AACH,eAAO,MAAM,wBAAwB,EAAE,mBAKtC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,wBAAwB,EAAE,mBAKtC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,2BAA2B,EAAE,IAAI,CAAC,oBAAoB,EAAE,WAAW,GAAG,UAAU,GAAG,QAAQ,CAIvG,CAAC"}
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 CHANGED
@@ -1,25 +1,32 @@
1
1
  /**
2
- * Hash generator pre configuration for making random self-validate **secrets**.
2
+ * Alwatr hash generator recommended configuration for making random self-validate **user-id**.
3
3
  */
4
- export const secretGeneratorPreConfig = {
5
- prefix: 's',
6
- algorithm: 'sha384',
4
+ export const userIdGeneratorRecommendedConfig = {
5
+ prefix: 'u',
6
+ algorithm: 'sha1',
7
7
  encoding: 'base64url',
8
8
  crcLength: 4,
9
9
  };
10
10
  /**
11
- * Hash generator pre configuration for making random self-validate **user-id**.
11
+ * Hash generator recommended configuration for making random self-validate **device-id**.
12
12
  */
13
- export const userIdGeneratorPreConfig = {
14
- prefix: 'u',
15
- algorithm: 'sha1',
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',
16
23
  encoding: 'base64url',
17
24
  crcLength: 4,
18
25
  };
19
26
  /**
20
- * Token generator pre configuration for making secure self-validate **user-token**.
27
+ * Token generator recommended configuration for making secure self-validate **user-token**.
21
28
  */
22
- export const userTokenGeneratorPreConfig = {
29
+ export const userTokenGeneratorRecommendedConfig = {
23
30
  prefix: 't',
24
31
  algorithm: 'sha224',
25
32
  encoding: 'base64url',
package/pre-config.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pre-config.js","sourceRoot":"","sources":["src/pre-config.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAwB;IAC3D,MAAM,EAAE,GAAG;IACX,SAAS,EAAE,QAAQ;IACnB,QAAQ,EAAE,WAAW;IACrB,SAAS,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAwB;IAC3D,MAAM,EAAE,GAAG;IACX,SAAS,EAAE,MAAM;IACjB,QAAQ,EAAE,WAAW;IACrB,SAAS,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAoE;IAC1G,MAAM,EAAE,GAAG;IACX,SAAS,EAAE,QAAQ;IACnB,QAAQ,EAAE,WAAW;CACtB,CAAC","sourcesContent":["import {HashGeneratorConfig, TokenGeneratorConfig} from './type.js';\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorPreConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorPreConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator pre configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorPreConfig: Pick<TokenGeneratorConfig, 'algorithm' | 'encoding' | 'prefix'> = {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n"]}
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 CHANGED
@@ -1,14 +1,41 @@
1
- import type { TokenGeneratorConfig, TokenStatus } from './type.js';
1
+ import { DurationString } from '@alwatr/math';
2
+ import type { CryptoAlgorithm, CryptoEncoding } from './type.js';
3
+ export type TokenValidity = 'valid' | 'invalid' | 'expired';
4
+ /**
5
+ * Represents the configuration for a token generator.
6
+ */
7
+ export interface TokenGeneratorConfig {
8
+ /**
9
+ * The prefix to be added to the generated hash.
10
+ */
11
+ prefix: string;
12
+ /**
13
+ * The algorithm used for hashing.
14
+ */
15
+ algorithm: CryptoAlgorithm;
16
+ /**
17
+ * The encoding used for the generated hash.
18
+ */
19
+ encoding: CryptoEncoding;
20
+ /**
21
+ * The secret used for encryption and decryption tokens.
22
+ */
23
+ secret: string;
24
+ /**
25
+ * The duration for which the token is valid.
26
+ */
27
+ duration: DurationString | 'infinite';
28
+ }
2
29
  /**
3
30
  * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).
4
31
  */
5
32
  export declare class AlwatrTokenGenerator {
6
33
  config: TokenGeneratorConfig;
7
- protected _duration: number | null;
34
+ private _duration;
8
35
  /**
9
36
  * The current epoch based on the configured duration.
10
37
  */
11
- get epoch(): number;
38
+ protected get _epoch(): number;
12
39
  /**
13
40
  * Creates a new instance of AlwatrTokenGenerator.
14
41
  * @param config The configuration for the token generator.
@@ -28,13 +55,13 @@ export declare class AlwatrTokenGenerator {
28
55
  * Verifies if a token is valid.
29
56
  * @param data The data used to generate the token.
30
57
  * @param token The token to verify.
31
- * @returns The status of the token verification.
58
+ * @returns The validity of the token.
32
59
  * @example
33
60
  * ```typescript
34
- * const validateStatus = tokenGenerator.verify(`${user.id}-${user.role}`, user.auth);
61
+ * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);
35
62
  * ```
36
63
  */
37
- verify(data: string, token: string): TokenStatus;
64
+ verify(data: string, token: string): TokenValidity;
38
65
  /**
39
66
  * Generates a cryptographic token based on the provided data and epoch.
40
67
  * @param data - The data to be used in the token generation.
package/token.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["src/token.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAC,oBAAoB,EAAE,WAAW,EAAC,MAAM,WAAW,CAAC;AAEjE;;GAEG;AACH,qBAAa,oBAAoB;IAcZ,MAAM,EAAE,oBAAoB;IAb/C,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAEnC;;OAEG;IACH,IAAI,KAAK,IAAI,MAAM,CAElB;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,WAAW;IAgBhD;;;;;OAKG;IACH,SAAS,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM;CAKzD"}
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 CHANGED
@@ -7,8 +7,8 @@ export class AlwatrTokenGenerator {
7
7
  /**
8
8
  * The current epoch based on the configured duration.
9
9
  */
10
- get epoch() {
11
- return this._duration == null ? 0 : Math.floor(Date.now() / this._duration);
10
+ get _epoch() {
11
+ return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);
12
12
  }
13
13
  /**
14
14
  * Creates a new instance of AlwatrTokenGenerator.
@@ -16,7 +16,7 @@ export class AlwatrTokenGenerator {
16
16
  */
17
17
  constructor(config) {
18
18
  this.config = config;
19
- this._duration = config.duration == null ? null : parseDuration(config.duration);
19
+ this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);
20
20
  }
21
21
  /**
22
22
  * Generates a HOTP token based on the provided data for special duration.
@@ -28,32 +28,27 @@ export class AlwatrTokenGenerator {
28
28
  * ```
29
29
  */
30
30
  generate(data) {
31
- return this._generate(data, this.epoch);
31
+ return this._generate(data, this._epoch);
32
32
  }
33
33
  /**
34
34
  * Verifies if a token is valid.
35
35
  * @param data The data used to generate the token.
36
36
  * @param token The token to verify.
37
- * @returns The status of the token verification.
37
+ * @returns The validity of the token.
38
38
  * @example
39
39
  * ```typescript
40
- * const validateStatus = tokenGenerator.verify(`${user.id}-${user.role}`, user.auth);
40
+ * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);
41
41
  * ```
42
42
  */
43
43
  verify(data, token) {
44
- const epoch = this.epoch;
45
- if (token === this._generate(data, epoch)) {
44
+ const epoch = this._epoch;
45
+ if (token === this._generate(data, epoch))
46
46
  return 'valid';
47
- }
48
- else if (this._duration == null) {
47
+ if (this._duration == 0)
49
48
  return 'invalid';
50
- }
51
- else if (token === this._generate(data, epoch - 1)) {
49
+ if (token === this._generate(data, epoch - 1))
52
50
  return 'expired';
53
- }
54
- else {
55
- return 'invalid';
56
- }
51
+ return 'invalid';
57
52
  }
58
53
  /**
59
54
  * Generates a cryptographic token based on the provided data and epoch.
@@ -62,9 +57,10 @@ export class AlwatrTokenGenerator {
62
57
  * @returns The generated cryptographic token.
63
58
  */
64
59
  _generate(data, epoch) {
65
- return this.config.prefix + createHmac(this.config.algorithm, data)
66
- .update(data + epoch)
67
- .digest(this.config.encoding);
60
+ return (this.config.prefix +
61
+ createHmac(this.config.algorithm, data)
62
+ .update(data + epoch)
63
+ .digest(this.config.encoding));
68
64
  }
69
65
  }
70
66
  //# sourceMappingURL=token.js.map
package/token.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"token.js","sourceRoot":"","sources":["src/token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAC,aAAa,EAAC,MAAM,cAAc,CAAC;AAI3C;;GAEG;AACH,MAAM,OAAO,oBAAoB;IAG/B;;OAEG;IACH,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;IAC9E,CAAC;IAED;;;OAGG;IACH,YAAmB,MAA4B;QAA5B,WAAM,GAAN,MAAM,CAAsB;QAC7C,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACnF,CAAC;IAED;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAY;QACnB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,IAAY,EAAE,KAAa;QAChC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QACzB,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,CAAC;YAC1C,OAAO,OAAO,CAAC;QACjB,CAAC;aACI,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE,CAAC;YAChC,OAAO,SAAS,CAAC;QACnB,CAAC;aACI,IAAI,KAAK,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC;YACnD,OAAO,SAAS,CAAC;QACnB,CAAC;aACI,CAAC;YACJ,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACO,SAAS,CAAC,IAAY,EAAE,KAAa;QAC7C,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC;aAChE,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC;aACpB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAClC,CAAC;CACF","sourcesContent":["import {createHmac} from 'node:crypto';\n\nimport {parseDuration} from '@alwatr/math';\n\nimport type {TokenGeneratorConfig, TokenStatus} from './type.js';\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n protected _duration: number | null;\n\n /**\n * The current epoch based on the configured duration.\n */\n get epoch(): number {\n return this._duration == null ? 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 == null ? null : 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 status of the token verification.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify(`${user.id}-${user.role}`, user.auth);\n * ```\n */\n verify(data: string, token: string): TokenStatus {\n const epoch = this.epoch;\n if (token === this._generate(data, epoch)) {\n return 'valid';\n }\n else if (this._duration == null) {\n return 'invalid';\n }\n else if (token === this._generate(data, epoch - 1)) {\n return 'expired';\n }\n else {\n return 'invalid';\n }\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 this.config.prefix + createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding);\n }\n}\n"]}
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 CHANGED
@@ -1,46 +1,11 @@
1
- import type { DurationString } from '@alwatr/math';
1
+ /**
2
+ * Represents a cryptographic algorithm.
3
+ * Supported algorithms include: 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'.
4
+ */
2
5
  export type CryptoAlgorithm = 'md5' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512';
6
+ /**
7
+ * Represents the encoding options for cryptographic operations.
8
+ * The encoding can be one of the following: 'base64', 'base64url', 'hex', or 'binary'.
9
+ */
3
10
  export type CryptoEncoding = 'base64' | 'base64url' | 'hex' | 'binary';
4
- export type TokenStatus = 'valid' | 'invalid' | 'expired';
5
- export type HashStatus = 'valid' | 'invalid';
6
- export interface TokenGeneratorConfig {
7
- prefix: string;
8
- /**
9
- * Secret string data to generate token.
10
- */
11
- secret: string;
12
- /**
13
- * Token expiration time.
14
- *
15
- * `null` mean without expiration time
16
- */
17
- duration: DurationString | null;
18
- /**
19
- * OpenSSl digest algorithm.
20
- */
21
- algorithm: CryptoAlgorithm;
22
- /**
23
- * Encoding of token.
24
- */
25
- encoding: CryptoEncoding;
26
- }
27
- export interface HashGeneratorConfig {
28
- prefix: string;
29
- /**
30
- * OpenSSl digest algorithm.
31
- */
32
- algorithm: CryptoAlgorithm;
33
- /**
34
- * Encoding of hash.
35
- */
36
- encoding: CryptoEncoding;
37
- /**
38
- * CRC hash max length.
39
- */
40
- crcLength?: number;
41
- }
42
- export interface UserGeneratorConfig {
43
- userId: HashGeneratorConfig;
44
- token: TokenGeneratorConfig;
45
- }
46
11
  //# sourceMappingURL=type.d.ts.map
package/type.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,cAAc,CAAC;AAEjD,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AACzF,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,WAAW,GAAG,KAAK,GAAG,QAAQ,CAAC;AAEvE,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,SAAS,GAAG,SAAS,CAAC;AAC1D,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,SAAS,CAAC;AAE7C,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;;;OAIG;IACH,QAAQ,EAAE,cAAc,GAAG,IAAI,CAAC;IAEhC;;OAEG;IACH,SAAS,EAAE,eAAe,CAAC;IAE3B;;OAEG;IACH,QAAQ,EAAE,cAAc,CAAC;CAC1B;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,SAAS,EAAE,eAAe,CAAC;IAE3B;;OAEG;IACH,QAAQ,EAAE,cAAc,CAAC;IAEzB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,mBAAmB,CAAC;IAC5B,KAAK,EAAE,oBAAoB,CAAC;CAC7B"}
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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"type.js","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"","sourcesContent":["import type {DurationString} from '@alwatr/math';\n\nexport type CryptoAlgorithm = 'md5' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512';\nexport type CryptoEncoding = 'base64' | 'base64url' | 'hex' | 'binary';\n\nexport type TokenStatus = 'valid' | 'invalid' | 'expired';\nexport type HashStatus = 'valid' | 'invalid';\n\nexport interface TokenGeneratorConfig {\n prefix: string;\n\n /**\n * Secret string data to generate token.\n */\n secret: string;\n\n /**\n * Token expiration time.\n *\n * `null` mean without expiration time\n */\n duration: DurationString | null;\n\n /**\n * OpenSSl digest algorithm.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * Encoding of token.\n */\n encoding: CryptoEncoding;\n}\n\nexport interface HashGeneratorConfig {\n prefix: string;\n\n /**\n * OpenSSl digest algorithm.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * Encoding of hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * CRC hash max length.\n */\n crcLength?: number;\n}\n\nexport interface UserGeneratorConfig {\n userId: HashGeneratorConfig;\n token: TokenGeneratorConfig;\n}\n"]}
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"]}
package/user.d.ts DELETED
@@ -1,64 +0,0 @@
1
- import { AlwatrHashGenerator } from './hash.js';
2
- import { AlwatrTokenGenerator } from './token.js';
3
- import type { UserGeneratorConfig, TokenStatus } from './type.js';
4
- /**
5
- * User factory for generating self-validate user-id and user-token.
6
- */
7
- export declare class AlwatrUserGenerator {
8
- protected _tokenGenerator: AlwatrTokenGenerator;
9
- protected _hashGenerator: AlwatrHashGenerator;
10
- /**
11
- * Creates a new instance of AlwatrUserFactory.
12
- * @param hashConfig The configuration for the hash generator.
13
- * @param tokenConfig The configuration for the token generator.
14
- */
15
- constructor(config: UserGeneratorConfig);
16
- /**
17
- * Generates a new self-verifiable user ID.
18
- * @returns The generated user ID.
19
- * @example
20
- * ```typescript
21
- * const newUser = {
22
- * id: userFactory.generateUserId(),
23
- * ...
24
- * }
25
- * ```
26
- */
27
- generateUserId(): string;
28
- /**
29
- * Validates a user ID without token.
30
- * @param userId The user ID to verify.
31
- * @returns A boolean indicating whether the user ID is valid.
32
- * @example
33
- * ```typescript
34
- * if (!userFactory.verifyUserId(user.id)) {
35
- * throw new Error('invalid_user');
36
- * }
37
- * ```
38
- */
39
- verifyUserId(userId: string): boolean;
40
- /**
41
- * Generates a user authentication token.
42
- * @param uniquelyList The list of values to generate the token from.
43
- * @returns The generated user token.
44
- * @example
45
- * ```typescript
46
- * const userToken = userFactory.generateToken([user.id, user.lpe]);
47
- * ```
48
- */
49
- generateToken(uniquelyList: (string | number | boolean)[]): string;
50
- /**
51
- * Verifies a user authentication token.
52
- * @param uniquelyList The list of values used to generate the token.
53
- * @param token The user token to verify.
54
- * @returns The status of the token verification.
55
- * @example
56
- * ```typescript
57
- * if (!userFactory.verifyToken([user.id, user.lpe], userToken)) {
58
- * throw new Error('invalid_token');
59
- * }
60
- * ```
61
- */
62
- verifyToken(uniquelyList: (string | number | boolean)[], token: string): TokenStatus;
63
- }
64
- //# sourceMappingURL=user.d.ts.map
package/user.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"user.d.ts","sourceRoot":"","sources":["src/user.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,KAAK,EAAC,mBAAmB,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAEjE;;GAEG;AACH,qBAAa,mBAAmB;IAC9B,SAAS,CAAC,eAAe,EAAE,oBAAoB,CAAC;IAChD,SAAS,CAAC,cAAc,EAAE,mBAAmB,CAAC;IAE9C;;;;OAIG;gBACS,MAAM,EAAE,mBAAmB;IAKvC;;;;;;;;;;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,GAAG,OAAO,CAAC,EAAE,GAAG,MAAM;IAIlE;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,YAAY,EAAE,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,WAAW;CAGrF"}
package/user.js DELETED
@@ -1,72 +0,0 @@
1
- import { AlwatrHashGenerator } from './hash.js';
2
- import { AlwatrTokenGenerator } from './token.js';
3
- /**
4
- * User factory for generating self-validate user-id and user-token.
5
- */
6
- export class AlwatrUserGenerator {
7
- /**
8
- * Creates a new instance of AlwatrUserFactory.
9
- * @param hashConfig The configuration for the hash generator.
10
- * @param tokenConfig The configuration for the token generator.
11
- */
12
- constructor(config) {
13
- this._hashGenerator = new AlwatrHashGenerator(config.userId);
14
- this._tokenGenerator = new AlwatrTokenGenerator(config.token);
15
- }
16
- /**
17
- * Generates a new self-verifiable user ID.
18
- * @returns The generated user ID.
19
- * @example
20
- * ```typescript
21
- * const newUser = {
22
- * id: userFactory.generateUserId(),
23
- * ...
24
- * }
25
- * ```
26
- */
27
- generateUserId() {
28
- return this._hashGenerator.generateRandomSelfValidate();
29
- }
30
- /**
31
- * Validates a user ID without token.
32
- * @param userId The user ID to verify.
33
- * @returns A boolean indicating whether the user ID is valid.
34
- * @example
35
- * ```typescript
36
- * if (!userFactory.verifyUserId(user.id)) {
37
- * throw new Error('invalid_user');
38
- * }
39
- * ```
40
- */
41
- verifyUserId(userId) {
42
- return this._hashGenerator.verifySelfValidate(userId);
43
- }
44
- /**
45
- * Generates a user authentication token.
46
- * @param uniquelyList The list of values to generate the token from.
47
- * @returns The generated user token.
48
- * @example
49
- * ```typescript
50
- * const userToken = userFactory.generateToken([user.id, user.lpe]);
51
- * ```
52
- */
53
- generateToken(uniquelyList) {
54
- return this._tokenGenerator.generate(uniquelyList.join());
55
- }
56
- /**
57
- * Verifies a user authentication token.
58
- * @param uniquelyList The list of values used to generate the token.
59
- * @param token The user token to verify.
60
- * @returns The status of the token verification.
61
- * @example
62
- * ```typescript
63
- * if (!userFactory.verifyToken([user.id, user.lpe], userToken)) {
64
- * throw new Error('invalid_token');
65
- * }
66
- * ```
67
- */
68
- verifyToken(uniquelyList, token) {
69
- return this._tokenGenerator.verify(uniquelyList.join(), token);
70
- }
71
- }
72
- //# sourceMappingURL=user.js.map
package/user.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"user.js","sourceRoot":"","sources":["src/user.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAIlD;;GAEG;AACH,MAAM,OAAO,mBAAmB;IAI9B;;;;OAIG;IACH,YAAY,MAA2B;QACrC,IAAI,CAAC,cAAc,GAAG,IAAI,mBAAmB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC7D,IAAI,CAAC,eAAe,GAAG,IAAI,oBAAoB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAChE,CAAC;IAED;;;;;;;;;;OAUG;IACH,cAAc;QACZ,OAAO,IAAI,CAAC,cAAc,CAAC,0BAA0B,EAAE,CAAC;IAC1D,CAAC;IAED;;;;;;;;;;OAUG;IACH,YAAY,CAAC,MAAc;QACzB,OAAO,IAAI,CAAC,cAAc,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;IACxD,CAAC;IAED;;;;;;;;OAQG;IACH,aAAa,CAAC,YAA2C;QACvD,OAAO,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC;IAC5D,CAAC;IAED;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,YAA2C,EAAE,KAAa;QACpE,OAAO,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;IACjE,CAAC;CACF","sourcesContent":["import { AlwatrHashGenerator } from './hash.js';\nimport { AlwatrTokenGenerator } from './token.js';\n\nimport type {UserGeneratorConfig, TokenStatus } from './type.js';\n\n/**\n * User factory for generating self-validate user-id and user-token.\n */\nexport class AlwatrUserGenerator {\n protected _tokenGenerator: AlwatrTokenGenerator;\n protected _hashGenerator: AlwatrHashGenerator;\n\n /**\n * Creates a new instance of AlwatrUserFactory.\n * @param hashConfig The configuration for the hash generator.\n * @param tokenConfig The configuration for the token generator.\n */\n constructor(config: UserGeneratorConfig) {\n this._hashGenerator = new AlwatrHashGenerator(config.userId);\n this._tokenGenerator = new AlwatrTokenGenerator(config.token);\n }\n\n /**\n * Generates a new self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: userFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._hashGenerator.generateRandomSelfValidate();\n }\n\n /**\n * Validates 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 (!userFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._hashGenerator.verifySelfValidate(userId);\n }\n\n /**\n * Generates a user authentication token.\n * @param uniquelyList The list of values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = userFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number | boolean)[]): string {\n return this._tokenGenerator.generate(uniquelyList.join());\n }\n\n /**\n * Verifies a user authentication token.\n * @param uniquelyList The list of values used to generate the token.\n * @param token The user token to verify.\n * @returns The status of the token verification.\n * @example\n * ```typescript\n * if (!userFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number | boolean)[], token: string): TokenStatus {\n return this._tokenGenerator.verify(uniquelyList.join(), token);\n }\n}\n"]}