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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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