@alwatr/crypto 4.2.1 → 4.3.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 +33 -0
- package/README.md +14 -0
- package/dist/api.d.ts +2 -2
- package/dist/api.d.ts.map +1 -1
- package/dist/main.cjs +360 -2
- package/dist/main.cjs.map +4 -4
- package/dist/main.d.ts.map +1 -1
- package/dist/main.mjs +328 -2
- package/dist/main.mjs.map +4 -4
- package/dist/token.d.ts +2 -2
- package/dist/token.d.ts.map +1 -1
- package/package.json +10 -11
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,39 @@
|
|
|
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.3.0](https://github.com/Alwatr/nanotron/compare/v4.2.2...v4.3.0) (2024-10-11)
|
|
7
|
+
|
|
8
|
+
### Features
|
|
9
|
+
|
|
10
|
+
* update `import`s & packages based on the latest changes of `nanolib` & prevent `sideeffects` from `build` result ([1d234b8](https://github.com/Alwatr/nanotron/commit/1d234b83152fb246b793476898e9cf026aa52874)) by @mohammadhonarvar
|
|
11
|
+
|
|
12
|
+
### Bug Fixes
|
|
13
|
+
|
|
14
|
+
* **crypto:** update types & `logger` & use `packageTracer` based on last changes of `nanolib` ([cf1a480](https://github.com/Alwatr/nanotron/commit/cf1a48071fe745226f6aed2afdf11038da5065e2)) by @mohammadhonarvar
|
|
15
|
+
|
|
16
|
+
### Code Refactoring
|
|
17
|
+
|
|
18
|
+
* update `import`s & packages based on the latest changes of `nanolib` ([7652b5d](https://github.com/Alwatr/nanotron/commit/7652b5d9cc69218f2ff28bda3d0d8f52f147c6f6)) by @mohammadhonarvar
|
|
19
|
+
|
|
20
|
+
### Miscellaneous Chores
|
|
21
|
+
|
|
22
|
+
* edited README ([d707d38](https://github.com/Alwatr/nanotron/commit/d707d389e085dd320402521cb23af5805013d777)) by @ArmanAsadian
|
|
23
|
+
|
|
24
|
+
### Dependencies update
|
|
25
|
+
|
|
26
|
+
* update ([834ffcc](https://github.com/Alwatr/nanotron/commit/834ffcc8f6de96cc11a1a6fa933f948b7813cde6)) by @mohammadhonarvar
|
|
27
|
+
|
|
28
|
+
## [4.2.2](https://github.com/Alwatr/nanotron/compare/v4.2.1...v4.2.2) (2024-09-29)
|
|
29
|
+
|
|
30
|
+
### Miscellaneous Chores
|
|
31
|
+
|
|
32
|
+
* **crypto:** change the license to AGPL-3.0 ([a37fb50](https://github.com/Alwatr/nanotron/commit/a37fb50898bb0bc909746f44bc34d14bcf255a61)) by @ArmanAsadian
|
|
33
|
+
|
|
34
|
+
### Dependencies update
|
|
35
|
+
|
|
36
|
+
* bump @types/node in the development-dependencies group ([9c8d7d5](https://github.com/Alwatr/nanotron/commit/9c8d7d518d9a5da2ea57ac2b210a8697267e6d3d)) by @dependabot[bot]
|
|
37
|
+
* update ([1c4ef63](https://github.com/Alwatr/nanotron/commit/1c4ef635fc969d4abd416aea2b954de674748da8)) by @AliMD
|
|
38
|
+
|
|
6
39
|
## [4.2.1](https://github.com/Alwatr/nanotron/compare/v4.2.0...v4.2.1) (2024-09-24)
|
|
7
40
|
|
|
8
41
|
### Dependencies update
|
package/README.md
CHANGED
|
@@ -18,3 +18,17 @@ A robust generator of secure authentication HOTP tokens, employing the HMAC-base
|
|
|
18
18
|
- [HMAC Generator/Tester Tool](https://www.freeformatter.com/hmac-generator.html). FreeFormatter.
|
|
19
19
|
- [How API Request Signing Works (And How to Implement HMAC in NodeJS)](https://blog.andrewhoang.me/how-api-request-signing-works-and-how-to-implement-it-in-nodejs-2/). (2016). Andrew Hoang.
|
|
20
20
|
- [Implement HMAC Authentication](https://support.google.com/admanager/answer/7637490?hl=en). Google Ad Manager Help.
|
|
21
|
+
|
|
22
|
+
## Sponsors
|
|
23
|
+
|
|
24
|
+
The following companies, organizations, and individuals support Nanotron ongoing maintenance and development. Become a Sponsor to get your logo on our README and website.
|
|
25
|
+
|
|
26
|
+
[](https://exirstudio.com)
|
|
27
|
+
|
|
28
|
+
### Contributing
|
|
29
|
+
|
|
30
|
+
Contributions are welcome! Please read our [contribution guidelines](https://github.com/Alwatr/.github/blob/next/CONTRIBUTING.md) before submitting a pull request.
|
|
31
|
+
|
|
32
|
+
### License
|
|
33
|
+
|
|
34
|
+
This project is licensed under the [AGPL-3.0 License](LICENSE).
|
package/dist/api.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { type Duration } from '@alwatr/nanolib';
|
|
1
2
|
import { AlwatrHashGenerator } from './hash.js';
|
|
2
3
|
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
|
*/
|
|
@@ -12,7 +12,7 @@ export interface CryptoFactoryConfig {
|
|
|
12
12
|
/**
|
|
13
13
|
* The duration for which the token is valid.
|
|
14
14
|
*/
|
|
15
|
-
duration:
|
|
15
|
+
duration: Duration | 'infinite';
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
18
|
* Crypto factory for generating self-validate user-id, user-token, secret, device-id.
|
package/dist/api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,QAAQ,EAAC,MAAM,iBAAiB,CAAC;AAE7D,OAAO,EAAC,mBAAmB,EAAC,MAAM,WAAW,CAAC;AAO9C,OAAO,EAAC,oBAAoB,EAAE,KAAK,aAAa,EAAC,MAAM,YAAY,CAAC;AAIpE;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,QAAQ,EAAE,QAAQ,GAAG,UAAU,CAAC;CACjC;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/dist/main.cjs
CHANGED
|
@@ -1,3 +1,361 @@
|
|
|
1
|
-
/* @alwatr/crypto v4.
|
|
2
|
-
"use strict";
|
|
1
|
+
/* @alwatr/crypto v4.3.0 */
|
|
2
|
+
"use strict";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/main.ts
|
|
22
|
+
var main_exports = {};
|
|
23
|
+
__export(main_exports, {
|
|
24
|
+
AlwatrCryptoFactory: () => AlwatrCryptoFactory,
|
|
25
|
+
AlwatrHashGenerator: () => AlwatrHashGenerator,
|
|
26
|
+
AlwatrTokenGenerator: () => AlwatrTokenGenerator,
|
|
27
|
+
deviceIdGeneratorRecommendedConfig: () => deviceIdGeneratorRecommendedConfig,
|
|
28
|
+
secretGeneratorRecommendedConfig: () => secretGeneratorRecommendedConfig,
|
|
29
|
+
userIdGeneratorRecommendedConfig: () => userIdGeneratorRecommendedConfig,
|
|
30
|
+
userTokenGeneratorRecommendedConfig: () => userTokenGeneratorRecommendedConfig
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(main_exports);
|
|
33
|
+
|
|
34
|
+
// src/hash.ts
|
|
35
|
+
var import_node_crypto = require("node:crypto");
|
|
36
|
+
var AlwatrHashGenerator = class {
|
|
37
|
+
/**
|
|
38
|
+
* Creates a new instance of the AlwatrHashGenerator class.
|
|
39
|
+
* @param config The configuration for the hash generator.
|
|
40
|
+
*/
|
|
41
|
+
constructor(config) {
|
|
42
|
+
this.config = config;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Generate a random hash.
|
|
46
|
+
* @returns The generated hash.
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* const clientId = hashGenerator.generateRandom();
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
generateRandom() {
|
|
53
|
+
return this.generate((0, import_node_crypto.randomBytes)(16));
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Generate a **self-validate** random hash.
|
|
57
|
+
* @returns The generated self-validated hash.
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* const userId = hashGenerator.generateRandomSelfValidate();
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
generateRandomSelfValidate() {
|
|
64
|
+
return this.generateSelfValidate((0, import_node_crypto.randomBytes)(16));
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Generate a hash from data.
|
|
68
|
+
* @param data - The data to generate the hash from.
|
|
69
|
+
* @returns The generated hash.
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* const crcHash = hashGenerator.generate(data);
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
generate(data) {
|
|
76
|
+
return this.config.prefix + (0, import_node_crypto.createHash)(this.config.algorithm).update(data).digest(this.config.encoding);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Generate a crc hash.
|
|
80
|
+
* @param data - The data to generate the crc hash from.
|
|
81
|
+
* @returns The generated crc hash.
|
|
82
|
+
*/
|
|
83
|
+
generateCrc(data) {
|
|
84
|
+
const crc = (0, import_node_crypto.createHash)("sha1").update(data).digest(this.config.encoding);
|
|
85
|
+
return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Generate a **self-validate** hash from data.
|
|
89
|
+
* @param data - The data to generate the self-validated hash from.
|
|
90
|
+
* @returns The generated self-validated hash.
|
|
91
|
+
* @example
|
|
92
|
+
* ```typescript
|
|
93
|
+
* const userId = hashGenerator.generateSelfValidate(data);
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
generateSelfValidate(data) {
|
|
97
|
+
const mainHash = this.generate(data);
|
|
98
|
+
const crcHash = this.generateCrc(mainHash);
|
|
99
|
+
return mainHash + crcHash;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Verify if the generated hash matches the provided hash.
|
|
103
|
+
* @param data - The data to verify.
|
|
104
|
+
* @param hash - The hash to compare against.
|
|
105
|
+
* @returns `true` if the hash is verified, `false` otherwise.
|
|
106
|
+
* @example
|
|
107
|
+
* ```typescript
|
|
108
|
+
* if (!hashGenerator.verify(data, hash)) {
|
|
109
|
+
* new Error('data_corrupted');
|
|
110
|
+
* }
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
verify(data, hash) {
|
|
114
|
+
return hash === this.generate(data);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Verify a **self-validate** hash to check if it was generated by this class (with the same options).
|
|
118
|
+
* @param hash - The self-validated hash to verify.
|
|
119
|
+
* @returns `true` if the hash is verified, `false` otherwise.
|
|
120
|
+
* @example
|
|
121
|
+
* ```typescript
|
|
122
|
+
* if (!hashGenerator.verifySelfValidate(hash)) {
|
|
123
|
+
* new Error('invalid_hash');
|
|
124
|
+
* }
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
verifySelfValidate(hash) {
|
|
128
|
+
const gapPos = hash.length - this.config.crcLength;
|
|
129
|
+
const mainHash = hash.slice(0, gapPos);
|
|
130
|
+
const crcHash = hash.slice(gapPos);
|
|
131
|
+
return crcHash === this.generateCrc(mainHash);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
// src/token.ts
|
|
136
|
+
var import_node_crypto2 = require("node:crypto");
|
|
137
|
+
var import_nanolib = require("@alwatr/nanolib");
|
|
138
|
+
var AlwatrTokenGenerator = class {
|
|
139
|
+
/**
|
|
140
|
+
* Creates a new instance of AlwatrTokenGenerator.
|
|
141
|
+
* @param config The configuration for the token generator.
|
|
142
|
+
*/
|
|
143
|
+
constructor(config) {
|
|
144
|
+
this.config = config;
|
|
145
|
+
this._duration = config.duration == "infinite" ? 0 : (0, import_nanolib.parseDuration)(config.duration);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* The current epoch based on the configured duration.
|
|
149
|
+
*/
|
|
150
|
+
get _epoch() {
|
|
151
|
+
return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Generates a HOTP token based on the provided data for special duration.
|
|
155
|
+
* @param data The data to generate the token from.
|
|
156
|
+
* @returns The generated token.
|
|
157
|
+
* @example
|
|
158
|
+
* ```typescript
|
|
159
|
+
* user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
generate(data) {
|
|
163
|
+
return this._generate(data, this._epoch);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Verifies if a token is valid.
|
|
167
|
+
* @param data The data used to generate the token.
|
|
168
|
+
* @param token The token to verify.
|
|
169
|
+
* @returns The validity of the token.
|
|
170
|
+
* @example
|
|
171
|
+
* ```typescript
|
|
172
|
+
* const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
verify(data, token) {
|
|
176
|
+
const epoch = this._epoch;
|
|
177
|
+
if (token === this._generate(data, epoch)) return "valid";
|
|
178
|
+
if (this._duration == 0) return "invalid";
|
|
179
|
+
if (token === this._generate(data, epoch - 1)) return "expired";
|
|
180
|
+
return "invalid";
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Generates a cryptographic token based on the provided data and epoch.
|
|
184
|
+
* @param data - The data to be used in the token generation.
|
|
185
|
+
* @param epoch - The epoch value to be used in the token generation.
|
|
186
|
+
* @returns The generated cryptographic token.
|
|
187
|
+
*/
|
|
188
|
+
_generate(data, epoch) {
|
|
189
|
+
return this.config.prefix + (0, import_node_crypto2.createHmac)(this.config.algorithm, data).update(data + epoch).digest(this.config.encoding);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// src/api.ts
|
|
194
|
+
var import_nanolib2 = require("@alwatr/nanolib");
|
|
195
|
+
|
|
196
|
+
// src/pre-config.ts
|
|
197
|
+
var userIdGeneratorRecommendedConfig = {
|
|
198
|
+
prefix: "u",
|
|
199
|
+
algorithm: "sha1",
|
|
200
|
+
encoding: "base64url",
|
|
201
|
+
crcLength: 4
|
|
202
|
+
};
|
|
203
|
+
var deviceIdGeneratorRecommendedConfig = {
|
|
204
|
+
...userIdGeneratorRecommendedConfig,
|
|
205
|
+
prefix: "d"
|
|
206
|
+
};
|
|
207
|
+
var secretGeneratorRecommendedConfig = {
|
|
208
|
+
prefix: "s",
|
|
209
|
+
algorithm: "sha384",
|
|
210
|
+
encoding: "base64url",
|
|
211
|
+
crcLength: 4
|
|
212
|
+
};
|
|
213
|
+
var userTokenGeneratorRecommendedConfig = {
|
|
214
|
+
prefix: "t",
|
|
215
|
+
algorithm: "sha224",
|
|
216
|
+
encoding: "base64url"
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// src/api.ts
|
|
220
|
+
__dev_mode__: import_nanolib2.packageTracer.add("@alwatr/crypto", "4.3.0");
|
|
221
|
+
var AlwatrCryptoFactory = class {
|
|
222
|
+
/**
|
|
223
|
+
* Creates a new instance of crypto factory.
|
|
224
|
+
* @param config The configuration used to create the crypto factory.
|
|
225
|
+
*/
|
|
226
|
+
constructor(config) {
|
|
227
|
+
this._generators = {
|
|
228
|
+
secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),
|
|
229
|
+
deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),
|
|
230
|
+
userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),
|
|
231
|
+
token: new AlwatrTokenGenerator({
|
|
232
|
+
...userTokenGeneratorRecommendedConfig,
|
|
233
|
+
...config
|
|
234
|
+
})
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Generate self-verifiable user ID.
|
|
239
|
+
* @returns The generated user ID.
|
|
240
|
+
* @example
|
|
241
|
+
* ```typescript
|
|
242
|
+
* const newUser = {
|
|
243
|
+
* id: cryptoFactory.generateUserId(),
|
|
244
|
+
* ...
|
|
245
|
+
* }
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
generateUserId() {
|
|
249
|
+
return this._generators.userId.generateRandomSelfValidate();
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Verify a user ID without token.
|
|
253
|
+
* @param userId The user ID to verify.
|
|
254
|
+
* @returns A boolean indicating whether the user ID is valid.
|
|
255
|
+
* @example
|
|
256
|
+
* ```typescript
|
|
257
|
+
* if (!cryptoFactory.verifyUserId(user.id)) {
|
|
258
|
+
* throw new Error('invalid_user');
|
|
259
|
+
* }
|
|
260
|
+
* ```
|
|
261
|
+
*/
|
|
262
|
+
verifyUserId(userId) {
|
|
263
|
+
return this._generators.userId.verifySelfValidate(userId);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Generate authentication token.
|
|
267
|
+
* @param uniquelyList The list of uniq values to generate the token from.
|
|
268
|
+
* @returns The generated user token.
|
|
269
|
+
* @example
|
|
270
|
+
* ```typescript
|
|
271
|
+
* const userToken = cryptoFactory.generateToken([user.id, user.lpe]);
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
274
|
+
generateToken(uniquelyList) {
|
|
275
|
+
return this._generators.token.generate(uniquelyList.join());
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Verify a authentication token.
|
|
279
|
+
* @param uniquelyList The list of uniq values used to generate the token.
|
|
280
|
+
* @param token The user token to verify.
|
|
281
|
+
* @returns The validity of the token.
|
|
282
|
+
* @example
|
|
283
|
+
* ```typescript
|
|
284
|
+
* if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {
|
|
285
|
+
* throw new Error('invalid_token');
|
|
286
|
+
* }
|
|
287
|
+
* ```
|
|
288
|
+
*/
|
|
289
|
+
verifyToken(uniquelyList, token) {
|
|
290
|
+
return this._generators.token.verify(uniquelyList.join(), token);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Generate self-verifiable secret.
|
|
294
|
+
* @returns The generated secret.
|
|
295
|
+
* @example
|
|
296
|
+
* ```typescript
|
|
297
|
+
* const config = {
|
|
298
|
+
* storageToken: cryptoFactory.generateSecret(),
|
|
299
|
+
* ...
|
|
300
|
+
* }
|
|
301
|
+
* ```
|
|
302
|
+
*/
|
|
303
|
+
generateSecret() {
|
|
304
|
+
return this._generators.secret.generateRandomSelfValidate();
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Verify a secret.
|
|
308
|
+
* @param secret The secret to verify.
|
|
309
|
+
* @returns A boolean indicating whether the secret is valid.
|
|
310
|
+
* @example
|
|
311
|
+
* ```typescript
|
|
312
|
+
* if (!cryptoFactory.verifySecret(config.storageToken)) {
|
|
313
|
+
* throw new Error('invalid_secret');
|
|
314
|
+
* }
|
|
315
|
+
* ```
|
|
316
|
+
*/
|
|
317
|
+
verifySecret(secret) {
|
|
318
|
+
return this._generators.secret.verifySelfValidate(secret);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Generate self-verifiable device ID.
|
|
322
|
+
* @returns The generated device ID.
|
|
323
|
+
* @example
|
|
324
|
+
* ```typescript
|
|
325
|
+
* const deviceId = deviceFactory.generateDeviceId();
|
|
326
|
+
* ```
|
|
327
|
+
*/
|
|
328
|
+
generateDeviceId() {
|
|
329
|
+
return this._generators.deviceId.generateRandomSelfValidate();
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Verify a device ID.
|
|
333
|
+
* @param deviceId The device ID to verify.
|
|
334
|
+
* @returns A boolean indicating whether the device ID is valid.
|
|
335
|
+
* @example
|
|
336
|
+
* ```typescript
|
|
337
|
+
* if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {
|
|
338
|
+
* throw {
|
|
339
|
+
* ok: false,
|
|
340
|
+
* status: 400,
|
|
341
|
+
* error: 'invalid_device_id',
|
|
342
|
+
* }
|
|
343
|
+
* }
|
|
344
|
+
* ```
|
|
345
|
+
*/
|
|
346
|
+
verifyDeviceId(deviceId) {
|
|
347
|
+
return this._generators.deviceId.verifySelfValidate(deviceId);
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
351
|
+
0 && (module.exports = {
|
|
352
|
+
AlwatrCryptoFactory,
|
|
353
|
+
AlwatrHashGenerator,
|
|
354
|
+
AlwatrTokenGenerator,
|
|
355
|
+
deviceIdGeneratorRecommendedConfig,
|
|
356
|
+
secretGeneratorRecommendedConfig,
|
|
357
|
+
userIdGeneratorRecommendedConfig,
|
|
358
|
+
userTokenGeneratorRecommendedConfig
|
|
359
|
+
});
|
|
360
|
+
/*! For license information please see main.cjs.LEGAL.txt */
|
|
3
361
|
//# sourceMappingURL=main.cjs.map
|
package/dist/main.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/main.ts", "../src/hash.ts", "../src/token.ts", "../src/
|
|
4
|
-
"sourcesContent": ["import {definePackage} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('@alwatr/crypto', __package_version__);\n", "import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type DurationString} from '@alwatr/parse-duration';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n", "import {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\nimport type {DurationString} from '@alwatr/parse-duration';\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../src/main.ts", "../src/hash.ts", "../src/token.ts", "../src/api.ts", "../src/pre-config.ts"],
|
|
4
|
+
"sourcesContent": ["export * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n", "import {createHash, randomBytes, type BinaryLike} 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 Duration} from '@alwatr/nanolib';\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: Duration | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n 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 {packageTracer, type Duration} from '@alwatr/nanolib';\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__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n 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 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"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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O,KAAK,YAAY,MAAM,OAAO,aAAa,KAAK,GAAG,KAAK;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,iBAAyB;AACvB,WAAO,KAAK,YAAY,OAAO,2BAA2B;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,aAAa,QAAyB;AACpC,WAAO,KAAK,YAAY,OAAO,mBAAmB,MAAM;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,mBAA2B;AACzB,WAAO,KAAK,YAAY,SAAS,2BAA2B;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,eAAe,UAA2B;AACxC,WAAO,KAAK,YAAY,SAAS,mBAAmB,QAAQ;AAAA,EAC9D;AACF;",
|
|
6
|
+
"names": ["import_node_crypto", "import_nanolib"]
|
|
7
7
|
}
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC"}
|
package/dist/main.mjs
CHANGED
|
@@ -1,3 +1,329 @@
|
|
|
1
|
-
/* @alwatr/crypto v4.
|
|
2
|
-
|
|
1
|
+
/* @alwatr/crypto v4.3.0 */
|
|
2
|
+
|
|
3
|
+
// src/hash.ts
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
var AlwatrHashGenerator = class {
|
|
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
|
+
|
|
104
|
+
// src/token.ts
|
|
105
|
+
import { createHmac } from "node:crypto";
|
|
106
|
+
import { parseDuration } from "@alwatr/nanolib";
|
|
107
|
+
var AlwatrTokenGenerator = class {
|
|
108
|
+
/**
|
|
109
|
+
* Creates a new instance of AlwatrTokenGenerator.
|
|
110
|
+
* @param config The configuration for the token generator.
|
|
111
|
+
*/
|
|
112
|
+
constructor(config) {
|
|
113
|
+
this.config = config;
|
|
114
|
+
this._duration = config.duration == "infinite" ? 0 : parseDuration(config.duration);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The current epoch based on the configured duration.
|
|
118
|
+
*/
|
|
119
|
+
get _epoch() {
|
|
120
|
+
return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Generates a HOTP token based on the provided data for special duration.
|
|
124
|
+
* @param data The data to generate the token from.
|
|
125
|
+
* @returns The generated token.
|
|
126
|
+
* @example
|
|
127
|
+
* ```typescript
|
|
128
|
+
* user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);
|
|
129
|
+
* ```
|
|
130
|
+
*/
|
|
131
|
+
generate(data) {
|
|
132
|
+
return this._generate(data, this._epoch);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Verifies if a token is valid.
|
|
136
|
+
* @param data The data used to generate the token.
|
|
137
|
+
* @param token The token to verify.
|
|
138
|
+
* @returns The validity of the token.
|
|
139
|
+
* @example
|
|
140
|
+
* ```typescript
|
|
141
|
+
* const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
verify(data, token) {
|
|
145
|
+
const epoch = this._epoch;
|
|
146
|
+
if (token === this._generate(data, epoch)) return "valid";
|
|
147
|
+
if (this._duration == 0) return "invalid";
|
|
148
|
+
if (token === this._generate(data, epoch - 1)) return "expired";
|
|
149
|
+
return "invalid";
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Generates a cryptographic token based on the provided data and epoch.
|
|
153
|
+
* @param data - The data to be used in the token generation.
|
|
154
|
+
* @param epoch - The epoch value to be used in the token generation.
|
|
155
|
+
* @returns The generated cryptographic token.
|
|
156
|
+
*/
|
|
157
|
+
_generate(data, epoch) {
|
|
158
|
+
return this.config.prefix + createHmac(this.config.algorithm, data).update(data + epoch).digest(this.config.encoding);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// src/api.ts
|
|
163
|
+
import { packageTracer } from "@alwatr/nanolib";
|
|
164
|
+
|
|
165
|
+
// src/pre-config.ts
|
|
166
|
+
var userIdGeneratorRecommendedConfig = {
|
|
167
|
+
prefix: "u",
|
|
168
|
+
algorithm: "sha1",
|
|
169
|
+
encoding: "base64url",
|
|
170
|
+
crcLength: 4
|
|
171
|
+
};
|
|
172
|
+
var deviceIdGeneratorRecommendedConfig = {
|
|
173
|
+
...userIdGeneratorRecommendedConfig,
|
|
174
|
+
prefix: "d"
|
|
175
|
+
};
|
|
176
|
+
var secretGeneratorRecommendedConfig = {
|
|
177
|
+
prefix: "s",
|
|
178
|
+
algorithm: "sha384",
|
|
179
|
+
encoding: "base64url",
|
|
180
|
+
crcLength: 4
|
|
181
|
+
};
|
|
182
|
+
var userTokenGeneratorRecommendedConfig = {
|
|
183
|
+
prefix: "t",
|
|
184
|
+
algorithm: "sha224",
|
|
185
|
+
encoding: "base64url"
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// src/api.ts
|
|
189
|
+
__dev_mode__: packageTracer.add("@alwatr/crypto", "4.3.0");
|
|
190
|
+
var AlwatrCryptoFactory = class {
|
|
191
|
+
/**
|
|
192
|
+
* Creates a new instance of crypto factory.
|
|
193
|
+
* @param config The configuration used to create the crypto factory.
|
|
194
|
+
*/
|
|
195
|
+
constructor(config) {
|
|
196
|
+
this._generators = {
|
|
197
|
+
secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),
|
|
198
|
+
deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),
|
|
199
|
+
userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),
|
|
200
|
+
token: new AlwatrTokenGenerator({
|
|
201
|
+
...userTokenGeneratorRecommendedConfig,
|
|
202
|
+
...config
|
|
203
|
+
})
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Generate self-verifiable user ID.
|
|
208
|
+
* @returns The generated user ID.
|
|
209
|
+
* @example
|
|
210
|
+
* ```typescript
|
|
211
|
+
* const newUser = {
|
|
212
|
+
* id: cryptoFactory.generateUserId(),
|
|
213
|
+
* ...
|
|
214
|
+
* }
|
|
215
|
+
* ```
|
|
216
|
+
*/
|
|
217
|
+
generateUserId() {
|
|
218
|
+
return this._generators.userId.generateRandomSelfValidate();
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Verify a user ID without token.
|
|
222
|
+
* @param userId The user ID to verify.
|
|
223
|
+
* @returns A boolean indicating whether the user ID is valid.
|
|
224
|
+
* @example
|
|
225
|
+
* ```typescript
|
|
226
|
+
* if (!cryptoFactory.verifyUserId(user.id)) {
|
|
227
|
+
* throw new Error('invalid_user');
|
|
228
|
+
* }
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
verifyUserId(userId) {
|
|
232
|
+
return this._generators.userId.verifySelfValidate(userId);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Generate authentication token.
|
|
236
|
+
* @param uniquelyList The list of uniq values to generate the token from.
|
|
237
|
+
* @returns The generated user token.
|
|
238
|
+
* @example
|
|
239
|
+
* ```typescript
|
|
240
|
+
* const userToken = cryptoFactory.generateToken([user.id, user.lpe]);
|
|
241
|
+
* ```
|
|
242
|
+
*/
|
|
243
|
+
generateToken(uniquelyList) {
|
|
244
|
+
return this._generators.token.generate(uniquelyList.join());
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Verify a authentication token.
|
|
248
|
+
* @param uniquelyList The list of uniq values used to generate the token.
|
|
249
|
+
* @param token The user token to verify.
|
|
250
|
+
* @returns The validity of the token.
|
|
251
|
+
* @example
|
|
252
|
+
* ```typescript
|
|
253
|
+
* if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {
|
|
254
|
+
* throw new Error('invalid_token');
|
|
255
|
+
* }
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
verifyToken(uniquelyList, token) {
|
|
259
|
+
return this._generators.token.verify(uniquelyList.join(), token);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Generate self-verifiable secret.
|
|
263
|
+
* @returns The generated secret.
|
|
264
|
+
* @example
|
|
265
|
+
* ```typescript
|
|
266
|
+
* const config = {
|
|
267
|
+
* storageToken: cryptoFactory.generateSecret(),
|
|
268
|
+
* ...
|
|
269
|
+
* }
|
|
270
|
+
* ```
|
|
271
|
+
*/
|
|
272
|
+
generateSecret() {
|
|
273
|
+
return this._generators.secret.generateRandomSelfValidate();
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Verify a secret.
|
|
277
|
+
* @param secret The secret to verify.
|
|
278
|
+
* @returns A boolean indicating whether the secret is valid.
|
|
279
|
+
* @example
|
|
280
|
+
* ```typescript
|
|
281
|
+
* if (!cryptoFactory.verifySecret(config.storageToken)) {
|
|
282
|
+
* throw new Error('invalid_secret');
|
|
283
|
+
* }
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
verifySecret(secret) {
|
|
287
|
+
return this._generators.secret.verifySelfValidate(secret);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Generate self-verifiable device ID.
|
|
291
|
+
* @returns The generated device ID.
|
|
292
|
+
* @example
|
|
293
|
+
* ```typescript
|
|
294
|
+
* const deviceId = deviceFactory.generateDeviceId();
|
|
295
|
+
* ```
|
|
296
|
+
*/
|
|
297
|
+
generateDeviceId() {
|
|
298
|
+
return this._generators.deviceId.generateRandomSelfValidate();
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Verify a device ID.
|
|
302
|
+
* @param deviceId The device ID to verify.
|
|
303
|
+
* @returns A boolean indicating whether the device ID is valid.
|
|
304
|
+
* @example
|
|
305
|
+
* ```typescript
|
|
306
|
+
* if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {
|
|
307
|
+
* throw {
|
|
308
|
+
* ok: false,
|
|
309
|
+
* status: 400,
|
|
310
|
+
* error: 'invalid_device_id',
|
|
311
|
+
* }
|
|
312
|
+
* }
|
|
313
|
+
* ```
|
|
314
|
+
*/
|
|
315
|
+
verifyDeviceId(deviceId) {
|
|
316
|
+
return this._generators.deviceId.verifySelfValidate(deviceId);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
export {
|
|
320
|
+
AlwatrCryptoFactory,
|
|
321
|
+
AlwatrHashGenerator,
|
|
322
|
+
AlwatrTokenGenerator,
|
|
323
|
+
deviceIdGeneratorRecommendedConfig,
|
|
324
|
+
secretGeneratorRecommendedConfig,
|
|
325
|
+
userIdGeneratorRecommendedConfig,
|
|
326
|
+
userTokenGeneratorRecommendedConfig
|
|
327
|
+
};
|
|
328
|
+
/*! For license information please see main.mjs.LEGAL.txt */
|
|
3
329
|
//# sourceMappingURL=main.mjs.map
|
package/dist/main.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/hash.ts", "../src/token.ts", "../src/
|
|
4
|
-
"sourcesContent": ["import {createHash, randomBytes, type BinaryLike} from 'node:crypto';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\n/**\n * Represents the configuration for a hash generator.\n */\nexport interface HashGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The length of the CRC (Cyclic Redundancy Check) value.\n */\n crcLength: number;\n}\n\n/**\n * Secure **self-validate** hash generator.\n */\nexport class AlwatrHashGenerator {\n /**\n * Creates a new instance of the AlwatrHashGenerator class.\n * @param config The configuration for the hash generator.\n */\n constructor(public config: HashGeneratorConfig) {}\n\n /**\n * Generate a random hash.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const clientId = hashGenerator.generateRandom();\n * ```\n */\n generateRandom(): string {\n return this.generate(randomBytes(16));\n }\n\n /**\n * Generate a **self-validate** random hash.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateRandomSelfValidate();\n * ```\n */\n generateRandomSelfValidate(): string {\n return this.generateSelfValidate(randomBytes(16));\n }\n\n /**\n * Generate a hash from data.\n * @param data - The data to generate the hash from.\n * @returns The generated hash.\n * @example\n * ```typescript\n * const crcHash = hashGenerator.generate(data);\n * ```\n */\n generate(data: BinaryLike): string {\n return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);\n }\n\n /**\n * Generate a crc hash.\n * @param data - The data to generate the crc hash from.\n * @returns The generated crc hash.\n */\n generateCrc(data: BinaryLike): string {\n const crc = createHash('sha1').update(data).digest(this.config.encoding);\n return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);\n }\n\n /**\n * Generate a **self-validate** hash from data.\n * @param data - The data to generate the self-validated hash from.\n * @returns The generated self-validated hash.\n * @example\n * ```typescript\n * const userId = hashGenerator.generateSelfValidate(data);\n * ```\n */\n generateSelfValidate(data: BinaryLike): string {\n const mainHash = this.generate(data);\n const crcHash = this.generateCrc(mainHash);\n return mainHash + crcHash;\n }\n\n /**\n * Verify if the generated hash matches the provided hash.\n * @param data - The data to verify.\n * @param hash - The hash to compare against.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verify(data, hash)) {\n * new Error('data_corrupted');\n * }\n * ```\n */\n verify(data: BinaryLike, hash: string): boolean {\n return hash === this.generate(data);\n }\n\n /**\n * Verify a **self-validate** hash to check if it was generated by this class (with the same options).\n * @param hash - The self-validated hash to verify.\n * @returns `true` if the hash is verified, `false` otherwise.\n * @example\n * ```typescript\n * if (!hashGenerator.verifySelfValidate(hash)) {\n * new Error('invalid_hash');\n * }\n * ```\n */\n verifySelfValidate(hash: string): boolean {\n const gapPos = hash.length - this.config.crcLength;\n const mainHash = hash.slice(0, gapPos);\n const crcHash = hash.slice(gapPos);\n return crcHash === this.generateCrc(mainHash);\n }\n}\n", "import {createHmac} from 'node:crypto';\n\nimport {parseDuration, type DurationString} from '@alwatr/parse-duration';\n\nimport type {CryptoAlgorithm, CryptoEncoding} from './type.js';\n\nexport type TokenValidity = 'valid' | 'invalid' | 'expired';\n\n/**\n * Represents the configuration for a token generator.\n */\nexport interface TokenGeneratorConfig {\n /**\n * The prefix to be added to the generated hash.\n */\n prefix: string;\n\n /**\n * The algorithm used for hashing.\n */\n algorithm: CryptoAlgorithm;\n\n /**\n * The encoding used for the generated hash.\n */\n encoding: CryptoEncoding;\n\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n generate(data: string): string {\n return this._generate(data, this._epoch);\n }\n\n /**\n * Verifies if a token is valid.\n * @param data The data used to generate the token.\n * @param token The token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth);\n * ```\n */\n verify(data: string, token: string): TokenValidity {\n const epoch = this._epoch;\n if (token === this._generate(data, epoch)) return 'valid';\n if (this._duration == 0) return 'invalid';\n if (token === this._generate(data, epoch - 1)) return 'expired';\n return 'invalid';\n }\n\n /**\n * Generates a cryptographic token based on the provided data and epoch.\n * @param data - The data to be used in the token generation.\n * @param epoch - The epoch value to be used in the token generation.\n * @returns The generated cryptographic token.\n */\n protected _generate(data: string, epoch: number): string {\n return (\n this.config.prefix +\n createHmac(this.config.algorithm, data)\n .update(data + epoch)\n .digest(this.config.encoding)\n );\n }\n}\n", "import type {HashGeneratorConfig} from './hash.js';\nimport type {TokenGeneratorConfig} from './token.js';\n\n/**\n * Alwatr hash generator recommended configuration for making random self-validate **user-id**.\n */\nexport const userIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 'u',\n algorithm: 'sha1',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Hash generator recommended configuration for making random self-validate **device-id**.\n */\nexport const deviceIdGeneratorRecommendedConfig: HashGeneratorConfig = {\n ...userIdGeneratorRecommendedConfig,\n prefix: 'd',\n};\n\n/**\n * Hash generator pre configuration for making random self-validate **secrets**.\n */\nexport const secretGeneratorRecommendedConfig: HashGeneratorConfig = {\n prefix: 's',\n algorithm: 'sha384',\n encoding: 'base64url',\n crcLength: 4,\n};\n\n/**\n * Token generator recommended configuration for making secure self-validate **user-token**.\n */\nexport const userTokenGeneratorRecommendedConfig: Omit<TokenGeneratorConfig, 'secret' | 'duration'> = {\n prefix: 't',\n algorithm: 'sha224',\n encoding: 'base64url',\n};\n", "import {AlwatrHashGenerator} from './hash.js';\nimport {\n deviceIdGeneratorRecommendedConfig,\n secretGeneratorRecommendedConfig,\n userIdGeneratorRecommendedConfig,\n userTokenGeneratorRecommendedConfig,\n} from './pre-config.js';\nimport {AlwatrTokenGenerator, type TokenValidity} from './token.js';\n\nimport type {DurationString} from '@alwatr/parse-duration';\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: DurationString | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n generateUserId(): string {\n return this._generators.userId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a user ID without token.\n * @param userId The user ID to verify.\n * @returns A boolean indicating whether the user ID is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyUserId(user.id)) {\n * throw new Error('invalid_user');\n * }\n * ```\n */\n verifyUserId(userId: string): boolean {\n return this._generators.userId.verifySelfValidate(userId);\n }\n\n /**\n * Generate authentication token.\n * @param uniquelyList The list of uniq values to generate the token from.\n * @returns The generated user token.\n * @example\n * ```typescript\n * const userToken = cryptoFactory.generateToken([user.id, user.lpe]);\n * ```\n */\n generateToken(uniquelyList: (string | number)[]): string {\n return this._generators.token.generate(uniquelyList.join());\n }\n\n /**\n * Verify a authentication token.\n * @param uniquelyList The list of uniq values used to generate the token.\n * @param token The user token to verify.\n * @returns The validity of the token.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) {\n * throw new Error('invalid_token');\n * }\n * ```\n */\n verifyToken(uniquelyList: (string | number)[], token: string): TokenValidity {\n return this._generators.token.verify(uniquelyList.join(), token);\n }\n\n /**\n * Generate self-verifiable secret.\n * @returns The generated secret.\n * @example\n * ```typescript\n * const config = {\n * storageToken: cryptoFactory.generateSecret(),\n * ...\n * }\n * ```\n */\n generateSecret(): string {\n return this._generators.secret.generateRandomSelfValidate();\n }\n\n /**\n * Verify a secret.\n * @param secret The secret to verify.\n * @returns A boolean indicating whether the secret is valid.\n * @example\n * ```typescript\n * if (!cryptoFactory.verifySecret(config.storageToken)) {\n * throw new Error('invalid_secret');\n * }\n * ```\n */\n verifySecret(secret: string): boolean {\n return this._generators.secret.verifySelfValidate(secret);\n }\n\n /**\n * Generate self-verifiable device ID.\n * @returns The generated device ID.\n * @example\n * ```typescript\n * const deviceId = deviceFactory.generateDeviceId();\n * ```\n */\n generateDeviceId(): string {\n return this._generators.deviceId.generateRandomSelfValidate();\n }\n\n /**\n * Verify a device ID.\n * @param deviceId The device ID to verify.\n * @returns A boolean indicating whether the device ID is valid.\n * @example\n * ```typescript\n * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) {\n * throw {\n * ok: false,\n * status: 400,\n * error: 'invalid_device_id',\n * }\n * }\n * ```\n */\n verifyDeviceId(deviceId: string): boolean {\n return this._generators.deviceId.verifySelfValidate(deviceId);\n }\n}\n", "import {definePackage} from '@alwatr/logger';\n\nimport type {} from '@alwatr/nano-build';\n\nexport * from './hash.js';\nexport * from './token.js';\nexport * from './api.js';\nexport * from './type.js';\nexport * from './pre-config.js';\n\ndefinePackage('@alwatr/crypto', __package_version__);\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": ["../src/hash.ts", "../src/token.ts", "../src/api.ts", "../src/pre-config.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 Duration} from '@alwatr/nanolib';\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: Duration | 'infinite';\n}\n\n/**\n * Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).\n */\nexport class AlwatrTokenGenerator {\n private _duration: number;\n\n /**\n * The current epoch based on the configured duration.\n */\n protected get _epoch(): number {\n return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration);\n }\n\n /**\n * Creates a new instance of AlwatrTokenGenerator.\n * @param config The configuration for the token generator.\n */\n constructor(public config: TokenGeneratorConfig) {\n this._duration = config.duration == 'infinite' ? 0 : parseDuration(config.duration);\n }\n\n /**\n * Generates a HOTP token based on the provided data for special duration.\n * @param data The data to generate the token from.\n * @returns The generated token.\n * @example\n * ```typescript\n * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`);\n * ```\n */\n 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 {packageTracer, type Duration} from '@alwatr/nanolib';\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__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\n/**\n * Configuration options for the CryptoFactory.\n */\nexport interface CryptoFactoryConfig {\n /**\n * The secret used for encryption and decryption tokens.\n */\n secret: string;\n\n /**\n * The duration for which the token is valid.\n */\n duration: Duration | 'infinite';\n}\n\n/**\n * Crypto factory for generating self-validate user-id, user-token, secret, device-id.\n */\nexport class AlwatrCryptoFactory {\n protected _generators;\n\n /**\n * Creates a new instance of crypto factory.\n * @param config The configuration used to create the crypto factory.\n */\n constructor(config: CryptoFactoryConfig) {\n this._generators = {\n secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig),\n deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig),\n userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig),\n token: new AlwatrTokenGenerator({\n ...userTokenGeneratorRecommendedConfig,\n ...config,\n }),\n } as const;\n }\n\n /**\n * Generate self-verifiable user ID.\n * @returns The generated user ID.\n * @example\n * ```typescript\n * const newUser = {\n * id: cryptoFactory.generateUserId(),\n * ...\n * }\n * ```\n */\n 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 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: 'sha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EAcA,YAAY,cAAmC,OAA8B;AAC3E,WAAO,KAAK,YAAY,MAAM,OAAO,aAAa,KAAK,GAAG,KAAK;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,iBAAyB;AACvB,WAAO,KAAK,YAAY,OAAO,2BAA2B;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,aAAa,QAAyB;AACpC,WAAO,KAAK,YAAY,OAAO,mBAAmB,MAAM;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,mBAA2B;AACzB,WAAO,KAAK,YAAY,SAAS,2BAA2B;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,eAAe,UAA2B;AACxC,WAAO,KAAK,YAAY,SAAS,mBAAmB,QAAQ;AAAA,EAC9D;AACF;",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
package/dist/token.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type Duration } from '@alwatr/nanolib';
|
|
2
2
|
import type { CryptoAlgorithm, CryptoEncoding } from './type.js';
|
|
3
3
|
export type TokenValidity = 'valid' | 'invalid' | 'expired';
|
|
4
4
|
/**
|
|
@@ -24,7 +24,7 @@ export interface TokenGeneratorConfig {
|
|
|
24
24
|
/**
|
|
25
25
|
* The duration for which the token is valid.
|
|
26
26
|
*/
|
|
27
|
-
duration:
|
|
27
|
+
duration: Duration | 'infinite';
|
|
28
28
|
}
|
|
29
29
|
/**
|
|
30
30
|
* Secure authentication HOTP token generator (HMAC-based One-Time Password algorithm).
|
package/dist/token.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../src/token.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgB,KAAK,
|
|
1
|
+
{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../src/token.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgB,KAAK,QAAQ,EAAC,MAAM,iBAAiB,CAAC;AAE7D,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,QAAQ,GAAG,UAAU,CAAC;CACjC;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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/crypto",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.0",
|
|
4
4
|
"description": "A robust generator of secure authentication HOTP tokens, employing the HMAC-based One-Time Password algorithm, accompanied by a suite of cryptographic utilities, all encapsulated within a compact TypeScript module.",
|
|
5
5
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
|
|
6
6
|
"keywords": [
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"require": "./dist/main.cjs"
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
|
-
"license": "
|
|
34
|
+
"license": "AGPL-3.0-only",
|
|
35
35
|
"files": [
|
|
36
36
|
"**/*.{js,mjs,cjs,map,d.ts,html,md}",
|
|
37
37
|
"!demo/**/*"
|
|
@@ -66,17 +66,16 @@
|
|
|
66
66
|
"clean": "rm -rfv dist *.tsbuildinfo"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@alwatr/
|
|
70
|
-
"@alwatr/parse-duration": "^1.0.11"
|
|
69
|
+
"@alwatr/nanolib": "^1.2.0"
|
|
71
70
|
},
|
|
72
71
|
"devDependencies": {
|
|
73
|
-
"@alwatr/nano-build": "^
|
|
74
|
-
"@alwatr/prettier-config": "^1.0.
|
|
75
|
-
"@alwatr/tsconfig-base": "^1.2
|
|
76
|
-
"@alwatr/type-helper": "^
|
|
77
|
-
"@types/node": "^22.
|
|
72
|
+
"@alwatr/nano-build": "^2.0.1",
|
|
73
|
+
"@alwatr/prettier-config": "^1.0.6",
|
|
74
|
+
"@alwatr/tsconfig-base": "^1.3.2",
|
|
75
|
+
"@alwatr/type-helper": "^2.0.2",
|
|
76
|
+
"@types/node": "^22.7.5",
|
|
78
77
|
"jest": "^29.7.0",
|
|
79
|
-
"typescript": "^5.6.
|
|
78
|
+
"typescript": "^5.6.3"
|
|
80
79
|
},
|
|
81
|
-
"gitHead": "
|
|
80
|
+
"gitHead": "5dd04b482d18bc8160ead9003f1d518512a62a8e"
|
|
82
81
|
}
|