Spaces:
Sleeping
Sleeping
Commit ·
de73cb8
unverified ·
0
Parent(s):
Copy from cas project
Browse files- .gitignore +6 -0
- .vscode/launch.json +28 -0
- .vscode/mcp.json +12 -0
- Dockerfile +9 -0
- README.md +61 -0
- app/ghsa2cve.py +15 -0
- app/main.py +266 -0
- app/prompts/cve_analysis.md +156 -0
- app/prompts/cve_analysis_json.md +48 -0
- app/reports/.gitkeep +0 -0
- app/static/scribe.gif +0 -0
- app/templates/demo.md +5 -0
- app/templates/favicon.png +0 -0
- app/templates/index.html +230 -0
- app/tmp.md +2 -0
- app/utils.py +264 -0
- requirements.txt +8 -0
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
.venv/
|
| 3 |
+
venv/
|
| 4 |
+
.DS_Store
|
| 5 |
+
tmp/
|
| 6 |
+
app/__pycache__/
|
.vscode/launch.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "0.2.0",
|
| 3 |
+
"configurations": [
|
| 4 |
+
{
|
| 5 |
+
"name": "FastAPI (uvicorn)",
|
| 6 |
+
"type": "python",
|
| 7 |
+
"request": "launch",
|
| 8 |
+
"module": "uvicorn",
|
| 9 |
+
"args": [
|
| 10 |
+
"app.main:app",
|
| 11 |
+
"--host", "127.0.0.1",
|
| 12 |
+
"--port", "8000",
|
| 13 |
+
"--reload"
|
| 14 |
+
],
|
| 15 |
+
"jinja": true,
|
| 16 |
+
"justMyCode": false,
|
| 17 |
+
"console": "internalConsole"
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"name": "ghsa2cve",
|
| 21 |
+
"request": "launch",
|
| 22 |
+
"type": "debugpy",
|
| 23 |
+
"program": "${workspaceFolder}/app/ghsa2cve.py",
|
| 24 |
+
"args": ["GHSA-222v-cx2c-q2f5"],
|
| 25 |
+
"console": "internalConsole"
|
| 26 |
+
}
|
| 27 |
+
]
|
| 28 |
+
}
|
.vscode/mcp.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"servers": {
|
| 3 |
+
// "cve_analysis__debug": {
|
| 4 |
+
// "type": "sse",
|
| 5 |
+
// "url": "http://localhost:8000/mcp"
|
| 6 |
+
// },
|
| 7 |
+
"cve_analysis_hf": {
|
| 8 |
+
"type": "sse",
|
| 9 |
+
"url": "https://dn-scribe-cas.hf.space/mcp"
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
}
|
Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY app /app/app
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
EXPOSE 7860
|
| 9 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: CVE Analysis Service (CAS)
|
| 3 |
+
emoji: 🛡️
|
| 4 |
+
colorFrom: gray
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: true
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
CVE Analysis Service for streaming markdown reports and JSON-based analysis using OpenAI.
|
| 12 |
+
|
| 13 |
+
Try it out [here](https://dn-scribe-cas.hf.space/viewer?cve_id=CVE-2024-9900)
|
| 14 |
+
|
| 15 |
+
- `/viewer?cve_id<CVE-ID>&refresh=<true|false>` → live stream report
|
| 16 |
+
- `/cached` → raw markdown report
|
| 17 |
+
- `/json?cve_id=<CVE-ID>&refresh=<true|false>` → JSON response
|
| 18 |
+
- `/healthz` → health check
|
| 19 |
+
- `/raw?cve_id=<CVE-ID>&refresh=<true|false>` → Returns raw markdown report content. If the report does not exist, it generates it using OpenAI.
|
| 20 |
+
- `/cve_info?cve_id=<CVE-ID>` → Fetches CVE information as JSON with error handling.
|
| 21 |
+
- `/ghsa_to_cve?ghsa_id=<GHSA-ID>` → Converts GHSA ID to CVE ID using OpenAI.
|
| 22 |
+
|
| 23 |
+
Swagger available (on hugging face) [here](https://dn-scribe-cas.hf.space/docs)
|
| 24 |
+
|
| 25 |
+
Example of converting GHSA to CVE:
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
curl -X GET "http://127.0.0.1:8000/ghsa_to_cve?ghsa_id=GHSA-832w-fhmw-w4f4" -H "accept: application/json"
|
| 29 |
+
|
| 30 |
+
{"ghsa_id":"GHSA-832w-fhmw-w4f4","cve_id":"CVE-2024-55890"}
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
MCP Config for VSCode:
|
| 35 |
+
Create a file named `mcp.json` in the `.vscode` folder of your project and add the following content:
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
```json
|
| 39 |
+
{
|
| 40 |
+
"servers": {
|
| 41 |
+
// "cve_analysis__debug": {
|
| 42 |
+
// "type": "sse",
|
| 43 |
+
// "url": "http://localhost:8000/mcp"
|
| 44 |
+
// },
|
| 45 |
+
"cve_analysis_hf": {
|
| 46 |
+
"type": "sse",
|
| 47 |
+
"url": "https://dn-scribe-cas.hf.space/mcp"
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
Function to convert from GHSA to CVE-ID:
|
| 54 |
+
|
| 55 |
+
A function based on OpenAI gpt-4o-mini-search-preview with costs as follows:
|
| 56 |
+
|
| 57 |
+
- 25$ per 1k API calls
|
| 58 |
+
- 0.15$ per 1M input tokens
|
| 59 |
+
- 0.60$ per 1M output tokens
|
| 60 |
+
|
| 61 |
+
Since the whole transaction is about 40 tokens, the real cost is the per-api-call cost.
|
app/ghsa2cve.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import openai
|
| 2 |
+
import json
|
| 3 |
+
import asyncio
|
| 4 |
+
|
| 5 |
+
from utils import ghsa_to_cve
|
| 6 |
+
|
| 7 |
+
if __name__ == "__main__":
|
| 8 |
+
import sys
|
| 9 |
+
if len(sys.argv) != 2:
|
| 10 |
+
print("Usage: python ghsa_to_cve.py <GHSA_ID>")
|
| 11 |
+
sys.exit(1)
|
| 12 |
+
|
| 13 |
+
ghsa_id = sys.argv[1]
|
| 14 |
+
cve_id = asyncio.run(ghsa_to_cve(ghsa_id))
|
| 15 |
+
print(f"GHSA ID: {ghsa_id} -> CVE ID: {cve_id}")
|
app/main.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, Query
|
| 2 |
+
from fastapi.responses import StreamingResponse, JSONResponse, HTMLResponse
|
| 3 |
+
from fastapi.responses import RedirectResponse
|
| 4 |
+
from fastapi.exceptions import HTTPException
|
| 5 |
+
|
| 6 |
+
from fastapi.templating import Jinja2Templates
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
import asyncio
|
| 9 |
+
import os
|
| 10 |
+
import aiofiles
|
| 11 |
+
import logging
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
from fastapi_mcp import FastApiMCP
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from app.utils import (
|
| 18 |
+
validate_cve_id,
|
| 19 |
+
is_safe_path,
|
| 20 |
+
report_exists,
|
| 21 |
+
_report_base_path,
|
| 22 |
+
_report_path,
|
| 23 |
+
_lock_path,
|
| 24 |
+
load_report,
|
| 25 |
+
write_report,
|
| 26 |
+
generate_openai_stream,
|
| 27 |
+
generate_openai_json,
|
| 28 |
+
get_cve_info,
|
| 29 |
+
ghsa_to_cve,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Configure logging
|
| 33 |
+
logging.basicConfig(level=logging.INFO)
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
app = FastAPI()
|
| 37 |
+
templates = Jinja2Templates(directory="app/templates")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
from fastapi.responses import PlainTextResponse, HTMLResponse, FileResponse
|
| 41 |
+
from fastapi.staticfiles import StaticFiles
|
| 42 |
+
|
| 43 |
+
# Mount static files
|
| 44 |
+
app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
| 45 |
+
|
| 46 |
+
# # Add a helper function to validate CVE-ID
|
| 47 |
+
# def validate_cve_id(cve_id: str):
|
| 48 |
+
# parts = cve_id.upper().split("-")
|
| 49 |
+
# if len(parts) != 3 or not parts[2].isdigit():
|
| 50 |
+
# raise HTTPException(status_code=400, detail="Invalid CVE ID format. Expected format: CVE-YYYY-NNNNN.")
|
| 51 |
+
|
| 52 |
+
@app.get("/cached", operation_id="get_cve_report_from_cache")
|
| 53 |
+
async def cached_report(cve_id: str, refresh: bool = Query(False)):
|
| 54 |
+
if not is_safe_path(_report_base_path(), _report_path(cve_id)):
|
| 55 |
+
raise HTTPException(status_code=400, detail="Unsafe path access detected; Got path: " + _report_path(cve_id))
|
| 56 |
+
if refresh:
|
| 57 |
+
try:
|
| 58 |
+
os.remove(_report_path(cve_id, suffix=".md"))
|
| 59 |
+
except FileNotFoundError:
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
if await report_exists(cve_id):
|
| 63 |
+
content = await load_report(cve_id)
|
| 64 |
+
return PlainTextResponse(content, media_type="text/markdown")
|
| 65 |
+
return PlainTextResponse("Report not found", status_code=404)
|
| 66 |
+
|
| 67 |
+
@app.get("/viewer", operation_id="viewer")
|
| 68 |
+
async def viewer(request: Request, cve_id: str, refresh: bool = Query(False)):
|
| 69 |
+
# validate_cve_id(cve_id) # Validate CVE-ID
|
| 70 |
+
return templates.TemplateResponse("index.html", {
|
| 71 |
+
"request": request,
|
| 72 |
+
"cve_id": cve_id,
|
| 73 |
+
"refresh": refresh
|
| 74 |
+
})
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@app.get("/stream", operation_id="stream")
|
| 78 |
+
async def stream(cve_id: str, refresh: bool = Query(False)):
|
| 79 |
+
if not is_safe_path(_report_base_path(), _report_path(cve_id)):
|
| 80 |
+
raise HTTPException(status_code=400, detail="Unsafe path access detected; Got path: " + _report_path(cve_id))
|
| 81 |
+
|
| 82 |
+
report_path = _report_path(cve_id)
|
| 83 |
+
lock_path = _lock_path(cve_id)
|
| 84 |
+
|
| 85 |
+
if os.path.exists(lock_path):
|
| 86 |
+
async def busy_wait():
|
| 87 |
+
yield f"data: Report is currently being generated, please wait or retry...\n\n"
|
| 88 |
+
return StreamingResponse(busy_wait(), media_type="text/event-stream")
|
| 89 |
+
|
| 90 |
+
if not refresh and await report_exists(cve_id):
|
| 91 |
+
async def yield_cached():
|
| 92 |
+
content = await load_report(cve_id)
|
| 93 |
+
yield f"event: end\ndata: {content}\n\n"
|
| 94 |
+
return StreamingResponse(yield_cached(), media_type="text/event-stream")
|
| 95 |
+
|
| 96 |
+
if refresh:
|
| 97 |
+
try:
|
| 98 |
+
os.remove(_report_path(cve_id, suffix=".md"))
|
| 99 |
+
except FileNotFoundError:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
open(lock_path, "w").close()
|
| 103 |
+
|
| 104 |
+
async def yield_live():
|
| 105 |
+
full_text = ""
|
| 106 |
+
logger.info(f"Starting OpenAI stream for {cve_id}")
|
| 107 |
+
try:
|
| 108 |
+
async for chunk in generate_openai_stream(cve_id):
|
| 109 |
+
logger.debug(f"Got chunk: {repr(chunk)}")
|
| 110 |
+
full_text += chunk
|
| 111 |
+
for line in chunk.splitlines():
|
| 112 |
+
yield f"data: {line}\n"
|
| 113 |
+
yield "\n"
|
| 114 |
+
logger.info(f"Completed OpenAI stream for {cve_id}, preview: {repr(full_text[:200])}")
|
| 115 |
+
await write_report(cve_id, full_text)
|
| 116 |
+
yield "event: end\ndata: [done]\n\n"
|
| 117 |
+
except Exception as e:
|
| 118 |
+
logger.exception(f"Error during OpenAI stream: {e}")
|
| 119 |
+
yield f"data: ❌ Error generating report: {str(e)}\n\n"
|
| 120 |
+
finally:
|
| 121 |
+
os.remove(_lock_path(cve_id))
|
| 122 |
+
|
| 123 |
+
return StreamingResponse(yield_live(), media_type="text/event-stream")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@app.get("/json", operation_id="get_cve_report_as_json")
|
| 127 |
+
async def json_analysis(cve_id: str, refresh: bool = Query(False)):
|
| 128 |
+
if not is_safe_path(_report_base_path(), _report_path(cve_id)):
|
| 129 |
+
raise HTTPException(status_code=400, detail="Unsafe path access detected; Got path: " + _report_path(cve_id))
|
| 130 |
+
if refresh:
|
| 131 |
+
try:
|
| 132 |
+
os.remove(_report_path(cve_id, suffix=".json"))
|
| 133 |
+
except FileNotFoundError:
|
| 134 |
+
pass
|
| 135 |
+
|
| 136 |
+
logger.info(f"Received JSON analysis request for cve_id={cve_id}, refresh={refresh}")
|
| 137 |
+
if not refresh and await report_exists(cve_id, suffix=".json"):
|
| 138 |
+
logger.info(f"JSON report exists for cve_id={cve_id}, loading report")
|
| 139 |
+
content = await load_report(cve_id, suffix=".json")
|
| 140 |
+
try:
|
| 141 |
+
return JSONResponse(content=json.loads(content))
|
| 142 |
+
except json.JSONDecodeError:
|
| 143 |
+
return JSONResponse(content={"error": "Invalid JSON format in cached report."}, status_code=500)
|
| 144 |
+
|
| 145 |
+
logger.info(f"Generating new JSON report for cve_id={cve_id}")
|
| 146 |
+
try:
|
| 147 |
+
result = await generate_openai_json(cve_id)
|
| 148 |
+
parsed_result = json.loads(result)
|
| 149 |
+
await write_report(cve_id, result, suffix=".json")
|
| 150 |
+
return JSONResponse(content=parsed_result)
|
| 151 |
+
except ValueError as e:
|
| 152 |
+
logger.error(f"Error generating JSON for cve_id={cve_id}: {e}")
|
| 153 |
+
return JSONResponse(content={"error": str(e)}, status_code=500)
|
| 154 |
+
except json.JSONDecodeError:
|
| 155 |
+
logger.error(f"Generated result is not valid JSON for cve_id={cve_id}")
|
| 156 |
+
return JSONResponse(content={"error": "Generated result is not valid JSON."}, status_code=500)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@app.get("/raw", operation_id="get_cve_report")
|
| 160 |
+
async def raw_report(cve_id: str, refresh: bool = Query(False)):
|
| 161 |
+
if not is_safe_path(_report_base_path(), _report_path(cve_id)):
|
| 162 |
+
raise HTTPException(status_code=400, detail="Unsafe path access detected; Got path: " + _report_path(cve_id))
|
| 163 |
+
|
| 164 |
+
if refresh:
|
| 165 |
+
try:
|
| 166 |
+
os.remove(_report_path(cve_id, suffix=".md"))
|
| 167 |
+
except FileNotFoundError:
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
if await report_exists(cve_id):
|
| 171 |
+
content = await load_report(cve_id)
|
| 172 |
+
return PlainTextResponse(content, media_type="text/plain")
|
| 173 |
+
|
| 174 |
+
# Generate the report using OpenAI if it doesn't exist
|
| 175 |
+
logger.info(f"Generating new raw report for cve_id={cve_id}")
|
| 176 |
+
full_report = ""
|
| 177 |
+
async for chunk in generate_openai_stream(cve_id):
|
| 178 |
+
full_report += chunk
|
| 179 |
+
|
| 180 |
+
await write_report(cve_id, full_report, suffix=".md")
|
| 181 |
+
return PlainTextResponse(full_report, media_type="text/plain")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@app.get("/", operation_id="redirect_to_viewer")
|
| 185 |
+
async def root_redirect(cve_id: str, refresh = Query(False)):
|
| 186 |
+
return RedirectResponse(f"/viewer?cve_id={cve_id}&refresh={refresh}")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@app.get("/healthz", operation_id="healthz")
|
| 190 |
+
def healthz():
|
| 191 |
+
return {"status": "ok"}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@app.get("/cve_info", operation_id="get_cve_info")
|
| 195 |
+
async def cve_info(cve_id: str):
|
| 196 |
+
"""
|
| 197 |
+
Endpoint to fetch CVE information.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
cve_id (str): The CVE identifier, e.g., "CVE-2025-1234".
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
JSONResponse: Parsed CVE data or error message.
|
| 204 |
+
"""
|
| 205 |
+
try:
|
| 206 |
+
cve_data = None
|
| 207 |
+
if validate_cve_id(cve_id): # Validate CVE-ID
|
| 208 |
+
cve_data = await get_cve_info(cve_id)
|
| 209 |
+
else:
|
| 210 |
+
raise HTTPException(status_code=400, detail="Invalid CVE ID format. Expected format: CVE-YYYY-NNNNN.")
|
| 211 |
+
|
| 212 |
+
if cve_data is None:
|
| 213 |
+
raise HTTPException(status_code=404, detail=f"CVE {cve_id} not found.")
|
| 214 |
+
return JSONResponse(content=cve_data)
|
| 215 |
+
except HTTPException as http_exc:
|
| 216 |
+
raise http_exc
|
| 217 |
+
except Exception as e:
|
| 218 |
+
logger.exception(f"Unexpected error while fetching CVE info for {cve_id}: {e}")
|
| 219 |
+
raise HTTPException(status_code=500, detail="Internal server error.")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@app.get("/ghsa_to_cve", operation_id="ghsa_to_cve")
|
| 223 |
+
async def ghsa_to_cve_endpoint(ghsa_id: str):
|
| 224 |
+
"""
|
| 225 |
+
Endpoint to convert a GHSA ID to a CVE ID.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
ghsa_id (str): The GHSA identifier, e.g., "GHSA-1234-5678-9abc".
|
| 229 |
+
|
| 230 |
+
Returns:
|
| 231 |
+
JSONResponse: The corresponding CVE ID or an error message.
|
| 232 |
+
"""
|
| 233 |
+
try:
|
| 234 |
+
cve_id = await ghsa_to_cve(ghsa_id)
|
| 235 |
+
return {"ghsa_id": ghsa_id, "cve_id": cve_id}
|
| 236 |
+
except ValueError as e:
|
| 237 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 238 |
+
except Exception as e:
|
| 239 |
+
logger.exception(f"Unexpected error while converting GHSA to CVE: {e}")
|
| 240 |
+
raise HTTPException(status_code=500, detail="Internal server error.")
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@app.get("/favicon.ico", include_in_schema=False)
|
| 244 |
+
def favicon():
|
| 245 |
+
"""
|
| 246 |
+
Endpoint to serve the favicon.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
FileResponse: The favicon image file.
|
| 250 |
+
"""
|
| 251 |
+
return FileResponse("app/templates/favicon.png")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
mcp = FastApiMCP(
|
| 255 |
+
app,
|
| 256 |
+
name="Get CVE Info", # Name for your MCP server
|
| 257 |
+
description="MCP server getting CVE raw info or full report", # Description
|
| 258 |
+
include_operations=["get_cve_info", "get_cve_report"]
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
# Mount the MCP server to your FastAPI app
|
| 262 |
+
mcp.mount()
|
| 263 |
+
|
| 264 |
+
# if __name__ == "__main__":
|
| 265 |
+
# import uvicorn
|
| 266 |
+
# uvicorn.run(app, host="0.0.0.0", port=8000)
|
app/prompts/cve_analysis.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an AppSec expert with hands-on experience in both cybersecurity and software development. Your task is to analyze a specific CVE, {cve_id}, and produce a clear, technically accurate, and actionable report.
|
| 2 |
+
|
| 3 |
+
The report may be a markdown document or JSON, depending on the system instructions provided.
|
| 4 |
+
|
| 5 |
+
⚠️ Your reputation is on the line — do not guess or assume. All claims must be supported with links to credible sources, and with specifics and not general info and advice. Include technical details. Prioritize.
|
| 6 |
+
|
| 7 |
+
🎯 Objective
|
| 8 |
+
Provide a complete assessment of the CVE, including severity, impact, exploitability, upgrade/migration risks, usage prevalence, possible mitigations, detection methods, and public exploits — all backed by evidence.
|
| 9 |
+
|
| 10 |
+
✅ Process
|
| 11 |
+
Get CVE Details as input
|
| 12 |
+
|
| 13 |
+
Identify severity (CVSS base score/vector), EPSS score, KEV status, exploitation method, publish/update dates.
|
| 14 |
+
|
| 15 |
+
Identify Affected & Fixed Versions
|
| 16 |
+
|
| 17 |
+
Determine product/package name and version(s) affected.
|
| 18 |
+
|
| 19 |
+
Locate patched version or mitigation (if available).
|
| 20 |
+
|
| 21 |
+
Assess Exploitability, if exploitable (or poc) provide links to and exploit poc or code.
|
| 22 |
+
|
| 23 |
+
Identify conditions needed for exploitation.
|
| 24 |
+
|
| 25 |
+
Determine if user interaction, privileges, or config are required.
|
| 26 |
+
Determine if the default configuration is vulnerable or special configuration required (if possible)
|
| 27 |
+
|
| 28 |
+
Provide a checklist to help teams evaluate whether their systems are affected.
|
| 29 |
+
|
| 30 |
+
Evaluate Upgrade Risks
|
| 31 |
+
|
| 32 |
+
Search the web (esp. StackOverflow, GitHub, vendor issues) for upgrade problems.
|
| 33 |
+
|
| 34 |
+
Assess if the fix introduces breaking changes, feature loss, or integration issues.
|
| 35 |
+
|
| 36 |
+
Provide links to specific discussions or changelogs.
|
| 37 |
+
|
| 38 |
+
Determine Feature Prevalence
|
| 39 |
+
|
| 40 |
+
Is this a niche or widely used feature? Search the web for usage context.
|
| 41 |
+
|
| 42 |
+
Provide direct links showing whether many users are affected.
|
| 43 |
+
|
| 44 |
+
This step informs prioritization.
|
| 45 |
+
|
| 46 |
+
Explore Mitigations
|
| 47 |
+
|
| 48 |
+
Search for and list alternatives to upgrading, such as:
|
| 49 |
+
|
| 50 |
+
WAF rules
|
| 51 |
+
|
| 52 |
+
Snort/Suricata signatures
|
| 53 |
+
|
| 54 |
+
Permissions/config changes
|
| 55 |
+
|
| 56 |
+
Vendor-provided hotfixes or flags
|
| 57 |
+
|
| 58 |
+
Cite sources for each.
|
| 59 |
+
|
| 60 |
+
Indicators of Compromise
|
| 61 |
+
|
| 62 |
+
Provide known IoCs or detection methods.
|
| 63 |
+
|
| 64 |
+
Suggest log entries, alerts, or system behavior to monitor.
|
| 65 |
+
|
| 66 |
+
Search for Exploits
|
| 67 |
+
|
| 68 |
+
Look for PoCs or working exploits (on GitHub, ExploitDB, etc.).
|
| 69 |
+
|
| 70 |
+
If available, summarize reliability and provide links/snippets.
|
| 71 |
+
|
| 72 |
+
🧠 Use Only Credible Sources
|
| 73 |
+
Always include direct links to specific pages:
|
| 74 |
+
|
| 75 |
+
https://nvd.nist.gov
|
| 76 |
+
|
| 77 |
+
https://www.cisa.gov
|
| 78 |
+
|
| 79 |
+
https://github.com
|
| 80 |
+
|
| 81 |
+
https://rapid7.com
|
| 82 |
+
|
| 83 |
+
https://bleepingcomputer.com
|
| 84 |
+
|
| 85 |
+
https://thehackernews.com
|
| 86 |
+
|
| 87 |
+
https://darkreading.com
|
| 88 |
+
|
| 89 |
+
https://vulcan.io/blog
|
| 90 |
+
|
| 91 |
+
https://threatpost.com
|
| 92 |
+
|
| 93 |
+
Stack Overflow discussions
|
| 94 |
+
|
| 95 |
+
Vendor advisory pages
|
| 96 |
+
|
| 97 |
+
---
|
| 98 |
+
|
| 99 |
+
⚖️ Recommendation Decision Matrix (for recommendation logic):
|
| 100 |
+
|
| 101 |
+
Condition Action
|
| 102 |
+
EPSS > 0.1 or known exploits Upgrade immediately
|
| 103 |
+
EPSS < 0.1 and no known exploit Upgrade in roadmap
|
| 104 |
+
Moderate severity + EPSS < 0.1 + niche usage Accept or defer
|
| 105 |
+
Alternatives exist Document them + monitor
|
| 106 |
+
|
| 107 |
+
---
|
| 108 |
+
|
| 109 |
+
CVE Input {cve_info}
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
📝 Output Format
|
| 114 |
+
Structure the report as follows:
|
| 115 |
+
Title:
|
| 116 |
+
**Analysis and Recommendation for [CVE-XXXX-XXXX](https://nvd.nist.gov/vuln/detail/CVE-XXXX-XXXX)**
|
| 117 |
+
|
| 118 |
+
Sections:
|
| 119 |
+
**Affected Products**:
|
| 120 |
+
One-liner summary of the issue + [Affected Products](http://scribe-security.github.io/redirect/redirect.html?path=%2Fproducer-products&searchFilters=vuln_id:CVE-XXXX-XXXX;;show_file_components:false)
|
| 121 |
+
|
| 122 |
+
**Vulnerability Summary**:
|
| 123 |
+
- Description of the vulnerability and consequences
|
| 124 |
+
- Severity: High/Medium/etc.
|
| 125 |
+
- CVSS: X.X (vector)
|
| 126 |
+
- EPSS: X.XX
|
| 127 |
+
- KEV: Yes/No
|
| 128 |
+
- Publish/Update Date
|
| 129 |
+
|
| 130 |
+
**Exploitability**:
|
| 131 |
+
- How it can be exploited
|
| 132 |
+
- Exploitation prerequisites
|
| 133 |
+
- Checklist to assess local exposure
|
| 134 |
+
|
| 135 |
+
**Upgrade Risk**:
|
| 136 |
+
- Breaking changes?
|
| 137 |
+
- User complaints?
|
| 138 |
+
- Integration risks?
|
| 139 |
+
- Links to upgrade notes/issues
|
| 140 |
+
|
| 141 |
+
**Alternative Mitigations**:
|
| 142 |
+
- WAF/IDS/permissions/config-based workarounds
|
| 143 |
+
- Vendor suggestions (if available)
|
| 144 |
+
- Effectiveness + citations
|
| 145 |
+
|
| 146 |
+
**Detection / IoCs**:
|
| 147 |
+
- Logs, alerts, files, or behavior to look for
|
| 148 |
+
- Detection rules (if available)
|
| 149 |
+
|
| 150 |
+
**Known Exploits**:
|
| 151 |
+
- PoCs or public exploit links
|
| 152 |
+
- Summary of complexity / reliability
|
| 153 |
+
|
| 154 |
+
**Final Recommendation**:
|
| 155 |
+
- Whether to handle this CVE and when
|
| 156 |
+
- Actionable next steps
|
app/prompts/cve_analysis_json.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an expert cybersecurity summarizer. You are given a CVE ID and optionally its background information.
|
| 2 |
+
|
| 3 |
+
Your task is to produce a clean JSON-formatted string that groups and summarizes the vulnerability into specific sections.
|
| 4 |
+
|
| 5 |
+
### Output format (must be valid JSON string):
|
| 6 |
+
|
| 7 |
+
{
|
| 8 |
+
"<Section Name>": [
|
| 9 |
+
{
|
| 10 |
+
"order": <integer>,
|
| 11 |
+
"content": "<Markdown-formatted summary paragraph>",
|
| 12 |
+
"links": "<Best fitting single URL (or null)>"
|
| 13 |
+
},
|
| 14 |
+
...
|
| 15 |
+
],
|
| 16 |
+
...
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
Example:
|
| 20 |
+
|
| 21 |
+
{
|
| 22 |
+
"Affected Products": [
|
| 23 |
+
{
|
| 24 |
+
"order": 1,
|
| 25 |
+
"content": "The vulnerability affects the XYZ product versions 1.0 to 2.0.",
|
| 26 |
+
"links": "https://example.com/vulnerability-details"
|
| 27 |
+
}
|
| 28 |
+
],
|
| 29 |
+
"Exploitability": [
|
| 30 |
+
{
|
| 31 |
+
"order": 1,
|
| 32 |
+
"content": "The vulnerability can be exploited remotely without authentication.",
|
| 33 |
+
"links": null
|
| 34 |
+
}
|
| 35 |
+
],
|
| 36 |
+
...
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
### Requirements:
|
| 40 |
+
|
| 41 |
+
- All output must be a **single JSON object**, returned as a **JSON object**, not pretty-printed.
|
| 42 |
+
- Follow the sections required in the user prompt (Affected Products, Exploitability, Upgrade Risks, Feature Prevalence, Mitigations, Indicators of Compromise etc.).
|
| 43 |
+
- no \n or extra spaces
|
| 44 |
+
- Do **not** wrap it in Markdown code blocks or add extra prose.
|
| 45 |
+
- If you have no link for a section, use `null` as the value of `links`.
|
| 46 |
+
- The JSON must be valid and parsable directly by `json.loads(...)` in Python.
|
| 47 |
+
|
| 48 |
+
Respond only with the raw JSON string — no explanation or intro.
|
app/reports/.gitkeep
ADDED
|
File without changes
|
app/static/scribe.gif
ADDED
|
app/templates/demo.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🛡️ CVE Report Demo
|
| 2 |
+
|
| 3 |
+
Click to generate and stream the live analysis for **CVE-2024-9999**:
|
| 4 |
+
|
| 5 |
+
👉 [View Report](https://huggingface.co/spaces/dn-scribe/cas?cve_id=CVE-2024-56337)
|
app/templates/favicon.png
ADDED
|
|
app/templates/index.html
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<title>CVE Report</title>
|
| 6 |
+
<style>
|
| 7 |
+
body {
|
| 8 |
+
font-family: Arial, sans-serif;
|
| 9 |
+
padding: 0;
|
| 10 |
+
margin: 0;
|
| 11 |
+
background-color: #fafafa;
|
| 12 |
+
display: flex;
|
| 13 |
+
flex-direction: column;
|
| 14 |
+
align-items: center;
|
| 15 |
+
height: 100vh;
|
| 16 |
+
text-align: center;
|
| 17 |
+
position: relative;
|
| 18 |
+
}
|
| 19 |
+
h2 {
|
| 20 |
+
margin: 20px 0 0 0;
|
| 21 |
+
}
|
| 22 |
+
#spinner {
|
| 23 |
+
font-size: 18px;
|
| 24 |
+
margin: 20px;
|
| 25 |
+
}
|
| 26 |
+
#output {
|
| 27 |
+
white-space: normal;
|
| 28 |
+
background: #ffffff;
|
| 29 |
+
border: 1px solid #ddd;
|
| 30 |
+
padding: 1em;
|
| 31 |
+
min-height: 300px;
|
| 32 |
+
overflow-y: auto;
|
| 33 |
+
width: 90%; /* Adjusted to adapt to page width */
|
| 34 |
+
margin: 20px auto;
|
| 35 |
+
line-height: 1.6;
|
| 36 |
+
font-size: 16px;
|
| 37 |
+
color: #333;
|
| 38 |
+
display: none;
|
| 39 |
+
text-align: left;
|
| 40 |
+
position: relative;
|
| 41 |
+
}
|
| 42 |
+
h1, h2, h3, h4, h5, h6 {
|
| 43 |
+
text-align: left;
|
| 44 |
+
}
|
| 45 |
+
#copyButton {
|
| 46 |
+
position: absolute;
|
| 47 |
+
top: 10px;
|
| 48 |
+
right: 10px;
|
| 49 |
+
background-color: #4CAF50;
|
| 50 |
+
color: white;
|
| 51 |
+
border: none;
|
| 52 |
+
padding: 10px 15px;
|
| 53 |
+
border-radius: 5px;
|
| 54 |
+
cursor: pointer;
|
| 55 |
+
font-size: 14px;
|
| 56 |
+
transition: opacity 0.5s ease;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
#copyButton.copied {
|
| 60 |
+
background-color: #28a745;
|
| 61 |
+
content: "✔";
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
#top-left-image {
|
| 65 |
+
position: absolute;
|
| 66 |
+
top: 10px;
|
| 67 |
+
left: 10px;
|
| 68 |
+
width: 100px; /* Increased size */
|
| 69 |
+
height: auto;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
#content {
|
| 73 |
+
display: flex;
|
| 74 |
+
flex-direction: column;
|
| 75 |
+
align-items: center;
|
| 76 |
+
justify-content: center;
|
| 77 |
+
flex-grow: 1;
|
| 78 |
+
}
|
| 79 |
+
</style>
|
| 80 |
+
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
| 81 |
+
</head>
|
| 82 |
+
<body>
|
| 83 |
+
<img id="top-left-image" src="/static/scribe.gif" alt="Scribe Logo" />
|
| 84 |
+
<div id="content">
|
| 85 |
+
<h2> CVE Report</h2>
|
| 86 |
+
<div id="spinner">⏳ Loading report...</div>
|
| 87 |
+
<div id="output"></div>
|
| 88 |
+
<button id="copyButton">Copy</button>
|
| 89 |
+
</div>
|
| 90 |
+
|
| 91 |
+
<script>
|
| 92 |
+
function copyToClipboard() {
|
| 93 |
+
const outputEl = document.getElementById("output");
|
| 94 |
+
const text = outputEl.innerHTML.replace(/<h1>(.*?)<\/h1>/g, '# $1')
|
| 95 |
+
.replace(/<h2>(.*?)<\/h2>/g, '## $1')
|
| 96 |
+
.replace(/<h3>(.*?)<\/h3>/g, '### $1')
|
| 97 |
+
.replace(/<h4>(.*?)<\/h4>/g, '#### $1')
|
| 98 |
+
.replace(/<h5>(.*?)<\/h5>/g, '##### $1')
|
| 99 |
+
.replace(/<h6>(.*?)<\/h6>/g, '###### $1')
|
| 100 |
+
.replace(/<strong>(.*?)<\/strong>/g, '**$1**')
|
| 101 |
+
.replace(/<em>(.*?)<\/em>/g, '*$1*')
|
| 102 |
+
.replace(/<ul>/g, '\n')
|
| 103 |
+
.replace(/<li>(.*?)<\/li>/g, '- $1')
|
| 104 |
+
.replace(/<\/ul>/g, '\n')
|
| 105 |
+
.replace(/<br\s*\/?>/g, '\n')
|
| 106 |
+
.replace(/<[^>]+>/g, ''); // Remove other HTML tags
|
| 107 |
+
navigator.clipboard.writeText(text).then(() => {
|
| 108 |
+
const copyButton = document.getElementById("copyButton");
|
| 109 |
+
copyButton.textContent = "✔ Copied";
|
| 110 |
+
copyButton.classList.add("copied");
|
| 111 |
+
setTimeout(() => {
|
| 112 |
+
copyButton.textContent = "Copy";
|
| 113 |
+
copyButton.classList.remove("copied");
|
| 114 |
+
}, 2000);
|
| 115 |
+
}).catch(err => {
|
| 116 |
+
console.error("Failed to copy content: ", err);
|
| 117 |
+
});
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
document.getElementById("copyButton").addEventListener("click", copyToClipboard);
|
| 121 |
+
|
| 122 |
+
document.addEventListener("DOMContentLoaded", async () => {
|
| 123 |
+
const params = new URLSearchParams(window.location.search);
|
| 124 |
+
const cveId = params.get("cve_id");
|
| 125 |
+
const refresh = params.get("refresh") === "true"; // 👈 parse refresh properly
|
| 126 |
+
const outputEl = document.getElementById("output");
|
| 127 |
+
const spinnerEl = document.getElementById("spinner");
|
| 128 |
+
|
| 129 |
+
if (!cveId) {
|
| 130 |
+
spinnerEl.innerText = "❌ Missing CVE ID.";
|
| 131 |
+
return;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
async function fetchCachedAndRender() {
|
| 135 |
+
try {
|
| 136 |
+
const res = await fetch(`/cached?cve_id=${cveId}` + (refresh ? `&refresh=true` : ""));
|
| 137 |
+
if (!res.ok) throw new Error("Report missing");
|
| 138 |
+
const text = await res.text();
|
| 139 |
+
spinnerEl.style.display = "none";
|
| 140 |
+
outputEl.innerHTML = marked.parse(text);
|
| 141 |
+
|
| 142 |
+
// Ensure links open in a new tab
|
| 143 |
+
const links = outputEl.querySelectorAll("a");
|
| 144 |
+
links.forEach(link => {
|
| 145 |
+
link.setAttribute("target", "_blank");
|
| 146 |
+
link.setAttribute("rel", "noopener noreferrer");
|
| 147 |
+
});
|
| 148 |
+
|
| 149 |
+
outputEl.style.display = "block";
|
| 150 |
+
} catch {
|
| 151 |
+
startStreaming();
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
function startStreaming() {
|
| 156 |
+
spinnerEl.innerText = "⏳ Generating report...";
|
| 157 |
+
const evtSource = new EventSource(`/stream?cve_id=${cveId}` + (refresh ? `&refresh=true` : ""));
|
| 158 |
+
let buffer = "";
|
| 159 |
+
|
| 160 |
+
evtSource.onmessage = (e) => {
|
| 161 |
+
buffer += e.data;
|
| 162 |
+
|
| 163 |
+
// Ensure the title is not mistakenly appended
|
| 164 |
+
const title = document.querySelector("h2").innerText.trim();
|
| 165 |
+
if (buffer.includes(title)) {
|
| 166 |
+
buffer = buffer.replace(new RegExp(`\\b${title}\\b`, 'g'), '').trim();
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
outputEl.innerHTML = marked.parse(buffer);
|
| 170 |
+
|
| 171 |
+
// Ensure links open in a new tab
|
| 172 |
+
const links = outputEl.querySelectorAll("a");
|
| 173 |
+
links.forEach(link => {
|
| 174 |
+
link.setAttribute("target", "_blank");
|
| 175 |
+
link.setAttribute("rel", "noopener noreferrer");
|
| 176 |
+
});
|
| 177 |
+
|
| 178 |
+
outputEl.style.display = "block";
|
| 179 |
+
outputEl.scrollTop = outputEl.scrollHeight;
|
| 180 |
+
};
|
| 181 |
+
|
| 182 |
+
evtSource.addEventListener("end", (e) => {
|
| 183 |
+
evtSource.close();
|
| 184 |
+
|
| 185 |
+
if (e.data !== "[done]") {
|
| 186 |
+
buffer = e.data;
|
| 187 |
+
outputEl.innerHTML = marked.parse(buffer);
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
spinnerEl.style.display = "none";
|
| 191 |
+
|
| 192 |
+
const links = outputEl.querySelectorAll("a");
|
| 193 |
+
links.forEach(link => {
|
| 194 |
+
link.setAttribute("target", "_blank");
|
| 195 |
+
link.setAttribute("rel", "noopener noreferrer");
|
| 196 |
+
});
|
| 197 |
+
|
| 198 |
+
outputEl.scrollTop = outputEl.scrollHeight;
|
| 199 |
+
});
|
| 200 |
+
|
| 201 |
+
// evtSource.addEventListener("end", (e) => {
|
| 202 |
+
// evtSource.close();
|
| 203 |
+
|
| 204 |
+
// // Remove existing buffer content to avoid duplication
|
| 205 |
+
// buffer = e.data;
|
| 206 |
+
|
| 207 |
+
// spinnerEl.style.display = "none";
|
| 208 |
+
// outputEl.innerHTML = marked.parse(buffer);
|
| 209 |
+
|
| 210 |
+
// const links = outputEl.querySelectorAll("a");
|
| 211 |
+
// links.forEach(link => {
|
| 212 |
+
// link.setAttribute("target", "_blank");
|
| 213 |
+
// link.setAttribute("rel", "noopener noreferrer");
|
| 214 |
+
// });
|
| 215 |
+
|
| 216 |
+
// outputEl.scrollTop = outputEl.scrollHeight;
|
| 217 |
+
// });
|
| 218 |
+
|
| 219 |
+
evtSource.onerror = (err) => {
|
| 220 |
+
console.error("Streaming error", err);
|
| 221 |
+
evtSource.close();
|
| 222 |
+
spinnerEl.innerText = "❌ Failed to generate report.";
|
| 223 |
+
};
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
fetchCachedAndRender();
|
| 227 |
+
});
|
| 228 |
+
</script>
|
| 229 |
+
</body>
|
| 230 |
+
</html>
|
app/tmp.md
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
I want to turn the service to support many types of reports, using the same index.html and interface
|
| 2 |
+
|
app/utils.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from datetime import datetime, timedelta
|
| 4 |
+
import aiofiles
|
| 5 |
+
import json
|
| 6 |
+
from openai import AsyncOpenAI
|
| 7 |
+
import httpx
|
| 8 |
+
|
| 9 |
+
# Configure logging
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
# get working directory
|
| 14 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 15 |
+
if "/Users/" in current_dir:
|
| 16 |
+
# If running on MacOS, set the report directory to a specific path
|
| 17 |
+
REPORT_DIR = "tmp/reports"
|
| 18 |
+
else:
|
| 19 |
+
REPORT_DIR = "/tmp/reports"
|
| 20 |
+
os.makedirs(REPORT_DIR, exist_ok=True)
|
| 21 |
+
|
| 22 |
+
client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 23 |
+
|
| 24 |
+
# Add a helper function to validate CVE-ID
|
| 25 |
+
def validate_cve_id(cve_id: str):
|
| 26 |
+
parts = cve_id.upper().split("-")
|
| 27 |
+
if len(parts) != 3 or not parts[2].isdigit():
|
| 28 |
+
return False
|
| 29 |
+
return True
|
| 30 |
+
|
| 31 |
+
def is_safe_path(base_path: str, target_path: str) -> bool:
|
| 32 |
+
"""
|
| 33 |
+
Validate that the target path is within the base path and does not involve directory traversal.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
base_path (str): The base directory path.
|
| 37 |
+
target_path (str): The target file path to validate.
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
bool: True if the target path is safe, False otherwise.
|
| 41 |
+
"""
|
| 42 |
+
# Resolve absolute paths
|
| 43 |
+
base_path = os.path.abspath(base_path)
|
| 44 |
+
target_path = os.path.abspath(target_path)
|
| 45 |
+
|
| 46 |
+
# Check if the target path starts with the base path
|
| 47 |
+
return os.path.commonpath([base_path]) == os.path.commonpath([base_path, target_path])
|
| 48 |
+
|
| 49 |
+
async def get_cve_info(cve_id: str) -> dict | None:
|
| 50 |
+
"""
|
| 51 |
+
Fetch CVE JSON data from cisagov/vulnrichment repo.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
cve_id (str): The CVE identifier, e.g., "CVE-2025-1234".
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
dict | None: Parsed CVE data or None if not found.
|
| 58 |
+
"""
|
| 59 |
+
try:
|
| 60 |
+
parts = cve_id.upper().split("-")
|
| 61 |
+
if len(parts) != 3 or not parts[2].isdigit():
|
| 62 |
+
logger.warning(f"Invalid CVE ID format: {cve_id}")
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
year, cve_num = parts[1], parts[2].lstrip("0")
|
| 66 |
+
padded = parts[2].zfill(4)
|
| 67 |
+
num_len = len(padded)
|
| 68 |
+
|
| 69 |
+
if num_len == 4:
|
| 70 |
+
group = f"{padded[0]}xxx"
|
| 71 |
+
elif num_len == 5:
|
| 72 |
+
group = f"{padded[:2]}xxx"
|
| 73 |
+
elif num_len == 6:
|
| 74 |
+
group = f"{padded[:3]}xxx"
|
| 75 |
+
else:
|
| 76 |
+
logger.warning(f"Unsupported CVE numeric length: {cve_id}")
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
url = f"https://raw.githubusercontent.com/cisagov/vulnrichment/develop/{year}/{group}/CVE-{year}-{padded}.json"
|
| 80 |
+
logger.info(f"Fetching CVE info from {url}")
|
| 81 |
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
| 82 |
+
resp = await client.get(url)
|
| 83 |
+
logger.info(f"Response status code: {resp}")
|
| 84 |
+
|
| 85 |
+
if resp.status_code == 200:
|
| 86 |
+
return resp.json()
|
| 87 |
+
elif resp.status_code == 404:
|
| 88 |
+
logger.info(f"CVE {cve_id} not found in vulnrichment.")
|
| 89 |
+
return None
|
| 90 |
+
else:
|
| 91 |
+
logger.error(f"Unexpected status {resp.status_code} for {url}")
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
logger.exception(f"Failed to fetch CVE info for {cve_id}: {e}")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
def _report_base_path() -> str:
|
| 99 |
+
return REPORT_DIR
|
| 100 |
+
|
| 101 |
+
def _report_path(cve_id: str, suffix=".md") -> str:
|
| 102 |
+
return os.path.join(REPORT_DIR, f"{cve_id}{suffix}")
|
| 103 |
+
|
| 104 |
+
def _lock_path(cve_id: str) -> str:
|
| 105 |
+
return os.path.join(REPORT_DIR, f".{cve_id}.lock")
|
| 106 |
+
|
| 107 |
+
async def report_exists(cve_id: str, suffix: str = ".md") -> bool:
|
| 108 |
+
path = _report_path(cve_id, suffix)
|
| 109 |
+
if not os.path.exists(path):
|
| 110 |
+
return False
|
| 111 |
+
mtime = datetime.fromtimestamp(os.path.getmtime(path))
|
| 112 |
+
return datetime.now() - mtime < timedelta(days=5)
|
| 113 |
+
|
| 114 |
+
async def load_report(cve_id: str, suffix: str = ".md") -> str:
|
| 115 |
+
path = os.path.join(REPORT_DIR, f"{cve_id}{suffix}")
|
| 116 |
+
logger.info(f"Loading report for cve_id={cve_id}, path={path}")
|
| 117 |
+
async with aiofiles.open(path, "r") as f:
|
| 118 |
+
content = await f.read()
|
| 119 |
+
logger.info(f"Report loaded for cve_id={cve_id}, content length={len(content)}")
|
| 120 |
+
return content if suffix == ".md" else json.loads(content)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
async def write_report(cve_id: str, content, suffix: str = ".md"):
|
| 124 |
+
path = os.path.join(REPORT_DIR, f"{cve_id}{suffix}")
|
| 125 |
+
try:
|
| 126 |
+
async with aiofiles.open(path, "w") as f:
|
| 127 |
+
if suffix == ".md":
|
| 128 |
+
await f.write(content)
|
| 129 |
+
else:
|
| 130 |
+
await f.write(json.dumps(content, indent=2))
|
| 131 |
+
logger.info(f"✅ Report written: {path}")
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.error(f"❌ Failed to write report to {path}: {e}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
async def get_cve_prompt(cve_id: str) -> str:
|
| 137 |
+
template = get_prompt_template("app/prompts/cve_analysis.md")
|
| 138 |
+
cve_info_text = ""
|
| 139 |
+
cve_info = await get_cve_info(cve_id)
|
| 140 |
+
if cve_info:
|
| 141 |
+
cve_info_text = json.dumps(cve_info, indent=2)
|
| 142 |
+
else:
|
| 143 |
+
cve_info_text = f"Could not retrieve data for {cve_id}. Search the web for information: CVSS score, description, exploitability, affected versions and references"
|
| 144 |
+
logging.info(f"Retrieved CVE info for {cve_id}: {cve_info_text}")
|
| 145 |
+
# if not cve_info:
|
| 146 |
+
# raise ValueError(f"Could not retrieve data for {cve_id}")
|
| 147 |
+
prompt = template.format(cve_id=cve_id, cve_info=cve_info_text)
|
| 148 |
+
return prompt
|
| 149 |
+
|
| 150 |
+
def get_prompt_template(path: str) -> str:
|
| 151 |
+
"""
|
| 152 |
+
Reads a prompt from a file and returns it as a string.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
path (str): The file path to read the prompt from.
|
| 156 |
+
|
| 157 |
+
Returns:
|
| 158 |
+
str: The content of the file as a string.
|
| 159 |
+
|
| 160 |
+
Raises:
|
| 161 |
+
FileNotFoundError: If the file does not exist.
|
| 162 |
+
IOError: If there is an error reading the file.
|
| 163 |
+
"""
|
| 164 |
+
try:
|
| 165 |
+
with open(path, "r", encoding="utf-8") as file:
|
| 166 |
+
return file.read()
|
| 167 |
+
except FileNotFoundError:
|
| 168 |
+
logger.error(f"Prompt file not found: {path}")
|
| 169 |
+
raise FileNotFoundError(f"The specified prompt file at '{path}' was not found. Please ensure the file exists and the path is correct.")
|
| 170 |
+
except IOError as e:
|
| 171 |
+
logger.error(f"Error reading prompt file {path}: {e}")
|
| 172 |
+
raise IOError(f"An error occurred while reading the prompt file at '{path}': {e}")
|
| 173 |
+
|
| 174 |
+
async def generate_openai_stream(cve_id: str, json_result: bool = False):
|
| 175 |
+
logger.info(f"Generating OpenAI stream for cve_id={cve_id}")
|
| 176 |
+
editing_directions = "Provide the result as markdown text."
|
| 177 |
+
if json_result:
|
| 178 |
+
editing_directions = get_prompt_template("app/prompts/cve_analysis_json.md") # No args
|
| 179 |
+
|
| 180 |
+
prompt = await get_cve_prompt(cve_id)
|
| 181 |
+
stream = await client.chat.completions.create(
|
| 182 |
+
model = "gpt-4o-search-preview",
|
| 183 |
+
web_search_options={
|
| 184 |
+
"search_context_size": "low",
|
| 185 |
+
},
|
| 186 |
+
messages=[
|
| 187 |
+
{"role": "system", "content": editing_directions},
|
| 188 |
+
{"role": "user", "content": prompt}],
|
| 189 |
+
stream=True,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
async for chunk in stream:
|
| 193 |
+
delta = chunk.choices[0].delta.content or ""
|
| 194 |
+
if delta:
|
| 195 |
+
logger.debug(f"Stream chunk received for cve_id={cve_id}, chunk length={len(delta)}")
|
| 196 |
+
yield delta
|
| 197 |
+
|
| 198 |
+
async def generate_openai_json(cve_id: str):
|
| 199 |
+
logger.info(f"Generating OpenAI JSON for cve_id={cve_id}")
|
| 200 |
+
prompt = await get_cve_prompt(cve_id)
|
| 201 |
+
system_prompt = get_prompt_template("app/prompts/cve_analysis_json.md")
|
| 202 |
+
model = "gpt-4o-search-preview"
|
| 203 |
+
response = await client.chat.completions.create(
|
| 204 |
+
model=model,
|
| 205 |
+
web_search_options={
|
| 206 |
+
"search_context_size": "low",
|
| 207 |
+
},
|
| 208 |
+
messages=[
|
| 209 |
+
{"role": "system", "content": system_prompt},
|
| 210 |
+
{"role": "user", "content": prompt}
|
| 211 |
+
],
|
| 212 |
+
)
|
| 213 |
+
text = response.choices[0].message.content
|
| 214 |
+
|
| 215 |
+
if not text.strip():
|
| 216 |
+
logger.error(f"OpenAI returned an empty response for cve_id={cve_id}")
|
| 217 |
+
raise ValueError("OpenAI returned an empty response. Unable to generate JSON.")
|
| 218 |
+
|
| 219 |
+
logger.info(f"OpenAI JSON generated for cve_id={cve_id}, response length={len(text)}")
|
| 220 |
+
return text
|
| 221 |
+
|
| 222 |
+
async def ghsa_to_cve(ghsa_id: str) -> str:
|
| 223 |
+
"""
|
| 224 |
+
Convert a GHSA ID to a CVE ID using OpenAI's API.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
ghsa_id (str): The GHSA identifier, e.g., "GHSA-1234-5678-9abc".
|
| 228 |
+
|
| 229 |
+
Returns:
|
| 230 |
+
str: The corresponding CVE ID or an error message.
|
| 231 |
+
"""
|
| 232 |
+
logger.info(f"Converting GHSA ID {ghsa_id} to CVE ID")
|
| 233 |
+
prompt = f"Convert the following GHSA ID to a CVE ID: {ghsa_id}. Return ONLY the CVE ID (or None if not found)."
|
| 234 |
+
model = "gpt-4o-search-preview"
|
| 235 |
+
response = await client.chat.completions.create(
|
| 236 |
+
model=model,
|
| 237 |
+
web_search_options={
|
| 238 |
+
"search_context_size": "low",
|
| 239 |
+
},
|
| 240 |
+
messages=[
|
| 241 |
+
{"role": "user", "content": prompt}
|
| 242 |
+
],
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Log input and output token usage
|
| 246 |
+
logger.info(f"Input tokens: {response.usage.prompt_tokens}, Output tokens: {response.usage.completion_tokens}")
|
| 247 |
+
|
| 248 |
+
cve_id = response.choices[0].message.content
|
| 249 |
+
|
| 250 |
+
if not cve_id.strip():
|
| 251 |
+
logger.error(f"OpenAI returned an empty response for cve_id={cve_id}")
|
| 252 |
+
raise ValueError("OpenAI returned an empty response. Unable to generate JSON.")
|
| 253 |
+
|
| 254 |
+
cve_id = cve_id.rstrip() # Remove any leading/trailing whitespace
|
| 255 |
+
if validate_cve_id(cve_id): # Validate CVE-ID
|
| 256 |
+
logger.info(f"OpenAI converted GHSA {ghsa_id} to CVE ID {cve_id}")
|
| 257 |
+
return cve_id
|
| 258 |
+
else:
|
| 259 |
+
logger.error(f"OpenAI returned an invalid CVE ID: {cve_id}")
|
| 260 |
+
raise ValueError(f"OpenAI returned an invalid CVE ID: {cve_id}")
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
jinja2
|
| 4 |
+
openai
|
| 5 |
+
aiofiles
|
| 6 |
+
httpx
|
| 7 |
+
mcp==1.7.0
|
| 8 |
+
fastapi-mcp
|