CodeSampleX

Ejemplo

bcryptjs 3.0.3: Yield to the event loop during asynchronous password hashing and salting with bcryptjs, preventing microtask starvation across fallback environments

Muestra verificada para npm bcryptjs 3.0.3: Yield to the event loop during asynchronous password hashing and salting with bcryptjs, preventing microtask…

sha256:9e219aeffefa5e13b5124aa75c30e8a8becf5610b02323cfaddece8768f99420

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
3
Claves de firma que lo compilaron
2
Entorno declarado node linux x64 node javascript npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-07

Caso

HOW
Objetivo
Yield to the event loop during asynchronous password hashing and salting with bcryptjs, preventing microtask starvation across fallback environments
Paquetes
Símbolos
  • bcrypt.genSalt
  • bcrypt.genSaltSync
  • bcrypt.hash
  • bcrypt.hashSync
  • bcrypt.compare
  • bcrypt.compareSync
  • bcrypt.truncates
  • bcrypt.getRounds
  • bcrypt.getSalt
Entorno
node
Creado
2026-08-16T06:23:38Z

Contrato

  1. assert bcryptjs package manifest confirms resolved version 3.0.3
  2. assert async bcrypt operations do not execute in the microtask phase, allowing queued process.nextTick microtasks to drain first
  3. assert fallback dispatcher in environments without setImmediate uses macrotasks (setTimeout / scheduler.postTask) rather than process.nextTick, preventing event loop starvation during async hashing
  4. assert async functions return a Promise when callback is omitted, but return undefined when a callback function is passed
  5. assert synchronous methods (hashSync, compareSync) throw Errors immediately on illegal arguments while asynchronous methods (hash, compare) return rejected Promises
  6. assert compare returns false rather than throwing when encountering a malformed or short hash string
  7. assert progressCallback tracks computation progress from 0.0 to 1.0 during async hashing and comparison
  8. assert genSalt shifts arguments when callback is passed as the second argument, and ignores legacy numeric seed_length preserving 16-byte salt length
  9. assert getSalt extracts the 29-character salt prefix from a 60-character hash and throws Illegal hash length on a raw 29-character salt string
  10. assert default generated salt revision is $2b$ in v3 while maintaining backward compatibility with legacy $2a$ vectors, and rejecting invalid revisions ($2x$, $1$)
  11. assert truncates() measures UTF-8 byte length against the 72-byte limit rather than character count, truncating 25 3-byte unicode characters (75 bytes) while keeping 24 characters (72 bytes)
  12. assert passwords exceeding 72 UTF-8 bytes produce identical hashes to their 72-byte prefix, creating cross-verification collisions

Archivos

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/hasher.mjs
  • test/contract.mjs

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Notes: bcryptjs Asynchronous Event Loop Yielding & Patch Fix

