GuardAPI Logo
GuardAPI

Fix SSRF (Server Side Request Forgery) in ElysiaJS

Server-Side Request Forgery (SSRF) in ElysiaJS occurs when an application fetches a remote resource based on user-supplied input without proper validation. In a Bun/Elysia environment, this typically involves the native 'fetch' API. Attackers exploit this to scan internal networks, access cloud metadata services (like 169.254.169.254), or bypass firewalls by making the server act as a proxy.

The Vulnerable Pattern

import { Elysia } from 'elysia';

new Elysia() .get(‘/fetch-metadata’, async ({ query }) => { // DANGER: Direct use of user input in fetch() const response = await fetch(query.url); return await response.text(); }) .listen(3000);

The Secure Implementation

The secure implementation mitigates SSRF by applying three layers of defense. First, it uses Elysia's TypeBox integration to ensure the input is at least a valid URI format. Second, it parses the string into a URL object to prevent obfuscation attacks (like @ symbols in the hostname). Third, it enforces a strict allowlist of domains and protocols, preventing the server from reaching out to internal IPs, loopback addresses, or cloud-specific metadata endpoints. Additionally, a timeout is implemented to prevent 'Blind SSRF' scenarios where an attacker tries to exhaust server resources by pointing to a slow-responding internal service.

import { Elysia, t } from 'elysia';

const ALLOWED_HOSTS = [‘api.trusted-partner.com’, ‘static.mysite.com’];

new Elysia() .get(‘/fetch-metadata’, async ({ query, set }) => { try { const targetUrl = new URL(query.url);

  // 1. Protocol Whitelisting
  if (targetUrl.protocol !== 'http:' && targetUrl.protocol !== 'https:') {
    set.status = 400;
    return { error: 'Invalid protocol' };
  }

  // 2. Domain Whitelisting
  if (!ALLOWED_HOSTS.includes(targetUrl.hostname)) {
    set.status = 403;
    return { error: 'Forbidden target' };
  }

  const response = await fetch(targetUrl.toString(), {
    signal: AbortSignal.timeout(5000) // 3. Prevent DoS via hanging requests
  });
  
  return await response.text();
} catch (e) {
  set.status = 400;
  return { error: 'Malformed URL' };
}

}, { query: t.Object({ url: t.String({ format: ‘uri’ }) }) }) .listen(3000);

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

Your ElysiaJS API might be exposed to SSRF (Server Side Request Forgery)

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.