CodeSampleX

示例

bcryptjs 3.0.3: Handle bcryptjs parameter asymmetries in hash salt defaults, genSalt rounds clamping, selective 60-character error throwing in compare, and non-standard Base64 decoding

已验证示例 — npm bcryptjs 3.0.3: Handle bcryptjs parameter asymmetries in hash salt defaults, genSalt rounds clamping, selective 60-character error throwing in…

sha256:728973545e45ca5700dadbdcde59e4ceb0c9e7cf083c2ca5d448fde147d2bfd9

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

执行证据

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

证据依据
签名契约通过
验证回执
3
构建过它的签名密钥
3
声明的环境 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
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-07

案例

HOW
目标
Handle bcryptjs parameter asymmetries in hash salt defaults, genSalt rounds clamping, selective 60-character error throwing in compare, and non-standard Base64 decoding
包
符号
  • bcryptjs.compareSync
  • bcryptjs.compare
  • bcryptjs.hashSync
  • bcryptjs.hash
  • bcryptjs.genSaltSync
  • bcryptjs.genSalt
  • bcryptjs.getRounds
  • bcryptjs.getSalt
  • bcryptjs.truncates
  • bcryptjs.encodeBase64
  • bcryptjs.decodeBase64
环境
node
创建时间
2026-08-16T06:23:33Z

契约

  1. assert hashSync permits omitting salt to default to 10 rounds while async hash rejects with 'Illegal arguments: string, undefined' unless salt or rounds is explicitly passed
  2. assert genSaltSync(0) evaluates 0 || 10 and silently produces a 10-round salt ($2b$10$) rather than 0 or minimum rounds
  3. assert genSaltSync clamps rounds 1..3 to 4 ($2b$04$) and rounds 32+ to 31 ($2b$31$), and that passing numeric string '10' throws rather than converting
  4. assert compareSync and compare return false on non-matching strings whose length is not 60, but throw/reject with 'Invalid salt version' on 60-character non-bcrypt strings
  5. assert compareSync throws on non-string inputs and throws 'Invalid salt revision' on 60-character strings starting with unsupported revision $2x$
  6. assert getRounds returns NaN without throwing on empty or malformed strings while getSalt strictly enforces length 60 and extracts 29 characters without syntax validation
  7. assert encodeBase64 and decodeBase64 use bcrypt's custom alphabet where 0x00 is '.' rather than 'A', causing standard RFC 4648 Base64 'AAAA' to decode to [8, 32, 130]
  8. assert $2a$, $2b$, and $2y$ produce 60-character hashes that verify with compareSync, while legacy $2$ produces a 59-character hash that always fails compareSync and throws in getSalt
  9. assert truncates measures UTF-8 byte length with boundary at 72 bytes (36 vs 37 multi-byte characters) and throws on non-string inputs

文件

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

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

源代码

NOTES.md
# bcryptjs API Traps & Parameter Asymmetries

## Prior Search 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"). This sample tackles a distinct angle: parameter handling asymmetries, rounds clamping quirks, selective error throwing in verification, and custom Base64 alphabet in `bcryptjs`'s primary API surface.

## What a Naive Model Writes Instead
A model writes `const hash = await bcrypt.hash(password)` assuming optional salt mirroring `hashSync(password)`, passes `genSaltSync(0)` expecting minimum rounds, and relies on `if (bcrypt.compareSync(pwd, hash))` expecting boolean false on any candidate hash.

