# PACKAGE: @nofinite/utils Shared TypeScript helpers, class name merge (cn), formatters, and custom hooks. You are using @nofinite/utils. Use `cn(...classes)` for conditional class joining. --- ### Document: utils/auth-and-crypto/page.mdx # Authentication and Cryptography **Nofinite Utils** provides production-hardened cryptographic primitives for authentication systems, session tokens, and one-time verification passcodes. ```ts import { hashPassword, verifyPassword, signToken, verifyToken, generateOTP, verifyOTP, isOtpExpired, hasExceededOtpAttempts, } from '@nofinite/utils'; ``` --- ## 1. Password Hashing (Argon2id) The password module uses **Argon2id**, the modern winner of the Password Hashing Competition. It provides superior resistance against GPU/ASIC brute-force cracking attacks compared to legacy bcrypt or PBKDF2: ```ts import { hashPassword, verifyPassword } from '@nofinite/utils/password'; // 1. Hash password with auto-generated cryptographic salt const hashedPassword = await hashPassword('user-plaintext-password', { memoryCost: 65536, // 64 MiB timeCost: 3, // 3 iterations parallelism: 4, // 4 threads }); console.log(hashedPassword); // $argon2id$v=19$m=65536,t=3,p=4$... // 2. Constant-time verification const isMatch = await verifyPassword(hashedPassword, 'user-plaintext-password'); console.log('Password match:', isMatch); // true ``` --- ## 2. JSON Web Tokens (JWT with JOSE) The JWT module implements strict, standards-compliant token signing and verification powered by the `jose` cryptographic suite: ```ts import { signToken, verifyToken } from '@nofinite/utils/jwt'; // 1. Sign JWT with typed payload and claims const token = await signToken( { sub: 'usr_849201', email: 'alex@nofinite.design', role: 'administrator', }, { expiresIn: '24h', issuer: 'https://auth.nofinite.design', audience: 'https://api.nofinite.design', } ); // 2. Verify token and decode claims try { const payload = await verifyToken(token, { issuer: 'https://auth.nofinite.design', audience: 'https://api.nofinite.design', }); console.log('Authenticated user:', payload.sub); } catch (error) { console.error('Invalid or expired token:', error); } ``` > [!NOTE] > `signToken` and `verifyToken` automatically read the signing secret from the `JWT_SECRET` environment variable unless an explicit secret key is provided. --- ## 3. Cryptographic One-Time Passwords (OTP) Engineered for 2-Factor Authentication (2FA), email verification, and SMS passcodes: ```ts import { generateOTP, verifyOTP, isOtpExpired, hasExceededOtpAttempts } from '@nofinite/utils/otp'; // 1. Generate secure 6-digit numeric OTP with 10-minute expiration const { otp, expiresAt } = generateOTP(6, { ttlMinutes: 10 }); console.log(`Your verification code is: ${otp}`); // 2. Check if OTP has expired if (isOtpExpired(expiresAt)) { throw new Error('Verification code has expired. Please request a new one.'); } // 3. Prevent brute-force spam by checking max failed attempts const currentFailedAttempts = 3; if (hasExceededOtpAttempts(currentFailedAttempts, 5)) { throw new Error('Too many failed attempts. Account temporarily locked.'); } // 4. Verify user input using constant-time string comparison const isValid = verifyOTP(otp, '123456'); if (isValid) { console.log('2FA verification successful'); } ``` --- ## API Reference ### Password Functions | Function | Signature | Description | | :--- | :--- | :--- | | `hashPassword` | `(password: string, options?: PasswordHashOptions) => Promise` | Hashes password string via Argon2id | | `verifyPassword` | `(hash: string, password: string) => Promise` | Performs constant-time verification against hash | --- ### JWT Functions | Function | Signature | Description | | :--- | :--- | :--- | | `signToken` | `(payload: JwtPayload, options?: JwtSignOptions) => Promise` | Issues signed JWT with expiration | | `verifyToken` | `(token: string, options?: JwtVerifyOptions) => Promise` | Validates signature and expiration | --- ### OTP Functions | Function | Signature | Description | | :--- | :--- | :--- | | `generateOTP` | `(length?: number, options?: OtpOptions) => { otp: string, expiresAt: Date }` | Generates secure numeric passcode | | `verifyOTP` | `(storedOtp: string, inputOtp: string) => boolean` | Constant-time string matching | | `isOtpExpired` | `(expiresAt: Date \| number) => boolean` | Checks if current timestamp exceeds expiry | | `hasExceededOtpAttempts` | `(attempts: number, maxAttempts?: number) => boolean` | Enforces rate-limiting guard | --- ### Document: utils/installation/page.mdx # Installation & Setup Add `@nofinite/utils` to your backend service, API handler, or serverless worker. --- ## 1. Package Installation Install `@nofinite/utils` using your package manager: ```bash # pnpm pnpm add @nofinite/utils # npm npm install @nofinite/utils # yarn yarn add @nofinite/utils # bun bun add @nofinite/utils ``` --- ## 2. Environment Variables Setup Configure the following environment variables in your `.env` or secrets manager: ```bash # Required for @nofinite/utils/jwt JWT_SECRET="your-ultra-secure-random-secret-key-at-least-32-chars-long" # Required for @nofinite/utils/email (ZeptoMail Transactional Email) ZEPTOMAIL_URL="api.zeptomail.com/" ZEPTOMAIL_TOKEN="your-zeptomail-send-mail-token" ZEPTOMAIL_FROM_EMAIL="noreply@yourdomain.com" ZEPTOMAIL_FROM_NAME="Your Application" ``` --- ## 3. Subpath Import Options `@nofinite/utils` is fully tree-shakeable. You can import from the root or target specific subpaths to minimize bundle size: ```ts // Option A: Root Import import { hashPassword, signToken, generateOTP } from '@nofinite/utils'; // Option B: Subpath Imports (Optimized for Serverless / Edge isolates) import { hashPassword, verifyPassword } from '@nofinite/utils/password'; import { signToken, verifyToken } from '@nofinite/utils/jwt'; import { generateOTP, verifyOTP } from '@nofinite/utils/otp'; import { generateUUID } from '@nofinite/utils/uuid'; import { requireEnv, getEnvBoolean } from '@nofinite/utils/env'; import { sendMail } from '@nofinite/utils/email'; ``` --- ## 4. Verification Test the package in any TypeScript script or route handler: ```ts import { hashPassword, verifyPassword } from '@nofinite/utils'; async function main() { const hash = await hashPassword('test-password'); const valid = await verifyPassword(hash, 'test-password'); console.log('Password verification passed:', valid); } main(); ``` --- ## Next Steps - Explore [Authentication & Cryptography](/utils/auth-and-crypto) for Argon2id hashing, JWT signing, and OTP logic. - Explore [System & Mail](/utils/system-and-mail) for environment parsing and ZeptoMail integration. --- ### Document: utils/llms/page.mdx # LLMs.txt Documentation How to get tools like Cursor, Windsurf, GitHub Copilot, ChatGPT, and Claude to understand `@nofinite/utils`. > [!TIP] > Looking for unified ecosystem presets or multi-package rules? Visit our central [AI Agents Hub](/ai). We support **LLMs.txt** files for making `@nofinite/utils` shared helpers, cryptography, and class name merge utilities directly available to large language models. --- ## Directory Overview The following machine-readable context files are available: - [`/utils/llms.txt`](/utils/llms.txt): The main LLMs index for `@nofinite/utils`. - [`/utils/llms-full.txt`](/utils/llms-full.txt): Complete context bundle containing utility helper methods and TypeScript signatures. - [`/llms.txt`](/llms.txt): Ecosystem index covering all 8 `@nofinite` libraries. - [`/llms-full.txt`](/llms-full.txt): The unified ecosystem bundle. --- ## Usage with Cursor & Windsurf ```markdown # Utils Rules for AI Assistants 1. Subpath & Root Imports: Import auth, crypto, and environment utilities from `@nofinite/utils` or subpaths (`@nofinite/utils/password`, `@nofinite/utils/jwt`, `@nofinite/utils/otp`, `@nofinite/utils/uuid`, `@nofinite/utils/env`, `@nofinite/utils/email`). 2. Zero Framework Dependency: `@nofinite/utils` is 100% framework-agnostic and runs on Node.js (>= 18), Edge workers, Cloudflare, and serverless runtimes. 3. Cryptographic Standards: Uses Argon2id for password hashing and JOSE for JWT signing and verification. ``` --- ### Document: utils/page.mdx --- ## Overview **Nofinite Utils** is a secure, lightweight, and 100% framework-agnostic utility library designed for modern TypeScript, Node.js, and Edge runtimes. It provides production-hardened helpers for critical backend infrastructure: Argon2id password hashing, jose-based JSON Web Token (JWT) lifecycle, high-entropy cryptographic OTPs, UUID v4 generation, strict environment variable parsing, and ZeptoMail transactional messaging. --- ## Architectural Invariants - **100% Framework Agnostic:** Zero dependencies on React, Vue, or any frontend DOM layer. Runs seamlessly on Node.js (`>= 18`), Cloudflare Workers, Fastify, Express, Hono, NestJS, and Next.js Route Handlers. - **Argon2id Password Security:** Leverages the state-of-the-art Argon2id cryptographic hashing algorithm (winner of the Password Hashing Competition) with automated salt generation. - **JOSE Standards-Compliant JWTs:** Powered by the battle-tested `jose` library with HS256/RS256 algorithm support and strict clock skew verification. - **Modular Subpath Exports:** Import only what you need via tree-shakeable subpaths: `@nofinite/utils/password`, `@nofinite/utils/jwt`, `@nofinite/utils/otp`, `@nofinite/utils/uuid`, `@nofinite/utils/env`, and `@nofinite/utils/email`. --- ## Core Capabilities - **Password Hashing (`/password`)**: High-entropy Argon2id password hashing and constant-time verification. - **JWT Authentication (`/jwt`)**: Type-safe token signing, verification, and claims decoding with configurable expiration. - **One-Time Passwords (`/otp`)**: Cryptographic numeric passcodes with expiry checks and brute-force attempt limits. - **Environment Handling (`/env`)**: Strictly typed environment variable getters with fallback and required validation. - **Unique Identifiers (`/uuid`)**: UUID v4 generation, binary buffer conversion, and validation. - **Transactional Messaging (`/email`)**: High-throughput transactional email delivery via ZeptoMail SMTP/API. --- ## Quick Example ```ts import { hashPassword, verifyPassword, signToken, verifyToken, generateOTP, requireEnv } from '@nofinite/utils'; // 1. Password Security with Argon2id const passwordHash = await hashPassword('super-secret-user-password'); const isValid = await verifyPassword(passwordHash, 'super-secret-user-password'); console.log('Password valid:', isValid); // true // 2. JWT Signing & Verification const token = await signToken( { sub: 'usr_9482', role: 'admin' }, { expiresIn: '2h' } ); const decoded = await verifyToken(token); console.log('User ID:', decoded.sub); // 3. Cryptographic OTP Generation const { otp, expiresAt } = generateOTP(6, { ttlMinutes: 10 }); console.log(`Generated OTP: ${otp}, expires at: ${expiresAt}`); // 4. Strict Environment Variable Validation const databaseUrl = requireEnv('DATABASE_URL'); ``` --- ## Module Catalog | Module | Subpath Export | Primary Functions | | :--- | :--- | :--- | | [**Auth & Crypto**](/utils/auth-and-crypto) | `@nofinite/utils/password`
`@nofinite/utils/jwt`
`@nofinite/utils/otp` | `hashPassword`, `verifyPassword`, `signToken`, `verifyToken`, `generateOTP`, `verifyOTP` | | [**System & Mail**](/utils/system-and-mail) | `@nofinite/utils/env`
`@nofinite/utils/uuid`
`@nofinite/utils/email` | `getEnv`, `requireEnv`, `getEnvBoolean`, `generateUUID`, `sendMail`, `sendBatchMail` | --- ## Next Steps - Follow the [Installation Guide](/utils/installation) to install and configure the package. - Explore [Authentication & Cryptography](/utils/auth-and-crypto) for detailed crypto signatures and security parameters. - Explore [System & Email](/utils/system-and-mail) for environment schemas and ZeptoMail integration. --- ### Document: utils/releases/page.mdx # Utils Releases **Latest version:** `v0.1.0` (02 February 2026) --- ## Overview This is the first public release of Nofinite Utils. Nofinite Utils is a lightweight, framework-agnostic utility library providing **production-ready helpers** for common backend and full‑stack needs such as authentication, security, identifiers, and environment handling. --- ## Included - OTP generation and verification (secure, hash-based) - Password hashing and verification (Argon2id) - JWT helpers with configurable algorithms and expiration - UUID v7 utilities (string + binary helpers) - Environment helpers (`isProd`, `isDev`, safe env access) - Email helpers (ZeptoMail integration) - Fully typed APIs with TypeScript support --- ## Design Goals - **Security-first** defaults - **Minimal API surface** - **Tree-shakable ES modules** - **Zero framework coupling** - **Explicit, readable utilities** --- ## Notes - This release establishes the public API surface. - All utilities are designed to work in Node.js environments. - Sensible defaults are provided, but most helpers are configurable. - APIs may evolve until a stable `v1.0.0`. --- ## Known Limitations - Email utilities rely on external providers (e.g. ZeptoMail). - JWT helpers currently focus on symmetric algorithms. - UUID utilities intentionally support **only UUID v7**. --- ### Document: utils/system-and-mail/page.mdx # System, UUID & Transactional Mail **Nofinite Utils** provides core server utilities for environment variable hygiene, high-entropy UUID generation, and transactional email distribution via ZeptoMail. ```ts import { getEnv, requireEnv, getEnvNumber, getEnvBoolean, isEnv, generateUUID, uuidToBuffer, bufferToUUID, sendMail, sendBatchMail, } from '@nofinite/utils'; ``` --- ## 1. Environment Variable Parsing (`/env`) Prevents silent configuration failures by enforcing strict type conversions and throwing early during server startup if required variables are missing: ```ts import { requireEnv, getEnv, getEnvNumber, getEnvBoolean, isEnv } from '@nofinite/utils/env'; // 1. Enforce existence of critical variables (throws if not set) const databaseUrl = requireEnv('DATABASE_URL'); const apiKey = requireEnv('STRIPE_SECRET_KEY'); // 2. Safe string getter with fallback const port = getEnv('PORT', '3000'); // 3. Strict numeric parsing with fallback const maxConnections = getEnvNumber('DB_MAX_POOL', 20); // 4. Boolean conversion ('true', '1', 'yes' -> true) const enableTelemetry = getEnvBoolean('ENABLE_TELEMETRY', false); // 5. Environment check if (isEnv('production')) { console.log('Running in production mode'); } ``` --- ## 2. UUID v4 Generation & Binary Buffers (`/uuid`) Generates RFC 4122 compliant UUID v4 strings, with built-in binary buffer converters for high-performance 16-byte database storage (`BINARY(16)`): ```ts import { generateUUID, uuidToBuffer, bufferToUUID } from '@nofinite/utils/uuid'; // 1. Generate fresh UUID v4 const id = generateUUID(); console.log('Generated ID:', id); // "c73bcdcc-2669-4bf6-81d3-e4ae73fb11fd" // 2. Convert to 16-byte Buffer for optimal database storage const buffer = uuidToBuffer(id); console.log('Buffer length:', buffer.length); // 16 bytes // 3. Reconstruct canonical UUID string from Buffer const restoredId = bufferToUUID(buffer); console.log('Restored ID:', restoredId); ``` --- ## 3. Transactional Email with ZeptoMail (`/email`) High-throughput transactional email delivery powered by Zoho ZeptoMail API: ### Environment Configuration ```bash ZEPTOMAIL_URL="api.zeptomail.com/" ZEPTOMAIL_TOKEN="your-zeptomail-send-mail-token" ZEPTOMAIL_FROM_EMAIL="noreply@yourdomain.com" ZEPTOMAIL_FROM_NAME="Your Application" ``` ### Sending a Single Email ```ts import { sendMail } from '@nofinite/utils/email'; await sendMail({ to: [ { email_address: { address: 'sarah.chen@example.com', name: 'Sarah Chen', }, }, ], subject: 'Welcome to Nofinite Cloud', htmlbody: `