## 1. `search_known_solution` Result
`search_known_solution` returned existing sample `sha256:bf227476fbe2d665af4c03c6862eecaa6a1760441669b86d3def01bcc85a4d35` ("Hash and verify passwords on Node without a native module, choosing between node:crypto's scrypt and bcryptjs"), which compares `bcryptjs` against `node:crypto`'s scrypt, package exports, and 72-byte string truncation.
This sample focuses on a distinct behavioural contract: the specific patch fix in **bcryptjs 3.0.3** (PR #164 / issue #80) that removed `process.nextTick` from the async dispatch chain to prevent event loop microtask starvation during password hashing across different runtime environments, along with asynchronous error rejection versus synchronous exception semantics, dual Promise/callback return values, and progress callback handling.

## 2. What a Model Would Have Written Instead
A model would assume `bcryptjs` async methods run in worker threads or use `process.nextTick` for async scheduling when `setImmediate` is unavailable, write `try { bcrypt.hash(null, 10); }` expecting synchronous exceptions, expect `bcrypt.hash(pwd, salt, callback)` to return an awaitable Promise, and call `bcrypt.getSalt(salt)` directly on generated 29-character salt strings.

## 3. How the Wrong Version Fails
In `bcryptjs` <= 3.0.2 in environments where `setImmediate` is missing or polyfilled, recursive Blowfish rounds scheduled via `process.nextTick` silently starve the event loop microtask queue, freezing timers (`setInterval`/`setTimeout`) and I/O handlers until hashing completes while building completely green.
csx.json
{"case":{"caseId":"case:sha256:d695126518e2ffca28ef60933c0c3f54f9f76f6f0e86150c744b989f424e12f4","contract":["assert bcryptjs package manifest confirms resolved version 3.0.3","assert async bcrypt operations do not execute in the microtask phase, allowing queued process.nextTick microtasks to drain first","assert fallback dispatcher in environments without setImmediate uses macrotasks (setTimeout / scheduler.postTask) rather than process.nextTick, preventing event loop starvation during async hashing","assert async functions return a Promise when callback is omitted, but return undefined when a callback function is passed","assert synchronous methods (hashSync, compareSync) throw Errors immediately on illegal arguments while asynchronous methods (hash, compare) return rejected Promises","assert compare returns false rather than throwing when encountering a malformed or short hash string","assert progressCallback tracks computation progress from 0.0 to 1.0 during async hashing and comparison","assert genSalt shifts arguments when callback is passed as the second argument, and ignores legacy numeric seed_length preserving 16-byte salt length","assert getSalt extracts the 29-character salt prefix from a 60-character hash and throws Illegal hash length on a raw 29-character salt string","assert default generated salt revision is $2b$ in v3 while maintaining backward compatibility with legacy $2a$ vectors, and rejecting invalid revisions ($2x$, $1$)","assert truncates() measures UTF-8 byte length against the 72-byte limit rather than character count, truncating 25 3-byte unicode characters (75 bytes) while keeping 24 characters (72 bytes)","assert passwords exceeding 72 UTF-8 bytes produce identical hashes to their 72-byte prefix, creating cross-verification collisions"],"goal":"Yield to the event loop during asynchronous password hashing and salting with bcryptjs, preventing microtask starvation across fallback environments","kind":"HOW","packages":["pkg:npm/bcryptjs@3.0.3"],"schemaVersion":1,"symbols":["bcrypt.genSalt","bcrypt.genSaltSync","bcrypt.hash","bcrypt.hashSync","bcrypt.compare","bcrypt.compareSync","bcrypt.truncates","bcrypt.getRounds","bcrypt.getSalt"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"javascript","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/bcryptjs@3.0.3"],"schemaVersion":1,"symbols":["bcrypt.genSalt","bcrypt.genSaltSync","bcrypt.hash","bcrypt.hashSync","bcrypt.compare","bcrypt.compareSync","bcrypt.truncates","bcrypt.getRounds","bcrypt.getSalt"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-bcryptjs-async-yielding",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-bcryptjs-async-yielding",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bcryptjs": "3.0.3"
      }
    },
    "node_modules/bcryptjs": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
      "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
      "license": "BSD-3-Clause",
      "bin": {
        "bcrypt": "bin/bcrypt"
      }
    }
  }
}
package.json
{
  "name": "csx-bcryptjs-async-yielding",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "bcryptjs": "3.0.3"
  }
}
src/hasher.mjs
import bcrypt from "bcryptjs";

/**
 * Generates an async bcrypt salt, returning a Promise.
 *
 * @param {number} [rounds=10]
 * @returns {Promise<string>}
 */
export function generateSaltAsync(rounds = 10) {
  return bcrypt.genSalt(rounds);
}

/**
 * Generates a sync bcrypt salt.
 *
 * @param {number} [rounds=10]
 * @returns {string}
 */
export function generateSaltSync(rounds = 10) {
  return bcrypt.genSaltSync(rounds);
}

/**
 * Hashes a password asynchronously with Promise or callback support,
 * optionally receiving computation progress updates.
 *
 * @param {string} password
 * @param {number|string} [saltOrRounds=10]
 * @param {function(Error, string=)=} callback
 * @param {function(number)=} progressCallback
 * @returns {Promise<string>|undefined}
 */
export function hashPasswordAsync(password, saltOrRounds = 10, callback, progressCallback) {
  if (callback) {
    return bcrypt.hash(password, saltOrRounds, callback, progressCallback);
  }
  return bcrypt.hash(password, saltOrRounds);
}

/**
 * Hashes a password synchronously.
 *
 * @param {string} password
 * @param {number|string} [saltOrRounds=10]
 * @returns {string}
 */
export function hashPasswordSync(password, saltOrRounds = 10) {
  return bcrypt.hashSync(password, saltOrRounds);
}

/**
 * Verifies a password against a hash asynchronously with Promise or callback support.
 *
 * @param {string} password
 * @param {string} hash
 * @param {function(Error, boolean=)=} callback
 * @param {function(number)=} progressCallback
 * @returns {Promise<boolean>|undefined}
 */
export function verifyPasswordAsync(password, hash, callback, progressCallback) {
  if (callback) {
    return bcrypt.compare(password, hash, callback, progressCallback);
  }
  return bcrypt.compare(password, hash);
}

/**
 * Verifies a password against a hash synchronously.
 *
 * @param {string} password
 * @param {string} hash
 * @returns {boolean}
 */
export function verifyPasswordSync(password, hash) {
  return bcrypt.compareSync(password, hash);
}

/**
 * Extracts metadata (revision, cost/rounds, salt prefix) from a stored bcrypt hash.
 *
 * @param {string} hash
 * @returns {{ rounds: number, salt: string }}
 */
export function inspectHashMetadata(hash) {
  return {
    rounds: bcrypt.getRounds(hash),
    salt: bcrypt.getSalt(hash),
  };
}

