When using user-derived strings (e.g., paths, filenames, extensions) to index plain JS objects as lookup tables, do not rely on inherited properties from the prototype chain. Use own-property checks (or Map) and add tests for malicious keys.
Standard
Object.hasOwn(dict, key) before using dict[key], orMap keyed by strings."__proto__", "constructor", "toString", and "prototype" as security test cases.Example (object + own-property check)
type IconSpec = { icon: unknown; className: string };
const BY_EXTENSION: Record<string, IconSpec> = {
ts: { icon: {}, className: "text-sky-600" },
};
function iconForPath(path: string): IconSpec {
const name = path.split(/[\\/]/).pop() ?? path;
const ext = name.includes(".") ? (name.split(".").pop() ?? "").toLowerCase() : "";
// Security: avoid inherited/prototype-chain keys being treated as valid.
if (Object.hasOwn(BY_EXTENSION, ext)) return BY_EXTENSION[ext];
// neutral fallback
return { icon: {}, className: "text-muted-foreground" };
}
Tests to add
path yields keys like __proto__, constructor, or toString.