## How the Wrong Version Fails
`await bcrypt.hash(password)` fails loudly with `Error: Illegal arguments: string, undefined`, `genSaltSync(0)` silently generates 10 rounds via `0 || 10` fallback, and `compareSync` against a 60-character malformed or `$2x$` hash throws an uncaught `Error: Invalid salt version` / `Invalid salt revision`, turning a failed login into an unhandled 500 crash.
csx.json
{"case":{"caseId":"case:sha256:5e95819738febe69f272d0fb0e348881bc284c61ffb942db125e5edc43663850","contract":["assert hashSync permits omitting salt to default to 10 rounds while async hash rejects with 'Illegal arguments: string, undefined' unless salt or rounds is explicitly passed","assert genSaltSync(0) evaluates 0 || 10 and silently produces a 10-round salt ($2b$10$) rather than 0 or minimum rounds","assert genSaltSync clamps rounds 1..3 to 4 ($2b$04$) and rounds 32+ to 31 ($2b$31$), and that passing numeric string '10' throws rather than converting","assert compareSync and compare return false on non-matching strings whose length is not 60, but throw/reject with 'Invalid salt version' on 60-character non-bcrypt strings","assert compareSync throws on non-string inputs and throws 'Invalid salt revision' on 60-character strings starting with unsupported revision $2x$","assert getRounds returns NaN without throwing on empty or malformed strings while getSalt strictly enforces length 60 and extracts 29 characters without syntax validation","assert encodeBase64 and decodeBase64 use bcrypt's custom alphabet where 0x00 is '.' rather than 'A', causing standard RFC 4648 Base64 'AAAA' to decode to [8, 32, 130]","assert $2a$, $2b$, and $2y$ produce 60-character hashes that verify with compareSync, while legacy $2$ produces a 59-character hash that always fails compareSync and throws in getSalt","assert truncates measures UTF-8 byte length with boundary at 72 bytes (36 vs 37 multi-byte characters) and throws on non-string inputs"],"goal":"Handle bcryptjs parameter asymmetries in hash salt defaults, genSalt rounds clamping, selective 60-character error throwing in compare, and non-standard Base64 decoding","kind":"HOW","packages":["pkg:npm/bcryptjs@3.0.3"],"schemaVersion":1,"symbols":["bcryptjs.compareSync","bcryptjs.compare","bcryptjs.hashSync","bcryptjs.hash","bcryptjs.genSaltSync","bcryptjs.genSalt","bcryptjs.getRounds","bcryptjs.getSalt","bcryptjs.truncates","bcryptjs.encodeBase64","bcryptjs.decodeBase64"]},"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.3"],"schemaVersion":1,"symbols":["bcryptjs.compareSync","bcryptjs.compare","bcryptjs.hashSync","bcryptjs.hash","bcryptjs.genSaltSync","bcryptjs.genSalt","bcryptjs.getRounds","bcryptjs.getSalt","bcryptjs.truncates","bcryptjs.encodeBase64","bcryptjs.decodeBase64"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-bcryptjs-api-traps",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-bcryptjs-api-traps",
      "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-api-traps",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "bcryptjs": "3.0.3"
  }
}
src/bcrypt_api.mjs
import bcrypt from "bcryptjs";

/**
 * bcryptjs API behaviors, asymmetries, and edge cases.
 *
 * bcryptjs is a pure JavaScript implementation of bcrypt with zero native
 * dependencies. While it mirrors the `bcrypt` native module API, its parameter
 * handling, error reporting, and async function signatures carry several subtle
 * traps that diverge from naive expectations.
 */

/**
 * Default log2 rounds used when omitted in synchronous hashing.
 */
export const DEFAULT_ROUNDS = 10;

/**
 * Minimum and maximum allowable cost factors in bcrypt.
 */
export const MIN_ROUNDS = 4;
export const MAX_ROUNDS = 31;

/**
 * bcrypt hash length for $2a$, $2b$, and $2y$ modular crypt format.
 * Structure: 4 chars identifier ($2b$) + 2 chars rounds + 1 char $ + 22 chars salt + 31 chars hash = 60 chars.
 */
export const BCRYPT_HASH_LENGTH = 60;
export const BCRYPT_SALT_LENGTH = 29;

