Registry / auth-security / ag-auth

ag-auth

JSON →
library2.1.1jsnpmunverified

ag-auth is the official authentication module for SocketCluster (now Asyngular), providing a robust mechanism for securing real-time applications using JSON Web Tokens (JWT). It handles the signing, verification, and management of authentication tokens. Currently at version 2.1.1, the package is actively maintained, with the latest significant update published in November 2025. It serves as the underlying engine for SocketCluster's `agServer.auth` object, abstracting the complexities of JWT handling. While alternative methods for JWT exist (e.g., direct `jsonwebtoken` usage), ag-auth integrates seamlessly into the SocketCluster ecosystem, offering a standardized and convenient approach to user authentication across HTTP and WebSocket flows. Its primary differentiator is this tight integration, ensuring compatibility and streamlined development within SocketCluster projects.

npm install ag-auth
INSTALL
IMPORT
SIG · AG-AUTH
A
ag-auth
auth-securityjavascriptv2.1.1
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
import { AuthEngine } from 'ag-auth';
const AuthEngine = require('ag-auth');
While `AuthEngine` can be imported for custom setups or direct usage, most users interact with `ag-auth` indirectly via the `agServer.auth` object within a SocketCluster worker.
SignTokenOptions
import { SignTokenOptions } from 'ag-auth';
Type import for configuring JWT signing, primarily used with TypeScript for better type safety.
VerifyTokenOptions
import { VerifyTokenOptions } from 'ag-auth';
Type import for configuring JWT verification, primarily used with TypeScript for better type safety.

This quickstart demonstrates how `ag-auth` (via `agServer.auth`) is used to sign and verify JWT tokens in a SocketCluster server, handling client authentication.

import { AGServer } from 'socketcluster-server'; import { AuthEngine } from 'ag-auth'; // Although usually accessed via agServer.auth const SECRET_KEY = process.env.AUTH_SECRET_KEY ?? 'my-secret-key-123'; const agServer = new AGServer({ authKey: SECRET_KEY, // If you were to override the default auth engine, you might do: // authEngine: new AuthEngine(SECRET_KEY) }); (async () => { for await (const { socket } of agServer.listen()) { (async () => { // This is how ag-auth functionality is typically accessed // via the agServer instance. const tokenData = { username: 'testuser', roles: ['admin'] }; try { // Sign a token using the configured authEngine (ag-auth) const token = await agServer.auth.signToken(tokenData, { expiresIn: '1h' }); console.log(`Signed JWT: ${token}`); // Simulate client sending token and server verifying socket.on('login', async (data) => { try { const decodedToken = await agServer.auth.verifyToken(data.token); console.log(`Socket ${socket.id} authenticated:`, decodedToken); socket.emit('authSuccess', { message: 'Authenticated successfully', user: decodedToken.username }); } catch (error) { console.error(`Socket ${socket.id} authentication failed:`, error.message); socket.emit('authFail', { message: 'Authentication failed', error: error.message }); } }); // Example: Client attempts to log in setTimeout(() => { console.log('Simulating client login attempt...'); socket.emit('login', { token: token }); }, 1000); } catch (error) { console.error('Error during auth setup:', error); } })(); } })(); console.log('SocketCluster server is listening for connections...');
Debug
Known issues
breakingSocketCluster v15+ transitioned authentication functions to return Promises instead of accepting callbacks. Code relying on callback-based `agServer.auth` methods will break.
fix
Update all calls to `agServer.auth.signToken` and `agServer.auth.verifyToken` (and similar) to use `await` or `.then()` for Promise resolution.
affects: >=15.0.0
breakingPrior to SocketCluster v1.3.0, authentication was session-based. Since v1.3.0, it shifted entirely to JSON Web Tokens (JWT). Direct session manipulation methods are deprecated.
fix
Refactor authentication logic to exclusively use JWTs, leveraging `agServer.auth.signToken` and `agServer.auth.verifyToken` for all authentication flows. Migrate any persistent session data to be included within JWT payloads or external stores.
affects: >=1.3.0
gotchaJWTs are signed, not encrypted. Do not store sensitive or secret data directly in the token's payload, as it can be easily read by anyone with access to the token.
fix
Only store non-sensitive user identifiers (e.g., user ID, roles) in JWT payloads. Fetch sensitive user data from a secure database or service after verifying the token.
affects: >=1.0.0
gotchaUsing a weak or compromised `authKey` (secret) makes JWTs vulnerable to forgery. An attacker could sign their own tokens and impersonate users.
fix
Always use a strong, randomly generated, long secret key for `agServer.authKey`. Store it securely (e.g., in environment variables) and rotate it periodically. Never hardcode it in source code.
affects: >=1.0.0
Errors
Common errors & fixes
JsonWebTokenError: invalid signature
The JWT provided by the client was signed with a different secret key than the one the server is using for verification, or the token has been tampered with.
fix
Ensure the `authKey` used when initializing `AGServer` is identical to the key used to sign the token. Check for accidental whitespace or character discrepancies. If tokens are issued by an external service, verify key synchronization.
TokenExpiredError: jwt expired
The JWT's expiration time (`exp` claim) has passed, making the token invalid.
fix
Implement token refresh mechanisms on the client-side, where a valid refresh token is used to obtain a new access token before the current one expires. Configure appropriate `expiresIn` values during token signing.
No authKey was specified when creating the AGServer instance.
The `authKey` option was not provided to the `AGServer` constructor, which is required for `ag-auth` to sign and verify tokens.
fix
Pass a secure secret key to the `authKey` option of the `AGServer` constructor: `new AGServer({ authKey: process.env.AUTH_SECRET_KEY });`
Upgrade
Version history
2.1.1latest on npm
Audit
Dependencies
jsonwebtokenrequiredCore dependency for creating, signing, and verifying JWTs.
sc-errorsrequiredProvides standardized error classes for SocketCluster, used for authentication-related errors.
Agent activity
62 hits · last 30 days
node
56
OpenAI (training)
1
Resources
ag-auth — npm install ag-auth · libregistry