/* @alwatr/crypto v4.6.0 */ "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/main.ts var main_exports = {}; __export(main_exports, { AlwatrCryptoFactory: () => AlwatrCryptoFactory, AlwatrHashGenerator: () => AlwatrHashGenerator, AlwatrTokenGenerator: () => AlwatrTokenGenerator, deviceIdGeneratorRecommendedConfig: () => deviceIdGeneratorRecommendedConfig, secretGeneratorRecommendedConfig: () => secretGeneratorRecommendedConfig, userIdGeneratorRecommendedConfig: () => userIdGeneratorRecommendedConfig, userTokenGeneratorRecommendedConfig: () => userTokenGeneratorRecommendedConfig }); module.exports = __toCommonJS(main_exports); // src/hash.ts var import_node_crypto = require("node:crypto"); var AlwatrHashGenerator = class { /** * Creates a new instance of the AlwatrHashGenerator class. * @param config The configuration for the hash generator. */ constructor(config) { this.config = config; } /** * Generate a random hash. * @returns The generated hash. * @example * ```typescript * const clientId = hashGenerator.generateRandom(); * ``` */ generateRandom() { return this.generate((0, import_node_crypto.randomBytes)(16)); } /** * Generate a **self-validate** random hash. * @returns The generated self-validated hash. * @example * ```typescript * const userId = hashGenerator.generateRandomSelfValidate(); * ``` */ generateRandomSelfValidate() { return this.generateSelfValidate((0, import_node_crypto.randomBytes)(16)); } /** * Generate a hash from data. * @param data - The data to generate the hash from. * @returns The generated hash. * @example * ```typescript * const crcHash = hashGenerator.generate(data); * ``` */ generate(data) { return this.config.prefix + (0, import_node_crypto.createHash)(this.config.algorithm).update(data).digest(this.config.encoding); } /** * Generate a crc hash. * @param data - The data to generate the crc hash from. * @returns The generated crc hash. */ generateCrc(data) { const crc = (0, import_node_crypto.createHash)("sha1").update(data).digest(this.config.encoding); return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength); } /** * Generate a **self-validate** hash from data. * @param data - The data to generate the self-validated hash from. * @returns The generated self-validated hash. * @example * ```typescript * const userId = hashGenerator.generateSelfValidate(data); * ``` */ generateSelfValidate(data) { const mainHash = this.generate(data); const crcHash = this.generateCrc(mainHash); return mainHash + crcHash; } /** * Verify if the generated hash matches the provided hash. * @param data - The data to verify. * @param hash - The hash to compare against. * @returns `true` if the hash is verified, `false` otherwise. * @example * ```typescript * if (!hashGenerator.verify(data, hash)) { * new Error('data_corrupted'); * } * ``` */ verify(data, hash) { return hash === this.generate(data); } /** * Verify a **self-validate** hash to check if it was generated by this class (with the same options). * @param hash - The self-validated hash to verify. * @returns `true` if the hash is verified, `false` otherwise. * @example * ```typescript * if (!hashGenerator.verifySelfValidate(hash)) { * new Error('invalid_hash'); * } * ``` */ verifySelfValidate(hash) { const gapPos = hash.length - this.config.crcLength; const mainHash = hash.slice(0, gapPos); const crcHash = hash.slice(gapPos); return crcHash === this.generateCrc(mainHash); } }; // src/token.ts var import_node_crypto2 = require("node:crypto"); var import_nanolib = require("@alwatr/nanolib"); var AlwatrTokenGenerator = class { /** * Creates a new instance of AlwatrTokenGenerator. * @param config The configuration for the token generator. */ constructor(config) { this.config = config; this._duration = config.duration == "infinite" ? 0 : (0, import_nanolib.parseDuration)(config.duration); } /** * The current epoch based on the configured duration. */ get _epoch() { return this._duration == 0 ? 0 : Math.floor(Date.now() / this._duration); } /** * Generates a HOTP token based on the provided data for special duration. * @param data The data to generate the token from. * @returns The generated token. * @example * ```typescript * user.auth = tokenGenerator.generate(`${user.id}-${user.role}`); * ``` */ generate(data) { return this._generate(data, this._epoch); } /** * Verifies if a token is valid. * @param data The data used to generate the token. * @param token The token to verify. * @returns The validity of the token. * @example * ```typescript * const validateStatus = tokenGenerator.verify([user.id,user.role].join(), user.auth); * ``` */ verify(data, token) { const epoch = this._epoch; if (token === this._generate(data, epoch)) return "valid"; if (this._duration == 0) return "invalid"; if (token === this._generate(data, epoch - 1)) return "expired"; return "invalid"; } /** * Generates a cryptographic token based on the provided data and epoch. * @param data - The data to be used in the token generation. * @param epoch - The epoch value to be used in the token generation. * @returns The generated cryptographic token. */ _generate(data, epoch) { return this.config.prefix + (0, import_node_crypto2.createHmac)(this.config.algorithm, data).update(data + epoch).digest(this.config.encoding); } }; // src/api.ts var import_nanolib2 = require("@alwatr/nanolib"); // src/pre-config.ts var userIdGeneratorRecommendedConfig = { prefix: "u", algorithm: "sha1", encoding: "base64url", crcLength: 4 }; var deviceIdGeneratorRecommendedConfig = { ...userIdGeneratorRecommendedConfig, prefix: "d" }; var secretGeneratorRecommendedConfig = { prefix: "s", algorithm: "sha384", encoding: "base64url", crcLength: 4 }; var userTokenGeneratorRecommendedConfig = { prefix: "t", algorithm: "sha224", encoding: "base64url" }; // src/api.ts __dev_mode__: import_nanolib2.packageTracer.add("@alwatr/crypto", "4.6.0"); var AlwatrCryptoFactory = class { /** * Creates a new instance of crypto factory. * @param config The configuration used to create the crypto factory. */ constructor(config) { this._generators = { secret: new AlwatrHashGenerator(secretGeneratorRecommendedConfig), deviceId: new AlwatrHashGenerator(deviceIdGeneratorRecommendedConfig), userId: new AlwatrHashGenerator(userIdGeneratorRecommendedConfig), token: new AlwatrTokenGenerator({ ...userTokenGeneratorRecommendedConfig, ...config }) }; } /** * Generate self-verifiable user ID. * @returns The generated user ID. * @example * ```typescript * const newUser = { * id: cryptoFactory.generateUserId(), * ... * } * ``` */ generateUserId() { return this._generators.userId.generateRandomSelfValidate(); } /** * Verify a user ID without token. * @param userId The user ID to verify. * @returns A boolean indicating whether the user ID is valid. * @example * ```typescript * if (!cryptoFactory.verifyUserId(user.id)) { * throw new Error('invalid_user'); * } * ``` */ verifyUserId(userId) { return this._generators.userId.verifySelfValidate(userId); } /** * Generate authentication token. * @param uniquelyList The list of uniq values to generate the token from. * @returns The generated user token. * @example * ```typescript * const userToken = cryptoFactory.generateToken([user.id, user.lpe]); * ``` */ generateToken(uniquelyList) { return this._generators.token.generate(uniquelyList.join()); } /** * Verify a authentication token. * @param uniquelyList The list of uniq values used to generate the token. * @param token The user token to verify. * @returns The validity of the token. * @example * ```typescript * if (!cryptoFactory.verifyToken([user.id, user.lpe], userToken)) { * throw new Error('invalid_token'); * } * ``` */ verifyToken(uniquelyList, token) { return this._generators.token.verify(uniquelyList.join(), token); } /** * Generate self-verifiable secret. * @returns The generated secret. * @example * ```typescript * const config = { * storageToken: cryptoFactory.generateSecret(), * ... * } * ``` */ generateSecret() { return this._generators.secret.generateRandomSelfValidate(); } /** * Verify a secret. * @param secret The secret to verify. * @returns A boolean indicating whether the secret is valid. * @example * ```typescript * if (!cryptoFactory.verifySecret(config.storageToken)) { * throw new Error('invalid_secret'); * } * ``` */ verifySecret(secret) { return this._generators.secret.verifySelfValidate(secret); } /** * Generate self-verifiable device ID. * @returns The generated device ID. * @example * ```typescript * const deviceId = deviceFactory.generateDeviceId(); * ``` */ generateDeviceId() { return this._generators.deviceId.generateRandomSelfValidate(); } /** * Verify a device ID. * @param deviceId The device ID to verify. * @returns A boolean indicating whether the device ID is valid. * @example * ```typescript * if (!deviceFactory.verifyDeviceId(bodyJson.deviceId)) { * throw { * ok: false, * status: 400, * error: 'invalid_device_id', * } * } * ``` */ verifyDeviceId(deviceId) { return this._generators.deviceId.verifySelfValidate(deviceId); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { AlwatrCryptoFactory, AlwatrHashGenerator, AlwatrTokenGenerator, deviceIdGeneratorRecommendedConfig, secretGeneratorRecommendedConfig, userIdGeneratorRecommendedConfig, userTokenGeneratorRecommendedConfig }); /*! For license information please see main.cjs.LEGAL.txt */ //# sourceMappingURL=main.cjs.map