Token Leakage in Feathersjs with Jwt Tokens
Token Leakage in Feathersjs with Jwt Tokens — how this combination creates or exposes the vulnerability
Token leakage in a FeathersJS application using JWT tokens occurs when JSON Web Tokens are inadvertently exposed beyond the intended access boundaries. FeathersJS, a framework for real-time applications, commonly integrates JWT-based authentication to manage stateless sessions. When misconfigured, this integration can expose tokens through multiple vectors, including server-side logs, error messages, browser storage, and insecure transport channels.
One common pattern in FeathersJS is the use of the @feathersjs/authentication and @feathersjs/authentication-jwt packages to handle authentication. These packages set tokens in HTTP-only cookies or in custom headers, but developers may inadvertently expose tokens by logging request or authentication objects. For example, if a service hook logs the entire authentication payload, the JWT can be written to console or monitoring systems, leading to leakage through log aggregation platforms.
Another vector arises from improper CORS or cookie settings. If the FeathersJS server does not explicitly restrict origins or set the Secure and SameSite attributes on cookies, tokens can be exposed to cross-origin requests or transmitted over non-HTTPS connections. An attacker who can observe or intercept such traffic may capture the token and replay it to impersonate the victim user.
Error handling misconfigurations also contribute to leakage. FeathersJS by default provides detailed error messages. If an invalid or expired JWT is sent, the framework may return stack traces or validation details that include token fragments or related metadata. These responses, when captured by browsers, proxies, or third-party error tracking services, can store sensitive token data inadvertently.
Client-side storage decisions further amplify risk. When frontend applications using frameworks such as React or Vue store JWTs in local storage or session storage to maintain user sessions, tokens become accessible to JavaScript running in the browser. If the FeathersJS client integration is configured to attach tokens from storage to request headers, any cross-site scripting (XSS) vulnerability can lead to token exfiltration. This is particularly critical in FeathersJS clients that automatically attach tokens to every outgoing call without additional safeguards.
Finally, the interaction between unauthenticated service routes and token handling can expose endpoints that should not require authentication but inadvertently propagate tokens. If a FeathersJS service is configured to allow public access and the client code attaches a JWT globally, tokens may be sent to and logged by unprotected routes, expanding the exposure surface beyond authenticated endpoints only.
Jwt Tokens-Specific Remediation in Feathersjs — concrete code fixes
To mitigate token leakage in FeathersJS when using JWT tokens, apply targeted configuration and code changes that reduce exposure across logging, transport, storage, and error handling paths.
First, configure JWT authentication to use HTTP-only, Secure, and SameSite cookies instead of client-side accessible storage. In your FeathersJS authentication setup, set the cookie option explicitly and avoid returning tokens in authentication responses.
const authentication = require('@feathersjs/authentication');
const jwt = require('@feathersjs/authentication-jwt');
app.configure(authentication({
secret: process.env.AUTH_SECRET,
strategies: ['jwt'],
cookie: {
name: 'feathers-jwt',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/'
}
}));
app.configure(jwt());
Second, ensure that authentication hooks do not log or serialize the token. Review hooks and service mixins to remove any code that writes the authentication object to logs. If debugging is required, redact the token value explicitly.
// Avoid logging the full authentication object
app.service('users').hooks({
before: {
create: [context => {
// Do not log context.params.authToken or similar fields
if (context.params && context.params.auth) {
const { token, ...safeAuth } = context.params.auth;
context.params.auth = safeAuth;
}
return context;
}]
}
});
Third, enforce strict CORS and transport security. Configure CORS to allow only trusted origins and ensure that JWT-related endpoints require secure transport.
const cors = require('@koa/cors');
app.use(cors({
origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : [],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
Fourth, customize error handling to prevent token leakage in responses. Replace default error formatting with a handler that removes authentication details from error payloads before they leave the server.
const { GeneralError } = require('@feathersjs/errors');
app.use((error, req, res, next) => {
const isAuthError = error.name === 'NotAuthenticated' || error.message.includes('token');
if (isAuthError) {
// Return a generic message without token or stack details
return next(new GeneralError('Invalid request'));
}
next(error);
});
Fifth, configure the FeathersJS client to avoid attaching tokens to requests that do not require authentication. When initializing the client, conditionally set the token only for authenticated services.
const { Client } = require('@feathersjs/client');
const authentication = require('@feathersjs/authentication-client');
const client = new Client();
client.configure(authentication({
storage: null, // Do not persist tokens in client storage
strategies: {
jwt: {
name: 'jwt',
implementation: authParams => {
// Attach token only when explicitly needed
return authParams && authParams.token ? { Authorization: `Bearer ${authParams.token}` } : {};
}
}
}
}));
These measures reduce the likelihood of token leakage by controlling where tokens are stored, how they are transmitted, and how errors and logs are handled within a FeathersJS application using JWT tokens.
middleBrick scans can identify token leakage risks in FeathersJS JWT setups
middleBrick can scan an unauthenticated API endpoint and detect patterns that indicate token leakage risks, such as missing Secure cookie flags, CORS misconfigurations, and verbose error handling that may expose JWT-related details. By analyzing the OpenAPI/Swagger spec and correlating it with runtime behavior, middleBrick provides findings with severity levels and remediation guidance, helping you address issues like those described above. For ongoing assurance, the Pro plan includes continuous monitoring to detect regressions, and the GitHub Action can fail builds if the security score drops below your defined threshold, while the Web Dashboard lets you track improvements over time.