Welcome, Sarah!

Your workspace has been successfully provisioned on us-east-1.

`, }); ``` ### Sending Batch Emails ```ts import { sendBatchMail } from '@nofinite/utils/email'; await sendBatchMail({ to: [ { email_address: { address: 'user1@example.com', name: 'User 1' }, merge_info: { discount_code: 'SAVE20' }, }, { email_address: { address: 'user2@example.com', name: 'User 2' }, merge_info: { discount_code: 'SAVE30' }, }, ], subject: 'Exclusive Subscriber Perks', htmlbody: '

Use your personalized code: {{discount_code}}

', }); ``` --- ## API Reference ### Env Functions | Function | Signature | Description | | :--- | :--- | :--- | | `requireEnv` | `(key: string) => string` | Returns env value or throws if missing | | `getEnv` | `(key: string, defaultValue?: string) => string` | Returns env value or fallback | | `getEnvNumber` | `(key: string, defaultValue?: number) => number` | Parses integer/float from env | | `getEnvBoolean` | `(key: string, defaultValue?: boolean) => boolean` | Parses boolean string (`'true'`, `'1'`, `'yes'`) | | `isEnv` | `(envName: string) => boolean` | Compares `NODE_ENV` to target string | --- ### UUID Functions | Function | Signature | Description | | :--- | :--- | :--- | | `generateUUID` | `() => string` | Generates canonical RFC 4122 UUID v4 | | `uuidToBuffer` | `(uuid: string) => Buffer` | Converts 36-char string to 16-byte Buffer | | `bufferToUUID` | `(buffer: Buffer) => string` | Converts 16-byte Buffer to UUID string | --- ### Email Functions | Function | Signature | Description | | :--- | :--- | :--- | | `sendMail` | `(options: SendMailOptions) => Promise` | Dispatches single transactional email | | `sendBatchMail` | `(options: SendBatchMailOptions) => Promise` | Dispatches bulk template email with merge tags | ---