/**
 * Checks whether a password string exceeds bcrypt's 72 UTF-8 byte limit.
 *
 * @param {string} password
 * @returns {boolean}
 */
export function isPasswordTruncated(password) {
  return bcrypt.truncates(password);
}
test/contract.mjs
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import * as bcrypt from "bcryptjs";
import {
  generateSaltAsync,
  generateSaltSync,
  hashPasswordAsync,
  hashPasswordSync,
  inspectHashMetadata,
  isPasswordTruncated,
  verifyPasswordAsync,
  verifyPasswordSync,
} from "../src/hasher.mjs";

// Verify exact resolved version in package manifest
const manifest = JSON.parse(
  readFileSync(new URL("./package.json", import.meta.resolve("bcryptjs")), "utf8"),
);
assert.equal(manifest.version, "3.0.3");

// ---------------------------------------------------------------------------
// 1. v3.0.3 Patch Fix (#164): Event loop macro-yielding without process.nextTick
// ---------------------------------------------------------------------------

// In v3.0.2 and earlier, when setImmediate was unavailable (e.g. browsers,
// edge runtimes, polyfilled environments), bcryptjs fell back to process.nextTick.
// In Node.js, process.nextTick queues microtasks that starve the event loop
// (timers and I/O) across recursive Blowfish crypt rounds.
// In v3.0.3, process.nextTick was removed from the fallback chain in favor of
// setImmediate -> scheduler.postTask -> setTimeout (macrotasks).

// A microtask queued via process.nextTick runs BEFORE the async bcrypt callback,
// proving bcrypt operations do not preempt microtasks.
const microtaskOrder = [];
process.nextTick(() => microtaskOrder.push("microtask"));
const saltPromise = generateSaltAsync(4).then(() => {
  microtaskOrder.push("bcrypt");
});
await saltPromise;
assert.deepEqual(
  microtaskOrder,
  ["microtask", "bcrypt"],
  "microtasks must drain before bcrypt async resolution",
);

// Even in an execution context without setImmediate, v3.0.3 yields via setTimeout/postTask
// rather than falling back to process.nextTick.
const origSetImmediate = globalThis.setImmediate;
try {
  delete globalThis.setImmediate;
  const targetUrl = new URL(import.meta.resolve("bcryptjs") + `?fallback=${Date.now()}`).href;
  const freshBcrypt = await import(targetUrl);
  const fallbackOrder = [];
  process.nextTick(() => fallbackOrder.push("microtask"));
  await new Promise((resolve) => {
    freshBcrypt.genSalt(4, (err, res) => {
      fallbackOrder.push("bcrypt-fallback");
      assert.ifError(err);
      assert.ok(res.startsWith("$2b$04$"));
      resolve();
    });
  });
  assert.deepEqual(
    fallbackOrder,
    ["microtask", "bcrypt-fallback"],
    "fallback dispatcher must yield to microtasks rather than using process.nextTick",
  );
} finally {
  globalThis.setImmediate = origSetImmediate;
}

// ---------------------------------------------------------------------------
// 2. Dual API: Promise resolution vs Callback return value
// ---------------------------------------------------------------------------

// When callback is omitted, async functions return a Promise.
const pSalt = generateSaltAsync(6);
assert.ok(pSalt instanceof Promise);
const resolvedSalt = await pSalt;
assert.equal(typeof resolvedSalt, "string");

// When a callback is supplied, the return value is strictly undefined.
// A caller awaiting this call would receive undefined rather than a Promise.
let cbCalled = false;
const cbReturn = hashPasswordAsync("test-password", resolvedSalt, (err, hash) => {
  assert.ifError(err);
  assert.equal(typeof hash, "string");
  cbCalled = true;
});
assert.equal(cbReturn, undefined, "callback invocation must return undefined, not a Promise");
await new Promise((resolve) => setImmediate(resolve));
assert.equal(cbCalled, true);

// ---------------------------------------------------------------------------
// 3. Asynchronous Error Rejection vs Synchronous Exceptions
// ---------------------------------------------------------------------------

// Synchronous methods throw immediately on illegal argument types.
assert.throws(
  () => hashPasswordSync(null, 10),
  (err) => {
    assert.ok(err instanceof Error);
    assert.match(err.message, /Illegal arguments/);
    return true;
  },
);

assert.throws(
  () => verifyPasswordSync(null, resolvedSalt),
  (err) => {
    assert.ok(err instanceof Error);
    assert.match(err.message, /Illegal arguments/);
    return true;
  },
);

// Asynchronous methods do NOT throw synchronously — they return a rejected Promise
// (or pass the Error to the callback). Un-awaited try/catch fails to catch them.
let syncThrew = false;
try {
  const rejectedPromise = hashPasswordAsync(null, 10);
  await assert.rejects(rejectedPromise, {
    message: "Illegal arguments: object, number",
  });
} catch {
  syncThrew = true;
}
assert.equal(syncThrew, false, "async hash with invalid args must not throw synchronously");

