Skip to content

SyedShaheerHussain/JavaScript-Malware-Analyzer-HTML

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 

Repository files navigation

🛡️ JS Sentinel

Static JavaScript Malware & Obfuscation Analysis Toolkit

Developed by: Syed Shaheer Hussain Copyright © 2026 Syed Shaheer Hussain. All Rights Reserved. License: MIT Category: Defensive Cybersecurity / Static Application Security Testing (SAST) Language: TypeScript / Node.js Interfaces: Command-Line Interface (CLI) + Standalone Browser GUI (drag & drop)

One-line description: JS Sentinel reads a JavaScript file, never runs it, and tells you — with a numeric risk score — how suspicious it looks, based on eval usage, obfuscation patterns, encoded payloads, hardcoded secrets, and other malware-style techniques.


📷 Screenshots

Screenshot 1

Screenshot 2

Screenshot 3

Screenshot 4

📑 Table of Contents

  1. Introduction & Overview
  2. Mission & Objectives
  3. What Is This Project (In Plain Words)
  4. Core Concepts You Should Know First
  5. Features & Functions
  6. Technologies Used
  7. Architecture Overview
  8. Flow Chart — How a Scan Happens
  9. Folder Structure
  10. File-by-File Explanation
  11. Risk Scoring Explained
  12. Installation Guide (Step by Step)
  13. How to Run — CLI Mode
  14. How to Run — Browser GUI Mode
  15. Where Does It Open? Is There a Host/Server/Login?
  16. Every Button & Screen in the GUI, Explained
  17. Sample Scan Walkthrough
  18. Advantages
  19. Disadvantages & Limitations
  20. Cautions & Important Notes
  21. Safety: Does This Tool Put You at Risk?
  22. Disclaimer
  23. What Was Studied / Learned Building This
  24. Future Enhancements & Roadmap
  25. Tags
  26. License & Copyright

📖 Introduction & Overview

JS Sentinel is a defensive, read-only static analysis tool for JavaScript files. It was built to answer one question quickly and safely:

"Is this .js file behaving like malware, or is it just normal code?"

It does this without ever executing the file it analyzes. Instead, it:

  • Parses the file into an Abstract Syntax Tree (AST) and walks through it looking for dangerous function calls (eval, Function(), etc.)
  • Runs a battery of regex/heuristic rules to catch obfuscation techniques (packers, JSFuck, hex/unicode escaping, anti-debugging tricks)
  • Finds and recursively decodes base64/hex-encoded strings hidden inside the file
  • Scans for hardcoded secrets (AWS keys, GitHub tokens, private keys, JWTs), crypto-miner signatures, and browser fingerprinting code
  • Combines everything into a weighted numeric risk score, translated into a human-friendly level: Safe → Low → Medium → High → Critical

It ships in two working forms:

Mode What it is Who it's for
🖥️ CLI A Node.js command-line tool (jssentinel scan file.js) Developers, CI/CD pipelines, terminal users
🌐 Browser GUI One self-contained .html file with drag-and-drop Anyone who prefers a visual, no-terminal experience

Both modes share the exact same analysis engine — same rules, same scoring, same results — so you can pick whichever is more convenient.


🎯 Mission & Objectives

  • ✅ Give developers and students a safe, transparent way to inspect suspicious JavaScript before running it
  • ✅ Demonstrate real static-analysis engineering: AST parsing, entropy math, regex signature design, weighted risk scoring
  • ✅ Keep the tool 100% read-only — analysis must never execute, eval, or run the target file
  • ✅ Make the tool usable by both terminal users (CLI) and non-technical users (browser GUI)
  • ✅ Keep everything local and private — no file is ever uploaded to a server or third party
  • ✅ Serve as an extensible portfolio-grade security project, with room to grow into a full platform (REST API, dashboard, YARA rules, etc.)

🧩 What Is This Project (In Plain Words)

Imagine you downloaded a .js file from somewhere and you're not sure if it's safe to run. Opening it in a text editor, it looks like a wall of confusing, minified gibberish. You don't want to just run it and find out the hard way.

