Registry / auth-security / secure-web-token

secure-web-token

JSON →
library1.2.8jsnpmunverified

Secure Web Token (SWT) is a Node.js library offering a security-focused alternative to traditional JSON Web Tokens (JWTs). Unlike JWTs, which are merely Base64 encoded, SWT employs AES-256-GCM encryption for payloads and implements server-side session binding, making tokens device-bound and preventing reuse on other devices. This approach significantly enhances security by making stolen tokens useless for attackers. The current stable version is 1.2.8. It provides a simple API with `sign()` and `verify()` functions, supporting expiry and HttpOnly session cookies. Key differentiators include full payload encryption, true device binding, and server-side session management, making it suitable for high-security applications like admin panels, SaaS dashboards, and internal tools where preventing token leakage and session hijacking is critical.

npm install secure-web-token
INSTALL
IMPORT
SIG · SECURE-WEB-TOKEN
S
secure-web-token
auth-securityjavascriptv1.2.8
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

sign
✓ import { sign } from 'secure-web-token'
✗ const sign = require('secure-web-token').sign
Primarily used in ESM contexts for creating encrypted, device-bound tokens. While CommonJS `require` syntax is supported, ESM is idiomatic for TypeScript projects.
verify
✓ import { verify } from 'secure-web-token'
✗ import verify from 'secure-web-token'
A named export; ensure you use destructuring for import. This function validates and decrypts tokens, requiring session context like `sessionId` and `fingerprint`.
getStore
✓ import { getStore } from 'secure-web-token'
✗ const { getStore } = require('secure-web-token')
Used to retrieve the configured session store instance. By default, it returns an in-memory store, which should be replaced with a persistent solution for production.

Demonstrates a basic Express.js server using `secure-web-token` to handle user login and protect a route. It shows how to `sign` a token with device binding, set an HttpOnly session cookie, and then `verify` the token and session context for authorized access.

import express from "express"; import cookieParser from "cookie-parser"; import { sign, verify, getStore } from "secure-web-token"; const app = express(); app.use(express.json()); app.use(cookieParser()); const SECRET = process.env.SWT_SECRET ?? 'a-very-secure-random-secret-key-of-at-least-32-characters'; // Use environment variable for production const store = getStore("memory"); // Default in-memory store, replace with persistent for production // Define a simple user for demonstration const demoUser = { userId: 123, username: "testuser" }; // --- Sign Token Example --- app.post('/login', (req, res) => { // In a real app, validate user credentials here const { token, sessionId } = sign(demoUser, SECRET, { fingerprint: true, // Enable device binding store: "memory", // Use the configured store expiresIn: 3600 // Token expires in 1 hour }); // Set HttpOnly cookie for sessionId res.cookie("swt_session", sessionId, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax' }); res.json({ message: "Login successful", token }); }); // --- Verify Token Example --- app.get('/protected', (req, res) => { try { const sessionId = req.cookies.swt_session; const token = req.headers.authorization?.split(" ")[1]; if (!sessionId || !token) { return res.status(401).json({ error: "Authentication required" }); } // Retrieve session data (e.g., fingerprint) from the store const session = store.getSession(sessionId); if (!session) { return res.status(401).json({ error: "Session not found or expired" }); } const payload = verify(token, SECRET, { sessionId, fingerprint: session.fingerprint, // Crucial for device binding store: "memory" // Use the configured store }); res.json({ message: "Access granted!", user: payload.data }); } catch (error) { console.error("Verification failed:", error); res.status(401).json({ error: "Unauthorized access" }); } }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log("Try: POST /login and then GET /protected with the token and cookie."); });
Debug
Known issues
gotchaThe default session store is in-memory. This store is volatile, meaning all sessions are lost on application restart and it does not support multi-instance deployments (load balancing). This is unsuitable for production environments requiring persistence or scalability.
fix
Implement and configure a persistent session store (e.g., Redis, database) by providing a custom `store` object to the `sign` and `verify` functions, or by extending `getStore`.
affects: >=1.0.0
gotchaThe `SECRET` key is critical for token encryption and decryption. Using a weak secret, exposing it publicly, or failing to keep it consistent across all application instances will lead to token validation failures or severe security vulnerabilities.
fix
Generate a strong, long, random secret. Store it securely (e.g., environment variable, KMS) and ensure all instances of your application use the exact same secret.
affects: >=1.0.0
breakingUnlike JWTs, `secure-web-token` is stateful and requires both the `sessionId` (typically from an HttpOnly cookie) and the `fingerprint` (retrieved from your session store) to be explicitly passed to the `verify` function. Failure to provide correct and matching session context will result in authentication failure, as the token is device-bound.
fix
Ensure `sessionId` is consistently passed from the client (e.g., HttpOnly cookie) and use it to retrieve the `fingerprint` from your server-side session store, then pass both to `verify` options.
affects: >=1.0.0
gotchaWhen integrating `secure-web-token` with a frontend framework, ensure HttpOnly cookies are correctly handled for the `sessionId`. Client-side JavaScript should not attempt to read or write the `swt_session` cookie directly, as it's designed for server-only access.
fix
Configure your frontend HTTP client (e.g., Axios, Fetch API) to send credentials (`credentials: 'include'`) and allow the browser to manage the HttpOnly cookie automatically. Do not attempt to access the `swt_session` cookie from JavaScript.
affects: >=1.0.0
Errors
Common errors & fixes
Unauthorized access
Token validation failed due to an invalid token, missing session context (`sessionId`, `fingerprint`), or an incorrect secret.
fix
Check if the token is present, unexpired, and correctly signed. Verify that the `sessionId` and associated `fingerprint` provided to `verify` match the server-side session, and that the `SECRET` is identical to the one used during `sign`.
Session not found or expired
The server-side session associated with the `sessionId` could not be found in the store or has expired.
fix
Ensure the `sessionId` is valid and the session exists in the configured store. This often indicates a missing or expired session, or a misconfigured session store (e.g., in-memory store reset).
Error: Invalid token signature
The token was tampered with, the `SECRET` used for verification is different from the one used for signing, or the token is malformed.
fix
Confirm the `SECRET` key used in `verify` is identical to the one used in `sign`. If the secret is correct, the token may have been tampered with or is corrupted. Ensure the token is passed correctly without modification.
Upgrade
Version history
1.2.8latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
22 hits · last 30 days
node
18
OpenAI (training)
1
Resources
secure-web-token — npm install secure-web-token · libregistry