TokenToolkit.js: Client-Side JavaScript Library for JWT, Base64, URL & Hashing

TokenToolkit.js: Client-Side JavaScript Library for JWT, Base64, URL & Hashing

TokenToolkit.js is a lightweight, zero-dependency ES6 JavaScript Module designed as a unified facade for deep JWT parsing, security analysis, Base64 file streaming, HTML entity processing, URL parsing, and client-side cryptographic hashing.

The library separates core data processing logic from the UI components of nKode utilities, enabling developers to integrate a secure, local-first token auditing and data transformation mechanism into their own applications.

JWT Decoding & Structural Inspection

The core engine of TokenToolkit.js features an advanced parsing suite dedicated to JSON Web Tokens, serving as the technical backbone for the online JWT Decoder & Inspector utility:

  • Client-Side Deconstruction: It splits, normalizes, and decodes standard three-part JWT structures directly in the browser, ensuring sensitive tokens never leave the user's machine.
  • Structured Components: Converts raw cryptographic strings into interactive JavaScript objects, exposing separate fields for the token's Header, Payload, and Signature.

Claim Enrichment & Smart Validation

The library minimizes boilerplate code by instantly outputting actionable diagnostic data for developers:

  • Automated Time Conversion: Intercepts standard Unix timestamps (exp, iat, nbf) and converts them into human-readable UTC strings (formattedDate) for effortless expiration checks.
  • Security Heuristics: Inspects each part of the token and appends detected anomalies (such as Algorithm Confusion or malformed structures) into an issues array. The toolkit includes 66 built-in validation checks.
  • Claim Classification: Separates claims into standard (RFC-compliant) and custom fields, providing detailed descriptions for standard claims within the UI.

Advanced Base64, Base64URL & File Streaming

Beyond JWTs, the library includes a high-performance Base64 subsystem engineered for file transformations, fully powering the Base64 Encoder and Base64 Decoder and Inspector utilities:

  • Smart Normalization: Accepts any Base64 string and automatically handles URL-safe variants, missing padding characters (=), or spaces without breaking.
  • File to Base64 Serialization: Converts raw browser file blobs or binary objects into standard Base64 data URLs smoothly via the Base64 from File utility.
  • Base64 to File Hydration: Extracts MIME types and processes raw byte arrays natively to reconstruct high-fidelity downloadable physical files through the Base64 to File tool, entirely client-side.

URL Percent-Encoding & Structural Parsing

The library features a dedicated structural URL engine designed to handle strict encoding specifications and inline diagnostics across the URL Encoder, URL Decoder, and URL Parser tools:

  • Flexible Encoding Targets: Offers separate modes for full query parameter serialization (encoding delimiters like /, ?, &) or standard URI preservation for repairing broken links.
  • Deep URL Deconstruction: Parses raw links into semantic objects, separating protocols, hostnames, port numbers, query parameter objects, and hash fragments.
  • Syntactic Validation: Audits strings before decoding, gracefully isolating truncated symbols (stray %) or illegal non-hexadecimal sequences (e.g., %G1) to return clean error payloads instead of triggering browser crashes.

HTML Entities & XSS Mitigation

The toolkit incorporates an HTML transformation engine for secure string encoding and decoding, driving the HTML Entities Encoder and HTML Entities Decoder:

  • XSS Protection: Provides safe conversions between raw strings and HTML entities, neutralizing high-risk injection characters like <, >, &, ", and '.
  • Broad Compatibility: Supports standard Named Entities, Decimal mappings, and Hexadecimal configurations for comprehensive coverage.

High-Precision Timestamp & Epoch Conversions

To eliminate manual timezone errors, a deterministic time engine handles epoch transformations under the hood of the Timestamp Converter:

  • Auto-Detection: Automatically identifies and handles both 10-digit Unix timestamps (seconds) and 13-digit JavaScript epoch values (milliseconds).
  • Localization: Deconstructs timestamps into ISO 8601 strings, UTC/GMT format, and local system time simultaneously.
  • Date Metrics: Returns rich object payloads detailing week numbers, day-of-year tracking, and leap year checks.

Cryptographic Hash Generation

For client-side data fingerprinting, TokenToolkit.js exposes an optimized hashing layer powering the online Hash Generator:

  • Multiple Algorithms: Generates secure message digests using standard algorithms including SHA-1, SHA-256, SHA-512, and MD5.
  • Privacy-First: Processes inputs asynchronously using native browser cryptographic primitives, keeping data strictly local.

Usage Example (Quick Start)

Integrating the library is straightforward and relies on standard ES6 native imports:

import TokenToolkit from "./TokenToolkit.js";

// 1. Validate and Parse a JSON Web Token
const tokenResult = TokenToolkit.decodeJWT("your.raw.jwt");
if (tokenResult.valid) {
    const jwt = tokenResult.jwt;
    console.log(jwt.toJSON()); // Clean JSON output
}

// 2. Safe URL-Safe Base64 Encoding without padding
const b64Result = TokenToolkit.encodeToBase64("Hello nKode!", { 
    base64Url: true, 
    removePadding: true 
});
console.log(b64Result.encodedText); // "SGVsbG8gbktvZGUh"

// 3. Robust URL Parsing and Analysis
const parsedUrl = TokenToolkit.parseUrl("https://nkode.gr/EN/tools?query=token&sort=desc");
console.log(parsedUrl.host); // "nkode.gr"
console.log(parsedUrl.queryParams); // { query: "token", sort: "desc" }

// 4. Native HTML Entity Escaping (XSS Protection)
const htmlResult = TokenToolkit.encodeHtmlEntities("<script>alert('xss')</script>");
console.log(htmlResult.encodedText); // "&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;"

// 5. Comprehensive Epoch & Timestamp Conversion
const timeResult = TokenToolkit.convertTimestamp(1778112000);
if (timeResult.valid) {
    console.log("ISO Date:", timeResult.telemetry.iso);
}

// 6. Cryptographic Hash Calculation
const hashResult = await TokenToolkit.generateHash("nKoding loops", "SHA-256");
console.log(hashResult.hexDigest); // Secure SHA-256 hex string

Availability

The library is distributed under the open-source GNU GPL v3.0 License. Open-source software should strictly respect data confidentiality (privacy-by-design), and you are welcome to inspect the source code, open issues, or submit pull requests.

The source code is available on GitHub via the official TokenToolkit GitHub Repository

To see it in action, you can inspect and analyze your data live using the Online Developer Utilities provided by nKode.

Read Also

JsonToolkit.js: A Local-First JavaScript JSON Management Library
JsonToolkit.js: A Local-First JavaScript JSON Management Library
new tool launch: JWT Decoder & Inspector
new tool launch: JWT Decoder & Inspector
IdCraft.js: javaScript library for generating and inspecting UUID (v4, v7) and NanoID
IdCraft.js: javaScript library for generating and inspecting UUID (v4, v7) and NanoID