Fix Improper Assets Management in Hapi
Improper Assets Management in Hapi.js often stems from 'Inert' misconfigurations that leak sensitive files or undocumented routes that bypass security controls. If you are mapping file systems to URIs without strict boundaries, you are handing attackers a map to your source code, environment variables, and internal tooling.
The Vulnerable Pattern
const Hapi = require('@hapi/hapi'); const Inert = require('@hapi/inert');const init = async () => { const server = Hapi.server({ port: 3000 }); await server.register(Inert);
// VULNERABILITY: Mapping the root directory with directory listing enabled. // This exposes .env, node_modules, and source code. server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: '.', listing: true } } }); await server.start();
}; init();
The Secure Implementation
The vulnerable code suffers from 'Directory Indexing' and 'Path Traversal' risks by serving the root directory ('.') and enabling 'listing: true'. An attacker can browse the entire project structure. The secure implementation follows the Principle of Least Privilege: 1) It uses path.join() to define a strict 'public' jail. 2) It explicitly disables directory listing. 3) It uses environment-based logic to prevent internal 'shadow' routes from being registered in production, ensuring the attack surface is minimized.
const Hapi = require('@hapi/hapi'); const Inert = require('@hapi/inert'); const path = require('path');const init = async () => { const server = Hapi.server({ port: 3000 }); await server.register(Inert);
// SECURE: Jail assets to a specific 'public' folder using absolute paths. // Disable listing and index to prevent reconnaissance. server.route({ method: 'GET', path: '/static/{param*}', handler: { directory: { path: path.join(__dirname, 'public'), listing: false, index: false, redirectToSlash: false } } }); // Only register internal/debug routes in non-production environments if (process.env.NODE_ENV !== 'production') { server.route({ method: 'GET', path: '/debug/status', handler: (request, h) => { return { status: 'ok' }; } }); } await server.start();
}; init();
Your Hapi API
might be exposed to Improper Assets Management
74% of Hapi apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.