GithubHelp home page GithubHelp logo

mister-hope / bcrypt-ts Goto Github PK

View Code? Open in Web Editor NEW
16.0 1.0 1.0 1.32 MB

Optimized bcrypt written in typescript with zero dependencies and 8KB Gzip size

License: Other

TypeScript 98.80% JavaScript 0.95% Shell 0.25%
bcrypt bcryptjs

bcrypt-ts's Introduction

bcrypt-ts

Optimized bcrypt written in typescript. Working in both Node.js and browser.

Heavily inspired by bcrypt.js.

Security considerations

Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power. (see)

While bcrypt-ts is compatible to the C++ bcrypt binding, it is providing pure JavaScript and thus slower about 30%, effectively reducing the number of iterations that can be processed in an equal time span.

The maximum input length is 72 bytes (note that UTF8 encoded characters use up to 4 bytes) and the length of generated hashes is 60 characters.

Highlights

  • 0 dependencies, with ONLY 8KB Gzip size
  • Written in typescript
  • Provide tree-shakable ES module

Usage

Node.js

On Node.js, the inbuilt crypto module's randomBytes interface is used to obtain secure random numbers.

Browser

In the browser, bcrypt.js relies on Web Crypto API's getRandomValues interface to obtain secure random numbers. If no cryptographically secure source of randomness is available, the package will throw an error.

How to choose between them

  • If you are using this package in pure Node.js environment, then you will probably use the node bundle.

  • If you are using bundler like webpack and vite, then you will probably use the browser bundle.

  • If you meet any issues that a incorrect bundle is used, you can use bcrypt-ts/node and bcrypt-ts/browser to force the correct bundle.

Usage - Sync

To hash a password:

import { genSaltSync, hashSync } from "bcrypt-ts";

const salt = genSaltSync(10);
const hash = hashSync("B4c0//", salt);
// Store hash in your password DB.

To check a password:

import { compareSync } from "bcrypt-ts";

// Load hash from your password DB.
compareSync("B4c0//", hash); // true
compareSync("not_bacon", hash); // false

Auto-gen a salt and hash at the same time:

import { hashSync } from "bcrypt-ts";

const hash = hashSync("bacon", 8);

Usage - Async

To hash a password:

import { genSalt, hash } from "bcrypt-ts";

genSalt(10)
  .then((salt) => hash("B4c0//", salt))
  .then((hash) => {
    // Store hash in your password DB.
  });

To check a password:

import { compare } from "bcrypt-ts";

// Load hash from your password DB.
const hash = "xxxxxx";

compare("B4c0//", hash).then((result) => {
  // result is `true`
});
compare("not_bacon", hash).then((result) => {
  // result is `false`
});

Auto-gen a salt and hash:

import { hash } from "bcrypt-ts";

hash("bacon").then((hash) => {
  // do something with hash
});

Note: Under the hood, asynchronisation splits a crypto operation into small chunks. After the completion of a chunk, the execution of the next chunk is placed on the back of JS event loop queue, thus efficiently sharing the computational resources with the other operations in the queue.

API

/**
 * Synchronously tests a string against a hash.
 *
 * @param content String to compare
 * @param hash Hash to test against
 */
export const compareSync: (content: string, hash: string) => boolean;
/**
 * Asynchronously compares the given data against the given hash.
 *
 * @param content Data to compare
 * @param hash Data to be compared to
 * @param progressCallback Callback successively called with the percentage of rounds completed
 *  (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
 */
export const compare: (
  content: string,
  hash: string,
  progressCallback?: ((percent: number) => void) | undefined,
) => Promise<boolean>;

/**
 * Synchronously generates a hash for the given string.
 *
 * @param contentString String to hash
 * @param salt Salt length to generate or salt to use, default to 10
 * @returns Resulting hash
 */
export const hashSync: (
  contentString: string,
  salt?: string | number,
) => string;
/**
 * Asynchronously generates a hash for the given string.
 *
 * @param contentString String to hash
 * @param salt Salt length to generate or salt to use
 * @param progressCallback Callback successively called with the percentage of rounds completed
 *  (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
 */
export const hash: (
  contentString: string,
  salt: number | string,
  progressCallback?: ((progress: number) => void) | undefined,
) => Promise<string>;

/**
 * Gets the number of rounds used to encrypt the specified hash.
 *
 * @param hash Hash to extract the used number of rounds from
 * @returns Number of rounds used
 * @throws {Error} If `hash` is not a string
 */
export const getRounds: (hash: string) => number;
/**
 * Gets the salt portion from a hash. Does not validate the hash.
 *
 * @param hash Hash to extract the salt from
 * @returns Extracted salt part
 * @throws {Error} If `hash` is not a string or otherwise invalid
 */
export const getSalt: (hash: string) => string;

/**
 * Synchronously generates a salt.
 *
 * @param rounds Number of rounds to use, defaults to 10 if omitted
 * @returns Resulting salt
 * @throws {Error} If a random fallback is required but not set
 */
export const genSaltSync: (rounds?: number) => string;
/**
 * Asynchronously generates a salt.
 *
 * @param rounds Number of rounds to use, defaults to 10 if omitted
 */
