---
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