/**
 * Safe password verification wrapper.
 *
 * TRAP: bcryptjs `compareSync(password, hash)` returns `false` if `hash.length !== 60`,
 * BUT if `hash` is exactly 60 characters and contains an invalid salt prefix (e.g. "x".repeat(60)
 * or an unsupported revision like "$2x$"), it THROWS an uncaught Error ("Invalid salt version: ...")
 * instead of returning `false`.
 *
 * In web services, this turns malformed database records or client-supplied hashes into 500 errors
 * rather than 401 unauthorized failures.
 *
 * @param {unknown} password - Plaintext password candidate
 * @param {unknown} hash - Stored password hash candidate
 * @returns {boolean} True if matching, false if mismatch, invalid length, invalid structure, or wrong types.
 */
export function safeCompare(password, hash) {
  if (typeof password !== "string" || typeof hash !== "string") {
    return false;
  }
  if (hash.length !== BCRYPT_HASH_LENGTH) {
    return false;
  }
  try {
    return bcrypt.compareSync(password, hash);
  } catch {
    return false;
  }
}

/**
 * Safe asynchronous password hashing wrapper.
 *
 * TRAP: `bcrypt.hashSync(password)` defaults the salt parameter to 10 rounds when omitted.
 * However, `bcrypt.hash(password)` does NOT default the salt; calling `bcrypt.hash(password)`
 * rejects with `Error: Illegal arguments: string, undefined`.
 *
 * This wrapper ensures consistent async behavior by providing the default rounds.
 *
 * @param {string} password - Plaintext password to hash
 * @param {number|string} [saltOrRounds=DEFAULT_ROUNDS] - Salt string or cost factor
 * @returns {Promise<string>}
 */
export async function safeHash(password, saltOrRounds = DEFAULT_ROUNDS) {
  if (typeof password !== "string") {
    throw new TypeError("Password must be a string");
  }
  return bcrypt.hash(password, saltOrRounds);
}

/**
 * Safely extracts the cost (rounds) from a bcrypt hash.
 *
 * TRAP: `bcrypt.getRounds(hash)` throws on non-string inputs, but returns `NaN` (without throwing)
 * on empty or malformed strings.
 *
 * @param {unknown} hash - Hash string
 * @returns {number|null} Rounds number or null if invalid
 */
export function safeGetRounds(hash) {
  if (typeof hash !== "string") {
    return null;
  }
  const rounds = bcrypt.getRounds(hash);
  return Number.isNaN(rounds) ? null : rounds;
}

/**
 * Safely extracts the modular crypt salt prefix from a bcrypt hash.
 *
 * TRAP: `bcrypt.getSalt(hash)` throws `Error: Illegal hash length: ... != 60` if length is not 60,
 * but blindly returns `hash.substring(0, 29)` without validating structure if length is 60.
 *
 * @param {unknown} hash - Hash string
 * @returns {string|null} 29-character salt prefix or null if invalid length/type
 */
export function safeGetSalt(hash) {
  if (typeof hash !== "string" || hash.length !== BCRYPT_HASH_LENGTH) {
    return null;
  }
  try {
    return bcrypt.getSalt(hash);
  } catch {
    return null;
  }
}
test/contract.mjs
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import bcrypt, {
  compare,
  compareSync,
  decodeBase64,
  encodeBase64,
  genSalt,
  genSaltSync,
  getRounds,
  getSalt,
  hash,
  hashSync,
  truncates,
} from "bcryptjs";

import {
  DEFAULT_ROUNDS,
  MIN_ROUNDS,
  MAX_ROUNDS,
  BCRYPT_HASH_LENGTH,
  BCRYPT_SALT_LENGTH,
  safeCompare,
  safeHash,
  safeGetRounds,
  safeGetSalt,
} from "../src/bcrypt_api.mjs";

// ---------------------------------------------------------------------------
// 1. Package structure & module resolution
// ---------------------------------------------------------------------------

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

// Verify default and named export parity
assert.equal(typeof bcrypt.hashSync, "function");
assert.equal(typeof bcrypt.compareSync, "function");
assert.equal(typeof bcrypt.genSaltSync, "function");
assert.equal(typeof bcrypt.hash, "function");
assert.equal(typeof bcrypt.compare, "function");
assert.equal(typeof bcrypt.genSalt, "function");
assert.equal(typeof bcrypt.getRounds, "function");
assert.equal(typeof bcrypt.getSalt, "function");
assert.equal(typeof bcrypt.truncates, "function");
assert.equal(typeof bcrypt.encodeBase64, "function");
assert.equal(typeof bcrypt.decodeBase64, "function");

