Registry / auth-security / sc-auth

sc-auth

JSON →
library6.0.0jsnpmunverified

sc-auth is a foundational authentication module specifically designed for the SocketCluster real-time framework. It facilitates JSON Web Token (JWT) based authentication, which is the default mechanism in SocketCluster. This package, currently at version 6.0.0 (released approximately eight years ago), handles the core logic for signing and verifying JWTs within a SocketCluster environment. While newer SocketCluster documentation often guides developers towards using `agServer.auth.signToken` or `jsonwebtoken` directly, `sc-auth` provides a structured `AuthEngine` for this purpose. Its primary role is to enable persistent user sessions, cross-browser tab authentication, and secure access control by signing arbitrary data objects with a secret key. Due to its age, developers should be aware that active development is minimal, and practices may have evolved in the broader SocketCluster ecosystem. Its release cadence is effectively dormant, with its last major update occurring many years ago.

npm install sc-auth
INSTALL
IMPORT
SIG · SC-AUTH
S
sc-auth
auth-securityjavascriptv6.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
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 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

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

AuthEngine
const AuthEngine = require('sc-auth').AuthEngine;
import { AuthEngine } from 'sc-auth';
The package primarily exports via CommonJS `module.exports`. For ESM, consider a dynamic import or a CommonJS wrapper.
createAuthEngine
const { createAuthEngine } = require('sc-auth');
An alternative export for creating the engine. Typically, you'd directly instantiate AuthEngine.
signToken
const { signToken } = require('sc-auth');
While AuthEngine has signToken, a top-level signToken utility may also be exposed (requires checking specific `index.js` for confirmation). The primary usage pattern is via an AuthEngine instance.

This quickstart demonstrates how to integrate `sc-auth` with a SocketCluster server to handle JWT-based authentication. It shows initializing the `AuthEngine`, using it to sign tokens upon a 'login' event, and implementing inbound middleware to verify token presence and perform basic role-based authorization for publishing to channels.

const http = require('http'); const socketClusterServer = require('socketcluster-server'); const { AuthEngine } = require('sc-auth'); const AUTH_KEY = process.env.AUTH_SIGNATURE_KEY ?? 'my-secret-auth-key'; // NEVER hardcode in production! const TOKEN_EXPIRY_IN_SECONDS = 3600; // 1 hour const httpServer = http.createServer(); const authEngine = new AuthEngine(AUTH_KEY, { algorithm: 'HS256', // Default algorithm expiresIn: TOKEN_EXPIRY_IN_SECONDS }); const agServer = socketClusterServer.attach(httpServer, { authKey: AUTH_KEY, authEngine: authEngine // Inject sc-auth's engine }); (async () => { for await (let { socket } of agServer.listener('connection')) { // Example of authenticating a socket after a login event socket.on('login', async (credentials, respond) => { if (credentials.username === 'user' && credentials.password === 'pass') { const tokenData = { username: credentials.username, role: 'admin' }; try { const token = await authEngine.signToken(tokenData); socket.authenticate(token); respond(); // Acknowledge successful login } catch (error) { respond(error); // Send error back to client } } else { respond(new Error('Invalid credentials')); } }); // Example middleware to check authenticated status agServer.setMiddleware(agServer.MIDDLEWARE_INBOUND, async (middlewareStream) => { for await (let action of middlewareStream) { if (action.type === action.PUBLISH_IN) { if (!action.socket.authToken) { action.block(new Error('Authentication required to publish.')); continue; } // Further authorization checks based on action.socket.authToken.role if (action.socket.authToken.role !== 'admin' && action.channel === 'adminChannel') { action.block(new Error('Not authorized for this channel.')); continue; } } action.next(); } }); } })(); httpServer.listen(8000, () => { console.log(`SocketCluster server listening on port 8000`); });
Debug
Known issues
breakingVersion 6.0.0 of `sc-auth` (and SocketCluster v15+) introduced a breaking change by transitioning from callback-based functions to Promise-based asynchronous operations. Code expecting callbacks will fail.
fix
Refactor asynchronous calls using `await` or `.then()` to handle Promises instead of traditional Node.js callbacks.
affects: >=6.0.0
gotchaThe `sc-auth` package has not seen active development in approximately eight years (as of 2026), with its last published version (6.0.0) dating back to then. While functional, it may lack modern features, security updates, or compatibility fixes for newer Node.js versions or evolving JWT standards.
fix
Evaluate whether direct use of the `jsonwebtoken` package or SocketCluster's `agServer.auth` methods are more suitable for new projects or if this package's functionalities can be safely migrated. Regularly audit dependencies for vulnerabilities.
affects: >=6.0.0
gotchaThe `authKey` (or signature key) used to sign and verify JWTs is critical for security. Hardcoding it, using a weak key, or exposing it publicly severely compromises the integrity of your authentication system.
fix
Always store the `authKey` in environment variables (e.g., `process.env.AUTH_SIGNATURE_KEY`) or a secure configuration management system. Ensure it is a long, cryptographically strong random string.
affects: *
gotchaJWTs, by design, are signed but not encrypted. Sensitive user data should never be stored directly in the JWT payload, as it can be read by anyone with the token.
fix
Only include non-sensitive information necessary for authorization (e.g., user ID, roles, permissions) in the JWT payload. Fetch sensitive user data from a secure backend store (e.g., database) after token verification.
affects: *
Errors
Common errors & fixes
TokenExpiredError: jwt expired
The provided JWT has passed its expiry time, making it invalid for use.
fix
Implement client-side logic to detect expired tokens and automatically request a new one (e.g., using a refresh token mechanism) or prompt the user to re-authenticate. Ensure server-side logic handles `TokenExpiredError` gracefully.
JsonWebTokenError: invalid signature
The JWT's signature does not match, indicating the token was tampered with or signed with a different secret key than the one used for verification.
fix
Verify that the same `authKey` (or signature key) is consistently used across all signing and verification points in your application. Ensure no part of the token was altered after signing. This often happens if an `authKey` is mismatched between different services or deployments.
TypeError: AuthEngine is not a constructor
Attempting to import `AuthEngine` using an incorrect syntax (e.g., CommonJS `require` in an ESM context, or an incorrect named import).
fix
For CommonJS, use `const AuthEngine = require('sc-auth').AuthEngine;`. If using ESM, `sc-auth` might not natively support it for direct named imports; consider `const { AuthEngine } = await import('sc-auth');` or wrapping it in a CommonJS file that exports an ESM-compatible module.
Error: Missing credentials for token verification
The `authKey` (or a corresponding public/private key pair) was not provided to the `AuthEngine` constructor or the `verifyToken` method.
fix
Ensure the `AuthEngine` is initialized with the correct `authKey` (e.g., `new AuthEngine(process.env.AUTH_SIGNATURE_KEY)`). Double-check environment variable loading and configuration.
Upgrade
Version history
6.0.0latest on npm
Audit
Dependencies
jsonwebtokenrequiredCore dependency for JWT signing and verification.
Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources