GuardAPI Logo
GuardAPI

Fix NoSQL Injection in ElysiaJS

NoSQL injection in the Bun/Elysia ecosystem typically manifests when developers pipe raw request bodies directly into database filters. In MongoDB/Mongoose environments, attackers can replace expected strings with query operators like $ne (not equal) or $gt (greater than) to bypass authentication or exfiltrate the entire user table. If you aren't validating the shape of your input, you're giving attackers direct control over your database queries.

The Vulnerable Pattern

import { Elysia } from 'elysia';
import { User } from './models';

const app = new Elysia() .post(‘/auth’, async ({ body }) => { // VULNERABLE: Direct injection via body object. // An attacker sends { “username”: { “$ne”: "" }, “password”: { “$ne”: "" } } // This bypasses credentials and returns the first user in the DB. const user = await User.findOne(body); return user || { error: ‘Unauthorized’ }; }) .listen(3000);

The Secure Implementation

The vulnerability stems from the database driver (like Mongoose) interpreting objects within the query as operators rather than literal values. To fix this, we implement two layers of defense. First, we use Elysia's built-in schema validation (via TypeBox) to ensure 'username' and 'password' are strictly strings; if an attacker sends an object, the request is rejected before it hits the handler. Second, we destructure the body and explicitly cast properties to String() to ensure that even if validation were bypassed, the database driver treats the input as a literal search term, neutralizing any nested MongoDB operators.

import { Elysia, t } from 'elysia';
import { User } from './models';

const app = new Elysia() .post(‘/auth’, async ({ body }) => { const { username, password } = body;

// SECURE: Querying with explicitly destructured and validated fields.
// Even if an object is passed, Elysia's schema validation will strip it
// or the driver will treat the destructured value as a literal string.
const user = await User.findOne({
  username: String(username),
  password: String(password)
});

return user || { error: 'Unauthorized' };

}, { // SECURE: Enforce strict type validation using TypeBox body: t.Object({ username: t.String(), password: t.String() }) }) .listen(3000);

System Alert • ID: 6148
Target: ElysiaJS API
Potential Vulnerability

Your ElysiaJS API might be exposed to NoSQL Injection

74% of ElysiaJS apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.