const PASSWORD = "mypassword123";

// ---------------------------------------------------------------------------
// 2. Asymmetric default salt / rounds between sync and async
// ---------------------------------------------------------------------------

// hashSync permits omitting salt: defaults to 10 rounds ($2b$10$...)
const syncHash = hashSync(PASSWORD);
assert.equal(syncHash.length, BCRYPT_HASH_LENGTH);
assert.ok(syncHash.startsWith("$2b$10$"));
assert.equal(getRounds(syncHash), DEFAULT_ROUNDS);

// hash(password) does NOT default salt: it rejects with Illegal arguments
await assert.rejects(
  async () => {
    await hash(PASSWORD);
  },
  {
    name: "Error",
    message: "Illegal arguments: string, undefined",
  },
);

// Explicit rounds or salt makes async hash work
const asyncHash = await hash(PASSWORD, 10);
assert.equal(asyncHash.length, BCRYPT_HASH_LENGTH);
assert.ok(asyncHash.startsWith("$2b$10$"));
assert.equal(compareSync(PASSWORD, asyncHash), true);

// safeHash wrapper provides the missing default
const safeWrappedHash = await safeHash(PASSWORD);
assert.equal(safeWrappedHash.length, BCRYPT_HASH_LENGTH);
assert.ok(safeWrappedHash.startsWith("$2b$10$"));

// genSalt() with 0 arguments defaults to 10 rounds as a Promise
const defaultSalt = await genSalt();
assert.equal(defaultSalt.length, BCRYPT_SALT_LENGTH);
assert.ok(defaultSalt.startsWith("$2b$10$"));

// ---------------------------------------------------------------------------
// 3. genSaltSync parameter parsing and rounds clamping
// ---------------------------------------------------------------------------

// Falsy 0 falls back to default 10 rounds because of `rounds = rounds || 10`
const saltZero = genSaltSync(0);
assert.ok(saltZero.startsWith("$2b$10$"));
assert.equal(getRounds(saltZero + "0".repeat(31)), 10);

// Undefined also falls back to default 10 rounds
const saltUndefined = genSaltSync(undefined);
assert.ok(saltUndefined.startsWith("$2b$10$"));

// Rounds 1 and 3 are clamped to MIN_ROUNDS (4)
const saltOne = genSaltSync(1);
assert.ok(saltOne.startsWith("$2b$04$"));
assert.equal(getRounds(saltOne + "0".repeat(31)), MIN_ROUNDS);

const saltThree = genSaltSync(3);
assert.ok(saltThree.startsWith("$2b$04$"));
assert.equal(getRounds(saltThree + "0".repeat(31)), MIN_ROUNDS);

// Rounds 31 is accepted as-is; rounds 32+ clamped to MAX_ROUNDS (31)
const salt31 = genSaltSync(31);
assert.ok(salt31.startsWith("$2b$31$"));
assert.equal(getRounds(salt31 + "0".repeat(31)), MAX_ROUNDS);

const salt32 = genSaltSync(32);
assert.ok(salt32.startsWith("$2b$31$"));
assert.equal(getRounds(salt32 + "0".repeat(31)), MAX_ROUNDS);

// Non-number argument throws rather than converting
assert.throws(() => genSaltSync("10"), {
  name: "Error",
  message: "Illegal arguments: string, undefined",
});

// ---------------------------------------------------------------------------
// 4. compareSync and compare error vs boolean return behavior
// ---------------------------------------------------------------------------

// Non-string arguments throw TypeError/Error
assert.throws(() => compareSync(null, syncHash), { message: "Illegal arguments: object, string" });
assert.throws(() => compareSync(PASSWORD, null), { message: "Illegal arguments: string, object" });
assert.throws(() => compareSync(12345, syncHash), { message: "Illegal arguments: number, string" });