JS Sentinel is like a metal detector for JavaScript: you wave the file through it, and it beeps loudly (a high risk score) if it detects things like:

  • Code that hides and later executes itself (eval(atob(...)))
  • Code disguised to stop you from reading it (obfuscators, packers, JSFuck)
  • Secret keys or tokens someone forgot to remove
  • Signs of cryptocurrency mining or browser fingerprinting
  • Code that tries to detect if it's being watched/debugged (so it can behave differently under analysis)

It never tells you "this file is 100% malware" — no static tool honestly can — but it gives you a fast, evidence-backed signal so you know whether a file deserves a closer, manual look.


🧠 Core Concepts You Should Know First

Concept Plain-English Explanation
AST (Abstract Syntax Tree) A tree-shaped representation of code structure, produced by a parser. Instead of treating code as plain text, JS Sentinel understands it as "this is a function call," "this is an assignment," etc. — much more reliable than simple text search.
Obfuscation Deliberately making code hard to read (renaming variables to _0x1a2b, packing code into a compressed blob, encoding strings) — legitimate for minification, but heavily abused by malware authors to hide intent.
Entropy (Shannon Entropy) A mathematical measure (0–8 bits/char) of how "random" a block of text looks. Hand-written code has low entropy; encrypted or compressed data has high entropy. High entropy in a .js file is a red flag.
Base64 / Hex Encoding Common ways to represent binary or hidden text as printable characters. Malware often base64-encodes a malicious URL or command so it doesn't appear as plain text in the file.
Signature Scanning Looking for known fixed patterns (like AKIA... for AWS keys, or coinhive for a known miner) — same idea as antivirus signature databases, but for source code patterns instead of binaries.
Risk Scoring Every suspicious finding is worth a certain number of points. All points are added up into one score, which is then mapped to a risk band (Safe/Low/Medium/High/Critical).
Static Analysis Analyzing code without running it — as opposed to "dynamic analysis" (sandboxing and actually executing the code to observe behavior). JS Sentinel is a static analyzer only.

✨ Features & Functions

1. AST-Based Dangerous API Detection

  • Detects eval(), Function() / new Function()
  • Detects setTimeout() / setInterval() called with a string argument (a hidden eval)
  • Detects DOM injection sinks: document.write(), innerHTML, outerHTML, insertAdjacentHTML
  • Detects network primitives: fetch, XMLHttpRequest, WebSocket, importScripts
  • Detects decode primitives: atob, unescape
  • Detects suspicious aliasing (e.g. const e = eval; to dodge simple text scanners)
  • Reports the exact line number and a short code snippet for every finding

