Unsafe dynamic method access

How to restrict which global JavaScript functions a caller can select.

Description

Using a URL fragment or a request query parameter to select a global function can expose functions the application never intended to offer. This applies to window in a browser, global in Node.js, and globalThis in either environment. eval executes a string as code. Function creates a function from a string, and its body runs when the new function is called. If the caller also controls the string that executes, their JavaScript can run with the permissions of the page or server process.

Potential impact

  • In a browser, code can access page content and any cookies or tokens available to scripts on that origin, or perform actions with the user's permissions.
  • On a server, code can access environment variables and application data available to the process, or change application state.
  • Long-running code can block a browser tab or the server's event loop.

Remediation

  • Register only the operations you intend to expose in a dedicated object or Map. Use Object.hasOwn(API, name) for an object or actions.has(name) for a Map, and reject unknown names.
  • If you need a global function, keep a fixed allow-list of names for that operation, such as encodeURIComponent and decodeURIComponent. Check the argument types as well.
  • Keep functions that treat strings as code, including eval and Function, out of the allow-list. Browser timers such as setTimeout and setInterval can also execute strings. Node.js timers require a callback function.
  • In browsers, enforce a script-src policy that omits 'unsafe-eval' to restrict string execution. In Node.js, --disallow-code-generation-from-strings restricts eval and Function when the application can run with that option.

Examples

The browser and Express snippets run in their respective environments. In the revised example, the browser and the Express /do route share the callApi helper.

Before

javascript
// Browser example
// The browser takes the function name from the URL fragment.
window.addEventListener('load', () => {
  const name = location.hash.slice(1);
  window[name]('42');
});

// Node.js (Express) example
const express = require('express');
const app = express();
app.get('/do', (req, res) => {
  // The server takes the function name from a request query parameter.
  const action = req.query.action;
  globalThis[action]('42');
  res.send('done');
});

After

javascript
// Register only public operations on an object with no prototype.
const API = Object.create(null);
API.ping = (d) => 'pong';
API.upper = (d) => String(d || '').toUpperCase();

function callApi(name, data) {
  if (typeof name !== 'string' || !Object.hasOwn(API, name) || typeof API[name] !== 'function') {
    throw new Error('invalid action');
  }
  return API[name](data);
}

// Browser example
window.addEventListener('load', () => {
  const name = location.hash.slice(1);
  try {
    const result = callApi(name, 'hello');
    console.log(result);
  } catch (e) {
    console.warn('blocked');
  }
});

// Node.js (Express) example
const express = require('express');
const app = express();
app.get('/do', (req, res) => {
  try {
    const result = callApi(req.query.action, req.query.data);
    res.json({ ok: true, result });
  } catch {
    res.status(400).json({ ok: false, error: 'invalid action' });
  }
});

// This route allows only the two URI conversion functions.
const SAFE_GLOBALS = Object.freeze(["encodeURIComponent", "decodeURIComponent"]);

app.get('/encode', (req, res, next) => {
  const { action, value = '' } = req.query;
  if (!SAFE_GLOBALS.includes(action) || typeof value !== 'string') {
    return res.status(400).send('invalid action or value');
  }
  try {
    return res.type('text/plain').send(globalThis[action](value));
  } catch (error) {
    if (error instanceof URIError) return res.status(400).send('invalid URI component');
    return next(error);
  }
});

Explanation:

  • Before: In both examples, the caller selects the function name and the argument is the fixed string '42'. Selecting eval evaluates that string as JavaScript. Selecting Function creates a function whose body runs only if the function is called.
  • After: The browser reads the action name from the URL fragment, and the /do route reads it from the query. Both dispatch only to functions registered directly on a dedicated object with no prototype. The separate /encode route allows only two global URI conversion functions, returns their output as text/plain, and responds with HTTP 400 if the input cannot be converted.

References