// Hashes with length !== 60 return false without throwing
assert.equal(compareSync(PASSWORD, ""), false);
assert.equal(compareSync(PASSWORD, "short"), false);
assert.equal(compareSync(PASSWORD, "x".repeat(59)), false);
assert.equal(compareSync(PASSWORD, "x".repeat(61)), false);
assert.equal(await compare(PASSWORD, "x".repeat(59)), false);

// TRAP: 60-character strings that are not valid bcrypt hashes THROW instead of returning false
const invalid60Chars = "x".repeat(60);
assert.throws(
  () => compareSync(PASSWORD, invalid60Chars),
  {
    name: "Error",
    message: "Invalid salt version: xx",
  },
);

await assert.rejects(
  async () => {
    await compare(PASSWORD, invalid60Chars);
  },
  {
    name: "Error",
    message: "Invalid salt version: xx",
  },
);

// 60-character string with unsupported revision throws revision error
const unsupportedRevision60 = "$2x$10$" + "0".repeat(53);
assert.equal(unsupportedRevision60.length, 60);
assert.throws(
  () => compareSync(PASSWORD, unsupportedRevision60),
  {
    name: "Error",
    message: "Invalid salt revision: x$",
  },
);

// safeCompare absorbs both type errors and 60-character parse throws
assert.equal(safeCompare(null, syncHash), false);
assert.equal(safeCompare(PASSWORD, null), false);
assert.equal(safeCompare(PASSWORD, invalid60Chars), false);
assert.equal(safeCompare(PASSWORD, unsupportedRevision60), false);
assert.equal(safeCompare(PASSWORD, syncHash), true);
assert.equal(safeCompare("wrongpassword", syncHash), false);

// ---------------------------------------------------------------------------
// 5. getRounds and getSalt divergence on malformed inputs
// ---------------------------------------------------------------------------

// getRounds returns parsed number for valid hash
assert.equal(getRounds("$2b$04$abcdefghijklmnopqrstuu"), 4);
assert.equal(getRounds("$2b$12$abcdefghijklmnopqrstuu"), 12);

// getRounds returns NaN without throwing on invalid string inputs
assert.ok(Number.isNaN(getRounds("")));
assert.ok(Number.isNaN(getRounds("not-a-hash")));
assert.ok(Number.isNaN(getRounds("x".repeat(60))));

// getRounds throws on non-string inputs
assert.throws(() => getRounds(null), { message: "Illegal arguments: object" });
assert.throws(() => getRounds(undefined), { message: "Illegal arguments: undefined" });

// safeGetRounds normalizes NaN to null
assert.equal(safeGetRounds(""), null);
assert.equal(safeGetRounds(null), null);
assert.equal(safeGetRounds(syncHash), 10);

// getSalt strictly enforces length === 60 and throws if not 60
assert.throws(() => getSalt(""), { message: "Illegal hash length: 0 != 60" });
assert.throws(() => getSalt("x".repeat(59)), { message: "Illegal hash length: 59 != 60" });
assert.throws(() => getSalt("x".repeat(61)), { message: "Illegal hash length: 61 != 60" });

// When length IS 60, getSalt extracts first 29 chars without validating salt structure
assert.equal(getSalt(invalid60Chars), "x".repeat(29));
assert.equal(getSalt(syncHash), syncHash.slice(0, 29));

// safeGetSalt returns null for invalid lengths or types
assert.equal(safeGetSalt(""), null);
assert.equal(safeGetSalt(null), null);
assert.equal(safeGetSalt(syncHash), syncHash.slice(0, 29));

// ---------------------------------------------------------------------------
// 6. Custom non-standard Base64 encoding
// ---------------------------------------------------------------------------

// bcrypt uses alphabet: ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
// Byte 0x00 is encoded as '.' (index 0)
const zeroBytes = [0, 0, 0];
const bcryptEncodedZeroes = encodeBase64(zeroBytes, 3);
assert.equal(bcryptEncodedZeroes, "....");

