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
signandverifyfunctions.
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) andexp(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:
- User logs in →
sign()generates token + server session - Server stores session internally (deviceId, fingerprint)
- Browser receives token + HttpOnly cookie → cannot read device ID
- verify()** checks session + fingerprint internally** → ensures single-device access
- 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-token7. 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