2. Obfuscation & Anti-Analysis Detection

  • Dean Edwards Packer signature (eval(function(p,a,c,k,e,d)...)
  • JSFuck encoding (code written using only []()!+)
  • AAEncode / JJEncode style encoding
  • Heavy \xNN / \uNNNN escape sequence usage
  • String-array indirection (_0x1a2b arrays + decoder function — the signature of tools like javascript-obfuscator)
  • Self-defending / anti-tamper code patterns
  • debugger; statement flooding (freezes attached DevTools)
  • DevTools / VM / sandbox detection heuristics (navigator.webdriver, window-size delta checks, etc.)
  • Headless browser fingerprint checks (Puppeteer, Playwright, HeadlessChrome)
  • Control-flow flattening dispatch-loop pattern (while(true) { switch(...) })
  • Overall file entropy measurement
  • Widespread hex-style identifier renaming detection

3. Base64 / Hex Payload Decoder

  • Scans every string literal in the file
  • Automatically detects and decodes base64 and hex encoded strings
  • Recursively decodes up to 5 nested layers (multi-stage droppers often encode a payload more than once)
  • Flags any decoded content that itself contains a URL, an IP address, or exec-like keywords (fetch(, powershell, /bin/sh, etc.)
  • Reports entropy of the decoded content too

4. Signature Scanner (Secrets / Miners / Fingerprinting)

  • Hardcoded secrets: AWS Access Keys, GitHub/Slack/Stripe/OpenAI tokens, PEM private key blocks, JWT-like tokens (all redacted in the report, never shown in full)
  • Crypto-miner references: CoinHive/CryptoNight signatures, stratum+tcp:// mining-pool protocol, WebAssembly + hashrate/Monero keyword combos
  • Browser fingerprinting: Canvas fingerprinting, AudioContext fingerprinting, navigator hardware/battery fingerprinting
  • Suspicious network patterns: URL shorteners (bit.ly, tinyurl, etc.), raw IP-based URLs
  • Anti-analysis: console.log/warn/error overwrite (used to silence debugging output)

5. Risk Scoring Engine

  • Every finding carries a point value based on severity
  • Decoded payloads add extra weight if suspicious, high-entropy, or nested
  • Final score is mapped to a band: Safe (0–20) → Low (21–50) → Medium (51–100) → High (101–200) → Critical (201+)

6. Reporting

  • Console report — colorized table, printed directly in the terminal
  • JSON report — full machine-readable result, for CI pipelines or other tools
  • Markdown report — human-readable .md file with tables and code blocks
  • HTML report — a polished, styled, single-file report you can open in any browser

7. Browser Drag-and-Drop GUI

  • One self-contained .html file, no install required
  • Drag a .js file onto the page (or click to browse)
  • Instant results, rendered as the same styled report
  • "Download JSON" button to save the raw result
  • 100% client-side — nothing is uploaded anywhere

8. CI/CD-Friendly Exit Codes

  • scan command exits with code 2 if the worst file scanned is High or Critical risk — perfect for failing a CI build automatically

🛠️ Technologies Used

Category Technology Purpose
Language TypeScript Type-safe source code for the whole engine and CLI
Runtime Node.js (18+, tested on 22) Executes the CLI
AST Parsing @babel/parser, @babel/traverse, @babel/types Parses JavaScript into an AST and walks it
CLI Framework commander Defines scan / report / decode subcommands and flags
Terminal Styling chalk Colorized console output
Terminal Tables cli-table3 Renders the findings table in the terminal
Bundler (GUI only) esbuild Bundles the analyzer engine into a single browser-ready JS file
Browser APIs File API, Web Crypto API (SubtleCrypto), TextDecoder Reads dropped files, computes SHA-256, and decodes bytes — all natively in-browser, no external libraries
Build Tooling tsc (TypeScript Compiler) Compiles src/*.ts into runnable dist/*.js

Note: the base64/hex decoder is written in pure JavaScript (no Buffer, no Node-only APIs) specifically so the exact same code can run unmodified in both Node (CLI) and the browser (GUI).


🏗️ Architecture Overview

JS Sentinel has a single shared analysis core consumed by two different front ends:

                    ┌────────────────────────┐
                    │   Analysis Core         │
                    │  (src/analyzer/*.ts)    │
                    │                         │
                    │  • astAnalyzer          │
                    │  • obfuscationDetector  │
                    │  • base64Analyzer       │
                    │  • signatureScanner     │
                    │  • riskScorer           │
                    │  • util (entropy, etc.) │
                    └───────────┬─────────────┘
                                │
                 ┌──────────────┴───────────────┐
                 │                               │
        ┌────────▼─────────┐           ┌─────────▼──────────┐
        │  Node CLI          │           │  Browser Bundle     │
        │  src/scanner.ts    │           │  src/web/           │
        │  src/cli.ts        │           │  browser-entry.ts   │
        │  (reads files with │           │  (reads dropped     │
        │   fs, hashes with  │           │   files with the    │
        │   Node crypto)     │           │   File API + Web    │
        │                    │           │   Crypto API)       │
        └────────┬───────────┘           └─────────┬───────────┘
                 │                                 │
        ┌────────▼─────────┐           ┌───────────▼───────────┐
        │ Console / JSON /  │           │  jssentinel-web.html   │
        │ Markdown / HTML   │           │  (drag & drop UI,      │
        │ report files      │           │   renders report live) │
        └───────────────────┘           └────────────────────────┘

Both front ends call the same functions from src/analyzer/, so results are guaranteed to be identical no matter which one you use.


🔄 Flow Chart — How a Scan Happens

 START
   │
   ▼
 Read source code (from disk in CLI, or via File API in browser)
   │
   ▼
 Compute SHA-256 hash + file size
   │
   ▼
 ┌────────────────────────────────────────────┐
 │ Run 4 engines in parallel (logically):     │
 │                                             │
 │ 1) astAnalyzer.ts     → AST walk findings   │
 │ 2) obfuscationDetector→ regex/entropy rules │
 │ 3) signatureScanner   → secrets/miner rules │
 │ 4) base64Analyzer.ts  → decode + inspect    │
 └────────────────────────────────────────────┘
   │
   ▼
 Merge all findings + decoded payloads
   │
   ▼
 riskScorer.ts → sum weighted points → map to Safe/Low/Medium/High/Critical
   │
   ▼
 Build AnalysisResult object
   │
   ▼
 ┌───────────────┬───────────────┬───────────────┬───────────────┐
 │ Console table  │ JSON file      │ Markdown file  │ HTML file/GUI  │
 └───────────────┴───────────────┴───────────────┴───────────────┘
   │
   ▼
  END (exit code 2 if High/Critical, for CI use)

📁 Folder Structure

js-sentinel/
├── src/
│   ├── types.ts                    # Shared TypeScript interfaces (Finding, AnalysisResult, DecodedPayload)
│   ├── scanner.ts                  # Node-only orchestrator: reads a file, calls all engines, hashes it
│   ├── cli.ts                      # Commander-based CLI entry point (scan / report / decode commands)
│   │
│   ├── analyzer/                   # The shared, environment-agnostic analysis engine
│   │   ├── util.ts                 # Shannon entropy, URL/IP extraction, base64-shape check
│   │   ├── astAnalyzer.ts          # Babel-parser AST walker — dangerous API detection
│   │   ├── obfuscationDetector.ts  # Regex + entropy heuristics for obfuscation/anti-analysis
│   │   ├── base64Analyzer.ts       # Pure-JS recursive base64/hex decoder
│   │   ├── signatureScanner.ts     # Secrets, crypto-miner, fingerprinting regex signatures
│   │   └── riskScorer.ts           # Point aggregation + Safe/Low/Medium/High/Critical bands
│   │
│   ├── report/
│   │   └── reportGenerator.ts      # Console, JSON, Markdown, and HTML renderers
│   │
│   └── web/                        # Everything needed for the browser GUI
│       ├── browser-entry.ts        # Browser-safe entry point → exposes window.jsSentinelScan
│       ├── index.template.html     # Drag-and-drop UI shell (bundle gets injected here)
│       └── bundle.js               # (generated by esbuild — not committed to git)
│
├── scripts/
│   └── build-web.js                # Injects bundle.js into index.template.html → jssentinel-web.html
│
├── samples/
│   ├── benign.js                   # Scores 0 / Safe — sanity check file
│   └── suspicious.js               # Synthetic fixture that trips every detection engine
│
├── jssentinel-web.html              # ⭐ Generated, ready-to-use standalone browser scanner
├── package.json                     # Dependencies, scripts, metadata
├── tsconfig.json                    # TypeScript compiler configuration
├── .gitignore
└── README.md

📜 File-by-File Explanation

File What it does
src/types.ts Defines the shapes every other file relies on: Finding (one detection), DecodedPayload (one decoded string), AnalysisResult (the full report object).
src/analyzer/util.ts Small math/text helpers: shannonEntropy() computes randomness of text; extractUrls()/extractIps() pull URLs/IPs out of any string; looksLikeBase64() sanity-checks a string's shape before trying to decode it.
src/analyzer/astAnalyzer.ts Parses the file with Babel's parser, then walks the resulting tree looking for calls to eval, Function, string-based timers, DOM sinks, and network APIs. Falls back to a looser parse mode if the strict parse fails (handles legacy/malformed scripts).
src/analyzer/obfuscationDetector.ts A table-driven rule engine — each rule is a { title, severity, points, test(code) } object. Runs every rule against the raw source text, plus a separate whole-file entropy check and a hex-identifier-density check.
src/analyzer/base64Analyzer.ts Finds all string literals ≥16 characters, checks if each looks like base64 or hex, decodes it with a pure-JavaScript decoder (works identically in Node and browser), and recurses up to 5 levels if the decoded output is itself encoded.
src/analyzer/signatureScanner.ts Another table-driven rule engine, this time using regex signatures for secrets, crypto-miners, and fingerprinting. Secret matches are automatically redacted (AKIA****************MPLE) before being placed in any report.
src/analyzer/riskScorer.ts Adds up every finding's points, adds bonus weight for suspicious/high-entropy/nested decoded payloads, and converts the final number into a Safe/Low/Medium/High/Critical label using fixed score bands.
src/scanner.ts The Node-only glue: reads the file from disk with fs, hashes it with Node's crypto module, calls all four analyzer engines, and returns one AnalysisResult.
src/cli.ts Defines the jssentinel command-line tool using commander: scan, report, and decode subcommands, with --json, --quiet, --format, --out flags.
src/report/reportGenerator.ts Turns an AnalysisResult into four different outputs: a colorized terminal table (printConsoleReport), JSON text (toJson), a Markdown document (toMarkdown), and a styled standalone HTML page (toHtml).
src/web/browser-entry.ts The browser equivalent of scanner.ts. Same four engines, but hashes with the Web Crypto API (crypto.subtle.digest) instead of Node's crypto, since browsers don't have Node's crypto module. Exposes everything as window.jsSentinelScan(code, fileName).
src/web/index.template.html The visual shell: the drag-and-drop zone, result cards, findings table, and all the JavaScript that wires up drag/drop events and renders the report as HTML. Contains a placeholder (__BUNDLE__) where the compiled engine gets inserted.
scripts/build-web.js A tiny Node script that reads index.template.html and bundle.js, replaces the placeholder with the bundle's contents, and writes the final jssentinel-web.html to the project root.
samples/benign.js A small, harmless script used to confirm the tool correctly reports 0 / Safe on normal code.
samples/suspicious.js A synthetic test file containing eval(atob(...)), string-based setTimeout, document.write, debugger; flooding, and a base64-encoded (harmless) payload — built specifically to exercise every detection rule at once. Nothing in it actually does anything dangerous; the "payload" is just console.log, and the risky call is commented out.

🧮 Risk Scoring Explained

Every finding has a severity and a point value:

Severity Typical Points
Low 5–10
Medium 10–20
High 20–35
Critical 40–100+

Formula:

riskScore = Σ(points of every finding)
          + 20  for each decoded payload flagged "suspicious"
          + 10  for each decoded payload with entropy ≥ 5.5
          + 10  for each decoded payload nested 2+ layers deep

Final band:

Score Range Risk Level Meaning
0 – 20 🟢 Safe Nothing notable found
21 – 50 🔵 Low Minor patterns, likely benign
51 – 100 🟡 Medium Worth a manual look
101 – 200 🟠 High Multiple strong indicators
201+ 🔴 Critical Very strong malware-style signal

⚙️ Installation Guide (Step by Step)

✅ Requirement: Node.js

  1. Download and install Node.js (version 18 or newer, 20/22 recommended) from https://nodejs.org
  2. Confirm it installed correctly:
    node -v
    npm -v

✅ Step 1 — Get the project

Extract the project folder (js-sentinel) anywhere on your computer, e.g.:

  • Windows: C:\Projects\js-sentinel
  • macOS/Linux: ~/js-sentinel

✅ Step 2 — Open a terminal inside the folder

cd js-sentinel

✅ Step 3 — Install dependencies

npm install

This downloads everything listed in package.json (Babel parser, commander, chalk, etc.) into a local node_modules folder.

✅ Step 4 — Build the CLI

npm run build

This compiles all TypeScript source files (src/**/*.ts) into runnable JavaScript inside dist/.

✅ Step 5 (optional) — Rebuild the browser GUI

Only needed if you changed any analyzer source code — the shipped jssentinel-web.html already works out of the box.

npm run build:web

Installation is now complete. You can use either the CLI or the browser GUI from here.


▶️ How to Run — CLI Mode

All commands are run from inside the project folder.

Scan a single file

node dist/cli.js scan path/to/file.js

Scan an entire folder (recursively finds .js/.mjs/.cjs)

node dist/cli.js scan path/to/project/

Get raw JSON output (for scripts / CI)

node dist/cli.js scan file.js --json

Get just the score and level (quick check)

node dist/cli.js scan file.js --quiet

Save a report to disk

node dist/cli.js report file.js --format md   -o report.md
node dist/cli.js report file.js --format json -o report.json
node dist/cli.js report file.js --format html -o report.html

Just decode embedded base64/hex strings

node dist/cli.js decode file.js

Try it on the included samples right now

node dist/cli.js scan samples/benign.js       # → 0 / Safe
node dist/cli.js scan samples/suspicious.js   # → 125 / High

Optional: install it as a global jssentinel command

npm link
jssentinel scan somefile.js

🌐 How to Run — Browser GUI Mode

No terminal needed at all for this mode.

  1. Locate jssentinel-web.html in the project's root folder
  2. Double-click it — it opens directly in your default browser (Chrome, Edge, Firefox, etc.)
  3. Drag a .js file onto the dashed drop zone — or click the drop zone to open a file picker instead
  4. The report appears instantly below: risk score, risk level, findings table, decoded payloads, URLs, IPs
  5. Click "Scan another file" to reset and analyze a different file
  6. Click "Download JSON" to save the raw result to your computer

You can also open it from a terminal if you prefer:

start report.html        # Windows
open report.html          # macOS
xdg-open report.html       # Linux

(Same command works for jssentinel-web.html.)


🌍 Where Does It Open? Is There a Host/Server/Login?

This is an important point of clarity, since some tools do require a server, host address, or login credentials — JS Sentinel does not:

Question Answer
Does it run on localhost? No. There is no server process at all.
Is there a port number, host, or URL to visit? No. You open the HTML file directly from your file system — the address bar will show a file:/// path, not http:// or localhost.
Do I need a username or password? No. There is no login system, no accounts, no backend.
Which browser does it open in? Whatever your default browser is (Chrome, Edge, Firefox, Safari, Brave — all work, since it's plain HTML/CSS/JS).
Is my file uploaded anywhere? No. The file is read using your browser's built-in File API and analyzed entirely inside the browser tab, in memory. Nothing leaves your device — there is no network request at all when scanning.
Does this replace or relate to phishing/email tools? No. This project has nothing to do with phishing simulation, email security, or credential capture — it is a JavaScript static malware analyzer. If you were thinking of a phishing-related project, that would be a separate tool entirely.

🖱️ Every Button & Screen in the GUI, Explained

Element What it does
Drop zone (dashed box, "Drag a .js file here, or click to choose one") Accepts a dragged file, or opens your OS file picker when clicked. Only .js, .mjs, .cjs files are expected.
Status line (small text under the drop zone) Shows which file is being scanned, and the timestamp once scanning finishes.
"Scan another file" button Clears the current report and status so you can drop a new file. Does not reload the page.
"Download JSON" button Saves the full AnalysisResult (all findings, decoded payloads, URLs, IPs, score) as a .json file using your browser's normal download flow.
Metadata cards (File / Size / SHA256 / Findings) Quick-glance facts about the scanned file. The SHA256 hash lets you uniquely identify this exact file version later.
Risk banner (big colored number) The overall score and level — green (Safe) through red (Critical).
Findings table Every individual detection: severity badge, points, category, title + description, and (when applicable) the exact line number and a code snippet as evidence.
Decoded Payloads section Shows any base64/hex string that was found and decoded, with its entropy and whether it was flagged suspicious (e.g. contained a URL).
URLs / IP Addresses sections Any URLs or IP addresses found anywhere in the raw file text.

🧪 Sample Scan Walkthrough

Running the included samples/suspicious.js (a harmless test fixture) produces:

Risk score: 125 (High)

Findings (7):
  HIGH    20 pts  dynamic-execution  Use of eval()
  MEDIUM  20 pts  anti-debugging     debugger; statement flooding
  MEDIUM  20 pts  anti-analysis      DevTools / VM detection heuristics
  MEDIUM  15 pts  dynamic-execution  setTimeout invoked with a string argument
  MEDIUM  15 pts  obfuscation        High overall file entropy (5.28 bits/char)
  MEDIUM  10 pts  dom-abuse          document.write() usage
  LOW      5 pts  obfuscation        Decoding primitive used: atob

Decoded Payloads (1):
  base64, depth 0, entropy 4.78, [suspicious]
  → fetch("http://198.51.100.23/beacon"); console.log("test payload only, harmless");

Running samples/benign.js (plain, ordinary code) produces:

Risk score: 0 (Safe)
No suspicious patterns detected by current rule set.

✅ Advantages

  • 🔒 Completely safe to use on untrusted files — the analyzed code is never executed
  • Fast — pure static analysis, no sandboxing or VM overhead
  • 🧩 Two interfaces from one engine — CLI for developers/CI, browser GUI for everyone else
  • 🌐 No installation needed for the GUI — one HTML file works anywhere
  • 🔐 Privacy-respecting — nothing is ever uploaded or sent over a network
  • 🧱 Transparent scoring — every point is traceable to a specific, documented rule
  • 🧵 Extensible — new detection rules are simple table entries, not deep rewrites
  • 🖥️ CI/CD-ready — non-zero exit code on high-risk findings

⚠️ Disadvantages & Limitations

  • 🚫 Not a guarantee — like all static analyzers, it can produce false positives (legitimate minified code can trip entropy/obfuscation rules) and false negatives (a sufficiently novel technique may not match any rule)
  • 🚫 No dynamic/behavioral analysis — it cannot see what code actually does at runtime, only what it looks like it might do
  • 🚫 Regex/heuristic rules can be evaded by a sufficiently motivated obfuscator designed specifically to bypass known signatures
  • 🚫 No built-in threat intelligence feed — it doesn't check hashes/URLs against live databases like VirusTotal (this was scoped out of the current version)
  • 🚫 Large first-time browser bundle (~1.3MB, because it embeds a full JavaScript parser) — irrelevant for local use, but worth knowing
  • 🚫 English-only report text — no localization yet

🚨 Cautions & Important Notes

⚠️ This tool is an aid to human judgment, not a replacement for it. A "Safe" score does not certify a file is harmless, and a "Critical" score does not certify a file is definitely malicious — always combine this with your own review and, where appropriate, established antivirus/EDR tools.

  • ℹ️ The bundled samples/suspicious.js is a synthetic test fixture only — its embedded "payload" is intentionally harmless (console.log), and the one genuinely risky call is left commented out. It exists purely so every rule has something to detect.
  • ℹ️ Secret-detection findings (AWS keys, tokens, etc.) are shown redacted in reports — never paste a report externally assuming the redaction hides everything perfectly; treat any detected secret as compromised and rotate it.
  • ℹ️ Always re-build (npm run build / npm run build:web) after modifying any source file — the CLI runs compiled dist/ output, and the GUI runs the bundled jssentinel-web.html; edits to .ts files alone won't change behavior until rebuilt.

🛡️ Safety: Does This Tool Put You at Risk?

No, by design. Here's exactly why:

  1. The analyzer only reads text and parses it into a tree — parsing is not the same as running. Babel's parser builds a data structure describing the code; it never invokes any function found inside it.
  2. There is no eval, Function, require, or import of the analyzed file anywhere in the JS Sentinel source code — the target file is pure input data, never treated as executable code by the tool itself.
  3. The browser GUI reads the dropped file using the standard File API (file.text()), which returns the file's contents as a plain string — it does not attach the file as a <script> tag or execute it in any way.
  4. No network calls are made during a scan. URLs found inside a scanned file are only ever displayed as text — JS Sentinel never visits them.

📛 Disclaimer

This project is provided for educational and defensive security purposes only. It is intended to help developers, students, and security enthusiasts learn about and detect suspicious JavaScript patterns.

  • It is not a certified antivirus product and carries no warranty of any kind, express or implied.
  • The author (Syed Shaheer Hussain) is not responsible for any damage, data loss, or security incident resulting from reliance on this tool's output.
  • Always use additional layers of security (updated antivirus, sandboxed execution, manual code review, threat intelligence services) for anything beyond casual/educational inspection.
  • Do not use this tool, or any output/technique from it, to build, conceal, or distribute malicious software. It exists strictly for defense and detection.

📚 What Was Studied / Learned Building This

Building JS Sentinel involved hands-on study and application of:

  • Abstract Syntax Trees and how JavaScript parsers (Babel) turn source text into structured, traversable trees
  • Static Application Security Testing (SAST) principles — how real security tools reason about code without executing it
  • Information theory basics — Shannon entropy, and why encrypted/compressed/packed data looks statistically different from hand-written source
  • Real-world malware obfuscation techniques — packers, JSFuck, AAEncode/JJEncode, control-flow flattening, anti-debugging tricks, sandbox/headless-browser evasion
  • Secret-pattern engineering — how services like GitHub's secret scanning recognize credential formats (AWS, Stripe, Slack, JWT, PEM, etc.) via regex
  • Cross-environment JavaScript engineering — writing decoder logic that works identically under Node.js (Buffer) and in a browser (no Buffer), by implementing base64/hex decoding in pure JS instead
  • CLI design with commander — subcommands, flags, exit codes for CI/CD integration
  • Bundling for the browser with esbuild — turning a modular TypeScript codebase into a single deployable script
  • Weighted risk-scoring system design — translating many small, boolean-ish detections into one continuous, actionable number

🚧 Future Enhancements & Roadmap

The current release is the core static-analysis engine + CLI + browser GUI. Planned/possible next phases (not yet implemented):

  • 🔲 REST API (Express) wrapping the same engine for server-side integration
  • 🔲 Full Electron/React desktop dashboard (multi-file workspace, AST explorer, charts)
  • 🔲 YARA rule engine integration for custom/community rule packs
  • 🔲 VirusTotal / ClamAV integration for hash and signature cross-checking
  • 🔲 Package/dependency & supply-chain analysis (package.json, install scripts, typosquatting checks)
  • 🔲 Source map recovery for minified/bundled production code
  • 🔲 SARIF export (for GitHub code-scanning integration)
  • 🔲 MITRE ATT&CK / OWASP mapping per finding
  • 🔲 Docker image + docker-compose for server deployments
  • 🔲 Role-based access control (RBAC) for multi-user/team deployments
  • 🔲 Automatic rule-pack updates

🏷️ Tags

#JavaScript #StaticAnalysis #MalwareAnalysis #Cybersecurity #ObfuscationDetection #SAST #TypeScript #NodeJS #CLI #DefensiveSecurity #AST #RiskScoring #OpenSource #SyedShaheerHussain


📄 License & Copyright

MIT License

Copyright (c) 2026 Syed Shaheer Hussain

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, subject to standard MIT License terms.

Developed by: Syed Shaheer Hussain Copyright © 2026 Syed Shaheer Hussain. All Rights Reserved.


End of documentation.

Releases

No releases published

Packages

 
 
 

Contributors