npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

secure-web-token

v1.2.3

Published

A secure web token utility

Readme

🔐 Secure Web Token (SWT)

1. About the Package

Secure Web Token (SWT) is a next-generation authentication token system designed for security-critical applications. Unlike traditional JWTs, SWT operates on a Device Registration and Server-Side Session Model, ensuring that tokens are intrinsically tied to specific devices and sessions.

Key highlights:

  • AES-256-GCM encryption: Ensures payloads are fully encrypted, not just Base64 encoded.
  • Device fingerprint binding: Tokens are locked to a device (or session) to prevent unauthorized reuse.
  • Server-side session store: Device IDs and sessions are managed securely on the backend, never exposed to the browser.
  • Simple developer experience: Easily integrate into Node.js applications with sign and verify functions.

SWT is ideal for mission-critical applications where security, controlled access, and device binding are required.


2. What Problem Does It Solve?

Traditional JWTs have several limitations:

  • JWT payloads are only Base64 encoded, not encrypted. Anyone can decode them.
  • If a token leaks, it can be reused from any device.
  • No built-in mechanism to restrict tokens to specific devices.
  • Cannot safely enforce single-device login without additional server logic.

SWT addresses these issues by:

  • Fully encrypting token payloads using AES-256-GCM.
  • Binding tokens to device fingerprints managed on the backend.
  • Preventing token reuse from unauthorized devices.
  • Supporting auto-generated device IDs for added security.
  • Managing sessions server-side, so sensitive identifiers never reach the browser.

Use cases:

  • Course platforms with anti-piracy requirements
  • SaaS dashboards
  • Admin panels with restricted access
  • Any system requiring device-bound authentication

3. Available Functions

sign()

Creates a secure, encrypted token.

Features:

  • Encrypts the payload completely
  • Adds iat (issued at) and exp (expiry) timestamps
  • Supports device fingerprint binding
  • Can auto-generate a device ID
  • Optional server-side session management
import { sign } from "secure-web-token";

const secret = "my-super-secret";

// Auto device registration + server session
const { token, sessionId } = sign(
  { userId: 1, role: "admin" },
  secret,
  { fingerprint: true, store: "memory", expiresIn: 3600 }
);

console.log("TOKEN:", token);
console.log("SESSION ID (internal, not exposed to browser):", sessionId);

verify()

Verifies and decrypts a token.

Checks performed:

  • Token format integrity
  • Signature correctness
  • Expiry check
  • Device fingerprint / session validation
import { verify, getStore } from "secure-web-token";

// Get the store instance (MemoryStore / Redis)
const store = getStore("memory");

try {
  const payload = verify(token, secret, {
    sessionId,          // Server-side session ID
    fingerprint: "abc", // Device fingerprint stored internally
    store: "memory"     // Must match the store used during sign()
  });

  console.log("USER DATA:", payload.data);
} catch (err) {
  console.error("AUTH ERROR:", err.message);
}

4. Server-Side Session Model (Recommended)

In SWT v2+, device verification is entirely server-side.
This prevents attackers from copying tokens and device IDs from one browser to another.

Workflow:

  1. User logs insign() generates token + server session
  2. Server stores session internally (deviceId, fingerprint)
  3. Browser receives token + HttpOnly cookie → cannot read device ID
  4. verify()** checks session + fingerprint internally** → ensures single-device access
  5. Session revocation automatically prevents token reuse

Example Express backend:

import express from "express";
import cookieParser from "cookie-parser";
import cors from "cors";
import { sign, verify, getStore } from "secure-web-token";

const app = express();
app.use(cors({ origin: true, credentials: true }));
app.use(cookieParser());
app.use(express.json());

const SECRET = "super-secret-key";
const store = getStore("memory");

// LOGIN
app.post("/login", (req, res) => {
  const user = { userId: 1, name: "John" };
  const { token, sessionId } = sign(user, SECRET, { fingerprint: true, store: "memory", expiresIn: 3600 });

  res.cookie("swt_session", sessionId, { httpOnly: true, sameSite: "strict", secure: false });
  res.json({ token });
});

// PROFILE
app.get("/profile", (req, res) => {
  try {
    const sessionId = req.cookies.swt_session;
    const session = store.getSession(sessionId);
    if (!session) throw new Error("Unauthorized or session expired");

    const token = req.headers.authorization?.split(" ")[1];
    const payload = verify(token, SECRET, { sessionId, fingerprint: session.fingerprint, store: "memory" });
    res.json({ user: payload.data });
  } catch (err) {
    res.status(401).json({ error: err.message });
  }
});

5. Payload Structure (Internal)

{
  "data": {
    "userId": 1,
    "role": "admin"
  },
  "iat": 1768368114,
  "exp": 1768369014,
  "fp": "device-fingerprint" // stored server-side
}

Note: The fp (fingerprint) and session ID are not exposed to the browser, making token copying attacks impossible.


6. Installation

npm install secure-web-token

7. Importing

// ESM
import { sign, verify, getStore } from "secure-web-token";

// CommonJS
const { sign, verify, getStore } = require("secure-web-token");

8. Summary of Features

  • 🔐 AES-256-GCM encryption
  • 🔒 Server-side session + device binding
  • ⏱ Expiry (iat + exp)
  • 🛡 Prevents token reuse on unauthorized devices
  • ⚡ Easy integration with Node.js / Express
  • ✅ Auto-generated device IDs
  • ✅ Fully optional server-side memory store