Spaces:
Sleeping
Sleeping
HsiehMinChieh Claude Opus 4.6 commited on
Commit ·
d8f8d2b
1
Parent(s): 6293b85
Add OSV.dev online vulnerability DB with static fallback
Browse filesSBOM analysis now refreshes its vulnerability data from OSV.dev on every
startup, querying tracked npm packages concurrently. Per-package failures
fall back to the bundled static database, so the tool still works offline.
The SBOM tab now shows the active data source and refresh timestamp.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (4)
- analyzer.py+10-3
- app.py+5
- export_html.py+8-2
- sbom.py+140-17
7 unmodified lines891011121314242 unmodified lines2572582592602612622632642652662672682692707 unmodified linesfrom tree_sitter_languages import get_parserfrom tree_sitter import Node as TSNodefrom mermaid_gen import generate_mermaid_flowchartfrom sbom import analyze_dependencies, Dependency, SEVERITY_ICONSlogging.basicConfig(level=logging.WARNING)242 unmodified linesreturn generate_mermaid_flowchart(self.main_funcs)def render_sbom_markdown(self) -> str:deps = self.report.dependenciesif not deps:return "# 相依套件 SBOM\n\n*未偵測到外部相依套件(檔案僅含內嵌程式碼)。*"vuln_count = sum(1 for d in deps if d.vulnerabilities)lines = ["# 相依套件 SBOM","\n> 漏洞資料為內建靜態清單,涵蓋常見前端函式庫的知名 CVE,非完整掃描。\n",f"- 外部相依套件:{len(deps)}",f"- 含已知漏洞套件:**{vuln_count}**","\n## 套件清單",7 unmodified lines891011121314242 unmodified lines2572582592602612622632642652662672682692702712722732742752762777 unmodified linesfrom tree_sitter_languages import get_parserfrom tree_sitter import Node as TSNodefrom mermaid_gen import generate_mermaid_flowchartfrom sbom import analyze_dependencies, Dependency, SEVERITY_ICONS, get_db_metadatalogging.basicConfig(level=logging.WARNING)242 unmodified linesreturn generate_mermaid_flowchart(self.main_funcs)def render_sbom_markdown(self) -> str:meta = get_db_metadata()src_line = f"> 漏洞資料來源:{meta['source']}"if meta["updated_at"]:src_line += f"|更新時間:{meta['updated_at']}"deps = self.report.dependenciesif not deps:return ("# 相依套件 SBOM\n\n" + src_line +"\n\n*未偵測到外部相依套件(檔案僅含內嵌程式碼)。*")vuln_count = sum(1 for d in deps if d.vulnerabilities)lines = ["# 相依套件 SBOM","\n" + src_line,"> 涵蓋常見前端函式庫的已知 CVE,非完整掃描。\n",f"- 外部相依套件:{len(deps)}",f"- 含已知漏洞套件:**{vuln_count}**","\n## 套件清單",
3 unmodified lines45678910111213143 unmodified linesimport shutilimport tracebackimport loggingfrom analyzer import HTMLJSAnalyzer, Exporterfrom export_html import generate_html_reportlogging.basicConfig(level=logging.ERROR)def analyze_uploaded_html(file_obj):if file_obj is None:return "⚠️ 請先上傳 HTML 檔案", "", "", "", gr.DownloadButton(visible=False)3 unmodified lines456789101112131415161718193 unmodified linesimport shutilimport tracebackimport loggingimport sbomfrom analyzer import HTMLJSAnalyzer, Exporterfrom export_html import generate_html_reportlogging.basicConfig(level=logging.ERROR)# Refresh the vulnerability database from OSV.dev on every startup._db_meta = sbom.refresh_vulnerability_db(timeout=10)logging.info("SBOM vulnerability DB: %s", _db_meta["source"])def analyze_uploaded_html(file_obj):if file_obj is None:return "⚠️ 請先上傳 HTML 檔案", "", "", "", gr.DownloadButton(visible=False)
1 unmodified line2345678109 unmodified lines11811912012112212376 unmodified lines2002012022032042052061 unmodified linefrom html import escape as html_escapefrom analyzer import HTMLJSAnalyzer, classify_functions, SIDE_EFFECT_ICONSfrom mermaid_gen import generate_mermaid_flowchartfrom sbom import SEVERITY_ICONSdef _build_caller_index(func_dict):109 unmodified linessbom_html = _generate_sbom_html(report.dependencies)vuln_dep_count = sum(1 for d in report.dependencies if d.vulnerabilities)html_content = f"""<!DOCTYPE html><html lang="zh-TW">76 unmodified lines<div id="tab-sbom" class="tab-content"><h2>相依套件 SBOM</h2><p style="color: #6c757d;">外部相依套件清單與已知漏洞比對。漏洞資料為內建靜態清單,涵蓋常見前端函式庫的知名 CVE,非完整掃描。</p><div class="header-panel"><div class="summary-grid"><div class="stat-box">1 unmodified line2345678109 unmodified lines11811912012112212312412512612712876 unmodified lines2052062072082092102112121 unmodified linefrom html import escape as html_escapefrom analyzer import HTMLJSAnalyzer, classify_functions, SIDE_EFFECT_ICONSfrom mermaid_gen import generate_mermaid_flowchartfrom sbom import SEVERITY_ICONS, get_db_metadatadef _build_caller_index(func_dict):109 unmodified linessbom_html = _generate_sbom_html(report.dependencies)vuln_dep_count = sum(1 for d in report.dependencies if d.vulnerabilities)sbom_meta = get_db_metadata()sbom_meta_text = f"漏洞資料來源:{sbom_meta['source']}"if sbom_meta["updated_at"]:sbom_meta_text += f"|更新時間:{sbom_meta['updated_at']}"safe_sbom_meta = html_escape(sbom_meta_text)html_content = f"""<!DOCTYPE html><html lang="zh-TW">76 unmodified lines<div id="tab-sbom" class="tab-content"><h2>相依套件 SBOM</h2><p style="color: #6c757d;">外部相依套件清單與已知漏洞比對,涵蓋常見前端函式庫的 CVE,非完整掃描。</p><p style="color: #6c757d; font-size: 0.9em;">{safe_sbom_meta}</p><div class="header-panel"><div class="summary-grid"><div class="stat-box">
12345678910111213141516171819205 unmodified lines262728293031323334353637383940414243444546474849505152535410 unmodified lines6566676869703 unmodified lines7475767778794 unmodified lines84858687888929 unmodified lines11912012112212312412510 unmodified lines136137138import refrom dataclasses import dataclass, fieldfrom typing import List, Optional# Curated offline vulnerability database for common front-end libraries.# A version v is affected by an entry when introduced <= v < fixed.# This is NOT an exhaustive CVE scan — it covers well-known issues only.KNOWN_VULNERABILITIES = {"jquery": [{"fixed": "1.9.0", "id": "CVE-2012-6708", "severity": "medium","desc": "選擇器解析造成的 XSS"},{"fixed": "3.0.0", "id": "CVE-2015-9251", "severity": "medium","desc": "跨網域 ajax 回應造成的 XSS"},{"fixed": "3.4.0", "id": "CVE-2019-11358", "severity": "medium","desc": "$.extend 原型污染 (prototype pollution)"},{"fixed": "3.5.0", "id": "CVE-2020-11022", "severity": "medium","desc": "htmlPrefilter 處理 HTML 造成的 XSS"},],"bootstrap": [5 unmodified lines"desc": "tooltip/popover 的 XSS"},],"lodash": [{"fixed": "4.17.12", "id": "CVE-2019-10744", "severity": "high","desc": "defaultsDeep 原型污染"},{"fixed": "4.17.19", "id": "CVE-2020-8203", "severity": "high","desc": "zipObjectDeep 原型污染"},{"fixed": "4.17.21", "id": "CVE-2021-23337", "severity": "high","desc": "template 函式的指令注入"},],"moment": [{"fixed": "2.19.3", "id": "CVE-2017-18214", "severity": "medium","desc": "字串解析造成的 ReDoS"},{"fixed": "2.29.4", "id": "CVE-2022-31129", "severity": "high","desc": "字串解析造成的 ReDoS"},],"axios": [{"fixed": "0.21.4", "id": "CVE-2021-3749", "severity": "medium","desc": "trim 正規表達式造成的 ReDoS"},{"fixed": "1.6.0", "id": "CVE-2023-45857", "severity": "medium","desc": "XSRF token 經由跨網域請求洩漏"},],"angular": [{"fixed": "1.7.9", "id": "CVE-2019-10768", "severity": "medium","desc": "AngularJS merge 原型污染"},{"fixed": "1.8.0", "id": "CVE-2020-7676", "severity": "medium","desc": "AngularJS 經由 SVG 的 XSS"},],}10 unmodified lines"angular.js": "angular",}SEVERITY_ICONS = {"high": "🔴", "medium": "🟠", "low": "🟡"}# package@version (jsdelivr/unpkg style, optionally /npm/ prefixed, optional @scope)3 unmodified lines# filename like jquery-3.4.1.min.js_PAT_FILENAME = re.compile(r'/([\w]+?)[-.]v?(\d+\.\d+(?:\.\d+)?)\.(?:min\.|slim\.)*(?:js|css)\b')@dataclassclass Dependency:4 unmodified linesvulnerabilities: List[dict] = field(default_factory=list)def _clean_name(raw: str) -> str:name = raw.lower().rsplit("/", 1)[-1]name = re.sub(r'\.(min|slim|bundle|esm|umd|core)$', '', name)29 unmodified linesdb_key = _NAME_ALIASES.get(name)if db_key and _is_precise(version):vt = _version_tuple(version)for vuln in KNOWN_VULNERABILITIES.get(db_key, []):introduced = _version_tuple(vuln.get("introduced", "0"))fixed = _version_tuple(vuln["fixed"])if introduced <= vt < fixed:10 unmodified linesseen.add(url)deps.append(parse_resource(url, kind))return deps12345678910111213141516171819202122235 unmodified lines293031323334353637383940414243444546474849505152535455565710 unmodified lines6869707172737475767778798081828384853 unmodified lines899091929394959697984 unmodified lines10310410510610710810911011111229 unmodified lines14214314414514614714810 unmodified lines159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261import jsonimport reimport urllib.requestfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import List, Optional# Fallback offline vulnerability database, used when OSV.dev is unreachable.# A version v is affected by an entry when introduced <= v < fixed.STATIC_VULNERABILITIES = {"jquery": [{"introduced": "0", "fixed": "1.9.0", "id": "CVE-2012-6708", "severity": "medium","desc": "選擇器解析造成的 XSS"},{"introduced": "0", "fixed": "3.0.0", "id": "CVE-2015-9251", "severity": "medium","desc": "跨網域 ajax 回應造成的 XSS"},{"introduced": "0", "fixed": "3.4.0", "id": "CVE-2019-11358", "severity": "medium","desc": "$.extend 原型污染 (prototype pollution)"},{"introduced": "0", "fixed": "3.5.0", "id": "CVE-2020-11022", "severity": "medium","desc": "htmlPrefilter 處理 HTML 造成的 XSS"},],"bootstrap": [5 unmodified lines"desc": "tooltip/popover 的 XSS"},],"lodash": [{"introduced": "0", "fixed": "4.17.12", "id": "CVE-2019-10744", "severity": "high","desc": "defaultsDeep 原型污染"},{"introduced": "0", "fixed": "4.17.19", "id": "CVE-2020-8203", "severity": "high","desc": "zipObjectDeep 原型污染"},{"introduced": "0", "fixed": "4.17.21", "id": "CVE-2021-23337", "severity": "high","desc": "template 函式的指令注入"},],"moment": [{"introduced": "0", "fixed": "2.19.3", "id": "CVE-2017-18214", "severity": "medium","desc": "字串解析造成的 ReDoS"},{"introduced": "0", "fixed": "2.29.4", "id": "CVE-2022-31129", "severity": "high","desc": "字串解析造成的 ReDoS"},],"axios": [{"introduced": "0", "fixed": "0.21.4", "id": "CVE-2021-3749", "severity": "medium","desc": "trim 正規表達式造成的 ReDoS"},{"introduced": "0", "fixed": "1.6.0", "id": "CVE-2023-45857", "severity": "medium","desc": "XSRF token 經由跨網域請求洩漏"},],"angular": [{"introduced": "0", "fixed": "1.7.9", "id": "CVE-2019-10768", "severity": "medium","desc": "AngularJS merge 原型污染"},{"introduced": "0", "fixed": "1.8.0", "id": "CVE-2020-7676", "severity": "medium","desc": "AngularJS 經由 SVG 的 XSS"},],}10 unmodified lines"angular.js": "angular",}# npm package name queried from OSV.dev for each tracked library.TRACKED_PACKAGES = {"jquery": "jquery","bootstrap": "bootstrap","lodash": "lodash","moment": "moment","axios": "axios","angular": "angular",}OSV_API_URL = "https://api.osv.dev/v1/query"SEVERITY_ICONS = {"high": "🔴", "medium": "🟠", "low": "🟡"}# package@version (jsdelivr/unpkg style, optionally /npm/ prefixed, optional @scope)3 unmodified lines# filename like jquery-3.4.1.min.js_PAT_FILENAME = re.compile(r'/([\w]+?)[-.]v?(\d+\.\d+(?:\.\d+)?)\.(?:min\.|slim\.)*(?:js|css)\b')# Active vulnerability DB; refreshed from OSV.dev at startup, falls back to static._active_db = {k: list(v) for k, v in STATIC_VULNERABILITIES.items()}_db_metadata = {"source": "內建靜態清單(尚未更新)", "updated_at": None}@dataclassclass Dependency:4 unmodified linesvulnerabilities: List[dict] = field(default_factory=list)def get_db_metadata() -> dict:return dict(_db_metadata)def _clean_name(raw: str) -> str:name = raw.lower().rsplit("/", 1)[-1]name = re.sub(r'\.(min|slim|bundle|esm|umd|core)$', '', name)29 unmodified linesdb_key = _NAME_ALIASES.get(name)if db_key and _is_precise(version):vt = _version_tuple(version)for vuln in _active_db.get(db_key, []):introduced = _version_tuple(vuln.get("introduced", "0"))fixed = _version_tuple(vuln["fixed"])if introduced <= vt < fixed:10 unmodified linesseen.add(url)deps.append(parse_resource(url, kind))return depsdef _osv_query(npm_name: str, timeout: float) -> dict:payload = json.dumps({"package": {"name": npm_name, "ecosystem": "npm"}}).encode("utf-8")req = urllib.request.Request(OSV_API_URL, data=payload,headers={"Content-Type": "application/json", "Accept": "application/json"},)with urllib.request.urlopen(req, timeout=timeout) as resp:return json.loads(resp.read().decode("utf-8"))def _severity_label(vuln: dict) -> str:raw = str((vuln.get("database_specific") or {}).get("severity", "")).upper()return {"LOW": "low", "MODERATE": "medium", "MEDIUM": "medium","HIGH": "high", "CRITICAL": "high"}.get(raw, "medium")def _parse_osv_vuln(vuln: dict, npm_name: str) -> List[dict]:entries = []cve = next((a for a in vuln.get("aliases", []) if a.startswith("CVE-")), None)vid = cve or vuln.get("id", "UNKNOWN")desc = (vuln.get("summary") or vuln.get("details") or "").strip().replace("\n", " ")if len(desc) > 80:desc = desc[:77] + "..."severity = _severity_label(vuln)for affected in vuln.get("affected", []):pkg = affected.get("package", {})if pkg.get("ecosystem") != "npm" or pkg.get("name") != npm_name:continuefor rng in affected.get("ranges", []):if rng.get("type") not in ("SEMVER", "ECOSYSTEM"):continueintroduced = "0"for event in rng.get("events", []):if "introduced" in event:introduced = event["introduced"]elif "fixed" in event:entries.append({"introduced": introduced, "fixed": event["fixed"],"id": vid, "severity": severity, "desc": desc,})introduced = "0"return entriesdef _dedupe(entries: List[dict]) -> List[dict]:seen, result = set(), []for e in entries:key = (e["id"], e["introduced"], e["fixed"])if key not in seen:seen.add(key)result.append(e)return resultdef refresh_vulnerability_db(timeout: float = 6.0) -> dict:"""Query OSV.dev for tracked packages and rebuild the active DB.Per-package failures fall back to the static DB for that package only.Runs all queries concurrently so total wait is roughly one timeout."""global _active_db, _db_metadatadef fetch(item):our_key, npm_name = itemtry:data = _osv_query(npm_name, timeout)except Exception:return our_key, Noneentries = []for vuln in data.get("vulns", []):entries.extend(_parse_osv_vuln(vuln, npm_name))return our_key, _dedupe(entries)new_db = {k: list(v) for k, v in STATIC_VULNERABILITIES.items()}ok = 0with ThreadPoolExecutor(max_workers=len(TRACKED_PACKAGES)) as ex:for our_key, entries in ex.map(fetch, TRACKED_PACKAGES.items()):if entries is None:continueok += 1if entries:new_db[our_key] = entriestotal = len(TRACKED_PACKAGES)if ok == total:source = "OSV.dev 線上資料庫"elif ok > 0:source = f"OSV.dev 線上資料庫(部分更新 {ok}/{total},其餘使用內建備援)"else:source = "內建靜態清單(OSV.dev 連線失敗,已使用備援)"_active_db = new_db_db_metadata = {"source": source,"updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),}return dict(_db_metadata)
analyzer.py+10-3
app.py+5
export_html.py+8-2
sbom.py+140-17