UNPKG

xypriss-security

Version:

Advanced High-Performance Security Framework. Military-grade encryption, post-quantum resilience, and fortified data structures.

219 lines 9.44 kB
/*************************************************************************** * XyPriss Security - Advanced Hyper-Modular Security Framework * * @author NEHONIX (Nehonix-Team - https://github.com/Nehonix-Team) * @license Nehonix Open Source License (NOSL) * * Copyright (c) 2025 NEHONIX. All rights reserved. ****************************************************************************/ import type { PasswordManagerOptions, BreachCheckResult, PassphraseOptions, PasswordGenerateOptions, PasswordStrengthResult } from "../types/PasswordManagerOptions"; /*************************************************************************** * ### PasswordManager * * A configurable, instance-based password manager. * Unlike the static `Password` class, `PasswordManager` is instantiated * once with all options pre-configured, so callers only need to pass * the raw password string at call time. * * This is the recommended pattern for large-scale projects: * configure once in a dedicated file, export the instance, and reuse * everywhere without repeating options. * * @example * // config/security.ts * export const passwords = new PasswordManager({ * algorithm: "argon2id", * memoryCost: 65536, * parallelism: 4, * iterations: 3, * pepper: process.env.PASSWORD_PEPPER, * }); * * // anywhere in the app: * const hash = await passwords.hash("user-raw-password"); * const valid = await passwords.verify("user-raw-password", hash); * const temp = passwords.generate({ length: 24, symbols: true }); * const passphrase = passwords.generatePassphrase({ wordCount: 5 }); * const pin = passwords.generatePin(6); * const info = passwords.strength("MyP@ss1!"); * const breach = await passwords.isBreached("hunter2"); * const stale = passwords.needsRehash(storedHash); */ export declare class PasswordManager { private readonly algo; private readonly memoryCost; private readonly iterations; private readonly parallelism; private readonly pepper; private readonly strengthOptions?; /** Cached wordlist for the strength method (preloaded if checkDictionary is enabled) */ private readonly cachedStrengthWordlist?; /** Lazy cache for passphrase wordlists to avoid repeated disk reads */ private passphraseWordlistCache; constructor(options?: PasswordManagerOptions); /** * Hashes a password using the instance's pre-configured options. * * @param password - The plain-text password to hash. * @param overrides - Optional per-call overrides for any constructor option. * @returns The encoded hash string, ready to be stored. */ hash(password: string, overrides?: Partial<PasswordManagerOptions>): Promise<string>; /** * Verifies a plain-text password against a stored hash. * * @param password - The password to verify. * @param hash - The stored hash to compare against. * @param overrides - Optional per-call override for the pepper. * @returns `true` if the password matches the hash, `false` otherwise. */ verify(password: string, hash: string, overrides?: Pick<PasswordManagerOptions, "pepper">): Promise<boolean>; /** * Checks if a string is a valid XyPriss hash, optionally matching * this manager's current algorithm. * * @param hash - The string to check. * @param strict - If `true`, only returns `true` if the hash matches the manager's algorithm. * @returns `true` if it's a valid hash, `false` otherwise. */ isHashed(hash: string, strict?: boolean): boolean; /** * Generates a cryptographically secure random password matching the given * criteria, with **guaranteed character-type coverage**. * * Security properties: * - Every enabled character type appears **at least once** in the output. * - `extra` characters are **injected at cryptographically random positions** * rather than appended, ensuring they don't cluster at the end. * - The final array is **Fisher-Yates shuffled** via `Random.Int` to remove * any positional bias introduced during construction. * - `length` is clamped to [8, 512] to prevent misuse. * - Throws `RangeError` if no character type is enabled (empty charset). * * @param options - Character set and length configuration. * @returns A plain-text randomly generated password string. * * @example * const pwd = passwords.generate({ length: 24, symbols: true }); */ generate(options?: PasswordGenerateOptions): string; /** * Generates a **memorable, high-entropy passphrase** using a curated * 256-word list (similar to Diceware / EFF methodology). * * Entropy: `log2(256^wordCount)` = `8 * wordCount` bits minimum. * With 5 words: ~40 bits base + number suffix ≈ 53 bits total. * With 6 words: ~48 bits base + number suffix ≈ 61 bits total. * * Security note: word selection uses `Random.Int` which must be backed * by a CSPRNG (e.g. `crypto.randomInt`). * * @param options - Passphrase configuration. * @returns A plain-text passphrase string. * * @example * passwords.generatePassphrase({ wordCount: 5, separator: "-" }); * // → "Bold-Cave-Iron-Jump-Warm-4827" */ generatePassphrase(options?: PassphraseOptions): string; /** * Generates a cryptographically secure numeric PIN. * * Each digit is drawn independently from the full [0-9] range. * The PIN is **zero-padded** to the requested length and returned as a * string to preserve leading zeros (e.g. "0472"). * * @param length - Number of digits. Must be between 4 and 32. @default 6 * @returns A plain-text numeric PIN string. * * @example * passwords.generatePin(6); // → "047291" */ generatePin(length?: number): string; /** * Evaluates the strength of a password and returns a detailed report. * * The score is computed from multiple orthogonal criteria: * - Length (up to 30 points) * - Character variety (up to 50 points) * - Absence of repetitions and sequences (up to 20 points deducted) * * @param password - The password to evaluate. * @returns A `PasswordStrengthResult` with score, label, and actionable suggestions. * * @example * const info = passwords.strength("MyP@ssw0rd!"); * console.log(info.score, info.label); // 82 "strong" */ strength(password: string): PasswordStrengthResult; /** * Checks whether a password has appeared in a publicly known data breach * using the **HaveIBeenPwned Pwned Passwords API v3** with **k-anonymity**. * * The full password is **never transmitted**. Only the first 5 characters of * its SHA-1 hex digest are sent over the network; the remainder of the * matching is performed locally. * * @param password - The plain-text password to check. * @returns A `BreachCheckResult` indicating breach status and occurrence count. * @throws If the network request fails or returns an unexpected status code. * * @example * const result = await passwords.isBreached("hunter2"); * if (result.breached) { * console.warn(`Password found ${result.occurrences} times in breach databases.`); * } */ isBreached(password: string): Promise<BreachCheckResult>; /** * Determines whether a stored hash was produced with weaker parameters than * the instance's current configuration (e.g. after a security upgrade). * * Supports Argon2id hash strings in the PHC string format: * `$argon2id$v=19$m=<mem>,t=<iter>,p=<par>$<salt>$<hash>` * * For other algorithms, returns `false` (no opinion) so the caller can * decide on a case-by-case basis. * * @param hash - The stored hash string to inspect. * @returns `true` if the hash should be re-hashed on next successful login. * * @example * if (passwords.needsRehash(user.passwordHash)) { * user.passwordHash = await passwords.hash(rawPassword); * await user.save(); * } */ needsRehash(hash: string): boolean; /** * Validates and normalizes a raw password string before hashing. * * Checks performed: * - Not empty or whitespace-only. * - Minimum length of 8 characters. * - Maximum length of 1024 characters (DoS guard against bcrypt-style * long-password attacks on other algorithms). * - Unicode NFC normalization (prevents homoglyph bypass attacks). * * @param password - The raw password string from user input. * @returns The NFC-normalized password, ready for hashing. * @throws `TypeError` if the input is not a string. * @throws `RangeError` if the password fails length validation. * * @example * const normalized = passwords.sanitizeInput(req.body.password); * const hash = await passwords.hash(normalized); */ sanitizeInput(password: unknown): string; /** * Returns a summary of the instance's current configuration. * The `pepper` is intentionally omitted from the output. */ getConfig(): { algorithm: string; memoryCost: number; iterations: number; parallelism: number; }; } //# sourceMappingURL=PasswordManager.d.ts.map