### Scrypt Configuration Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md An example demonstrating how to instantiate the Scrypt hash driver with a custom configuration object. Ensure the 'cost' parameter is a power of two. ```typescript const config: ScryptConfig = { cost: 32768, blockSize: 8, parallelization: 2, saltSize: 16, maxMemory: 64 * 1024 * 1024, keyLength: 64 } const scrypt = new Scrypt(config) ``` -------------------------------- ### HashManager Configuration Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md An example showing how to configure the HashManager with multiple driver factories. This allows for on-demand instantiation of different hashing algorithms like Argon, Bcrypt, and Scrypt. ```typescript const factories: Record = { argon: () => new Argon({ iterations: 4 }), bcrypt: () => new Bcrypt({ rounds: 12 }), scrypt: () => new Scrypt({ cost: 32768 }) } const manager = new HashManager({ default: 'argon', list: factories }) ``` -------------------------------- ### ArgonConfig Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md Shows how to define a custom configuration for the Argon2 hash driver. This example sets higher memory and parallelism for increased security. ```typescript const config: ArgonConfig = { variant: 'id', version: 0x13, iterations: 4, memory: 131072, parallelism: 6, saltSize: 16, hashLength: 32 } const argon = new Argon(config) ``` -------------------------------- ### ScryptAsync Usage Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Validators.md Demonstrates how to use the scryptAsync function to hash a password with specific Scrypt options. The example shows how to import the function and log the length of the resulting hash. ```typescript import { scryptAsync } from '@adonisjs/hash' const hash = await scryptAsync('password', Buffer.from('salt'), 64, { cost: 16384, blockSize: 8, parallelization: 1, maxmem: 32 * 1024 * 1024 }) console.log(hash.length) // 64 ``` -------------------------------- ### Example Usage of HashDriverContract Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md Demonstrates how to use the `verify` method from the HashDriverContract to authenticate a user. ```typescript function authenticateUser( driver: HashDriverContract, storedHash: string, userPassword: string ): Promise { return driver.verify(storedHash, userPassword) } ``` -------------------------------- ### BcryptConfig Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md An example of configuring the Bcrypt hash driver with a custom number of rounds for increased security. Version 'b' (0x62) is recommended. ```typescript const config: BcryptConfig = { rounds: 12, saltSize: 16, version: 0x62 // 'b' } const bcrypt = new Bcrypt(config) ``` -------------------------------- ### HashManagerFactory Create Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Shows how to create a HashManager instance after configuring the factory, including setting a default driver and hashing a password. ```typescript const factory = new HashManagerFactory() .merge({ default: 'argon', list: { argon: () => new Argon({}), } }) const manager = factory.create() const hash = await manager.make('password') ``` -------------------------------- ### PHC Format Examples Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/PhcFormatter.md Examples illustrating the structure of PHC formatted strings for different algorithms like Argon2, Bcrypt, and Scrypt. ```plaintext $argon2id$v=19$t=3,m=65536,p=4$saltstring$hashstring $bcrypt$v=98$r=10$saltstring$hashstring $scrypt$n=16384,r=8,p=1$saltstring$hashstring ``` -------------------------------- ### HashManagerFactory Merge Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Demonstrates merging configurations to create a new factory with different hasher options. The original factory remains unchanged. ```typescript const factory = new HashManagerFactory() const newFactory = factory.merge({ default: 'argon', list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}), } }) // Original factory is unchanged // newFactory has the new configuration ``` -------------------------------- ### Using Fake Driver with HashManager for Testing Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Fake.md Demonstrates how to enable fake mode using HashManager.fake() for fast, non-hashing tests. This setup bypasses actual hashing and uses instant string equality for verification. ```typescript import { HashManager } from '@adonisjs/hash' import { Argon } from '@adonisjs/hash/drivers/argon' describe('User authentication', () => { it('should authenticate user with correct password', async () => { const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}) } }) // Enable fake mode for fast testing using _ = manager.fake() // Hashing is now instant and plain text const hash = await manager.make('password') console.log(hash) // 'password' // Verification uses string equality const isValid = await manager.verify('password', 'password') console.log(isValid) // true }) }) ``` -------------------------------- ### Handle Manager Initialization Errors Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/errors.md Catch RuntimeException during HashManager initialization if essential configuration properties like 'list' or 'default' are missing. This ensures robust manager setup. ```typescript try { const manager = new HashManager({ // Missing 'list' or 'default' } as any) const hash = await manager.make('password') } catch (error) { if (error instanceof RuntimeException) { console.error('Manager not configured:', error.message) } } ``` -------------------------------- ### PhcNode Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md Illustrates the structure of a `PhcNode` object, representing a deserialized Argon2id hash string. ```typescript const phcString = '$argon2id$v=19$t=3,m=65536,p=4$salt$hash' const node: PhcNode<{ t: number; m: number; p: number }> = { id: 'argon2id', version: 19, params: { t: 3, m: 65536, p: 4 }, salt: Buffer.from([...]), hash: Buffer.from([...]) } ``` -------------------------------- ### Usage in Hash Drivers (Verification) Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/PhcFormatter.md Example of how PhcFormatter is used internally by hash drivers during password verification (verify). ```typescript // During verification (verify) const phcNode = formatter.deserialize(phcString) const newHash = calculateHash(plaintext, phcNode.params) ``` -------------------------------- ### Usage in Hash Drivers (Hashing) Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/PhcFormatter.md Example of how PhcFormatter is used internally by hash drivers during the password hashing process (make). ```typescript // During hashing (make) const salt = Buffer.from(randomBytes(16)) const hash = Buffer.from(cryptoHash) const phcString = formatter.serialize(salt, hash, { id: 'argon2id', version: 19, params: { t: 3, m: 65536, p: 4 } }) ``` -------------------------------- ### Multiple Configurations for Different Environments Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Illustrates creating distinct factory configurations for different environments (e.g., test and production) with varying driver parameters. ```typescript const baseFactory = new HashManagerFactory() // Configuration for different environments const testFactory = baseFactory.merge({ default: 'argon', list: { argon: () => new Argon({ iterations: 2, memory: 8192 }), } }) const prodFactory = baseFactory.merge({ default: 'argon', list: { argon: () => new Argon({ iterations: 4, memory: 131072 }), } }) const testManager = testFactory.create() const prodManager = prodFactory.create() ``` -------------------------------- ### Instantiate Hash with Argon Driver Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Hash.md Demonstrates how to create a new Hash instance using the Argon driver. Ensure the Argon driver is properly configured. ```typescript const hash = new Hash(new Argon({})) ``` -------------------------------- ### Argon2 Configuration with Pepper Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Example of using a secret pepper with Argon2. The pepper is not stored in the hash and is required for verification. ```typescript import { Secret } from '@poppinss/utils' const argon = new Argon({ secret: new Secret('application-wide-pepper-string') }) // Pepper is not stored; verification requires the same pepper ``` -------------------------------- ### Fake Driver Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Fake.md Initializes the Fake driver. It does not accept any configuration parameters. ```APIDOC ## Constructor ```typescript new Fake() ``` The Fake driver takes no configuration parameters. ``` -------------------------------- ### Custom Configuration Usage Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Demonstrates configuring the HashManagerFactory with multiple drivers and specifying a default. It also shows how to use a specific driver. ```typescript const factory = new HashManagerFactory() .merge({ default: 'argon', list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}), scrypt: () => new Scrypt({}), } }) const manager = factory.create() // Use default (argon) const hash1 = await manager.make('password') // Use specific driver const hash2 = await manager.use('bcrypt').make('password') ``` -------------------------------- ### Importing Driver-Specific Types Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md Demonstrates importing configuration types from specific driver entry points for better modularity. ```typescript // Or from specific drivers import type { ArgonConfig } from '@adonisjs/hash/drivers/argon' import type { BcryptConfig } from '@adonisjs/hash/drivers/bcrypt' import type { ScryptConfig } from '@adonisjs/hash/drivers/scrypt' ``` -------------------------------- ### Secret Usage Example Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md Demonstrates how to use the Secret type to securely pass a secret pepper to the Argon hash driver. The 'release' method is used internally by the driver. ```typescript import { Secret } from '@poppinss/utils' const secret = new Secret('my-secret-pepper') const argon = new Argon({ secret: secret }) ``` -------------------------------- ### Default Configuration Usage Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Illustrates using the HashManagerFactory with its default settings, which typically utilize the Scrypt driver. ```typescript const factory = new HashManagerFactory() const manager = factory.create() // Uses Scrypt as the default driver const hash = await manager.make('password') ``` -------------------------------- ### Scrypt Constructor with Minimal Configuration for Testing Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Scrypt.md Instantiates the Scrypt class with minimal, reasonable values for cost and memory, suitable for testing purposes. ```typescript const scrypt = new Scrypt({ cost: 1024, // Minimum reasonable value for testing blockSize: 8, parallelization: 1, maxMemory: 16 * 1024 * 1024 // 16 MiB }) ``` -------------------------------- ### Validator Error Messages Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Validators.md Provides examples of consistent error messages generated by AdonisJS validators for configuration options. These messages indicate type, range, or value constraints. ```plaintext TypeError: The "{label}" option must be an integer TypeError: The "{label}" option must be in the range ({min} <= {label} <= {max}) TypeError: The "{label}" option must be one of: {values} ``` -------------------------------- ### Configure HashManager with Multiple Drivers Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Sets up the HashManager with multiple hashing drivers (Argon, Bcrypt, Scrypt). Allows switching between drivers for different purposes or compatibility needs. Demonstrates using the default driver and explicitly selecting a specific driver. ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({ iterations: 4 }), bcrypt: () => new Bcrypt({ rounds: 12 }), scrypt: () => new Scrypt({ cost: 32768 }) } }) // Use default const hash1 = await manager.make('password') // Use specific driver const hash2 = await manager.use('bcrypt').make('password') ``` -------------------------------- ### make Method Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Fake.md Generates a "hash" of a given plain text value. The Fake driver returns the plain text value itself without any modification. ```APIDOC ## make ```typescript async make(value: string): Promise ``` Returns the plain text value without any hashing. ### Parameters #### Path Parameters - value (string) - Required - The plain text value ### Returns `Promise` - A promise that resolves to the same value passed in ### Example ```typescript const fake = new Fake() const result = await fake.make('password') console.log(result) // 'password' ``` ``` -------------------------------- ### Get Hash Instance using HashManager Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Retrieve a Hash instance for a specific driver using the 'use' method. It returns cached instances to optimize performance. If no hasher is specified, it defaults to the configured default hasher. ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}), scrypt: () => new Scrypt({}), } }) // Use the default hasher const defaultHasher = manager.use() const hash1 = await defaultHasher.make('password') // Use a specific hasher const bcryptHasher = manager.use('bcrypt') const hash2 = await bcryptHasher.make('password') // Same hasher instance is returned from cache const bcryptHasher2 = manager.use('bcrypt') console.log(bcryptHasher === bcryptHasher2) // true ``` -------------------------------- ### Argon Basic Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Argon.md Instantiate Argon with default settings for variant, version, iterations, memory, and parallelism. ```typescript const argon = new Argon({}) // Uses defaults: variant='id', version=0x13, iterations=3, memory=65536, parallelism=4 ``` -------------------------------- ### Basic Hashing with Argon Driver Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/README.md Demonstrates basic password hashing and verification using the Argon driver. Ensure the Argon driver and Hash wrapper are imported. ```typescript import { Argon } from '@adonisjs/hash/drivers/argon' import { Hash } from '@adonisjs/hash' const driver = new Argon({}) const hash = new Hash(driver) const hashed = await hash.make('password') const isValid = await hash.verify(hashed, 'password') ``` -------------------------------- ### Using Multiple Hash Drivers with HashManager Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/README.md Shows how to configure and use the HashManager to switch between different hashing algorithms like Argon and Bcrypt. The manager allows defining a default driver and a list of available drivers. ```typescript import { HashManager } from '@adonisjs/hash' import { Argon } from '@adonisjs/hash/drivers/argon' import { Bcrypt } from '@adonisjs/hash/drivers/bcrypt' const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}) } }) const hash1 = await manager.make('password') // Uses Argon const hash2 = await manager.use('bcrypt').make('password') // Uses Bcrypt ``` -------------------------------- ### Direct Instantiation of Fake Driver Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Fake.md Shows how to directly instantiate the Fake driver and use it with the Hash wrapper class. This is an alternative to using HashManager for testing specific components. ```typescript const fake = new Fake() const hash = new Hash(fake) const hashed = await hash.make('test') const isValid = await hash.verify(hashed, 'test') ``` -------------------------------- ### make Method Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Hashes a plain text value using the default hasher. ```APIDOC ## make ### Description Hash a plain text value using the default hasher. ### Method POST (or equivalent SDK method call) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters * **value** (string) - Required - The plain text value to hash. ### Returns * **Promise** - A promise that resolves to the hashed value. ### Example ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}) } }) const hashed = await manager.make('password') ``` ``` -------------------------------- ### Testing HashManager with Fake Mode Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Shows how to set up the HashManagerFactory for testing by configuring it with a specific driver and enabling fake mode for fast assertions. ```typescript import test from 'japa' import { HashManagerFactory } from '@adonisjs/hash/factories' test('user authentication', async (assert) => { const factory = new HashManagerFactory() .merge({ default: 'argon', list: { argon: () => new Argon({}), } }) const manager = factory.create() // Enable fake mode for fast testing using _ = manager.fake() const hash = await manager.make('password') assert.equal(hash, 'password') const verified = await manager.verify('password', 'password') assert.isTrue(verified) }) ``` -------------------------------- ### Bcrypt Configuration using Version A Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Bcrypt.md Specify the use of Bcrypt version 'a' (0x61) during instantiation. ```typescript const bcrypt = new Bcrypt({ version: 0x61 // 'a' }) ``` -------------------------------- ### Verify and Rehash Legacy Bcrypt Hashes Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Bcrypt.md Demonstrates how to use the Bcrypt driver to verify a legacy hash and rehash it to the modern PHC format if necessary. Ensure the Bcrypt driver is initialized with desired rounds. ```typescript const bcrypt = new Bcrypt({ rounds: 12 }) // Legacy hash from old system const legacyHash = '$2b$10$N3HEDUkEqHDTL5Mq4IQGSuIm0o5hOiGGsKMRFDEGYDhHgKtXEH8ni' // Verification works const verified = await bcrypt.verify(legacyHash, 'password') // But it needs rehashing to use PHC format if (verified && bcrypt.needsReHash(legacyHash)) { const newHash = await bcrypt.make('password') // Save newHash to database } ``` -------------------------------- ### Bcrypt Basic Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Bcrypt.md Instantiate Bcrypt with default configuration values for rounds, salt size, and version. ```typescript const bcrypt = new Bcrypt({}) // Uses defaults: rounds=10, saltSize=16, version=0x62 (v=98) ``` -------------------------------- ### Scrypt Constructor with Default Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Scrypt.md Instantiates the Scrypt class using default configuration values for cost, block size, and parallelization. ```typescript const scrypt = new Scrypt({}) // Uses defaults: cost=16384, blockSize=8, parallelization=1 ``` -------------------------------- ### Scrypt Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Scrypt.md Initializes a new Scrypt hashing instance with configurable parameters. The constructor accepts a ScryptConfig object to set memory-hard parameters like cost, blockSize, and parallelization. ```APIDOC ## Constructor Scrypt ### Description Initializes a new Scrypt hashing instance with configurable parameters. The constructor accepts a ScryptConfig object to set memory-hard parameters like cost, blockSize, and parallelization. ### Parameters #### Constructor Parameters - **config.cost** (`number`) - Optional - CPU/memory cost parameter (N). Must be a power of two greater than one. Higher values increase security (2 to 2³²-1). Default: `16384` - **config.blockSize** (`number`) - Optional - Block size parameter (r). Memory block size in 128-byte units (1 to 2³²-1). Default: `8` - **config.parallelization** (`number`) - Optional - Parallelization parameter (p). Number of parallel tasks (1 to ⌊(2³²-1)×32 / (128×r)⌋). Default: `1` - **config.saltSize** (`number`) - Optional - Size of the generated salt in bytes (8 to 1024). Default: `16` - **config.keyLength** (`number`) - Optional - Desired output key length in bytes (64 to 128). Default: `64` - **config.maxMemory** (`number`) - Optional - Maximum memory to use in bytes (≥ 128×cost×blockSize). Default: `33554432` ``` -------------------------------- ### Environment-Specific Hash Configuration (Testing) Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Sets up the HashManager for testing environments using a factory and a fake driver for rapid testing. This configuration optimizes for speed during automated tests. ```typescript const factory = new HashManagerFactory() .merge({ default: 'argon', list: { argon: () => new Argon({ iterations: 2, memory: 8192 }) } }) const manager = factory.create() using _ = manager.fake() // For fastest tests ``` -------------------------------- ### Chaining Factory Methods Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Demonstrates the fluent configuration of HashManagerFactory by chaining the merge and create methods. ```typescript const manager = new HashManagerFactory() .merge({ default: 'bcrypt', list: { bcrypt: () => new Bcrypt({ rounds: 12 }), scrypt: () => new Scrypt({ cost: 32768 }), } }) .create() ``` -------------------------------- ### Import Main Hash Package Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/README.md Import the main Hash and HashManager classes from the '@adonisjs/hash' package. ```typescript import { Hash, HashManager } from '@adonisjs/hash' import type { HashDriverContract } from '@adonisjs/hash/types' ``` -------------------------------- ### Importing Hash Types from Main Package Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/types.md Shows how to import various type definitions from the main '@adonisjs/hash/types' entry point. ```typescript // From main entry import type { HashDriverContract, ArgonVariants, ArgonConfig, BcryptConfig, ScryptConfig, PhcNode, ManagerDriverFactory } from '@adonisjs/hash/types' ``` -------------------------------- ### Configure HashManager without a Default Driver Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Sets up the HashManager with multiple drivers but no default specified. This requires explicitly selecting a driver for each hashing operation. Attempting to use the default will result in an error. ```typescript const manager = new HashManager({ list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}) } }) // Error: must specify driver // await manager.make('password') // Throws RuntimeException // Must use specific driver const hash = await manager.use('argon').make('password') ``` -------------------------------- ### HashManagerFactory Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Initializes a new HashManagerFactory. It can be configured with a default hasher and a list of available hasher implementations. If no configuration is provided, it defaults to using the Scrypt hasher. ```APIDOC ## Constructor HashManagerFactory ### Description Initializes a new HashManagerFactory. It can be configured with a default hasher and a list of available hasher implementations. If no configuration is provided, it defaults to using the Scrypt hasher. ### Signature ```typescript new HashManagerFactory(config?: { default?: keyof KnownHashers list: KnownHashers }) ``` ### Parameters #### Config Object - **config.default** (`keyof KnownHashers`) - Optional - Default hasher to use. Defaults to 'scrypt'. - **config.list** (`KnownHashers`) - Optional - Record of hasher names to factory functions. Defaults to `{ scrypt: () => new Scrypt({}) }`. ### Type Parameters - **KnownHashers extends Record** - Record type mapping driver names to factory functions. ``` -------------------------------- ### Argon Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Argon.md Initializes a new instance of the Argon class with optional configuration for the Argon2 algorithm. ```APIDOC ## new Argon(config: ArgonConfig) ### Description Initializes a new instance of the Argon class with optional configuration for the Argon2 algorithm. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | config.variant | `'d' | 'i' | 'id'` | No | `'id'` | The Argon2 variant to use. 'd' optimizes for GPU attacks, 'i' optimizes for side-channel attacks, 'id' balances both | | config.version | `0x10 | 0x13` | No | `0x13` | The Argon2 version. 0x13 is the latest and recommended | | config.iterations | `number` | No | `3` | Time cost parameter (iterations). Higher values increase security at the cost of computation time (2 to 2³²-1) | | config.memory | `number` | No | `65536` | Memory cost parameter in KiB. Higher values increase security and memory usage (8×parallelism to 2³²-1) | | config.parallelism | `number` | No | `4` | Parallelization parameter. Number of parallel threads (1 to 2²⁴-1) | | config.saltSize | `number` | No | `16` | Size of the generated salt in bytes (8 to 1024) | | config.secret | `Secret` | No | — | Optional pepper/secret string for additional security. Not encoded in hash, so verification requires same secret | | config.hashLength | `number` | No | `32` | Size of the hash output in bytes (4 to 2³²-1) | ``` -------------------------------- ### HashManager Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Initializes a new HashManager instance. It requires a configuration object specifying the default hasher and a list of available hasher factories. ```APIDOC ## Constructor HashManager ### Description Initializes a new HashManager instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (object) - Required - Configuration object for the HashManager. * **config.default** (keyof KnownHashers) - Optional - The name of the default hasher to use. If not specified, calls to methods without a hasher argument will raise an error. * **config.list** (KnownHashers) - Yes - Record of hasher names to factory functions that create driver instances. ### Type Parameter * `KnownHashers extends Record` - A record type mapping driver names to factory functions. ### Example ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}), scrypt: () => new Scrypt({}), } }) ``` ``` -------------------------------- ### make Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Argon.md Asynchronously hashes a plain text value using the Argon2 algorithm. ```APIDOC ## async make(value: string): Promise ### Description Hash a plain text value using Argon2. ### Method None (This is a method of the Argon class) ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |---|---|---|---| | value | `string` | Yes | The plain text value to hash | ### Returns `Promise` - A promise that resolves to the Argon2 hash in PHC format ### Example ```typescript const argon = new Argon({ variant: 'id', iterations: 3, memory: 65536, parallelism: 4 }) const hash = await argon.make('my-password') // $argon2id$v=19$t=3,m=65536,p=4$drxJBWzWahR5tMubp+a1Sw$L/Oh2uw6QKW77i/KQ8eGuOt3ui52hEmmKlu1KBVBxiM ``` ``` -------------------------------- ### Scrypt Constructor with Balanced Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Scrypt.md Instantiates the Scrypt class with a balanced set of security parameters, offering a compromise between security and performance. ```typescript const scrypt = new Scrypt({ cost: 32768, blockSize: 8, parallelization: 2 }) ``` -------------------------------- ### Hash Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Hash.md Initializes a new instance of the Hash class with a specified driver implementation. ```APIDOC ## Constructor Hash ### Description Initializes a new instance of the Hash class with a specified driver implementation. ### Parameters #### Path Parameters - **driver** (HashDriverContract) - Required - The hash driver implementation to use for cryptographic operations ``` -------------------------------- ### make Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Hash.md Hashes a plain text value using the configured algorithm, returning the hashed value in PHC format. ```APIDOC ## make ### Description Hash a plain text value using the configured algorithm. ### Parameters #### Path Parameters - **value** (string) - Required - The plain text value to hash ### Returns `Promise` - A promise that resolves to the hashed value in PHC format ### Example ```typescript const hash = new Hash(new Argon({})) const hashed = await hash.make('secret-password') console.log(hashed) // $argon2id$v=19$t=3,m=4096,p=1$... ``` ``` -------------------------------- ### Import Individual Hash Drivers Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/README.md Import specific hashing drivers like Argon, Bcrypt, or Scrypt from their respective modules. ```typescript import { Argon } from '@adonisjs/hash/drivers/argon' import { Bcrypt } from '@adonisjs/hash/drivers/bcrypt' import { Scrypt } from '@adonisjs/hash/drivers/scrypt' ``` -------------------------------- ### make Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Scrypt.md Hashes a plain text value using the Scrypt algorithm with the configured parameters. It returns a promise that resolves to the generated hash in PHC string format. ```APIDOC ## Method make ### Description Hashes a plain text value using the Scrypt algorithm with the configured parameters. It returns a promise that resolves to the generated hash in PHC string format. ### Parameters #### Path Parameters - **value** (`string`) - Required - The plain text value to hash ### Returns `Promise` - A promise that resolves to the Scrypt hash in PHC format ### Example ```typescript const scrypt = new Scrypt({ cost: 16384, blockSize: 8, parallelization: 1 }) const hash = await scrypt.make('my-password') // $scrypt$n=16384,r=8,p=1$iILKD1gVSx6bqualYqyLBQ$DNzIISdmTQS6sFdQ1tJ3UCZ7Uun4uGHNjj0x8FHOqB0pf2LYsu9Xaj5MFhHg21qBz8l5q/oxpeV+ZkgTAj+OzQ ``` ``` -------------------------------- ### make Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Bcrypt.md Hashes a plain text value using the Bcrypt algorithm, producing a hash in PHC string format. ```APIDOC ## async make(value: string): Promise ### Description Hash a plain text value using Bcrypt. ### Method None (Instance method) ### Endpoint None (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (`string`) - Required - The plain text value to hash ### Returns `Promise` - A promise that resolves to the Bcrypt hash in PHC format ``` -------------------------------- ### verify Method Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Verifies a plain text value against a hash using the default hasher. ```APIDOC ## verify ### Description Verify a plain text value against a hash using the default hasher. ### Method POST (or equivalent SDK method call) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters * **hashedValue** (string) - Required - The hashed value to verify against. * **plainValue** (string) - Required - The plain text value to verify. ### Returns * **Promise** - True if verification succeeds, false otherwise. ### Example ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}) } }) const hashed = await manager.make('password') const isValid = await manager.verify(hashed, 'password') ``` ``` -------------------------------- ### verify Method Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Fake.md Verifies if a plain text value matches a "hashed" value. The Fake driver performs a simple string equality check. ```APIDOC ## verify ```typescript async verify(hashedValue: string, plainValue: string): Promise ``` Verifies by comparing the two values for exact string equality. ### Parameters #### Path Parameters - hashedValue (string) - Required - The "hashed" value - plainValue (string) - Required - The plain text value to verify ### Returns `Promise` - True if both values are exactly equal ### Example ```typescript const fake = new Fake() await fake.verify('password', 'password') // true await fake.verify('password', 'other') // false ``` ``` -------------------------------- ### Bcrypt Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Bcrypt.md Initializes a new instance of the Bcrypt class with optional configuration for security and performance. ```APIDOC ## new Bcrypt(config: BcryptConfig) ### Description Initializes a new instance of the Bcrypt class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config.rounds** (`number`) - Optional - The cost factor. Determines the number of key expansion rounds. Higher values increase security and computation time (4 to 31). Default: `10` - **config.saltSize** (`number`) - Optional - Size of the generated salt in bytes (8 to 1024). Default: `16` - **config.version** (`0x61 | 0x62`) - Optional - The Bcrypt version. 0x61 is 'a', 0x62 is 'b'. Version b is recommended. Default: `0x62` ``` -------------------------------- ### Scrypt Standard Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md The recommended standard configuration for Scrypt, balancing computational cost and memory usage. ```typescript const scrypt = new Scrypt({ cost: 16384, blockSize: 8, parallelization: 1 }) ``` -------------------------------- ### Fake Driver Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Fake.md Instantiates the Fake driver. It does not require any configuration parameters. ```typescript new Fake() ``` -------------------------------- ### use Method Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Retrieves a Hash instance for a specified driver, returning cached instances to avoid recreation. ```APIDOC ## use ### Description Get a `Hash` instance for the specified driver. Returns cached instances to avoid recreating drivers. ### Method GET (or equivalent SDK method call) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Method Parameters * **hasher** (Hasher) - Optional - The name of the hasher to use. Defaults to the hasher configured as default in the HashManager. ### Returns * **Hash** - A Hash instance for the specified driver. ### Throws * **RuntimeException** - If no hasher is specified and no default is configured. ### Example ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}), scrypt: () => new Scrypt({}), } }) // Use the default hasher const defaultHasher = manager.use() const hash1 = await defaultHasher.make('password') // Use a specific hasher const bcryptHasher = manager.use('bcrypt') const hash2 = await bcryptHasher.make('password') // Same hasher instance is returned from cache const bcryptHasher2 = manager.use('bcrypt') console.log(bcryptHasher === bcryptHasher2) // true ``` ``` -------------------------------- ### HashManagerFactory.create Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Instantiates a HashManager using the current configuration of the factory. This method is used to obtain a usable HashManager instance for hashing operations. ```APIDOC ## Method create ### Description Instantiates a HashManager using the current configuration of the factory. This method is used to obtain a usable HashManager instance for hashing operations. ### Signature ```typescript create(): HashManager ``` ### Returns - **HashManager** - A new HashManager instance. ### Example ```typescript const factory = new HashManagerFactory() .merge({ default: 'argon', list: { argon: () => new Argon({}), } }) const manager = factory.create() const hash = await manager.make('password') ``` ``` -------------------------------- ### Scrypt Constructor with High Security Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Scrypt.md Instantiates the Scrypt class with high security parameters, significantly increasing memory and time requirements. Includes a custom maxMemory setting. ```typescript const scrypt = new Scrypt({ cost: 65536, // Increased from default blockSize: 16, // Increased from default parallelization: 8, maxMemory: 256 * 1024 * 1024 // 256 MiB }) // Uses significantly more memory and time ``` -------------------------------- ### Pre-validate Configuration for Hash Driver Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/errors.md Create a function to pre-validate configuration before instantiating a hash driver. This allows for graceful fallback to default settings in case of invalid configuration. ```typescript function createHashDriver(config: any) { try { return new Argon(config) } catch (error) { console.error('Invalid configuration:', error) // Fall back to default return new Argon({}) } } ``` -------------------------------- ### Argon Configuration using D Variant Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Argon.md Instantiate Argon with the 'd' variant, which is optimized for protection against GPU-based attacks. ```typescript const argon = new Argon({ variant: 'd' }) ``` -------------------------------- ### Import Hash Types Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/README.md Import various types and interfaces related to hash drivers and configurations. ```typescript import type { HashDriverContract, ArgonConfig, BcryptConfig, ScryptConfig, PhcNode, ArgonVariants, ManagerDriverFactory } from '@adonisjs/hash/types' ``` -------------------------------- ### HashManagerFactory Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Instantiates a new HashManagerFactory. If no configuration is provided, it defaults to using the Scrypt driver. ```typescript new HashManagerFactory(config?: { default?: keyof KnownHashers list: KnownHashers }) ``` -------------------------------- ### Import Hash Manager Factory Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/README.md Import the HashManagerFactory for creating hash manager instances. ```typescript import { HashManagerFactory } from '@adonisjs/hash/factories' ``` -------------------------------- ### Configure HashManager with a Single Driver (Argon) Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Sets up the HashManager to use only the Argon driver. This is a basic configuration for applications primarily using Argon2. ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}) } }) ``` -------------------------------- ### fake Method Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Enables fake hashing for testing purposes. In fake mode, the driver returns plain text as the hash and performs verification via simple string equality. ```APIDOC ## fake ### Description Enable fake hashing for testing. The fake driver returns plain text as hash and verifies by simple string equality. ### Method POST (or equivalent SDK method call) ### Endpoint N/A (SDK method) ### Parameters None ### Returns * **object** - An object with a `dispose` symbol for use with async context managers. ### Example ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}), } }) // Enable fake mode for testing using _ = manager.fake() const hash = await manager.make('password') // 'password' const isValid = await manager.verify('password', 'password') // true ``` ``` -------------------------------- ### HashManager Constructor Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Instantiate the HashManager with a default hasher and a list of available hasher factories. The 'list' parameter is required and maps hasher names to functions that create driver instances. ```typescript new HashManager({ default?: keyof KnownHashers list: KnownHashers }) ``` -------------------------------- ### verify Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Argon.md Asynchronously verifies a plain text value against a pre-computed Argon2 hash. ```APIDOC ## async verify(hashedValue: string, plainValue: string): Promise ### Description Verify a plain text value against an Argon2 hash. Returns false for invalid hashes instead of throwing. ### Method None (This is a method of the Argon class) ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |---|---|---|---| | hashedValue | `string` | Yes | The Argon2 hash to verify against | | plainValue | `string` | Yes | The plain text value to verify | ### Returns `Promise` - True if verification succeeds, false otherwise ### Example ```typescript const argon = new Argon({}) const hash = await argon.make('secret-password') const isValid = await argon.verify(hash, 'secret-password') // true const isInvalid = await argon.verify(hash, 'wrong-password') // false ``` ``` -------------------------------- ### Argon2 Balanced Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Recommended configuration for web applications, balancing security and performance. ```typescript const argon = new Argon({ variant: 'id', iterations: 3, memory: 65536, parallelism: 4 }) ``` -------------------------------- ### Testing with Fake Hash Driver Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/README.md Illustrates how to use the fake driver for fast testing scenarios. The fake driver bypasses actual hashing, performing only string equality checks. This is useful for unit tests where hashing performance is not critical. ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}) } }) // Fast tests with fake driver using _ = manager.fake() const hash = await manager.make('password') // No hashing const verified = await manager.verify(hash, 'password') // String equality ``` -------------------------------- ### HashManager assertEquals and assertNotEquals Delegation Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/errors.md Shows how HashManager's `assertEquals` and `assertNotEquals` methods delegate their functionality to the underlying Hash instance's corresponding methods. ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}) } }) const hashed = await manager.make('password') try { await manager.assertEquals(hashed, 'wrong-password') } catch (error) { // AssertionError thrown } ``` -------------------------------- ### HashManagerFactory.merge Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManagerFactory.md Creates a new factory instance with an updated configuration, allowing for fluent chaining of configuration settings. This method does not modify the original factory instance. ```APIDOC ## Method merge ### Description Creates a new factory instance with an updated configuration, allowing for fluent chaining of configuration settings. This method does not modify the original factory instance. ### Signature ```typescript merge>( config: { default?: keyof Hashers list: Hashers } ): HashManagerFactory ``` ### Parameters #### Config Object - **config.default** (`keyof Hashers`) - Optional - Default hasher to use. - **config.list** (`Hashers`) - Required - Record of hasher names to factory functions. ### Returns - **HashManagerFactory** - A new factory instance with the merged configuration. ### Example ```typescript const factory = new HashManagerFactory() const newFactory = factory.merge({ default: 'argon', list: { argon: () => new Argon({}), bcrypt: () => new Bcrypt({}), } }) ``` ``` -------------------------------- ### Bcrypt Legacy Version Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Configures Bcrypt to use the legacy version 'a'. Version 'b' is recommended for general use. ```typescript const bcrypt = new Bcrypt({ version: 0x61 // 'a' (version b is recommended) }) ``` -------------------------------- ### Scrypt Fast Configuration Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md A fast configuration for Scrypt, primarily intended for testing or development environments where performance is key. ```typescript const scrypt = new Scrypt({ cost: 1024, blockSize: 8, parallelization: 1 }) ``` -------------------------------- ### Environment-Specific Hash Configuration (Development) Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Configures the Argon2 driver with specific parameters for development environments. This allows for faster hashing during development while using more secure parameters in production. ```typescript const driver = process.env.NODE_ENV === 'development' ? new Argon({ iterations: 2, memory: 8192 }) : new Argon({ iterations: 4, memory: 131072 }) ``` -------------------------------- ### Validate Scrypt Configuration Parameters Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/configuration.md Demonstrates configuration validation for the Scrypt driver, showing a TypeError for an invalid 'cost' option. Ensures the 'cost' parameter is within the acceptable range. ```typescript // Invalid cost for Scrypt new Scrypt({ cost: 100 }) // TypeError: The "cost" option must be in the range (2 <= cost <= 4294967295) ``` -------------------------------- ### Scrypt Construction with Invalid Cost Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/Scrypt.md Demonstrates catching a TypeError when constructing a Scrypt instance with an invalid 'cost' parameter that is not a power of two. The 'verify' method returns false for invalid hashes, but invalid configurations throw during construction. ```typescript try { const scrypt = new Scrypt({ cost: 100 // Error: must be a power of two }) } catch (error) { console.error(error.message) } ``` -------------------------------- ### Enable Fake Hashing for Testing Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/api-reference/HashManager.md Activate fake hashing mode using the 'fake' method for testing purposes. In this mode, the fake driver returns plain text as the hash and verifies using simple string equality. The returned object can be used with async context managers for automatic cleanup. ```typescript const manager = new HashManager({ default: 'argon', list: { argon: () => new Argon({}), } }) // Enable fake mode for testing using _ = manager.fake() const hash = await manager.make('password') // 'password' const isValid = await manager.verify('password', 'password') // true ``` -------------------------------- ### Handle HashManager Configuration Error Source: https://github.com/adonisjs/hash/blob/10.x/_autodocs/errors.md Catch RuntimeException when HashManager.use() is called without a default driver configured or specified. This occurs when no default hasher is defined in the configuration. ```typescript const manager = new HashManager({ list: { argon: () => new Argon({}) } // No 'default' specified }) try { await manager.make('password') } catch (error) { if (error instanceof RuntimeException) { console.error(error.message) // Cannot create hash instance. No default hasher is defined in the config } } ```