// Asynchronous compare with non-60 char hash string answers false, not an Error.
const shortHashCompare = await verifyPasswordAsync("test-password", "$2b$10$tooshort");
assert.equal(shortHashCompare, false);

// ---------------------------------------------------------------------------
// 4. Progress Callback Interface
// ---------------------------------------------------------------------------

// bcrypt.hash and bcrypt.compare accept a 4th argument: progressCallback(ratio: number).
// Progress values range between 0.0 (start) and 1.0 (completion).
const progressSnapshots = [];
const trackedHash = await new Promise((resolve, reject) => {
  bcrypt.hash(
    "secret-passphrase",
    6,
    (err, result) => {
      if (err) reject(err);
      else resolve(result);
    },
    (progress) => {
      progressSnapshots.push(progress);
    },
  );
});
assert.equal(typeof trackedHash, "string");
assert.ok(progressSnapshots.length >= 2, "progressCallback should be invoked at start and end");
assert.equal(progressSnapshots[0], 0);
assert.equal(progressSnapshots[progressSnapshots.length - 1], 1);

// ---------------------------------------------------------------------------
// 5. genSalt Argument Overloading & Ignored seed_length
// ---------------------------------------------------------------------------

// Passing callback as the second argument shifts arguments correctly.
const shiftedSalt = await new Promise((resolve) => {
  bcrypt.genSalt((err, salt) => {
    assert.ifError(err);
    resolve(salt);
  });
});
assert.ok(shiftedSalt.startsWith("$2b$10$"));

// Passing a numeric seed_length does not alter salt size: bcrypt salts are fixed at 16 bytes.
const saltWithSeed = generateSaltSync(10, 32);
assert.equal(saltWithSeed.length, 29); // "$2b$10$" (7) + 22 base64 chars = 29
// getSalt requires a full 60-character hash string and throws if given a 29-character salt string
assert.throws(
  () => bcrypt.getSalt(saltWithSeed),
  /Illegal hash length: 29 != 60/,
);
const hashFromSalt = hashPasswordSync("pass", saltWithSeed);
assert.equal(bcrypt.getSalt(hashFromSalt), saltWithSeed);

// ---------------------------------------------------------------------------
// 6. Default $2b$ Format and Backward Compatibility
// ---------------------------------------------------------------------------

const generatedSalt = generateSaltSync(8);
assert.ok(generatedSalt.startsWith("$2b$08$"), "default salt revision in v3 is 2b");

const meta = inspectHashMetadata(hashPasswordSync("password123", generatedSalt));
assert.equal(meta.rounds, 8);
assert.equal(meta.salt, generatedSalt);

// Verified against legacy jBCrypt $2a$ test vectors
const legacyVector = "$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s.";
assert.equal(verifyPasswordSync("", legacyVector), true);
assert.equal(bcrypt.getRounds(legacyVector), 6);

// Unsupported / invalid salt revisions are rejected
assert.throws(
  () => bcrypt.hashSync("password", "$2x$10$abcdefghijklmnopqrstuu"),
  /Invalid salt revision: x\$/,
);
assert.throws(
  () => bcrypt.hashSync("password", "$1$10$abcdefghijklmnopqrstuu"),
  /Invalid salt version: \$1/,
);

// ---------------------------------------------------------------------------
// 7. UTF-8 Byte Truncation vs Character Length in truncates()
// ---------------------------------------------------------------------------

// 24 three-byte UTF-8 characters = 72 bytes (exactly at boundary) -> false
const kanji24 = "語".repeat(24);
assert.equal(kanji24.length, 24);
assert.equal(Buffer.byteLength(kanji24, "utf8"), 72);
assert.equal(isPasswordTruncated(kanji24), false);

// 25 three-byte UTF-8 characters = 75 bytes (> 72 bytes) -> true
const kanji25 = "語".repeat(25);
assert.equal(kanji25.length, 25);
assert.equal(Buffer.byteLength(kanji25, "utf8"), 75);
assert.equal(isPasswordTruncated(kanji25), true);

// Passwords exceeding 72 bytes share hash collisions with their 72-byte prefix
const prefix72 = "A".repeat(72);
const longPassA = `${prefix72}-suffix-one`;
const longPassB = `${prefix72}-suffix-two`;
const hashA = hashPasswordSync(longPassA, 4);
assert.equal(verifyPasswordSync(longPassB, hashA), true, "bcrypt truncates at 72 bytes");
assert.equal(verifyPasswordSync(prefix72, hashA), true, "prefix alone verifies against truncated hash");

console.log("contract ok");

Seeder de origen

csx-seed