Publish Factory v3.0 Open-Core teaser
Browse files- .cursor_mcp_config.json +10 -0
- README.md +16 -0
- claude_desktop_config.json +10 -0
- server_free.py +398 -0
- train.parquet +3 -0
.cursor_mcp_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"mcpServers": {
|
| 3 |
+
"npm_postinstall_script_obfuscation_guard": {
|
| 4 |
+
"command": "python",
|
| 5 |
+
"args": [
|
| 6 |
+
"server.py"
|
| 7 |
+
]
|
| 8 |
+
}
|
| 9 |
+
}
|
| 10 |
+
}
|
README.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
tags:
|
| 4 |
+
- mcp
|
| 5 |
+
- cursor
|
| 6 |
+
- claude-desktop
|
| 7 |
+
- ast-guard
|
| 8 |
+
- security
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# npm postinstall & Obfuscated Lifecycle Script Guard MCP (Open-Core Community Teaser)
|
| 12 |
+
|
| 13 |
+
> **Dual-Licensing Notice:** This free Hugging Face teaser (`server_free.py`, max 5 scans, & 50-sample `train.parquet`) is licensed under **CC-BY-NC-4.0** (non-commercial research & local evaluation only).
|
| 14 |
+
> Commercial use, CI/CD SARIF integration (`--scan --sarif --fail-on-critical`), and the full 500-sample AST-mutated corpus + 30-incident `knowledge_base.json` require a commercial license.
|
| 15 |
+
|
| 16 |
+
👉 **[Upgrade to Pro (20% Off with code `LAUNCH20`)](https://emgena.com/trainingslager?product=npm_postinstall_script_obfuscation_guard&coupon=LAUNCH20)**
|
claude_desktop_config.json
ADDED
|
@@ -0,0 +1,10 @@
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
EMGENA SENTINEL MCP SERVER - COMMUNITY EVALUATION EDITION (CC-BY-NC-4.0)
|
| 4 |
+
Package: npm_postinstall_script_obfuscation_guard
|
| 5 |
+
Title: npm postinstall & Obfuscated Lifecycle Script Guard MCP
|
| 6 |
+
Upgrade to Commercial Pro (Unlimited AST Scans + CI/CD SARIF Gate + B2B VAT Invoice):
|
| 7 |
+
https://emgena.com/trainingslager?product=npm_postinstall_script_obfuscation_guard&coupon=LAUNCH20
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import sys, os, json, ast, time, re
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, Dict, List, Tuple
|
| 13 |
+
|
| 14 |
+
if sys.platform == "win32":
|
| 15 |
+
try:
|
| 16 |
+
sys.stdout.reconfigure(encoding="utf-8")
|
| 17 |
+
sys.stderr.reconfigure(encoding="utf-8")
|
| 18 |
+
except Exception:
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
SESSION_SCANS = 0
|
| 22 |
+
MAX_FREE_SCANS = 5
|
| 23 |
+
UPGRADE_URL = "https://emgena.com/trainingslager?product=npm_postinstall_script_obfuscation_guard&coupon=LAUNCH20"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
import math as _math
|
| 27 |
+
|
| 28 |
+
SAFE_VALUE_MARKERS = (
|
| 29 |
+
"redacted", "placeholder", "example", "changeme", "your_", "dummy", "mock",
|
| 30 |
+
"***", "xxxx", "<", "alias/", "vault:", "kms:", "secret_ref", "env:",
|
| 31 |
+
"os.environ", "getenv", "test_", "rfc2606", "rfc5737",
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def _shannon_entropy(data: str) -> float:
|
| 35 |
+
if not data:
|
| 36 |
+
return 0.0
|
| 37 |
+
freq = {}
|
| 38 |
+
for ch in data:
|
| 39 |
+
freq[ch] = freq.get(ch, 0) + 1
|
| 40 |
+
length = len(data)
|
| 41 |
+
return -sum((cnt / length) * _math.log2(cnt / length) for cnt in freq.values())
|
| 42 |
+
|
| 43 |
+
def _mask_preview(val: str) -> str:
|
| 44 |
+
s = str(val).replace("\n", " ").strip()
|
| 45 |
+
if len(s) <= 8:
|
| 46 |
+
return "****"
|
| 47 |
+
return s[:4] + "****" + s[-4:]
|
| 48 |
+
|
| 49 |
+
def _call_name(node: ast.Call) -> str:
|
| 50 |
+
if isinstance(node.func, ast.Name):
|
| 51 |
+
return node.func.id.lower()
|
| 52 |
+
if isinstance(node.func, ast.Attribute):
|
| 53 |
+
return node.func.attr.lower()
|
| 54 |
+
return ""
|
| 55 |
+
|
| 56 |
+
def _full_attr_name(node: ast.AST) -> str:
|
| 57 |
+
parts = []
|
| 58 |
+
cur = node
|
| 59 |
+
while isinstance(cur, ast.Attribute):
|
| 60 |
+
parts.append(cur.attr.lower())
|
| 61 |
+
cur = cur.value
|
| 62 |
+
if isinstance(cur, ast.Name):
|
| 63 |
+
parts.append(cur.id.lower())
|
| 64 |
+
return ".".join(reversed(parts))
|
| 65 |
+
|
| 66 |
+
def _has_kw(node: ast.Call, name: str) -> bool:
|
| 67 |
+
return any(kw.arg and kw.arg.lower() == name.lower() for kw in node.keywords)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
SENSITIVE_VAR_NAMES = {
|
| 71 |
+
"api_key", "apikey", "secret", "secret_key", "private_key", "signing_key",
|
| 72 |
+
"master_key", "aes_key", "rsa_key", "ec_key", "client_secret", "auth_token",
|
| 73 |
+
"access_token", "refresh_token", "bearer_token", "password", "passwd", "pwd",
|
| 74 |
+
"db_password", "credentials", "service_account_json", "mnemonic", "seed_phrase",
|
| 75 |
+
"aws_secret_access_key", "stripe_secret_key", "openai_api_key", "hf_token",
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
DOMAIN_REGEX_RULES = [
|
| 79 |
+
("EMGENA-SEC-001", "CRITICAL", "CWE-798", "PEM / OpenSSH / RSA / EC / PGP Private Key Header",
|
| 80 |
+
re.compile(r"-----BEGIN (?:OPENSSH |RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----|-----BEGIN PGP PRIVATE KEY BLOCK-----")),
|
| 81 |
+
("EMGENA-SEC-002", "CRITICAL", "CWE-798", "AWS Access Key ID (AKIA/ASIA)",
|
| 82 |
+
re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
|
| 83 |
+
("EMGENA-SEC-003", "CRITICAL", "CWE-798", "Stripe Live/Restricted API Key",
|
| 84 |
+
re.compile(r"\b(?:sk|rk)_live_[0-9A-Za-z]{16,}\b")),
|
| 85 |
+
("EMGENA-SEC-004", "CRITICAL", "CWE-798", "GitHub Personal/OAuth/App Access Token",
|
| 86 |
+
re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{20,}\b")),
|
| 87 |
+
("EMGENA-SEC-005", "CRITICAL", "CWE-798", "OpenAI / Anthropic Secret API Key",
|
| 88 |
+
re.compile(r"\bsk-(?:proj-|ant-[A-Za-z0-9-]+-)?[A-Za-z0-9_-]{20,}\b")),
|
| 89 |
+
("EMGENA-SEC-006", "HIGH", "CWE-798", "Hugging Face User Access Token",
|
| 90 |
+
re.compile(r"\bhf_[A-Za-z0-9]{20,}\b")),
|
| 91 |
+
("EMGENA-SEC-007", "CRITICAL", "CWE-798", "GCP Service Account JSON Private Key",
|
| 92 |
+
re.compile(r'"type"\s*:\s*"service_account"|"private_key_id"\s*:\s*"[a-f0-9]{16,}"')),
|
| 93 |
+
("EMGENA-SEC-008", "HIGH", "CWE-798", "Slack Bot/User Token",
|
| 94 |
+
re.compile(r"\bxox[baprs]-[0-9A-Za-z-]{16,}\b")),
|
| 95 |
+
("EMGENA-SEC-009", "HIGH", "CWE-798", "Database URI with Embedded Password",
|
| 96 |
+
re.compile(r"(?:postgres|postgresql|mysql|mongodb|redis)://[^:\s'\"]+:[^@\s'\"]{4,}@")),
|
| 97 |
+
("EMGENA-SEC-010", "HIGH", "CWE-321", "Signed JWT Token Literal",
|
| 98 |
+
re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b")),
|
| 99 |
+
("EMGENA-SEC-011", "HIGH", "CWE-532", "SSH Key File Path Exfiltration (~/.ssh/id_*)",
|
| 100 |
+
re.compile(r"~?/\.ssh/id_(?:rsa|ed25519|ecdsa)|ssh_auth_sock", re.IGNORECASE)),
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
def _looks_safe_secret(s: str) -> bool:
|
| 104 |
+
low = s.lower().strip()
|
| 105 |
+
if len(low) < 8:
|
| 106 |
+
return True
|
| 107 |
+
if any(m in low for m in SAFE_VALUE_MARKERS):
|
| 108 |
+
return True
|
| 109 |
+
if re.fullmatch(r"[A-Z0-9_]+", s) and "_" in s and len(s) < 35:
|
| 110 |
+
return True
|
| 111 |
+
return False
|
| 112 |
+
|
| 113 |
+
class DomainASTVisitor(ast.NodeVisitor):
|
| 114 |
+
"""Real-world Secret, Entropy & Subprocess AST Visitor."""
|
| 115 |
+
def __init__(self, pro_mode: bool = True):
|
| 116 |
+
self.pro_mode = pro_mode
|
| 117 |
+
self.findings = []
|
| 118 |
+
|
| 119 |
+
def _check_secret_literal(self, var_name: str, val_node: ast.AST, line: int):
|
| 120 |
+
if isinstance(val_node, ast.Constant) and isinstance(val_node.value, (str, bytes)):
|
| 121 |
+
raw = val_node.value.decode("utf-8", "ignore") if isinstance(val_node.value, bytes) else val_node.value
|
| 122 |
+
if _looks_safe_secret(raw):
|
| 123 |
+
return
|
| 124 |
+
vlow = var_name.lower()
|
| 125 |
+
is_sensitive_var = (vlow in SENSITIVE_VAR_NAMES) or any(
|
| 126 |
+
k in vlow for k in ("secret", "private_key", "signing_key", "master_key", "api_key", "passwd", "password", "token")
|
| 127 |
+
)
|
| 128 |
+
if is_sensitive_var and len(raw) >= 10:
|
| 129 |
+
ent = _shannon_entropy(raw)
|
| 130 |
+
if ent >= 3.0 or "-----begin" in raw.lower() or len(raw) >= 16:
|
| 131 |
+
self.findings.append({
|
| 132 |
+
"rule_id": "EMGENA-AST-101", "severity": "CRITICAL", "cwe": "CWE-798", "line": line,
|
| 133 |
+
"message": f"Hardcoded credential literal assigned to '{var_name}' (entropy={ent:.2f})",
|
| 134 |
+
"preview": _mask_preview(raw),
|
| 135 |
+
"remediation": f"Load '{var_name}' via os.environ.get('{var_name.upper()}') or KMS/Vault."
|
| 136 |
+
})
|
| 137 |
+
return
|
| 138 |
+
if self.pro_mode and isinstance(val_node.value, str) and len(raw) >= 22 and " " not in raw:
|
| 139 |
+
ent = _shannon_entropy(raw)
|
| 140 |
+
if ent >= 4.25 and any(c.isdigit() for c in raw) and any(c.isalpha() for c in raw):
|
| 141 |
+
self.findings.append({
|
| 142 |
+
"rule_id": "EMGENA-ENT-201", "severity": "HIGH", "cwe": "CWE-798", "line": line,
|
| 143 |
+
"message": f"High-entropy secret candidate in AST string literal for '{var_name}' (H={ent:.2f})",
|
| 144 |
+
"preview": _mask_preview(raw),
|
| 145 |
+
"remediation": "Move high-entropy tokens out of source literals into an encrypted secret manager."
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
def visit_Assign(self, node):
|
| 149 |
+
for t in node.targets:
|
| 150 |
+
if isinstance(t, ast.Name):
|
| 151 |
+
self._check_secret_literal(t.id, node.value, getattr(node, "lineno", 1))
|
| 152 |
+
elif isinstance(t, ast.Attribute):
|
| 153 |
+
self._check_secret_literal(t.attr, node.value, getattr(node, "lineno", 1))
|
| 154 |
+
self.generic_visit(node)
|
| 155 |
+
|
| 156 |
+
def visit_AnnAssign(self, node):
|
| 157 |
+
if isinstance(node.target, ast.Name) and node.value is not None:
|
| 158 |
+
self._check_secret_literal(node.target.id, node.value, getattr(node, "lineno", 1))
|
| 159 |
+
self.generic_visit(node)
|
| 160 |
+
|
| 161 |
+
def visit_Dict(self, node):
|
| 162 |
+
for k, v in zip(node.keys, node.values):
|
| 163 |
+
if isinstance(k, ast.Constant) and isinstance(k.value, str) and v is not None:
|
| 164 |
+
self._check_secret_literal(k.value, v, getattr(k, "lineno", 1))
|
| 165 |
+
self.generic_visit(node)
|
| 166 |
+
|
| 167 |
+
def visit_Call(self, node):
|
| 168 |
+
fname = _call_name(node)
|
| 169 |
+
for kw in node.keywords:
|
| 170 |
+
if kw.arg and kw.arg.lower() == "shell" and isinstance(kw.value, ast.Constant) and kw.value.value is True:
|
| 171 |
+
self.findings.append({
|
| 172 |
+
"rule_id": "EMGENA-AST-301", "severity": "HIGH", "cwe": "CWE-78",
|
| 173 |
+
"line": getattr(node, "lineno", 1),
|
| 174 |
+
"message": f"Subprocess call '{fname}(..., shell=True)' enables command/env exfiltration.",
|
| 175 |
+
"preview": f"{fname}(..., shell=True)",
|
| 176 |
+
"remediation": "Pass argument array with shell=False."
|
| 177 |
+
})
|
| 178 |
+
if self.pro_mode and _full_attr_name(node.func) == "os.system":
|
| 179 |
+
self.findings.append({
|
| 180 |
+
"rule_id": "EMGENA-AST-302", "severity": "HIGH", "cwe": "CWE-78",
|
| 181 |
+
"line": getattr(node, "lineno", 1),
|
| 182 |
+
"message": "Direct os.system() shell invocation detected.",
|
| 183 |
+
"preview": "os.system(...)",
|
| 184 |
+
"remediation": "Use subprocess.run([...], shell=False, check=True)."
|
| 185 |
+
})
|
| 186 |
+
self.generic_visit(node)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
SCAN_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".env", ".json", ".yaml", ".yml", ".sh", ".toml", ".tf", ".ini", ".sql"}
|
| 190 |
+
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "mlx_data"}
|
| 191 |
+
|
| 192 |
+
def run_domain_ast_scan(code: str, pro_mode: bool = True) -> list:
|
| 193 |
+
findings = []
|
| 194 |
+
if not code or not code.strip():
|
| 195 |
+
return findings
|
| 196 |
+
|
| 197 |
+
rules = DOMAIN_REGEX_RULES if pro_mode else DOMAIN_REGEX_RULES[:4]
|
| 198 |
+
for lineno, raw_line in enumerate(code.splitlines(), 1):
|
| 199 |
+
code_no_comment = raw_line.split("#")[0]
|
| 200 |
+
low = code_no_comment.lower()
|
| 201 |
+
if any(m in low for m in ("redacted", "placeholder", "example_only", "safe_sanitized", "***", "'except':", '"except":', "deny_cidr", "block_cidr", "block_privileged")):
|
| 202 |
+
continue
|
| 203 |
+
for rule_id, sev, cwe, desc, pat in rules:
|
| 204 |
+
m = pat.search(code_no_comment)
|
| 205 |
+
if m:
|
| 206 |
+
findings.append({
|
| 207 |
+
"rule_id": rule_id,
|
| 208 |
+
"severity": sev,
|
| 209 |
+
"cwe": cwe,
|
| 210 |
+
"line": lineno,
|
| 211 |
+
"message": desc,
|
| 212 |
+
"preview": _mask_preview(m.group(0)),
|
| 213 |
+
"remediation": "Remediate detected policy violation before execution or commit."
|
| 214 |
+
})
|
| 215 |
+
|
| 216 |
+
try:
|
| 217 |
+
tree = ast.parse(code)
|
| 218 |
+
visitor = DomainASTVisitor(pro_mode=pro_mode)
|
| 219 |
+
visitor.visit(tree)
|
| 220 |
+
findings.extend(visitor.findings)
|
| 221 |
+
except SyntaxError as e:
|
| 222 |
+
findings.append({
|
| 223 |
+
"rule_id": "EMGENA-SYNTAX-000",
|
| 224 |
+
"severity": "CRITICAL",
|
| 225 |
+
"cwe": "CWE-20",
|
| 226 |
+
"line": getattr(e, "lineno", 1) or 1,
|
| 227 |
+
"message": f"Python AST SyntaxError: {e.msg}",
|
| 228 |
+
"preview": str(e.text or "").strip()[:60],
|
| 229 |
+
"remediation": "Fix Python syntax before deploying or loading into MCP context."
|
| 230 |
+
})
|
| 231 |
+
|
| 232 |
+
seen = set()
|
| 233 |
+
unique = []
|
| 234 |
+
for f in findings:
|
| 235 |
+
key = (f["rule_id"], f["line"])
|
| 236 |
+
if key not in seen:
|
| 237 |
+
seen.add(key)
|
| 238 |
+
unique.append(f)
|
| 239 |
+
return unique
|
| 240 |
+
|
| 241 |
+
def scan_directory_or_file(target_path: str) -> dict:
|
| 242 |
+
p = Path(target_path)
|
| 243 |
+
files = [p] if p.is_file() else [
|
| 244 |
+
f for f in p.rglob("*")
|
| 245 |
+
if f.is_file() and (f.suffix.lower() in SCAN_EXTENSIONS or f.name.startswith(".env"))
|
| 246 |
+
and not any(sd in f.parts for sd in SKIP_DIRS)
|
| 247 |
+
and f.name not in ("server.py", "server_free.py")
|
| 248 |
+
]
|
| 249 |
+
all_results = []
|
| 250 |
+
for fp in files:
|
| 251 |
+
try:
|
| 252 |
+
txt = fp.read_text(encoding="utf-8", errors="ignore")
|
| 253 |
+
except Exception:
|
| 254 |
+
continue
|
| 255 |
+
if len(txt) > 512 * 1024:
|
| 256 |
+
continue
|
| 257 |
+
hits = run_domain_ast_scan(txt, pro_mode=True)
|
| 258 |
+
for h in hits:
|
| 259 |
+
h["file"] = str(fp)
|
| 260 |
+
all_results.append(h)
|
| 261 |
+
return {"files_scanned": len(files), "total_findings": len(all_results), "findings": all_results}
|
| 262 |
+
|
| 263 |
+
def build_sarif(scan_res: dict, pkg_id: str) -> dict:
|
| 264 |
+
runs_results = []
|
| 265 |
+
for f in scan_res["findings"]:
|
| 266 |
+
runs_results.append({
|
| 267 |
+
"ruleId": f["rule_id"],
|
| 268 |
+
"level": "error" if f["severity"] == "CRITICAL" else "warning",
|
| 269 |
+
"message": {"text": f"{f['message']} ({f['preview']}) -> {f['remediation']}"},
|
| 270 |
+
"locations": [{
|
| 271 |
+
"physicalLocation": {
|
| 272 |
+
"artifactLocation": {"uri": f.get("file", "unknown")},
|
| 273 |
+
"region": {"startLine": int(f.get("line", 1))}
|
| 274 |
+
}
|
| 275 |
+
}]
|
| 276 |
+
})
|
| 277 |
+
return {
|
| 278 |
+
"version": "2.1.0",
|
| 279 |
+
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
| 280 |
+
"runs": [{
|
| 281 |
+
"tool": {"driver": {"name": f"EMGENA-{pkg_id}", "version": "3.0.0"}},
|
| 282 |
+
"results": runs_results
|
| 283 |
+
}]
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _legacy_package_check(code: str, code_text: str, tool_name: str) -> bool:
|
| 288 |
+
return False
|
| 289 |
+
|
| 290 |
+
def execute_tool(tool_name: str, arguments: dict) -> dict:
|
| 291 |
+
global SESSION_SCANS
|
| 292 |
+
if SESSION_SCANS >= MAX_FREE_SCANS:
|
| 293 |
+
return {
|
| 294 |
+
"package": "npm_postinstall_script_obfuscation_guard",
|
| 295 |
+
"defect_detected": False,
|
| 296 |
+
"is_safe": False,
|
| 297 |
+
"status": "COMMUNITY_LIMIT_REACHED",
|
| 298 |
+
"error": f"Community Edition limit ({MAX_FREE_SCANS} scans/session) reached. Unlock Commercial Pro (code LAUNCH20): {UPGRADE_URL}",
|
| 299 |
+
"_emgena_commercial_pro": {"upgrade_url": UPGRADE_URL, "coupon": "LAUNCH20"}
|
| 300 |
+
}
|
| 301 |
+
SESSION_SCANS += 1
|
| 302 |
+
if not isinstance(arguments, dict):
|
| 303 |
+
arguments = {}
|
| 304 |
+
code = (arguments.get("code_content") or arguments.get("code") or arguments.get("code_snippet") or arguments.get("raw_chunk_text") or arguments.get("chunk_text") or arguments.get("flawed_code") or arguments.get("payload") or arguments.get("sql") or arguments.get("prompt") or arguments.get("source") or "")
|
| 305 |
+
if not isinstance(code, str):
|
| 306 |
+
code = json.dumps(code, ensure_ascii=False)
|
| 307 |
+
if not code.strip():
|
| 308 |
+
return {"package": "npm_postinstall_script_obfuscation_guard", "defect_detected": False, "is_safe": True, "status": "EMPTY_CODE", "findings": []}
|
| 309 |
+
|
| 310 |
+
ast_valid = True
|
| 311 |
+
try:
|
| 312 |
+
ast.parse(code)
|
| 313 |
+
except SyntaxError:
|
| 314 |
+
ast_valid = False
|
| 315 |
+
|
| 316 |
+
lines = [l.split("#")[0] for l in code.splitlines()]
|
| 317 |
+
code_text = "\n".join(lines).lower()
|
| 318 |
+
real_findings = run_domain_ast_scan(code, pro_mode=False)
|
| 319 |
+
legacy_hit = _legacy_package_check(code, code_text, tool_name) if ast_valid else False
|
| 320 |
+
defect_detected = bool(real_findings) or legacy_hit or (not ast_valid)
|
| 321 |
+
|
| 322 |
+
return {
|
| 323 |
+
"package": "npm_postinstall_script_obfuscation_guard",
|
| 324 |
+
"tool": tool_name,
|
| 325 |
+
"edition": "COMMUNITY_EVALUATION (CC-BY-NC-4.0)",
|
| 326 |
+
"status": "VIOLATION_DETECTED" if defect_detected else "PASS_VALIDATED",
|
| 327 |
+
"defect_detected": defect_detected,
|
| 328 |
+
"is_safe": not defect_detected,
|
| 329 |
+
"scans_remaining": max(0, MAX_FREE_SCANS - SESSION_SCANS),
|
| 330 |
+
"findings": real_findings,
|
| 331 |
+
"_emgena_pro_notice": f"Commercial deployment or CI/CD --sarif requires Commercial License -> {UPGRADE_URL}"
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
TOOLS_SPEC = [
|
| 335 |
+
{
|
| 336 |
+
"name": "scan_npm_postinstall_script_o",
|
| 337 |
+
"description": "AST/SARIF static analyzer for npm postinstall & Obfuscated Lifecycle Script Guard MCP"
|
| 338 |
+
},
|
| 339 |
+
{
|
| 340 |
+
"name": "audit_npm_postinstall_script_",
|
| 341 |
+
"description": "Deterministic policy & config audit for npm postinstall & Obfuscated Lifecycle Script Guard MCP"
|
| 342 |
+
}
|
| 343 |
+
]
|
| 344 |
+
TOOLS = TOOLS_SPEC
|
| 345 |
+
|
| 346 |
+
def process_message(message: dict) -> dict:
|
| 347 |
+
msg_id = message.get("id")
|
| 348 |
+
method = message.get("method")
|
| 349 |
+
params = message.get("params", {}) or {}
|
| 350 |
+
if method == "initialize":
|
| 351 |
+
return {
|
| 352 |
+
"jsonrpc": "2.0", "id": msg_id,
|
| 353 |
+
"result": {
|
| 354 |
+
"protocolVersion": "2024-11-05",
|
| 355 |
+
"capabilities": {"tools": {"listChanged": False}},
|
| 356 |
+
"serverInfo": {"name": "npm_postinstall_script_obfuscation_guard_community", "version": "3.0.0-free"}
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
elif method == "notifications/initialized":
|
| 360 |
+
return None
|
| 361 |
+
elif method == "tools/list":
|
| 362 |
+
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
|
| 363 |
+
elif method == "tools/call":
|
| 364 |
+
tname = params.get("name", "")
|
| 365 |
+
args = params.get("arguments", {})
|
| 366 |
+
tool_res = execute_tool(tname, args)
|
| 367 |
+
return {
|
| 368 |
+
"jsonrpc": "2.0", "id": msg_id,
|
| 369 |
+
"result": {
|
| 370 |
+
"content": [{"type": "text", "text": json.dumps(tool_res, indent=2, ensure_ascii=False)}],
|
| 371 |
+
"isError": False
|
| 372 |
+
}
|
| 373 |
+
}
|
| 374 |
+
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
|
| 375 |
+
|
| 376 |
+
def main():
|
| 377 |
+
if "--scan" in sys.argv:
|
| 378 |
+
print(f"CLI --scan & --sarif CI/CD Gate requires Commercial Pro. Unlock with LAUNCH20: {UPGRADE_URL}")
|
| 379 |
+
sys.exit(2)
|
| 380 |
+
while True:
|
| 381 |
+
line = sys.stdin.readline()
|
| 382 |
+
if not line:
|
| 383 |
+
break
|
| 384 |
+
line = line.strip()
|
| 385 |
+
if not line:
|
| 386 |
+
continue
|
| 387 |
+
try:
|
| 388 |
+
req = json.loads(line)
|
| 389 |
+
resp = process_message(req)
|
| 390 |
+
if resp is not None:
|
| 391 |
+
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
|
| 392 |
+
sys.stdout.flush()
|
| 393 |
+
except Exception as e:
|
| 394 |
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}) + "\n")
|
| 395 |
+
sys.stdout.flush()
|
| 396 |
+
|
| 397 |
+
if __name__ == "__main__":
|
| 398 |
+
main()
|
train.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cd7fd5f47a7daca37c001e2c0d6b02dae995d3694a533335d2121737d1adea8a
|
| 3 |
+
size 21072
|