Description
When a request supplies an object method's name, JavaScript looks for the property on the object and its prototype chain. If the property is missing or its value is not callable, the call throws a TypeError. If it is callable, the request may invoke a method the application never intended to expose.
Potential impact
- An unknown action can cause the request to fail. In a synchronous Express handler like the one below, Express passes the exception to its error handler.
- A caller may select an internal or inherited method and trigger behavior outside the set of actions the application offers.
Remediation
- For a few operations, use an explicit
switch. For dynamic lookup, register only the functions you intend to expose on a dedicated object. - Use
Object.hasOwnto check that the name is registered directly on the object before reading the value. Verifytypeof value === "function"before calling it, and return an error for unknown or non-callable actions.
Examples
Before
javascript
const actions = {
play(data) {
return data;
},
};
app.get("/perform/:action", (req, res) => {
res.send(actions[req.params.action](req.query.payload));
});
After
javascript
const actions = Object.freeze({
play(data) {
return data;
},
});
app.get("/perform/:action", (req, res) => {
const name = req.params.action;
if (!Object.hasOwn(actions, name) || typeof actions[name] !== "function") {
return res.status(400).send("Unsupported action");
}
return res.json(actions[name](req.query.payload ?? null));
});
Explanation:
- Before: The handler uses the
actionpath parameter directly as a method name. An unregistered name can cause the request to fail or resolve to an inherited method. - After: The handler calls the requested action only when it is registered directly on
actionsand its value is a function. It returns theplayresult as JSON, usingnullwhenpayloadis omitted. Unsupported actions receive HTTP 400.