/** * Copyright 2026 - present Nazmul Hassan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { D as NumericString, ni as GenericObject, y as Maybe } from "../index-Dx3yeNwR.cjs"; import { c as DecodedToken, f as SignetPayload, m as TokenString, u as SignOptions, v as VerifiedToken, y as VerifyOptions } from "../hash-CfaR4RGb.cjs"; import { a as isUUIDv4, c as isUUIDv7, i as isUUIDv3, l as isUUIDv8, n as isUUIDv1, o as isUUIDv5, r as isUUIDv2, s as isUUIDv6, t as decodeUUID, u as uuid, w as isUUID } from "../uuid-DQCQn6oV.cjs"; import { t as generateRandomID } from "../basics-CBvx8-Bb.cjs"; //#region src/hash/Cipher.d.ts /** * @class Lightweight stream-cipher–style encryption utility using `HMAC-SHA256` for keystream generation and authentication. * - The class derives separate encryption and MAC keys from the provided secret. * * @remarks * - **The encryption scheme is:** * - keystream = `HMAC(encKey, iv || counter)` * - ciphertext = `plaintext XOR keystream` * - tag = `HMAC(macKey, iv || ciphertext)` * - This is a custom construction and should not be used for production-grade cryptographic security. * - `Cipher` class is a pure JS implementation. It does not rely on `crypto` or Web APIs. */ declare class Cipher { #private; /** * * Creates a new `Cipher` instance using the provided secret. * * @param secret - The secret string used to derive encryption and MAC keys. * Must be a non-empty string. */ constructor(secret: string); /** * * Encrypts a UTF-8 string. * - The output format is: `base64( iv || ciphertext || tag )` * * @param text - The plaintext string to encrypt. * @returns A base64-encoded encrypted token. */ encrypt(text: string): string; /** * * Checks if a token is structurally valid and contains a matching MAC using the same secret. * * @param token - The base64-encoded encrypted blob to validate. * @returns `true` if the MAC is valid, `false` otherwise. */ isValid(token: string): boolean; /** * * Decrypts a previously encrypted token. * - Throws an error if the tag does not match or the token is malformed. * * @param token - The base64-encoded token produced by `encrypt`. * @returns The decrypted plaintext string. */ decrypt(token: string): string; } //#endregion //#region src/hash/core.d.ts /** * * Computes the `MD5` digest of the given string using a pure JavaScript implementation. * * @remarks * - Pure JavaScript implementation — runs on any JS engine. Does not rely on `crypto` or **Web APIs** or other external libraries. * - Highly inspired by the algorithm used in {@link https://github.com/eustatos/pure-md5.git pure-md5} package. * * @param str - Input text to hash. * * @returns The `MD5` hash as a 32-character hex string. * * @example * const hash = md5("hello"); * // → "5d41402abc4b2a76b9719d911017c592" * * * @example * // Used inside UUID v3 * const digest = md5(namespace + name); */ declare function md5(str: string): string; /** * * Computes the `SHA-1` digest of the given string using a pure JavaScript implementation. * * @remarks Pure JavaScript implementation — runs on any JS engine. Does not rely on `crypto` or **Web APIs** or other external libraries. * * @param msg - Input text to hash. * * @returns The `SHA-1` hash as a 40-character hex string. * * @example * const hash = sha1("hello"); * // → "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d" * * @example * // Used inside UUID v5 * const digest = sha1(namespace + name); */ declare function sha1(msg: string): string; /** * * Computes the `SHA-256` hash of a `UTF-8` string and returns it as a lowercase hexadecimal string. * * @param msg - The input string to hash. Can contain any `UTF-8` characters. * @returns A 64-character lowercase hexadecimal string representing the `SHA-256` hash. * * @remarks Pure JavaScript implementation — runs on any JS engine. Does not rely on `crypto` or **Web APIs** or other external libraries. * * @example * ```typescript * // Basic usage * const hash = sha256('hello'); * // Returns: '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824' * * // Empty string * const emptyHash = sha256(''); * // Returns: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' * * // Unicode string * const unicodeHash = sha256('Hello পৃথিবী!'); * // Returns: '7037e204b825b83553ba336a6ec35b796d505599286ae864729ed6cb33ae9fe1' * ``` * * @see {@link https://toolbox-x.vercel.app/docs/utils/hash/encoding#sha256bytes sha256Bytes} for hashing raw bytes * @see {@link https://toolbox-x.vercel.app/docs/utils/hash/encoding#utf8tobytes utf8ToBytes} for converting string to bytes * @see {@link https://toolbox-x.vercel.app/docs/utils/hash/encoding#bytestohex bytesToHex} for converting bytes to a hexadecimal string */ declare function sha256(msg: string): string; //#endregion //#region src/hash/Signet.d.ts /** * @class A lightweight, secure implementation of JWT-like tokens using `HMAC-SHA256` signatures. * - This class provides methods to create, verify, and decode tokens with a simple API similar to JSON Web Tokens (`JWT`) * but with a smaller footprint and zero dependencies. * * @remarks * - **Features:** * - `HMAC-SHA256` signatures for security * - Time-based claims (expiration, not-before) * - Standard claims (audience, issuer, subject) * - Constant-time signature comparison to prevent timing attacks * - Automatic date conversion for timestamp claims * - `Base64` URL-safe encoding (standard `Base64` in this implementation) * * - **Security considerations:** * - Keep the secret key secure and rotate periodically * - Use appropriate token expiration times * - Validate all claims relevant to your application * - Store tokens securely (HTTP-only cookies recommended for web) * * @example * ```typescript * // Create a token signer * const signet = new Signet('my-secret-key'); * * // Sign a token with custom payload and options * const token = signet.sign( * { userId: 123, role: 'admin' }, * { * expiresIn: '1h', * audience: 'my-app', * issuer: 'auth-service' * } * ); * * // Verify a token * const result = signet.verify(token, { * audience: 'my-app', * issuer: 'auth-service' * }); * * if (result.isValid) { * console.log('Valid token for user:', result.payload.userId); * } else { * console.log('Invalid token:', result.error); * } * * // Decode without verification * const decoded = signet.decode(token); * console.log('Token payload:', decoded.payload); * ``` */ declare class Signet { #private; /** * * Creates a new `Signet` instance with the specified secret key. * * @param secret - The secret key used for signing and verifying tokens. * Must be a non-empty string. * * @throws If the secret is not a non-empty string. * * @remarks * - The secret is converted to `UTF-8` bytes and stored internally. * - Choose a strong secret (at least 32 characters) and store it securely. * - For production, consider using key rotation strategies. * * @example * ```typescript * // Initialize with a secret key * const signet = new Signet('super-secret-key-123'); * * // Use environment variable for the secret * const signet = new Signet(process.env.JWT_SECRET!); * ``` */ constructor(secret: string); /** * * Creates and signs a new token with the given payload and options. * * @param payload - Custom data to include in the token payload. * Must be a `non-empty object`. * @param options - Optional configuration for token claims and expiration. * * @returns A signed token string in the format `header.payload.signature`. * * @throws If payload is not a valid object. * * @remarks * - **The token structure follows JWT format:** * - Header: Contains algorithm (`HS256`) and token type (`SIGNET+JWT`) * - Payload: Includes standard claims (`iat`, `exp`, `nbf`, `aud`, `sub`, `iss`) plus custom data * - Signature: `HMAC-SHA256(signingInput, secret)` (the result of the hash) * - Signing Inputs: `base64(header) + "." + base64(payload)` (the string that gets hashed) * * - **Automatic claims added:** * - `iat` (issued at): Current time in seconds * - `iatDate`: Current time as Date object * - If `expiresIn` is provided: `exp` and `expDate` * - If `notBefore` is provided: `nbf` and `nbfDate` * * @example * ```typescript * // Basic token with custom data * const token = signet.sign({ userId: 123, name: 'John' }); * * // Token with expiration and claims * const token = signet.sign( * { userId: 123 }, * { * expiresIn: '2h', * audience: 'api.example.com', * issuer: 'auth-service', * subject: 'user-123' * } * ); * * // Token valid after 5 minutes * const token = signet.sign( * { action: 'reset-password' }, * { notBefore: '5m' } * ); * ``` */ sign(payload: GenericObject, options?: SignOptions): TokenString; /** * * Decodes a token without verifying its signature. * * @typeParam T - Type of custom data in the token payload. * @param token - The token string to decode. * * @returns The decoded token parts including header, payload, and signatures. * * @throws If the token is malformed, empty, or cannot be parsed. * * @remarks * - Use this method when you need to inspect token contents without verification. * - **Warning:** This does not validate the signature, so the data may have been tampered with. * - Always use {@link verify} method for security-critical operations. * - The payload includes both timestamp values (numbers) and {@link Date} objects for convenience. * * @example * ```typescript * // Decode token to inspect contents * const decoded = signet.decode(token); * console.log('Header:', decoded.header); * console.log('Payload:', decoded.payload); * console.log('Signature:', decoded.signature); * * // Access custom payload data with type safety * const decoded = signet.decode<{ userId: number }>(token); * const userId = decoded.payload.userId; // Type: number * ``` */ decode(token: string): DecodedToken; /** * * Checks if a token has expired based on its `exp` claim. * * @param token - The token to check. * * @returns `true` if the token has an `exp` claim and current time is past it, * `false` if token has no expiration or is still valid. * * @throws If the token is malformed or cannot be decoded. * * @remarks * - Tokens without `exp` claim are considered non-expiring (returns `false`) * - Uses current system time for comparison ({@link Date.now()}) * - Does not verify the signature (use only with trusted tokens or after verification) * * @example * ```typescript * // Check expiration * if (signet.hasExpired(token)) { * console.log('Token has expired'); * // Prompt user to re-authenticate * } * * // Use with other validation * const isValid = !signet.hasExpired(token) && !signet.isTooEarly(token); * ``` */ hasExpired(token: string): boolean; /** * * Checks if a token's `nbf` (not-before) claim indicates it's too early to use. * * @param token - The token to check. * * @returns `true` if the token has an `nbf` claim and current time is before it, * `false` if token has no `nbf` claim or is already valid. * * @throws If the token is malformed or cannot be decoded. * * @remarks * - Useful for implementing time-based access control, like activation links that shouldn't be used until a certain time. * - Uses current system time for comparison ({@link Date.now()}) * - Does not verify the signature (use only with trusted tokens or after verification) * * @example * ```typescript * // Check if token is active yet * if (signet.isTooEarly(token)) { * console.log('Token not valid yet'); * // Wait before using * } * ``` */ isTooEarly(token: string): boolean; /** * * Validates a token's `iss` (issuer) claim against an expected value. * * @param token - The token to check. * @param expected - The expected issuer value. If `undefined`, always returns `false`. * * @returns `true` if the token has an `iss` claim that doesn't match the expected value, * `false` if issuer matches, token has no issuer claim, or expected issuer is undefined. * * @throws If the token is malformed or cannot be decoded. * * @remarks Use this to ensure tokens come from trusted sources in multi-issuer scenarios. * * @example * ```typescript * // Validate issuer * if (signet.isInvalidIssuer(token, 'auth-service')) { * console.log('Token from unexpected issuer'); * // Reject token * } * * // With optional issuer check * const issuer = process.env.EXPECTED_ISSUER; * if (issuer && signet.isInvalidIssuer(token, issuer)) { * throw new Error('Invalid issuer'); * } * ``` */ isInvalidIssuer(token: string, expected: Maybe): boolean; /** * * Validates a token's `aud` (audience) claim against expected values. * * @param token - The token to check. * @param expected - The expected audience(s). Can be a string or array of strings. * If `undefined`, always returns `false`. * * @returns `true` if the token has an `aud` claim and none of its values match any of the expected audiences, `false` otherwise. * * @throws If the token is malformed or cannot be decoded. * * @remarks * - Tokens can have single audience (string) or multiple audiences (string[]) * - Returns `false` (valid) if at least one audience matches * - Useful for multi-tenant or multi-service architectures * * @example * ```typescript * // Single audience check * if (signet.isInvalidAudience(token, 'api.example.com')) { * console.log('Token not intended for this audience'); * } * * // Multiple allowed audiences * const validAudiences = ['web-app', 'mobile-app', 'admin-panel']; * if (signet.isInvalidAudience(token, validAudiences)) { * throw new Error('Invalid audience'); * } * * // Token with multiple audiences * // Token payload: { aud: ['web-app', 'mobile-app'] } * // Check if at least one matches * const isValid = !signet.isInvalidAudience(token, ['web-app', 'admin-panel']); * // Returns false (valid) because 'web-app' matches * ``` */ isInvalidAudience(token: string, expected: Maybe): boolean; /** * * Validates a token's `sub` (subject) claim against an expected value. * * @param token - The token to check. * @param expected - The expected subject value. If `undefined`, always returns `false`. * * @returns `true` if the token has a `sub` claim that doesn't match the expected value, * `false` if subject matches, token has no subject claim, or expected subject is undefined. * * @throws If the token is malformed or cannot be decoded. * * @remarks * - Use this to ensure tokens are being used by the intended user/entity. * - Common for authorization checks where tokens should be user-specific. * * @example * ```typescript * // Validate subject * const userId = 'user-123'; * if (signet.isInvalidSubject(token, userId)) { * console.log('Token not for this user'); * // Reject request * } * * // Optional subject validation * const expectedSubject = getExpectedSubjectFromRequest(); * if (expectedSubject && signet.isInvalidSubject(token, expectedSubject)) { * return response.status(403).send('Invalid subject'); * } * ``` */ isInvalidSubject(token: string, expected: Maybe): boolean; /** * * Verifies a token's signature and validates all claims. * * @typeParam T - Type of custom data in the token payload. * @param token - The token string to verify. * @param options - Optional validation criteria for token claims. * * @returns A {@link VerifiedToken} object indicating success or failure. * - If valid: `{ isValid: true, payload: SignetPayload }` * - If invalid: `{ isValid: false, error: string }` * * @remarks * - **Performs the following checks in order:** * - Token structure (3 parts separated by dots) * - Base64 decoding of header and payload * - JSON parsing of header and payload * - Signature verification (constant-time comparison) * - Expiration check (if `exp` claim exists) * - Not-before check (if `nbf` claim exists) * - Issuer validation (if provided in options) * - Audience validation (if provided in options) * - Subject validation (if provided in options) * * - **This is the recommended method for most token validation scenarios.** * * @example * ```typescript * // Basic verification * const result = signet.verify(token); * if (result.isValid) { * console.log('Valid token:', result.payload); * } else { * console.log('Invalid token:', result.error); * } * * // With claim validation * const result = signet.verify(token, { * audience: 'api.example.com', * issuer: 'auth-service', * subject: 'user-123' * }); * * // Type-safe custom payload * interface UserToken { * userId: number; * role: string; * } * const result = signet.verify(token); * if (result.isValid) { * const { userId, role } = result.payload; * // userId and role are typed * } * ``` */ verify(token: string, options?: VerifyOptions): VerifiedToken; /** * * Verifies a token and throws an error if invalid. * * @typeParam T - Type of custom data in the token payload. * @param token - The token string to verify. * @param options - Optional validation criteria for token claims. * * @returns A valid {@link VerifiedToken} with `isValid: true`. * * @throws If the token is invalid, with a message describing the failure. * * @remarks * - This method is a convenience wrapper around {@link verify} that throws instead of returning an error object. * - Useful for `express`-style middleware or when you want to handle authentication failures with exceptions. * - The thrown error message is the same as the `error` property in the invalid result from {@link verify}. * * @example * ```typescript * // Use in middleware/guard * function authMiddleware(req, res, next) { * const token = req.headers.authorization?.replace('Bearer ', ''); * * try { * const result = signet.verifyOrThrow(token, { * audience: 'api.example.com' * }); * req.user = result.payload; * next(); * } catch (error) { * res.status(401).json({ error: error.message }); * } * } * * // In application code * try { * const result = signet.verifyOrThrow(token); * // Token is guaranteed valid here * processUserRequest(result.payload); * } catch (error) { * handleAuthError(error); * } * ``` */ verifyOrThrow(token: string, options?: VerifyOptions): VerifiedToken; /** * * Extracts only the payload from a token without full verification. * * @typeParam T - Type of custom data in the token payload. * @param token - The token string to decode. * * @returns The token payload including standard claims and custom data. * * @throws If the token is malformed, empty, or cannot be parsed. * * @remarks * - This is a convenience method equivalent to `decode(token).payload`. * * - **Security Note:** This method does NOT verify the token signature. * * - **Only use it when:** * - You've already verified the token elsewhere * - The token comes from a trusted source * - You're debugging or logging * - The operation is not security-critical * * - For security-sensitive operations, always use {@link verify} or {@link verifyOrThrow} method. * * @example * ```typescript * // Quick payload extraction for non-critical operations * const payload = signet.decodePayload(token); * console.log('User ID:', payload.userId); * console.log('Issued at:', payload.iatDate); * * // Type-safe with custom interface * interface AppToken { * userId: number; * permissions: string[]; * } * const payload = signet.decodePayload(token); * const canDelete = payload.permissions.includes('delete'); * ``` */ decodePayload(token: string): SignetPayload; } //#endregion //#region src/hash/TextCodec.d.ts /** * @class `TextCodec` provides **UTF-8–safe** conversions between `text`, `hex`, `binary`, and `Base64` representations using byte-level transformations. * * @example * TextCodec.utf8ToHex('ভাষা'); // 'e0 a6 ad e0 a6 be e0 a6 b7 e0 a6 be' * TextCodec.hexToUtf8('e0 a6 ad e0 a6 be'); // 'ভা' */ declare class TextCodec { private constructor(); /** * @static Validates whether a string represents a valid hexadecimal byte sequence. * * @param hex - Hex string, spaced or un-spaced (e.g. "ff 0a" or "ff0a") * @returns `true` if the input is valid hex byte string * * @example * TextCodec.isValidHex('ff 0a'); */ static isValidHex(hex: string): boolean; /** * @static Validates whether a string represents a valid binary byte sequence. * * @param binary - Binary string, spaced or un-spaced * @returns `true` if the input is valid binary byte string * * @example * TextCodec.isValidBinary('01000001'); */ static isValidBinary(binary: string): boolean; /** * @static Validates whether a string represents a valid Base64-encoded string. * * @param b64 - Base64 string to check * @returns `true` if the input is valid Base64-encoded string * * @example * TextCodec.isValidBase64('SGVsbG8='); */ static isValidBase64(b64: string): boolean; /** * @static Converts UTF-8 text into hexadecimal byte representation. * * @param text - UTF-8 text to convert * @param spaced - Whether to separate bytes with spaces, defaults to `true` * @returns Hexadecimal byte string * * @example * TextCodec.utf8ToHex('Hi'); */ static utf8ToHex(text: string, spaced?: boolean): string; /** * @static Converts UTF-8 text into binary byte representation. * * @param text - UTF-8 text to convert * @param spaced - Whether to separate bytes with spaces, defaults to `true` * @returns Binary byte string * * @example * TextCodec.utf8ToBinary('A'); */ static utf8ToBinary(text: string, spaced?: boolean): string; /** * @static Converts hexadecimal byte string into UTF-8 text. * * @param hex - Hexadecimal byte string * @returns Decoded UTF-8 text * * @example * TextCodec.hexToUtf8('48 69'); */ static hexToUtf8(hex: string): string; /** * @static Converts binary byte string into UTF-8 text. * * @param binary - Binary byte string * @returns Decoded UTF-8 text * * @example * TextCodec.binaryToUtf8('01001000 01101001'); */ static binaryToUtf8(binary: string): string; /** * @static Converts hexadecimal byte string into binary byte string. * * @param hex - Hexadecimal byte string * @param spaced - Whether to separate bytes with spaces, defaults to `true` * @returns Binary byte string * * @example * TextCodec.hexToBinary('ff'); */ static hexToBinary(hex: string, spaced?: boolean): string; /** * @static Converts binary byte string into hexadecimal byte string. * * @param binary - Binary byte string * @param spaced - Whether to separate bytes with spaces, defaults to `true` * @returns Hexadecimal byte string * * @example * TextCodec.binaryToHex('00000001'); */ static binaryToHex(binary: string, spaced?: boolean): string; /** * @static Converts a Base64-encoded string into UTF-8 text. * * @param b64 - Base64 encoded string * @returns Decoded UTF-8 text * * @example * TextCodec.base64ToUtf8('SGVsbG8='); */ static base64ToUtf8(b64: string): string; /** * @static Converts UTF-8 text into a Base64-encoded string. * * @param text - UTF-8 text to encode * @returns Base64 encoded string * * @example * TextCodec.utf8ToBase64('Hello'); */ static utf8ToBase64(text: string): string; /** * @static Converts Base64 directly into hexadecimal byte string. * * @param b64 - Base64 encoded string * @param spaced - Whether to separate bytes with spaces, defaults to `true` * @returns Hexadecimal byte string * * @example * TextCodec.base64ToHex('SGVsbG8='); */ static base64ToHex(b64: string, spaced?: boolean): string; /** * @static Converts Base64 directly into binary byte string. * * @param b64 - Base64 encoded string * @param spaced - Whether to separate bytes with spaces, defaults to `true` * @returns Binary byte string * * @example * TextCodec.base64ToBinary('SGVsbG8='); */ static base64ToBinary(b64: string, spaced?: boolean): string; /** * @static Converts hexadecimal byte string into a Base64 string. * * @param hex - Hexadecimal byte string * @returns Base64 encoded string * * @example * TextCodec.hexToBase64('48 69'); */ static hexToBase64(hex: string): string; /** * @static Converts binary byte string into a Base64 string. * * @param binary - Binary byte string * @returns Base64 encoded string * * @example * TextCodec.binaryToBase64('01001000 01101001'); */ static binaryToBase64(binary: string): string; } //#endregion //#region src/hash/utils.d.ts /** * * Generates random bytes in the {@link Uint8Array} format. * * @param size - The length of the byte array to generate. Defaults to `8`. * @returns A random array of bytes. * * @example * ```typescript * const bytes = randomBytes(16); * // Returns something like: Uint8Array(16) [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 224, 166, 170, 224, 167, 131] * * // Empty array * const empty = randomBytes(0); * // Returns: Uint8Array(0) [] * * // Zero or negative values are treated as 0 * const zero = randomBytes(-5); * // Returns: Uint8Array(0) [] * ``` * * @remarks * - It uses {@link crypto.getRandomValues} when available for secure randomness, and falls back to {@link Math.random} if not. * - If {@link crypto.getRandomValues} is available (supported environments include browser and Node.js), it is used for cryptographically secure random number generation. * - In environments where {@link crypto.getRandomValues} is not available, the function falls back to {@link Math.random}, which is **not** cryptographically secure. * - {@link crypto.getRandomValues} fills the array with random values in the range [0, 255] (inclusive). * - {@link Math.random} returns values in the range [0, 1) (exclusive of 1), so the values are scaled to [0, 255]. * - If `size` is 0 or negative, an empty `Uint8Array` is returned. */ declare function randomBytes(size?: number): Uint8Array; /** * * Generates a random hexadecimal string of the specified length. * * @param length - Number of hex characters to generate. * @param uppercase - Whether to return uppercase `A–F` characters. Defaults to `false` (lowercase). * * @returns A randomly generated hexadecimal string. * * @remarks * - This function generates a random hexadecimal string of the specified length. * - It uses {@link crypto.getRandomValues} when available for secure randomness, and falls back to {@link Math.random} if not. * - The output is a string of hex characters (`0–9`, `a–f` or `A–F`) with no prefixes or separators. * - If `length` is `0` or negative, an empty string is returned. * * @example * // 16-character lowercase hex * const id = randomHex(16); * * @example * // 8-character uppercase hex * const token = randomHex(8, true); */ declare function randomHex(length: number, uppercase?: boolean): string; /** * * Generates a random numeric string of the specified length. * * @param length - Length of the numeric string. Defaults to `6`. * @returns A randomly generated numeric string. * * @example * ```typescript * const otp = randomNumeric(6); * // Returns something like: '123456' * ``` * * @remarks * - If `length` is `0` or negative, an empty string is returned. */ declare function randomNumeric(length?: number): NumericString; /** * * Generates a random alphanumeric string (letters and numbers) of the specified length. * * @param length - The desired length of the random string. Defaults to `8`. * @param uppercase - If `true`, the string will contain uppercase letters (A-Z). Defaults to `false` (lowercase). * * @returns A random string composed of alphanumeric characters. * * @example * ```typescript * // Generate a random 8-character alphanumeric string (default: lowercase) * const randomStr = randomAlphaNumeric(8); * // Example output: "a7b2f9d1" * * // Generate a 12-character uppercase alphanumeric string * const randomUpper = randomAlphaNumeric(12, true); * // Example output: "X5K9P2M7H4L3" * * // Generate a 6-character string * const shortStr = randomAlphaNumeric(6); * ``` * * @remarks * - The function generates random bytes and converts them to base-36 (0-9, a-z) characters. * - If `length` is `0` or negative, an empty string is returned. */ declare function randomAlphaNumeric(length?: number, uppercase?: boolean): string; /** * * Converts a UTF-8 string to a byte array (`Uint8Array`). * * This function encodes a JavaScript string into UTF-8 bytes, handling all Unicode code points including supplementary characters (surrogate pairs). * * @example * ```typescript * // Basic ASCII * const asciiBytes = utf8ToBytes('hello'); * // Returns: * Uint8Array(5) [104, 101, 108, 108, 111] * * // Unicode characters * const unicodeBytes = utf8ToBytes('Hello পৃথিবী!'); * // Returns: * Uint8Array(25) [ * 72, 101, 108, 108, 111, 32, * 224, 166, 170, 224, 167, 131, * 224, 166, 165, 224, 166, 191, * 224, 166, 172, 224, 167, 128, * 33 * ] * ``` * * @param str - The input string to encode as UTF-8 bytes. * @returns A `Uint8Array` containing the UTF-8 encoded bytes. * * @remarks * - The encoding follows the UTF-8 specification: * - 1-byte sequence for code points U+0000 to U+007F (ASCII) * - 2-byte sequence for code points U+0080 to U+07FF * - 3-byte sequence for code points U+0800 to U+FFFF * - 4-byte sequence for code points U+10000 to U+10FFFF (surrogate pairs) * * **Note:** Invalid surrogate pairs in the input string are silently ignored. * * @see {@link bytesToUtf8} for the inverse operation */ declare function utf8ToBytes(str: string): Uint8Array; /** * * Converts `UTF-8` encoded bytes back to a string. * * This function decodes a `Uint8Array` containing `UTF-8` bytes into a JavaScript string. * * @example * ```typescript * // Decode UTF-8 bytes * const bytes = new Uint8Array([104, 101, 108, 108, 111]); * const str = bytesToUtf8(bytes); * // Returns: 'hello' * * // Round-trip conversion * const original = 'Hello 🌍'; * const bytes = utf8ToBytes(original); * const decoded = bytesToUtf8(bytes); * console.log(original === decoded); // true * ``` * * @param bytes - A `Uint8Array` containing `UTF-8` encoded bytes. * @returns The decoded string. * * @remarks * - The function handles all valid `UTF-8` sequences: * - 1-byte sequences (0xxxxxxx) → ASCII characters * - 2-byte sequences (110xxxxx 10xxxxxx) * - 3-byte sequences (1110xxxx 10xxxxxx 10xxxxxx) * - 4-byte sequences (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx) → surrogate pairs * * @see {@link utf8ToBytes} for the inverse operation */ declare function bytesToUtf8(bytes: Uint8Array): string; /** * * Decodes a `Base64` string to bytes. * - This function converts a `Base64`-encoded string back to its original byte representation. * - It handles standard `Base64` encoding with '=', '+', '/' characters. * * @example * ```typescript * // Decode Base64 string * const bytes = base64ToBytes('aGVsbG8gd29ybGQ='); * // Returns: Uint8Array(11) [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] * * // Empty string * const empty = base64ToBytes(''); * // Returns: Uint8Array(0) [] * ``` * * @param str - The `Base64`-encoded string to decode. * @returns A `Uint8Array` containing the decoded bytes. * * @remarks * - The function supports: * - Standard `Base64` alphabet (A-Z, a-z, 0-9, +, /) * - Padding with '=' characters * - Ignores whitespace (though not explicitly trimmed in this implementation) * * @see {@link bytesToBase64} for the inverse operation */ declare function base64ToBytes(str: string): Uint8Array; /** * * Encodes bytes to a `Base64` string. * - This function converts a `Uint8Array` to a `Base64`-encoded string using the standard `Base64` alphabet with padding. * * @example * ```typescript * // Encode bytes to Base64 * const bytes = new Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]); * const b64 = bytesToBase64(bytes); * // Returns: 'aGVsbG8gd29ybGQ=' * * // Empty array * const empty = bytesToBase64(new Uint8Array(0)); * // Returns: '' * ``` * * @param bytes - The bytes to encode as `Base64`. * @returns The `Base64`-encoded string. * * @remarks * The encoding uses: * - Standard `Base64` alphabet (A-Z, a-z, 0-9, +, /) * - '=' padding for incomplete groups * - No line breaks or whitespace * * This is a pure JavaScript implementation that doesn't rely on `btoa()`. * * @see {@link base64ToBytes} for the inverse operation */ declare function bytesToBase64(bytes: Uint8Array): string; /** * * Concatenates multiple `Uint8Array`s into a single `Uint8Array`. * - This function efficiently combines multiple byte arrays without creating intermediate strings or arrays. * * @example * ```typescript * // Concatenate multiple arrays * const a = new Uint8Array([1, 2, 3]); * const b = new Uint8Array([4, 5]); * const c = new Uint8Array([6, 7, 8, 9]); * const result = concatBytes(a, b, c); * // Returns: Uint8Array(9) [1, 2, 3, 4, 5, 6, 7, 8, 9] * * // Single array * const single = concatBytes(new Uint8Array([1, 2, 3])); * // Returns: Uint8Array(3) [1, 2, 3] * * // No arrays * const empty = concatBytes(); * // Returns: Uint8Array(0) [] * ``` * * @param parts - One or more `Uint8Array`s to concatenate. * @returns A new `Uint8Array` containing all the bytes from the input arrays in the order they were provided. * * @remarks The function allocates a single `Uint8Array` of the total combined length and copies all bytes into it using `set()` for optimal performance. */ declare function concatBytes(...parts: Uint8Array[]): Uint8Array; /** * * Computes the `SHA-256` hash of raw bytes. * - This is a pure JavaScript implementation of the `SHA-256` cryptographic hash function that operates directly on byte arrays (`Uint8Array`). * * @example * ```typescript * // Hash raw bytes * const bytes = new Uint8Array([104, 101, 108, 108, 111]); // "hello" * const hash = sha256Bytes(bytes); * // Returns: Uint8Array(32) with SHA-256 hash * * // Verify with string hash * const strHash = sha256('hello'); * const bytesHash = bytesToHex(sha256Bytes(utf8ToBytes('hello'))); * console.log(strHash === bytesHash); // true * ``` * * @param message - The bytes to hash as a `Uint8Array`. * @returns A `Uint8Array` of 32 bytes (256 bits) containing the `SHA-256` hash. * * @remarks * - Implementation details: * - Follows the `SHA-256` specification (FIPS 180-4) * - Uses big-endian byte order throughout * - Processes messages in 512-bit (64-byte) blocks * - Applies proper padding with message length * - Uses all required `SHA-256` round constants * - Returns hash as 32-byte array * * @see {@link hmacSha256} for `HMAC-SHA256` computation */ declare function sha256Bytes(message: Uint8Array): Uint8Array; /** * * Computes `HMAC-SHA256` (Hash-based Message Authentication Code using `SHA-256`). * - This function implements the `HMAC` algorithm with `SHA-256` as the underlying hash function, providing message authentication and integrity verification. * * @example * ```typescript * // Basic HMAC calculation * const key = new TextEncoder().encode('secret-key'); * const message = new TextEncoder().encode('Hello, world!'); * const hmac = hmacSha256(key, message); * * // Using with string inputs * const keyBytes = new TextEncoder().encode('my-key'); * const msgBytes = new TextEncoder().encode('data to authenticate'); * const hmacResult = hmacSha256(keyBytes, msgBytes); * const hexResult = bytesToHex(hmacResult); * ``` * * @param key - The secret key as a `Uint8Array`. * @param message - The message to authenticate as a `Uint8Array`. * @returns A `Uint8Array` of 32 bytes containing the `HMAC-SHA256` tag. * * @remarks * - Algorithm steps: * - 1. Keys longer than 64 bytes are hashed with `SHA-256` * - 2. Keys shorter than 64 bytes are padded with zeros * - 3. Inner hash: `SHA-256((key ⊕ ipad) || message)` where ipad = 0x36 repeated * - 4. Outer hash: `SHA-256((key ⊕ opad) || inner_hash)` where opad = 0x5C repeated * * - The implementation follows RFC 2104 and RFC 4231 specifications. * - Block size for `SHA-256` HMAC is 64 bytes (512 bits). * * **Common use cases:** * - API authentication tokens * - Message integrity verification * - Key derivation (as part of `HKDF`) * * @see {@link sha256Bytes} for the underlying hash function */ declare function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array; /** * * Converts a `Uint8Array` to a `Uint32Array` with big-endian byte order. * - This function groups bytes into 32-bit integers, reading them in big-endian (most significant byte first) order. Missing bytes are treated as zero. * * @example * ```typescript * // Convert bytes to 32-bit integers * const bytes = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC]); * const words = uint8To32ArrayBE(bytes); * // Returns: Uint32Array(2) [0x12345678, 0x9ABC0000] or equivalent: Uint32Array(2) [ 305419896, 2596012032 ] * * // Partial final word * const partial = new Uint8Array([0xFF, 0xEE, 0xDD]); * const words2 = uint8To32ArrayBE(partial); * // Returns: Uint32Array(1) [0xFFEEDD00] or equivalent: Uint32Array(1) [ 4293844224 ] * ``` * * @param bytes - The bytes to convert to 32-bit words. * @returns A `Uint32Array` containing the 32-bit big-endian words. * * @remarks * - Input length doesn't need to be a multiple of 4 * - Missing bytes in the final word are padded with zeros * - Byte order: `bytes[0]` is the most significant byte of `out[0]` * - This is useful for cryptographic operations that work with 32-bit words */ declare function uint8To32ArrayBE(bytes: Uint8Array): Uint32Array; /** * * Converts a 32-bit integer into a 4-byte `Uint8Array` in big-endian (network) byte order. * - This function takes a 32-bit integer and encodes it as 4 bytes with the most significant byte first (big-endian order), which is the standard for network protocols and many cryptographic operations. * * @example * ```typescript * // Convert integer to bytes * const bytes = intTo4BytesBE(0x12345678); * // Returns: Uint8Array(4) [0x12, 0x34, 0x56, 0x78] or equivalent: Uint8Array(4) [ 18, 52, 86, 120 ] * * // Maximum 32-bit value * const maxBytes = intTo4BytesBE(0xFFFFFFFF); * // Returns: Uint8Array(4) [0xFF, 0xFF, 0xFF, 0xFF] * * // Zero * const zeroBytes = intTo4BytesBE(0); * // Returns: Uint8Array(4) [0x00, 0x00, 0x00, 0x00] * ``` * * @param n - The 32-bit integer to convert. Values beyond 32 bits will be truncated. * @returns A 4-byte `Uint8Array` representing the value in big-endian format. * * @remarks * - The function uses unsigned 32-bit arithmetic (`>>>` operator) * - Only the lower 32 bits of the input are used (truncation) * - Output is always exactly 4 bytes * - Big-endian order: byte[0] = most significant, byte[3] = least significant * * **Common use cases:** * - Encoding message lengths in network protocols * - Preparing data for cryptographic operations * - Converting integers for storage or transmission * * @see {@link uint8To32ArrayBE} for bytes to 32-bit integers conversion */ declare function intTo4BytesBE(n: number): Uint8Array; /** * * Converts a `Uint8Array` to a lowercase hexadecimal string. * - This function encodes binary data (bytes) as a hexadecimal string, with each byte represented as two lowercase hexadecimal digits (0-9, a-f). * * @example * ```typescript * // Convert bytes to hex * const bytes = new Uint8Array([0x12, 0xAB, 0xFF, 0x00]); * const hex = bytesToHex(bytes); * // Returns: '12abff00' * * // Empty array * const emptyHex = bytesToHex(new Uint8Array(0)); * // Returns: '' * * // SHA-256 hash to hex * const hashBytes = sha256Bytes(utf8ToBytes('hello')); * const hashHex = bytesToHex(hashBytes); * // Returns: '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824' * ``` * * @param bytes - The bytes to convert to hexadecimal representation. * @returns A lowercase hexadecimal string where each byte is represented by two characters (00-ff). * * @remarks * - Always returns lowercase letters (a-f) * - Zero pads single-digit hex values (e.g., 0x0F → "0f", not "f") * - Efficient O(n) implementation using string concatenation * - No prefix (e.g., no "0x" at the beginning) * * **Common use cases:** * - Displaying cryptographic hashes and signatures * - Debugging binary data * - Converting binary data for JSON serialization * - Creating hex-encoded strings for APIs and protocols * * @see {@link hexToBytes} for reverse process */ declare function bytesToHex(bytes: Uint8Array): string; /** * * Converts a hexadecimal string to a `Uint8Array`. * - This function decodes a hexadecimal-encoded string into its raw byte representation, where every two hexadecimal characters (00–ff) are converted into one byte. * * @example * // Convert hex to bytes * const hex = '12abff00'; * const bytes = hexToBytes(hex); * // Returns: Uint8Array(4) [18, 171, 255, 0] * * // Empty string * const emptyBytes = hexToBytes(''); * // Returns: Uint8Array [] * * // Decode SHA-256 hash from hex * const hashHex = '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'; * const hashBytes = hexToBytes(hashHex); * // Returns: Uint8Array(32) * * @param hex - A hexadecimal string where each byte is represented by two characters (00–ff). * @returns A `Uint8Array` containing the decoded bytes. Returns an empty array for invalid input. * * @remarks * - Accepts lowercase and uppercase hexadecimal characters (0–9, a–f, A–F) with or without space between bytes * - Ignores no prefixes (e.g., does not support "0x") * - Requires an even number of hexadecimal characters * - Efficient O(n) implementation with direct byte parsing * * **Common use cases:** * - Decoding cryptographic hashes and signatures * - Parsing hex-encoded binary payloads * - Reconstructing binary data from storage or transport formats * - Working with low-level protocols and binary APIs * * @see {@link bytesToHex} for the reverse process */ declare function hexToBytes(hex: string): Uint8Array; //#endregion export { Cipher, Signet, TextCodec, base64ToBytes, bytesToBase64, bytesToHex, bytesToUtf8, concatBytes, decodeUUID, generateRandomID, generateRandomID as getRandomID, generateRandomID as randomID, hexToBytes, hmacSha256, intTo4BytesBE, isUUID, isUUIDv1, isUUIDv2, isUUIDv3, isUUIDv4, isUUIDv5, isUUIDv6, isUUIDv7, isUUIDv8, md5, randomAlphaNumeric, randomBytes, randomHex, randomNumeric, sha1, sha256, sha256Bytes, uint8To32ArrayBE, utf8ToBytes, uuid };