export const genSalt: (rounds?: number) => Promise<string>;

License

New-BSD / MIT (see)

bcrypt-ts's People

Contributors

mister-hope avatar mlecoq avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

mlecoq

bcrypt-ts's Issues

Anyway to remove the Buffer type so it is compatible with cloudflare workers?

When running tsc I get this error:

node_modules/bcrypt-ts/dist/node.d.mts:7:52 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.

7 declare const encodeBase64: (byteArray: number[] | Buffer, length: number) => string;

I don't want to install node type definitions because I am using this in cloudflare workers which doesn't support node.

I am using typescript for the first time so I am not aware on the best way to solve this issue, maybe I can't use this library?

Update docs for browser usage

First off, thank you so much for creating bcrypt-ts ๐Ÿ™‚๏ธ

I was trying to run it on the browser (using Vite as bundler) without success until I noticed there's an oversight in the docs:

If you meet any issues that a incorrect bundle is used, you can use bcrypt-ts/node and bcrypt-ts/client to force the correct bundle.

For browser usage, it's brcrypt-ts/browser not client

Cannot find module 'bcrypt-ts/node' or its corresponding type declarations.

I get issues when importing this module in our jest environment (import { hashSync } from 'bcrypt-ts'). So as suggested in the README I switched to import { hashSync } from 'bcrypt-ts/node' and while that fixes things to work correctly when running our tests we get errors in vscode that I cannot resolve:

Cannot find module 'bcrypt-ts/node' or its corresponding type declarations.

Any ideas?

This was a workaround in our repo (to get the tests to run when using import { hashSync } from 'bcrypt-ts') but I'd prefer not to have to hardcode these things in jest config (we are using yarn workspaces in a monorepo):

  moduleNameMapper: {
    'bcrypt-ts': '<rootDir>/../../node_modules/bcrypt-ts/dist/node.cjs',
  },

I guess the reason this works is because jest sees an import which you have mapped to an mjs file, not cjs file.

SyntaxError: Cannot use import statement outside a module

version "bcrypt-ts": "5.0.2"

Steps To Reproduce

Run the code below

import { hashSync } from "bcrypt-ts";
const defaultPassword = 'secret'
const digest = hashSync(defaultPassword);

using one of the following commands node -r esbuild-register ./script.ts or ts-node ./script.ts

The current behavior

Facing with this error in the console

SyntaxError: Cannot use import statement outside a module

Workaround

Don't trust the editor autocomplete and import manually the library below

import { hashSync } from "bcrypt-ts/node";

Could not find a declaration file for module 'bcrypt-ts'

import { compare } from 'bcrypt-ts'

Gives me the error:

Could not find a declaration file for module 'bcrypt-ts'. '/home/repos/fauna-hono-workers-boilerplate/node_modules/bcrypt-ts/dist/node.cjs' implicitly has an 'any' type.
  Try `npm i --save-dev @types/bcrypt-ts` if it exists or add a new declaration (.d.ts) file containing `declare module 'bcrypt-ts';`

Any idea how to solve this?

issue on Vercel-edge

With the version 5.0.1

I have the following error

Error: WebCryptoAPI is not available
    at (../../node_modules/bcrypt-ts/dist/browser.mjs:1:16165)
    at (../../node_modules/bcrypt-ts/dist/browser.mjs:1:16397)
    at (../../node_modules/bcrypt-ts/dist/browser.mjs:1:17620)

using

 bcrypt.hashSync(password, 12)

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Location: .github/renovate.json
Error type: Invalid JSON (parsing failed)
Message: Syntax error near
// au

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update dependency @commitlint/cli to v19.4.0
  • chore(deps): update dependency vite to v5.4.0

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/issue-daily.yml
  • actions-cool/issues-helper v3
  • actions-cool/issues-helper v3
  • actions-cool/issues-helper v3
.github/workflows/issue-labeled.yml
  • actions-cool/issues-helper v3
  • actions-cool/issues-helper v3
.github/workflows/test.yml
  • actions/checkout v4
  • pnpm/action-setup v4
  • actions/setup-node v4
  • codecov/codecov-action v4
npm
package.json
  • @commitlint/cli 19.3.0
  • @commitlint/config-conventional 19.2.2
  • @rollup/plugin-alias 5.1.0
  • @rollup/plugin-replace 5.0.7
  • @types/node 22.1.0
  • @vitest/coverage-v8 2.0.5
  • commit-and-tag-version 12.4.1
  • cz-git 1.9.4
  • esbuild 0.23.0
  • eslint 9.8.0
  • eslint-config-mister-hope 0.2.2
  • husky 9.1.4
  • nano-staged 0.8.0
  • prettier 3.3.3
  • rimraf 6.0.1
  • rollup 4.20.0
  • rollup-plugin-dts 6.1.1
  • rollup-plugin-esbuild 6.1.1
  • typescript 5.5.4
  • vite 5.3.5
  • vitest 2.0.5
  • node >=18
  • pnpm 9.6.0

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.