CodeSampleX

示例

bcryptjs 3.0.2: Configure bcryptjs PRNG via setRandomFallback when native crypto is unavailable and avoid silent degeneration to static salts or string cost crashes

已验证示例 — npm bcryptjs 3.0.2: Configure bcryptjs PRNG via setRandomFallback when native crypto is unavailable and avoid silent degeneration to static salts or…

sha256:ba1006652d1d549b0fa903945df23dbba37b405ccded650cb40820cf827a4b90

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
2
声明的环境 node linux x64 node node npm

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
Configure bcryptjs PRNG via setRandomFallback when native crypto is unavailable and avoid silent degeneration to static salts or string cost crashes
包
符号
  • bcryptjs.setRandomFallback
  • bcryptjs.genSaltSync
  • bcryptjs.hashSync
  • bcryptjs.compareSync
  • bcryptjs.getRounds
  • bcryptjs.getSalt
环境
node
创建时间
2026-08-16T06:23:38Z

契约

  1. Throws when native crypto is unavailable without setRandomFallback
  2. Math.random as fallback silently degrades to constant dot salt ($2b$10$......................)
  3. Proper byte-array PRNG fallback produces unique 29-character salts and valid 60-character bcrypt hashes
  4. Unparsed string cost factors fail loudly instead of being coerced to integers

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# bcryptjs Configuration and PRNG Fallback Trap

## `search_known_solution` Result
`search_known_solution` returned no exact matches for `bcryptjs` (returned only unrelated low-confidence index matches such as httpx proxy bypass `sha256:0728fe25161f1933e31446621571a110d671c4d2b171f4c6017034f4d5b3b426`), meaning the trap is unaddressed on the network.

## What a Model Would Have Written Instead
When handling environments without native crypto (or bundlers configuring `"browser": {"crypto": false}`), a model writes `bcrypt.setRandomFallback(Math.random)` expecting a standard 0-1 float PRNG, and passes unparsed environment variables like `process.env.SALT_ROUNDS` directly to `bcrypt.hash(pwd, process.env.SALT_ROUNDS)`.

## How the Wrong Version Fails
The `Math.random` fallback fails silently with a green build by returning a single float rather than an `Array`/`Uint8Array` of byte numbers `[0, 255]`, causing bcryptjs's base64 encoder to access `undefined` byte values, mask to 0, and emit identical static dot salts (`$2b$10$......................`) for every password, while passing raw string cost factors fails loudly with `Error: Invalid salt version: 10` because bcryptjs treats string arguments as pre-computed salt hashes rather than cost rounds.
csx.json
{"case":{"caseId":"case:sha256:e3b14a65d80dbbe95c08ccc059365972e02bbb45ff2219cdaa5b3dedec05aa71","contract":["Throws when native crypto is unavailable without setRandomFallback","Math.random as fallback silently degrades to constant dot salt ($2b$10$......................)","Proper byte-array PRNG fallback produces unique 29-character salts and valid 60-character bcrypt hashes","Unparsed string cost factors fail loudly instead of being coerced to integers"],"goal":"Configure bcryptjs PRNG via setRandomFallback when native crypto is unavailable and avoid silent degeneration to static salts or string cost crashes","kind":"HOW","packages":["pkg:npm/bcryptjs@3.0.2"],"schemaVersion":1,"symbols":["bcryptjs.setRandomFallback","bcryptjs.genSaltSync","bcryptjs.hashSync","bcryptjs.compareSync","bcryptjs.getRounds","bcryptjs.getSalt"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/bcryptjs@3.0.2"],"schemaVersion":1,"symbols":["bcryptjs.setRandomFallback","bcryptjs.genSaltSync","bcryptjs.hashSync","bcryptjs.compareSync","bcryptjs.getRounds","bcryptjs.getSalt"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-bcryptjs-config",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-bcryptjs-config",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "bcryptjs": "^3.0.2"
      }
    },
    "node_modules/bcryptjs": {
      "version": "3.0.2",
      "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.2.tgz",
      "integrity": "sha512-k38b3XOZKv60C4E2hVsXTolJWfkGRMbILBIe2IBITXciy5bOsTKot5kDrf3ZfufQtQOUN5mXceUEpU1rTl9Uog==",
      "license": "BSD-3-Clause",
      "bin": {
        "bcrypt": "bin/bcrypt"
      }
    }
  }
}
package.json
{
  "name": "npm-bcryptjs-config",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "commonjs",
  "dependencies": {
    "bcryptjs": "^3.0.2"
  }
}
test/contract.mjs
import assert from "node:assert/strict";
import nodeCrypto from "node:crypto";
import bcrypt, {
  setRandomFallback,
  genSaltSync,
  hashSync,
  compareSync,
  getRounds,
  getSalt,
} from "bcryptjs";

