GuardAPI Logo
GuardAPI

Fix Logic Flow Bypass in Hapi

Logic flow bypass in Hapi.js typically occurs when developers assume a linear execution of routes without enforcing server-side state transitions. Attackers bypass intermediate steps—like MFA challenges or payment confirmations—by directly invoking the final handler. To secure this, you must implement strict state-machine validation using Hapi's route prerequisites ('pre') or lifecycle extensions.

The Vulnerable Pattern

server.route({
  method: 'POST',
  path: '/account/change-email',
  handler: async (request, h) => {
    // VULNERABILITY: Assumes the user has already passed the /verify-otp step
    // An attacker can skip the OTP process and POST directly here.
    const { newEmail } = request.payload;
    await db.users.update(request.auth.credentials.id, { email: newEmail });
    return { success: true };
  }
});

The Secure Implementation

The fix utilizes Hapi's 'pre' prerequisite property to enforce a server-side state check before the main handler executes. Instead of trusting the client's request flow, we query a server-side session store to verify that the 'otp_verified' flag is true. If the prerequisite fails, the handler is never invoked. Finally, the state is cleared post-execution to prevent the reuse of the verified state for subsequent unauthorized actions.

server.route({
  method: 'POST',
  path: '/account/change-email',
  options: {
    pre: [
      {
        method: async (request, h) => {
          const session = await db.sessions.get(request.auth.artifacts.sid);
          if (!session.otp_verified) {
            throw Boom.forbidden('Step bypass detected: OTP verification required');
          }
          return true;
        },
        assign: 'isVerified'
      }
    ],
    handler: async (request, h) => {
      const { newEmail } = request.payload;
      await db.users.update(request.auth.credentials.id, { email: newEmail });
      // Reset state to prevent replay
      await db.sessions.update(request.auth.artifacts.sid, { otp_verified: false });
      return { success: true };
    }
  }
});
System Alert • ID: 3606
Target: Hapi API
Potential Vulnerability

Your Hapi API might be exposed to Logic Flow Bypass

74% of Hapi 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.