JavaScript library

Integrate credential generation, verification and signing into your app with @zelktools/core.

@zelktools/core · npm

Install and import

npm install @zelktools/core

The package is ESM and includes TypeScript declarations. Import functions from @zelktools/core. When a function needs fresh randomness, pass browserRandom from @zelktools/core/browser in the browser, or nodeRandom from @zelktools/core/node on the server. Keep the Node entry point out of client bundles. For the examples below, use a modern Node.js runtime (such as Node 24) or a modern browser; Web Crypto operations in browsers need a secure context such as HTTPS or localhost.

Offer a “suggest password” button

Call the generator from the button's click handler. The result's value goes into the password field. Enabling a character class makes it available; setting a minimum guarantees the site's policy is met.

import { generatePassword } from "@zelktools/core";
import { browserRandom } from "@zelktools/core/browser";

const { value } = generatePassword({
  length: 32,
  uppercase: true, lowercase: true, numbers: true, symbols: true,
  minimumUppercase: 1, minimumLowercase: 1, minimumNumbers: 1, minimumSymbols: 1,
}, browserRandom);

For a password someone will type by hand, a passphrase can be easier to enter. This recipe picks six independent words from the English wordlist. It does not produce wallet recovery phrases.

import { generatePassphrase } from "@zelktools/core";
import { browserRandom } from "@zelktools/core/browser";

const { value } = generatePassphrase(
  { words: 6, wordlist: "english", separator: "-" },
  browserRandom,
);

Store a password at signup and check it at login

Run both steps on the server. Save the returned encoded string in the user record: it includes the algorithm, cost parameters, salt, and derived hash. At login, read that same string and call verifyPassword; hashing the candidate again with a new salt will not reproduce it.

import { hashPassword, verifyPassword } from "@zelktools/core";
import { nodeRandom } from "@zelktools/core/node";

export async function hashForSignup(password) {
  const { encoded } = await hashPassword(password, { algorithm: "scrypt" }, nodeRandom);
  return encoded;
}

export async function checkLogin(candidate, storedHash) {
  const { matches, needsRehash } = await verifyPassword(candidate, storedHash);
  if (!matches) return { authenticated: false };
  return {
    authenticated: true,
    replacementHash: needsRehash ? await hashForSignup(candidate) : undefined,
  };
}

Persist replacementHash when present. The package also supports pbkdf2-sha256. Use digest for checksums, not for password storage.

Provision an application secret

For Auth.js v5, generate AUTH_SECRET once per environment, store it in your secret manager, and inject it at runtime. Generating a new key on each process start would invalidate sessions that depend on the old key.

import { formatSecretEnv, generateSecret } from "@zelktools/core";
import { nodeRandom } from "@zelktools/core/node";

const { value } = generateSecret("authjs", nodeRandom);
const envEntry = formatSecretEnv("authjs", value); // AUTH_SECRET=<generated value>

Other presets are session, webhook, django, and jwt-hs256. The last gives you shared key material, not a signed JWT. Keep these values out of client bundles, logs, and source control.

Use an opaque URL-safe token for the link and store only its SHA-256 digest in the invitation record. Unlike a human password, this token starts with 32 cryptographically random bytes.

import { digest, encodeBytes, encodeDigestText, generateToken } from "@zelktools/core";
import { nodeRandom } from "@zelktools/core/node";

export async function invitationLookupKey(token) {
  const result = await digest({ algorithm: "SHA-256", input: encodeDigestText(token) });
  return encodeBytes(result.digest, "hex");
}

const { value: token } = generateToken({ bytes: 32, encoding: "base64url" }, nodeRandom);
const lookupKey = await invitationLookupKey(token);

Send token to the recipient. On redemption, derive the same lookup key, check the invitation's recipient and expiry, and mark it used atomically. Storage, delivery, and expiration are application responsibilities.

Check a small download against its release checksum

Pass the original bytes, not text decoded from the file. Supply the expected hash from a trusted release manifest. matches: false means the bytes differ; a malformed expected digest raises an error instead.

import { verifyDigest } from "@zelktools/core";

export async function checkDownload(bytes, expectedHex) {
  const { matches } = await verifyDigest({
    algorithm: "SHA-256", input: bytes, expected: expectedHex, encoding: "hex",
  });
  return matches;
}

bytes can be a Uint8Array or a Node Buffer. The digest API accepts up to 1 MiB per call; use a streaming hash implementation for large artifacts. A matching checksum proves agreement with the supplied digest, not who published it.

Sign the exact body of an outgoing webhook

For an integration you control, agree with the recipient on the key encoding, message format, algorithm, and header. In this example the shared key is hex (as returned by the webhook preset), and the signature covers the UTF-8 bytes of the JSON string.

import { encodeBytes, generateHmac } from "@zelktools/core";

export async function signedWebhook(event, sharedHexKey) {
  const body = JSON.stringify(event);
  const { tag } = await generateHmac({
    algorithm: "SHA-256", key: sharedHexKey, keyEncoding: "hex",
    input: body, inputEncoding: "utf8",
  });
  return { body, headers: {
    "Content-Type": "application/json",
    "X-Signature": encodeBytes(tag, "hex"),
  } };
}

Send the returned body unchanged. generateHmac creates a tag; it does not verify incoming webhooks or prevent replay. For a third-party service, follow its signing specification.

Skip duplicate imports

Index small uploads by their bytes rather than their filenames. Store this key with the import record; a unique constraint prevents simultaneous duplicates. The digest limit is 1 MiB.

import { digest, encodeBytes } from "@zelktools/core";

export async function importKey(bytes) {
  const result = await digest({ algorithm: "SHA-256", input: bytes });
  return encodeBytes(result.digest, "hex");
}

Correlate jobs and events

Attach the same ID to a job and its completion event. A v7 UUID contains a timestamp; choose v4 for a random identifier. Neither grants access.

import { generateUuid } from "@zelktools/core";
import { nodeRandom } from "@zelktools/core/node";

const jobId = generateUuid("v7", nodeRandom);
const event = { type: "job.completed", jobId };

Send bytes in JSON

Encode binary data before serialization and decode it on receipt. For text, convertText handles UTF-8. Base64 is reversible, not encryption.

import { encodeBytes, decodeBytes, convertText } from "@zelktools/core";

const json = JSON.stringify({ data: encodeBytes(Uint8Array.of(0, 255), "base64") });
const bytes = decodeBytes(JSON.parse(json).data, "base64"); // [0, 255]
const hex = convertText({ format: "hex", operation: "encode", input: "café" }); // 636166c3a9

Offer feedback while choosing a password

Call this from a local input handler. These heuristics do not check breach lists or certify strength.

import { analyzePassword } from "@zelktools/core";

export function passwordHints(value) {
  const { suggestions, warnings } = analyzePassword(value);
  return warnings.length ? suggestions : [];
}

Plan a password-hash migration

Inspect a supported stored verifier to read its cost without a login attempt. For unfamiliar strings, inspectHash only suggests formats; never select a login algorithm from length alone.

import { inspectHash, inspectPasswordHash } from "@zelktools/core";

export function reviewRecord(stored) {
  const info = inspectHash(stored);
  if (info.format !== "password-hash") return { candidates: info.candidates };
  const { algorithm, parameters, needsRehash } = inspectPasswordHash(stored);
  return { algorithm, parameters, needsRehash };
}

Invalid input can raise ZelkError: use code to distinguish errors and field when available. Keep raw inputs out of logs.

Next: Integration decisions: choose a primitive, count bytes, handle errors and test your integration.

On this page