// Save original crypto methods to simulate environments where native crypto is absent/restricted
const originalCrypto = globalThis.crypto;
const originalRandomBytes = nodeCrypto.randomBytes;

function disableNativeCrypto() {
  delete globalThis.crypto;
  nodeCrypto.randomBytes = () => {
    throw new Error("Native crypto module disabled in restricted environment");
  };
}

function restoreNativeCrypto() {
  globalThis.crypto = originalCrypto;
  nodeCrypto.randomBytes = originalRandomBytes;
  setRandomFallback(null);
}

// -----------------------------------------------------------------------------
// 1. Without WebCrypto / crypto module and without setRandomFallback: throws error
// -----------------------------------------------------------------------------
disableNativeCrypto();

assert.throws(
  () => {
    genSaltSync(10);
  },
  {
    name: "Error",
    message:
      "Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative",
  },
  "genSaltSync must throw when native crypto is unavailable and no fallback is set"
);

// -----------------------------------------------------------------------------
// 2. The Naive Trap: passing Math.random as fallback fails silently to static salt
// -----------------------------------------------------------------------------
// Naive models pass Math.random, expecting a 0-1 float to be converted internally.
// Because Math.random returns a float number rather than an array of byte values,
// bcrypt's base64 encoder accesses undefined indices, masks them to 0, and silently
// emits constant '.' characters, yielding identical static salts for every invocation.
setRandomFallback(Math.random);

const naiveSalt1 = genSaltSync(10);
const naiveSalt2 = genSaltSync(10);

assert.equal(
  naiveSalt1,
  "$2b$10$......................",
  "Math.random fallback silently degrades to constant dot salt"
);
assert.equal(
  naiveSalt1,
  naiveSalt2,
  "Math.random fallback generates identical salts across separate calls"
);

// -----------------------------------------------------------------------------
// 3. Correct PRNG Configuration: fallback must return Array/Uint8Array of byte values [0-255]
// -----------------------------------------------------------------------------
// Deterministic pseudo-random byte generator for verification
let seed = 123456789;
function pseudoRandomBytes(len) {
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    seed = (seed * 1664525 + 1013904223) >>> 0;
    bytes[i] = (seed >>> 24) & 0xff;
  }
  return bytes;
}

setRandomFallback(pseudoRandomBytes);

const customSalt1 = genSaltSync(10);
const customSalt2 = genSaltSync(10);

assert.notEqual(
  customSalt1,
  customSalt2,
  "Proper PRNG fallback generates distinct salts"
);
assert.notEqual(
  customSalt1,
  "$2b$10$......................",
  "Proper PRNG fallback does not degrade to static dot salt"
);
assert.equal(
  customSalt1.length,
  29,
  "Bcrypt salt string must be exactly 29 characters ($2b$10$ + 22 base64 chars)"
);
assert.equal(
  getRounds(customSalt1),
  10,
  "Rounds extracted from custom salt must match requested cost factor"
);

// Hash and compare with custom fallback
const password = "correct horse battery staple";
const hash = hashSync(password, customSalt1);

assert.equal(hash.length, 60, "Bcrypt hash must be 60 characters");
assert.equal(
  getSalt(hash),
  customSalt1,
  "Extracted salt from hash must match generated salt"
);
assert.equal(
  compareSync(password, hash),
  true,
  "Password must verify successfully against hash"
);
assert.equal(
  compareSync("wrong password", hash),
  false,
  "Wrong password must fail verification"
);

// Restore native crypto for subsequent checks
restoreNativeCrypto();

// -----------------------------------------------------------------------------
// 4. Configuration Trap: Environment variable string cost factor vs salt string
// -----------------------------------------------------------------------------
// In Node.js, process.env values are strings. When passing a string to hashSync,
// bcryptjs assumes it is a full pre-computed salt ($2b$...), NOT a round count.
const envRoundsString = "10";

assert.throws(
  () => {
    hashSync(password, envRoundsString);
  },
  {
    name: "Error",
    message: "Invalid salt version: 10",
  },
  "Passing string cost factor to hashSync fails because string is parsed as salt version"
);

assert.throws(
  () => {
    genSaltSync(envRoundsString);
  },
  {
    name: "Error",
    message: "Illegal arguments: string, undefined",
  },
  "Passing string cost factor to genSaltSync fails strict type check"
);

// Passing parsed integer works correctly
const parsedRounds = parseInt(envRoundsString, 10);
const envSalt = genSaltSync(parsedRounds);
const envHash = hashSync(password, envSalt);
assert.equal(compareSync(password, envHash), true);

console.log("All bcryptjs configuration contract assertions passed.");

原始种子者

csx-seed