htpasswd

2.4.6 · active · verified Sun Apr 19

The `htpasswd` package provides a Node.js implementation of Apache's `htpasswd` utility, designed for managing HTTP Basic Authentication password files. It functions primarily as a command-line interface tool, offering various password encryption methods including MD5 (default), bcrypt, SHA, crypt(), and plaintext. The current stable version is 2.4.6. Its release cadence appears to be infrequent, with recent updates mainly addressing ownership and minor version bumps rather than continuous feature additions. Key differentiators include its direct emulation of the Apache utility's CLI and support for multiple hashing algorithms, making it suitable for environments where direct `htpasswd` file manipulation is required programmatically or via script.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates programmatic usage of the `htpasswd` library to create a new password file, add a user with bcrypt encryption, verify passwords, and delete the user.

import { Htpasswd } from 'htpasswd';
import * as path from 'path';
import * as fs from 'fs/promises';

async function runHtpasswdExample() {
  const filePath = path.join(__dirname, 'example.htpasswd');
  const username = 'testuser';
  const password = 'securePassword123';
  const wrongPassword = 'wrongPassword';

  try {
    // 1. Create a new htpasswd file and add a user (using bcrypt by default)
    // Default bcrypt cost is 5. Using 10 here for better security.
    const htpasswd = new Htpasswd(filePath, { create: true, bcrypt: true, cost: 10 });
    await htpasswd.add(username, password);
    console.log(`User '${username}' added to '${filePath}' with bcrypt hash.`);
    const content = await fs.readFile(filePath, 'utf8');
    console.log('File content:\n', content);

    // 2. Verify the correct password
    const isCorrect = await htpasswd.verify(username, password);
    console.log(`Password for '${username}' is correct: ${isCorrect}`);

    // 3. Try to verify with a wrong password
    const isWrong = await htpasswd.verify(username, wrongPassword);
    console.log(`Password for '${username}' with wrong input: ${isWrong}`);

    // 4. Delete the user
    await htpasswd.delete(username);
    console.log(`User '${username}' deleted from '${filePath}'.`);
    const updatedContent = await fs.readFile(filePath, 'utf8');
    console.log('File content after deletion:\n', updatedContent);

  } catch (error: any) {
    console.error('Error during htpasswd operations:', error.message);
  } finally {
    // Clean up the created file
    try {
      await fs.unlink(filePath);
      console.log(`Cleaned up '${filePath}'.`);
    } catch (e) {
      // Ignore if file doesn't exist or permissions issue during cleanup
    }
  }
}

runHtpasswdExample();

view raw JSON →