// In standard RFC 4648 Base64, [0, 0, 0] is "AAAA"
const standardBase64Zeroes = Buffer.from(zeroBytes).toString("base64");
assert.equal(standardBase64Zeroes, "AAAA");

// decodeBase64 with bcrypt alphabet
assert.deepEqual(decodeBase64("....", 3), [0, 0, 0]);

// Passing standard RFC 4648 "AAAA" to bcrypt decodeBase64 decodes 'A' as value 2
assert.deepEqual(decodeBase64("AAAA", 3), [8, 32, 130]);
assert.notDeepEqual(decodeBase64("AAAA", 3), [0, 0, 0]);

// ---------------------------------------------------------------------------
// 7. Supported minor revisions vs $2$ 59-char shortfall and $2x$ rejection
// ---------------------------------------------------------------------------

const dummySaltBody = "0".repeat(22);

// $2a$, $2b$, and $2y$ are supported and produce 60-character hashes
const canonicalSalt = genSaltSync(4);
const h = hashSync(PASSWORD, canonicalSalt);
assert.equal(h.length, 60);
assert.equal(compareSync(PASSWORD, h), true);
assert.equal(getRounds(h), 4);
assert.equal(getSalt(h), canonicalSalt);

for (const rev of ["$2a$", "$2b$", "$2y$"]) {
  const customSalt = rev + "04$" + dummySaltBody;
  assert.equal(customSalt.length, 29);
  const hCustom = hashSync(PASSWORD, customSalt);
  assert.equal(hCustom.length, 60);
  assert.ok(hCustom.startsWith(rev + "04$"));
  assert.equal(compareSync(PASSWORD, hCustom), true);
  assert.equal(getRounds(hCustom), 4);
}

// $2x$ is explicitly rejected with invalid revision error
const salt2x = "$2x$04$" + dummySaltBody;
assert.throws(
  () => hashSync(PASSWORD, salt2x),
  {
    name: "Error",
    message: "Invalid salt revision: x$",
  },
);

// Original $2$ (no minor revision) format has 6-char prefix + 22 salt = 28 char salt
// This produces a 59-character hash, which causes compareSync to return false and getSalt to throw!
const salt2 = "$2$04$" + dummySaltBody;
assert.equal(salt2.length, 28);
const hash2 = hashSync(PASSWORD, salt2);
assert.equal(hash2.length, 59);

// compareSync returns false because hash.length !== 60
assert.equal(compareSync(PASSWORD, hash2), false);

// getSalt throws because hash.length !== 60
assert.throws(
  () => getSalt(hash2),
  {
    name: "Error",
    message: "Illegal hash length: 59 != 60",
  },
);

// ---------------------------------------------------------------------------
// 8. truncates boundary behavior and type checks
// ---------------------------------------------------------------------------

// 72 ASCII bytes fits within limit (returns false)
assert.equal(truncates("A".repeat(72)), false);

// 73 ASCII bytes exceeds limit (returns true)
assert.equal(truncates("A".repeat(73)), true);

// Multi-byte UTF-8: 36 accented characters = 72 bytes (fits)
const fitsUtf8 = "é".repeat(36);
assert.equal(fitsUtf8.length, 36);
assert.equal(Buffer.byteLength(fitsUtf8, "utf8"), 72);
assert.equal(truncates(fitsUtf8), false);

// 37 accented characters = 74 bytes (truncates)
const truncatesUtf8 = "é".repeat(37);
assert.equal(truncatesUtf8.length, 37);
assert.equal(Buffer.byteLength(truncatesUtf8, "utf8"), 74);
assert.equal(truncates(truncatesUtf8), true);

// Non-string arguments throw
assert.throws(() => truncates(null), { message: "Illegal arguments: object" });
assert.throws(() => truncates(Buffer.from("A".repeat(80))), { message: "Illegal arguments: object" });

console.log("contract ok");

原始种子者

csx-seed