Add interactive architecture builder with live suggestions
Browse files- New 'Build Diagram' tab with 2-step wizard:
Step 1: searchable service picker (55+ services across AWS/GCP/Azure/CI-CD/Security)
with category filters and live suggestion panel that updates as you select services
Step 2: drag-and-drop canvas with connect mode to draw arrows between services;
live analysis sidebar shows connection-aware suggestions (isolated nodes, unmonitored compute, etc.)
- 11 pure-JS suggestion rules fire in real time β no backend call until Analyze is clicked
- New /analyze-interactive POST endpoint accepts JSON components+connections -> runs all analyzers
- Stat counter updated to 7+ input formats; Interactive Builder chip added to landing page
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (2)
- web/app.py+35-1
- web/static/index.html+507-8
9 unmodified lines101112131415161 unmodified line18192021222329 unmodified lines5354555657589 unmodified linesif os.getenv("ANTHROPIC_API_KEY"):os.environ["ANTHROPIC_API_KEY"] = os.getenv("ANTHROPIC_API_KEY")from fastapi import FastAPI, File, Form, UploadFile, HTTPExceptionfrom fastapi.responses import HTMLResponsefrom fastapi.staticfiles import StaticFiles1 unmodified linefrom archlens.analyzers.security import SecurityAnalyzerfrom archlens.analyzers.cost import CostAnalyzerfrom archlens.models.findings import AnalysisReportapp = FastAPI(title="ArchLens", description="Architecture security & cost analyzer")29 unmodified linesraise HTTPException(status_code=500, detail=str(exc))async def _parse_upload(file: UploadFile, format_hint: Optional[str]) -> object:suffix = Path(file.filename).suffixwith tempfile.TemporaryDirectory() as tmp:9 unmodified lines101112131415161 unmodified line1819202122232429 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929 unmodified linesif os.getenv("ANTHROPIC_API_KEY"):os.environ["ANTHROPIC_API_KEY"] = os.getenv("ANTHROPIC_API_KEY")from fastapi import FastAPI, File, Form, UploadFile, HTTPException, Requestfrom fastapi.responses import HTMLResponsefrom fastapi.staticfiles import StaticFiles1 unmodified linefrom archlens.analyzers.security import SecurityAnalyzerfrom archlens.analyzers.cost import CostAnalyzerfrom archlens.models.findings import AnalysisReportfrom archlens.models.architecture import ArchitectureModel, Component, Connection, ComponentTypeapp = FastAPI(title="ArchLens", description="Architecture security & cost analyzer")29 unmodified linesraise HTTPException(status_code=500, detail=str(exc))@app.post("/analyze-interactive")async def analyze_interactive(request: Request):try:data = await request.json()model = ArchitectureModel(name=data.get("name", "Interactive Diagram"),source="interactive",)for c in data.get("components", []):try:ctype = ComponentType[c.get("type", "OTHER")]except KeyError:ctype = ComponentType.OTHERmodel.components.append(Component(id=c["id"],name=c["name"],type=ctype,provider=c.get("provider", "generic"),service=c.get("service", ""),))for conn in data.get("connections", []):model.connections.append(Connection(source_id=conn["source_id"],target_id=conn["target_id"],label=conn.get("label", ""),))findings = SecurityAnalyzer().analyze(model) + CostAnalyzer().analyze(model)report = AnalysisReport(architecture_name=model.name, findings=findings)return _report_to_dict(report)except Exception as exc:raise HTTPException(status_code=500, detail=str(exc))async def _parse_upload(file: UploadFile, format_hint: Optional[str]) -> object:suffix = Path(file.filename).suffixwith tempfile.TemporaryDirectory() as tmp:
395 unmodified lines39639739839940040153 unmodified lines45545645745845946046170 unmodified lines5325335345355365375 unmodified lines5435445455465475485495501 unmodified line5525535545555565575582 unmodified lines56156256356456556650 unmodified lines617618619620621622623624625626627131 unmodified lines759760761762763764395 unmodified linesborder: 1px solid #065f46;}/* FOOTER */footer {background: #1e293b; color: #94a3b8;53 unmodified lines<div class="stat-label">Cost optimizations</div></div><div class="stat-card"><div class="stat-num green">4</div><div class="stat-label">Input formats supported</div></div></div>70 unmodified lines<div class="chip c4">👁 draw.io diagram</div><div class="chip c5">☁ AWS Config export</div><div class="chip c6">☁ GCP Asset Inventory</div></div></section>5 unmodified lines<div class="input-panel"><div class="tabs"><button class="tab active" onclick="switchTab('file')">Upload File</button><button class="tab" onclick="switchTab('text')">Describe in Text</button></div><div id="tab-file" class="tab-content active">1 unmodified line<input type="file" id="fileInput" accept=".tf,.json,.yaml,.yml,.xml,.drawio,.txt,.md" onchange="onFileSelect(this)" /><div class="icon">📂</div><p><strong>Click to upload</strong> or drag & drop</p><p>Terraform (.tf) Β· CloudFormation (.yaml/.json) Β· draw.io (.xml/.drawio) Β· AWS Config (.json) Β· GCP Asset (.json) Β· Text (.txt)</p><div class="file-name" id="fileName"></div></div></div>2 unmodified lines<textarea id="textInput" placeholder="Describe your architecture in plain English... Example: We have a Python web app on AWS EC2 m5.xlarge, a PostgreSQL RDS db.r5.2xlarge with no encryption, an S3 bucket for uploads set to public, and no monitoring configured."></textarea></div><button class="analyze-btn" id="analyzeBtn" onclick="runAnalysis()">Analyze Architecture</button></div>50 unmodified linesfunction switchTab(tab) {activeTab = tab;document.querySelectorAll('.tab').forEach((t, i) => {t.classList.toggle('active', (i === 0 && tab === 'file') || (i === 1 && tab === 'text'));});document.getElementById('tab-file').classList.toggle('active', tab === 'file');document.getElementById('tab-text').classList.toggle('active', tab === 'text');}function onFileSelect(input) {131 unmodified linesreturn lines.join('\n');}function findingCard(f) {const card = document.createElement('div');card.className = 'finding-card ' + f.severity;395 unmodified lines39639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950053 unmodified lines55455555655755855956070 unmodified lines6316326336346356366375 unmodified lines6436446456466476486496506511 unmodified line6536546556566576586592 unmodified lines66266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773850 unmodified lines789790791792793794795796797798799800801131 unmodified lines933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263395 unmodified linesborder: 1px solid #065f46;}/* BUILDER TAB */.bstep-indicator { display:flex; align-items:center; margin-bottom:20px; }.bstep { display:flex; align-items:center; gap:7px; font-size:12px; font-weight:700; color:#4a5568; }.bstep.active { color:#a5b4fc; }.bstep.done { color:#34d399; }.bstep-num { width:24px; height:24px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:11px; font-weight:900; border:2px solid currentColor; flex-shrink:0; }.bstep-divider { flex:1; height:2px; background:#1e2d4a; margin:0 12px; min-width:32px; }.picker-controls { display:flex; flex-direction:column; gap:10px; margin-bottom:14px; }.service-search { width:100%; padding:9px 14px; background:#0d1a30; border:1.5px solid #1e2d4a; border-radius:10px; color:#e2e8f0; font-size:13px; outline:none; }.service-search:focus { border-color:#6366f1; }.service-search::placeholder { color:#3d5080; }.cat-tabs { display:flex; flex-wrap:wrap; gap:5px; }.cat-tab { padding:5px 13px; border-radius:99px; font-size:11px; font-weight:700; cursor:pointer; border:1.5px solid #1e2d4a; background:transparent; color:#64748b; transition:all 0.15s; }.cat-tab.active { background:#1e1b4b; color:#a5b4fc; border-color:#3730a3; }.cat-tab:hover:not(.active) { border-color:#4c1d95; color:#a5b4fc; }.service-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(100px,1fr)); gap:8px; max-height:240px; overflow-y:auto; padding-right:4px; margin-bottom:16px; scrollbar-width:thin; scrollbar-color:#1e2d4a transparent; }.service-card { background:#0d1a30; border:1.5px solid #1e2d4a; border-radius:10px; padding:10px 6px; cursor:pointer; text-align:center; transition:all 0.15s; user-select:none; position:relative; }.service-card:hover { border-color:#4c1d95; background:#131d3d; transform:translateY(-1px); }.service-card.selected { border-color:#818cf8; background:#1a1a3e; }.service-card.selected::after { content:'β'; position:absolute; top:4px; right:7px; font-size:9px; color:#818cf8; font-weight:900; }.svc-prov { font-size:8px; font-weight:800; text-transform:uppercase; padding:2px 5px; border-radius:99px; display:inline-block; margin-bottom:5px; }.prov-aws { background:#1c1007; color:#fbbf24; }.prov-gcp { background:#052e16; color:#6ee7b7; }.prov-azure { background:#0c1a2e; color:#7dd3fc; }.prov-generic { background:#1a1d2e; color:#94a3b8; }.svc-icon { font-size:16px; font-weight:900; color:#c4b5fd; margin:2px 0; font-family:monospace; }.svc-name { font-size:10px; font-weight:700; color:#e2e8f0; line-height:1.2; }.stack-row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; border-top:1px solid #1e2d4a; padding-top:14px; margin-bottom:12px; }.stack-label { font-size:11px; font-weight:800; color:#64748b; text-transform:uppercase; white-space:nowrap; }.stack-chips { display:flex; flex-wrap:wrap; gap:5px; flex:1; min-height:24px; }.stack-chip { display:flex; align-items:center; gap:4px; padding:3px 9px; border-radius:99px; font-size:11px; font-weight:700; background:#1e1b4b; color:#a5b4fc; border:1.5px solid #3730a3; cursor:pointer; }.stack-chip:hover { background:#2d1d6b; }.stack-chip-x { font-size:9px; color:#6366f1; }.continue-btn { padding:9px 20px; border-radius:99px; font-size:13px; font-weight:800; cursor:pointer; background:linear-gradient(135deg,#3730a3,#4c1d95); color:#c4b5fd; border:none; transition:transform 0.15s,opacity 0.15s; white-space:nowrap; }.continue-btn:hover:not(:disabled) { transform:translateY(-1px); }.continue-btn:disabled { opacity:0.35; cursor:not-allowed; }.sugg-panel { background:#080f1e; border:1.5px solid #1e2d4a; border-radius:10px; padding:12px 14px; }.sugg-title { font-size:10px; font-weight:800; text-transform:uppercase; letter-spacing:0.5px; color:#64748b; margin-bottom:9px; }.sugg-item { display:flex; align-items:flex-start; gap:7px; font-size:11px; color:#94a3b8; margin-bottom:6px; line-height:1.45; }.sugg-item.warn { color:#fdba74; }.sugg-item.good { color:#6ee7b7; }.sugg-item.crit { color:#fca5a5; }.sugg-item.info { color:#93c5fd; }.sugg-dot { width:6px; height:6px; border-radius:50%; flex-shrink:0; margin-top:3px; }.sugg-dot.warn { background:#f97316; }.sugg-dot.good { background:#34d399; }.sugg-dot.crit { background:#ef4444; }.sugg-dot.info { background:#60a5fa; }/* CANVAS (step 2) */.canvas-header { display:flex; align-items:center; gap:7px; margin-bottom:10px; flex-wrap:wrap; }.mode-btn { padding:7px 15px; border-radius:99px; font-size:11px; font-weight:700; cursor:pointer; border:1.5px solid #1e2d4a; background:transparent; color:#64748b; transition:all 0.15s; }.mode-btn.active { background:#1e1b4b; color:#a5b4fc; border-color:#3730a3; }.mode-btn.danger { color:#f87171; border-color:#991b1b; }.mode-btn.danger:hover { background:#450a0a; }.mode-btn:hover:not(.active):not(.danger) { border-color:#4c1d95; color:#a5b4fc; }.mode-hint { font-size:11px; color:#4a5568; margin-left:auto; font-style:italic; }.canvas-wrap { display:flex; gap:12px; align-items:flex-start; }.diagram-canvas {flex:1; position:relative; height:400px; min-width:0;background:#080f1e;background-image:linear-gradient(rgba(255,255,255,0.025) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.025) 1px,transparent 1px);background-size:26px 26px;border:1.5px solid #1e2d4a; border-radius:12px; overflow:hidden;}.edge-layer { position:absolute; top:0; left:0; width:100%; height:100%; pointer-events:none; overflow:visible; }.diagram-node { position:absolute; min-width:110px; background:#131d35; border:2px solid #1e2d4a; border-radius:9px; padding:7px 11px; user-select:none; z-index:10; transition:border-color 0.12s,box-shadow 0.12s; }.diagram-node.connect-mode:hover { border-color:#6366f1; }.diagram-node.connect-source { border-color:#818cf8; box-shadow:0 0 0 3px rgba(129,140,248,0.25); }.node-badge { font-size:8px; font-weight:800; text-transform:uppercase; padding:2px 6px; border-radius:99px; display:inline-block; margin-bottom:4px; }.node-name { font-size:11px; font-weight:700; color:#e2e8f0; line-height:1.25; }.node-prov { font-size:9px; color:#4a5568; margin-top:1px; }.nt-COMPUTE { background:#1e1b4b; color:#a5b4fc; }.nt-DATABASE { background:#0e4d6e; color:#7dd3fc; }.nt-STORAGE { background:#1c1007; color:#fbbf24; }.nt-SERVERLESS { background:#2d0a4e; color:#d8b4fe; }.nt-CONTAINER { background:#0a2e1f; color:#6ee7b7; }.nt-NETWORK { background:#0c2a1a; color:#86efac; }.nt-IAM { background:#3d1a00; color:#fdba74; }.nt-MONITORING { background:#1a1a00; color:#fde047; }.nt-QUEUE { background:#1a0a2e; color:#c4b5fd; }.nt-CACHE { background:#1a0808; color:#fca5a5; }.nt-CDN { background:#001a1a; color:#5eead4; }.nt-GATEWAY { background:#1a1200; color:#fcd34d; }.nt-OTHER { background:#111; color:#94a3b8; }.canvas-sugg { width:200px; flex-shrink:0; background:#080f1e; border:1.5px solid #1e2d4a; border-radius:12px; padding:12px 14px; max-height:400px; overflow-y:auto; }.canvas-footer { display:flex; justify-content:space-between; align-items:center; margin-top:14px; }.back-btn { padding:9px 18px; border-radius:99px; font-size:12px; font-weight:700; cursor:pointer; border:1.5px solid #1e2d4a; background:transparent; color:#64748b; transition:all 0.15s; }.back-btn:hover { border-color:#4c1d95; color:#a5b4fc; }.builder-analyze-btn { padding:11px 28px; border-radius:99px; font-size:13px; font-weight:800; cursor:pointer; background:linear-gradient(135deg,#2e1065,#1e1b4b); color:#c4b5fd; border:1px solid #4c1d95; box-shadow:0 4px 20px rgba(46,16,101,0.4); transition:transform 0.15s,box-shadow 0.15s; }.builder-analyze-btn:hover:not(:disabled) { transform:translateY(-1px); box-shadow:0 6px 28px rgba(46,16,101,0.6); }.builder-analyze-btn:disabled { opacity:0.4; cursor:not-allowed; }/* FOOTER */footer {background: #1e293b; color: #94a3b8;53 unmodified lines<div class="stat-label">Cost optimizations</div></div><div class="stat-card"><div class="stat-num green">7+</div><div class="stat-label">Input formats supported</div></div></div>70 unmodified lines<div class="chip c4">👁 draw.io diagram</div><div class="chip c5">☁ AWS Config export</div><div class="chip c6">☁ GCP Asset Inventory</div><div class="chip c1">✏ Interactive Builder</div></div></section>5 unmodified lines<div class="input-panel"><div class="tabs"><button class="tab active" data-tab="file" onclick="switchTab('file')">Upload File</button><button class="tab" data-tab="text" onclick="switchTab('text')">Describe in Text</button><button class="tab" data-tab="builder" onclick="switchTab('builder')">✏ Build Diagram</button></div><div id="tab-file" class="tab-content active">1 unmodified line<input type="file" id="fileInput" accept=".tf,.json,.yaml,.yml,.xml,.drawio,.txt,.md" onchange="onFileSelect(this)" /><div class="icon">📂</div><p><strong>Click to upload</strong> or drag & drop</p><p>Terraform (.tf) · CloudFormation (.yaml/.json) · draw.io (.xml/.drawio) · AWS Config (.json) · GCP Asset (.json) · Text (.txt)</p><div class="file-name" id="fileName"></div></div></div>2 unmodified lines<textarea id="textInput" placeholder="Describe your architecture in plain English... Example: We have a Python web app on AWS EC2 m5.xlarge, a PostgreSQL RDS db.r5.2xlarge with no encryption, an S3 bucket for uploads set to public, and no monitoring configured."></textarea></div><!-- BUILDER TAB --><div id="tab-builder" class="tab-content"><!-- Step 1: Pick Services --><div id="builder-step1"><div class="bstep-indicator"><div class="bstep active" id="bsi1"><div class="bstep-num">1</div> Pick Services</div><div class="bstep-divider"></div><div class="bstep" id="bsi2"><div class="bstep-num">2</div> Draw & Connect</div></div><div class="picker-controls"><input class="service-search" id="serviceSearch" type="text" placeholder="Search services (EC2, RDS, Jenkins...)" oninput="renderServiceGrid()"><div class="cat-tabs"><button class="cat-tab active" data-cat="all" onclick="setCat(this)">All</button><button class="cat-tab" data-cat="aws" onclick="setCat(this)">AWS</button><button class="cat-tab" data-cat="gcp" onclick="setCat(this)">GCP</button><button class="cat-tab" data-cat="azure" onclick="setCat(this)">Azure</button><button class="cat-tab" data-cat="cicd" onclick="setCat(this)">CI/CD</button><button class="cat-tab" data-cat="monitoring" onclick="setCat(this)">Monitoring</button><button class="cat-tab" data-cat="security" onclick="setCat(this)">Security</button></div></div><div class="service-grid" id="serviceGrid"></div><div class="stack-row"><span class="stack-label">Stack:</span><div class="stack-chips" id="stackChips"></div><button class="continue-btn" id="continueBtn" onclick="goToStep2()" disabled>Connect Services →</button></div><div class="sugg-panel"><div class="sugg-title">💡 Architecture Suggestions</div><div id="suggList"><div class="sugg-item info"><div class="sugg-dot info"></div><span>Add services to see recommendations</span></div></div></div></div><!-- Step 2: Canvas --><div id="builder-step2" style="display:none"><div class="bstep-indicator"><div class="bstep done" id="bsi1b"><div class="bstep-num">✓</div> Pick Services</div><div class="bstep-divider"></div><div class="bstep active"><div class="bstep-num">2</div> Draw & Connect</div></div><div class="canvas-header"><button class="mode-btn active" id="modeDrag" onclick="setMode('drag')">∥ Drag</button><button class="mode-btn" id="modeConnect" onclick="setMode('connect')">→ Connect</button><button class="mode-btn danger" onclick="removeLastEdge()">✕ Undo</button><span class="mode-hint" id="modeHint">Drag nodes to arrange your architecture</span></div><div class="canvas-wrap"><div class="diagram-canvas" id="diagramCanvas"><svg id="canvasSvg" class="edge-layer"></svg></div><div class="canvas-sugg"><div class="sugg-title">🔍 Live Analysis</div><div id="canvasSuggList"></div></div></div><div class="canvas-footer"><button class="back-btn" onclick="goToStep1()">← Back</button><button class="builder-analyze-btn" id="builderAnalyzeBtn" onclick="runBuilderAnalysis()">Analyze Architecture →</button></div></div></div><!-- /BUILDER TAB --><button class="analyze-btn" id="analyzeBtn" onclick="runAnalysis()">Analyze Architecture</button></div>50 unmodified linesfunction switchTab(tab) {activeTab = tab;document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t.dataset.tab === tab));['file','text','builder'].forEach(id => {document.getElementById('tab-' + id).classList.toggle('active', id === tab);});const analyzeBtn = document.getElementById('analyzeBtn');analyzeBtn.style.display = tab === 'builder' ? 'none' : 'block';if (tab === 'builder') renderServiceGrid();}function onFileSelect(input) {131 unmodified linesreturn lines.join('\n');}// ===================== INTERACTIVE BUILDER =====================const SERVICES = [// AWS{id:'aws_ec2', name:'EC2', provider:'aws', cat:'aws', type:'COMPUTE', service:'ec2', icon:'EC2'},{id:'aws_lambda', name:'Lambda', provider:'aws', cat:'aws', type:'SERVERLESS', service:'lambda', icon:'λ'},{id:'aws_ecs', name:'ECS', provider:'aws', cat:'aws', type:'CONTAINER', service:'ecs', icon:'ECS'},{id:'aws_eks', name:'EKS', provider:'aws', cat:'aws', type:'CONTAINER', service:'eks', icon:'EKS'},{id:'aws_fargate', name:'Fargate', provider:'aws', cat:'aws', type:'CONTAINER', service:'fargate', icon:'FG'},{id:'aws_rds', name:'RDS', provider:'aws', cat:'aws', type:'DATABASE', service:'rds', icon:'RDS'},{id:'aws_aurora', name:'Aurora', provider:'aws', cat:'aws', type:'DATABASE', service:'aurora', icon:'AUR'},{id:'aws_dynamodb', name:'DynamoDB', provider:'aws', cat:'aws', type:'DATABASE', service:'dynamodb', icon:'DDB'},{id:'aws_s3', name:'S3', provider:'aws', cat:'aws', type:'STORAGE', service:'s3', icon:'S3'},{id:'aws_vpc', name:'VPC', provider:'aws', cat:'aws', type:'NETWORK', service:'vpc', icon:'VPC'},{id:'aws_cloudfront',name:'CloudFront', provider:'aws', cat:'aws', type:'CDN', service:'cloudfront', icon:'CF'},{id:'aws_apigw', name:'API Gateway', provider:'aws', cat:'aws', type:'GATEWAY', service:'apigateway', icon:'APIGW'},{id:'aws_alb', name:'ALB', provider:'aws', cat:'aws', type:'GATEWAY', service:'alb', icon:'ALB'},{id:'aws_nat', name:'NAT Gateway', provider:'aws', cat:'aws', type:'NETWORK', service:'nat_gateway', icon:'NAT'},{id:'aws_elasticache',name:'ElastiCache', provider:'aws', cat:'aws', type:'CACHE', service:'elasticache', icon:'EC'},{id:'aws_sqs', name:'SQS', provider:'aws', cat:'aws', type:'QUEUE', service:'sqs', icon:'SQS'},{id:'aws_sns', name:'SNS', provider:'aws', cat:'aws', type:'QUEUE', service:'sns', icon:'SNS'},{id:'aws_iam', name:'IAM', provider:'aws', cat:'aws', type:'IAM', service:'iam_role', icon:'IAM'},{id:'aws_cognito', name:'Cognito', provider:'aws', cat:'aws', type:'IAM', service:'cognito', icon:'COG'},{id:'aws_cloudwatch',name:'CloudWatch', provider:'aws', cat:'aws', type:'MONITORING', service:'cloudwatch', icon:'CW'},{id:'aws_sg', name:'Security Group',provider:'aws', cat:'aws', type:'NETWORK', service:'security_group', icon:'SG'},{id:'aws_secrets', name:'Secrets Mgr', provider:'aws', cat:'aws', type:'IAM', service:'secrets_manager', icon:'SM'},// GCP{id:'gcp_gce', name:'Compute Engine',provider:'gcp', cat:'gcp', type:'COMPUTE', service:'gce_instance', icon:'GCE'},{id:'gcp_cloudrun', name:'Cloud Run', provider:'gcp', cat:'gcp', type:'SERVERLESS', service:'cloud_run', icon:'CR'},{id:'gcp_gke', name:'GKE', provider:'gcp', cat:'gcp', type:'CONTAINER', service:'gke', icon:'GKE'},{id:'gcp_cloudsql', name:'Cloud SQL', provider:'gcp', cat:'gcp', type:'DATABASE', service:'cloud_sql', icon:'SQL'},{id:'gcp_spanner', name:'Spanner', provider:'gcp', cat:'gcp', type:'DATABASE', service:'spanner', icon:'SPN'},{id:'gcp_firestore', name:'Firestore', provider:'gcp', cat:'gcp', type:'DATABASE', service:'firestore', icon:'FST'},{id:'gcp_gcs', name:'Cloud Storage', provider:'gcp', cat:'gcp', type:'STORAGE', service:'gcs_bucket', icon:'GCS'},{id:'gcp_pubsub', name:'Pub/Sub', provider:'gcp', cat:'gcp', type:'QUEUE', service:'pubsub', icon:'PS'},{id:'gcp_memstore', name:'Memorystore', provider:'gcp', cat:'gcp', type:'CACHE', service:'memorystore', icon:'MEM'},{id:'gcp_monitor', name:'Cloud Monitor', provider:'gcp', cat:'gcp', type:'MONITORING', service:'cloud_monitoring', icon:'MON'},// Azure{id:'az_vm', name:'Azure VM', provider:'azure', cat:'azure', type:'COMPUTE', service:'azure_vm', icon:'VM'},{id:'az_functions', name:'Functions', provider:'azure', cat:'azure', type:'SERVERLESS', service:'azure_functions', icon:'FN'},{id:'az_aks', name:'AKS', provider:'azure', cat:'azure', type:'CONTAINER', service:'aks', icon:'AKS'},{id:'az_sql', name:'Azure SQL', provider:'azure', cat:'azure', type:'DATABASE', service:'azure_sql', icon:'SQL'},{id:'az_blob', name:'Blob Storage', provider:'azure', cat:'azure', type:'STORAGE', service:'blob_storage', icon:'BLOB'},{id:'az_monitor', name:'Azure Monitor', provider:'azure', cat:'azure', type:'MONITORING', service:'azure_monitor', icon:'MON'},{id:'az_iam', name:'Azure AD', provider:'azure', cat:'azure', type:'IAM', service:'azure_ad', icon:'AAD'},// CI/CD & Tools{id:'t_jenkins', name:'Jenkins', provider:'generic', cat:'cicd', type:'OTHER', service:'jenkins', icon:'JNK'},{id:'t_gha', name:'GitHub Actions',provider:'generic', cat:'cicd', type:'OTHER', service:'github_actions', icon:'GHA'},{id:'t_gitlab', name:'GitLab CI', provider:'generic', cat:'cicd', type:'OTHER', service:'gitlab_ci', icon:'GL'},{id:'t_terraform', name:'Terraform', provider:'generic', cat:'cicd', type:'OTHER', service:'terraform', icon:'TF'},{id:'t_docker', name:'Docker', provider:'generic', cat:'cicd', type:'CONTAINER', service:'docker', icon:'DKR'},{id:'t_k8s', name:'Kubernetes', provider:'generic', cat:'cicd', type:'CONTAINER', service:'kubernetes', icon:'K8S'},{id:'t_ansible', name:'Ansible', provider:'generic', cat:'cicd', type:'OTHER', service:'ansible', icon:'ANS'},// Monitoring{id:'m_datadog', name:'Datadog', provider:'generic', cat:'monitoring',type:'MONITORING', service:'datadog', icon:'DD'},{id:'m_grafana', name:'Grafana', provider:'generic', cat:'monitoring',type:'MONITORING', service:'grafana', icon:'GF'},{id:'m_prometheus', name:'Prometheus', provider:'generic', cat:'monitoring',type:'MONITORING', service:'prometheus', icon:'PRO'},{id:'m_pagerduty', name:'PagerDuty', provider:'generic', cat:'monitoring',type:'MONITORING', service:'pagerduty', icon:'PD'},{id:'m_sentry', name:'Sentry', provider:'generic', cat:'monitoring',type:'MONITORING', service:'sentry', icon:'SNT'},{id:'m_newrelic', name:'New Relic', provider:'generic', cat:'monitoring',type:'MONITORING', service:'newrelic', icon:'NR'},// Security{id:'s_vault', name:'Vault', provider:'generic', cat:'security', type:'IAM', service:'vault', icon:'VLT'},{id:'s_snyk', name:'Snyk', provider:'generic', cat:'security', type:'MONITORING', service:'snyk', icon:'SNK'},{id:'s_waf', name:'AWS WAF', provider:'aws', cat:'security', type:'NETWORK', service:'waf', icon:'WAF'},{id:'s_sg', name:'Sec. Group', provider:'aws', cat:'security', type:'NETWORK', service:'security_group', icon:'SG'},];let selectedSvcs = new Map();let currentCat = 'all';let builderNodes = [];let builderEdges = [];let builderMode = 'drag';let connectSrc = null;function renderServiceGrid() {const grid = document.getElementById('serviceGrid');if (!grid) return;const q = (document.getElementById('serviceSearch').value || '').toLowerCase();const filtered = SERVICES.filter(s => {const matchCat = currentCat === 'all' || s.cat === currentCat;const matchQ = !q || s.name.toLowerCase().includes(q) || s.provider.includes(q) || s.service.includes(q);return matchCat && matchQ;});grid.innerHTML = filtered.map(s => `<div class="service-card ${selectedSvcs.has(s.id) ? 'selected' : ''}" onclick="toggleSvc('${s.id}')" title="${s.name} (${s.provider})"><div><span class="svc-prov prov-${s.provider}">${s.provider.toUpperCase()}</span></div><div class="svc-icon">${s.icon}</div><div class="svc-name">${s.name}</div></div>`).join('');}function setCat(el) {currentCat = el.dataset.cat;document.querySelectorAll('.cat-tab').forEach(t => t.classList.toggle('active', t.dataset.cat === currentCat));renderServiceGrid();}function toggleSvc(id) {const svc = SERVICES.find(s => s.id === id);if (!svc) return;if (selectedSvcs.has(id)) selectedSvcs.delete(id);else selectedSvcs.set(id, svc);renderServiceGrid();updateStack();}function updateStack() {const chips = document.getElementById('stackChips');chips.innerHTML = [...selectedSvcs.values()].map(s =>`<span class="stack-chip" onclick="toggleSvc('${s.id}')">${s.name} <span class="stack-chip-x">✕</span></span>`).join('');document.getElementById('continueBtn').disabled = selectedSvcs.size === 0;const types = new Set([...selectedSvcs.values()].map(s => s.type));renderSuggestions(types, [], 'suggList');}// --- Live suggestion rules (pure client-side) ---function computeSuggestions(types, edges, nodes) {const has = t => types.has(t);const suggs = [];if ((has('COMPUTE') || has('SERVERLESS') || has('CONTAINER')) && !has('MONITORING'))suggs.push({l:'crit', t:'No monitoring β critical gap. Add CloudWatch, Datadog, or Grafana'});if (has('DATABASE') && !has('MONITORING'))suggs.push({l:'warn', t:'Database with no monitoring β query anomalies will go undetected'});if (has('COMPUTE') && !has('GATEWAY') && !has('CDN'))suggs.push({l:'warn', t:'Compute exposed without a Gateway or CDN β add API Gateway or ALB'});if (has('STORAGE') && !has('IAM'))suggs.push({l:'warn', t:'Storage without IAM β public access risk. Add access control'});if ((has('COMPUTE') || has('DATABASE')) && !has('NETWORK'))suggs.push({l:'warn', t:'No VPC/Network isolation β resources may be publicly reachable'});if (has('CONTAINER') && !has('IAM'))suggs.push({l:'warn', t:'Containers need service accounts/RBAC β add IAM or Azure AD'});if (has('QUEUE') && !has('MONITORING'))suggs.push({l:'warn', t:'Queues should have dead-letter queue alerts configured'});if (has('IAM'))suggs.push({l:'info', t:'IAM present β verify least-privilege; avoid wildcard (*) actions'});if (has('MONITORING') && (has('COMPUTE') || has('SERVERLESS')))suggs.push({l:'good', t:'Monitoring + compute is a solid observability foundation'});if (has('GATEWAY') || has('CDN'))suggs.push({l:'good', t:'Gateway/CDN layer adds traffic control and DDoS protection'});if (has('NETWORK'))suggs.push({l:'good', t:'Network isolation (VPC/Subnet) is a strong security boundary'});// Edge-based suggestionsif (nodes.length > 0) {const connectedIds = new Set(edges.flatMap(e => [e.source, e.target]));nodes.forEach(n => {if (['DATABASE','STORAGE'].includes(n.type) && !connectedIds.has(n.id))suggs.push({l:'warn', t:`${n.name} is isolated β not connected to any other service`});});const mon = nodes.find(n => n.type === 'MONITORING');const computes = nodes.filter(n => ['COMPUTE','SERVERLESS','CONTAINER'].includes(n.type));if (mon && computes.length > 0) {const wired = edges.some(e =>(e.source === mon.id && computes.some(c => c.id === e.target)) ||(e.target === mon.id && computes.some(c => c.id === e.source)));suggs.push(wired? {l:'good', t:`${mon.name} is wired to compute β good observability`}: {l:'warn', t:`${mon.name} not connected to compute β wire it up`});}}if (suggs.length === 0)suggs.push({l:'info', t:'Architecture looks reasonable β run full analysis for detailed findings'});return suggs;}function renderSuggestions(types, edges, containerId, nodes) {const list = document.getElementById(containerId);if (!list) return;const items = computeSuggestions(types, edges || [], nodes || []);list.innerHTML = items.map(s =>`<div class="sugg-item ${s.l}"><div class="sugg-dot ${s.l}"></div><span>${s.t}</span></div>`).join('');}// --- Step navigation ---function goToStep2() {if (selectedSvcs.size === 0) return;builderNodes = []; builderEdges = []; connectSrc = null; builderMode = 'drag';document.getElementById('builder-step1').style.display = 'none';document.getElementById('builder-step2').style.display = 'block';const canvas = document.getElementById('diagramCanvas');[...canvas.children].forEach(c => { if (c.id !== 'canvasSvg') c.remove(); });document.getElementById('canvasSvg').innerHTML = svgDefs();const svcs = [...selectedSvcs.values()];const cols = Math.min(Math.ceil(Math.sqrt(svcs.length + 1)), 4);const nW = 118, nH = 64, gX = 28, gY = 20, pX = 18, pY = 18;svcs.forEach((svc, i) => {const col = i % cols, row = Math.floor(i / cols);const node = {id: svc.id, name: svc.name, type: svc.type, provider: svc.provider, service: svc.service,x: pX + col*(nW+gX), y: pY + row*(nH+gY), el: null};builderNodes.push(node);spawnNode(node, canvas);});setMode('drag');refreshCanvasSugg();}function goToStep1() {document.getElementById('builder-step2').style.display = 'none';document.getElementById('builder-step1').style.display = 'block';}function svgDefs() {return '<defs><marker id="ah" markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto"><polygon points="0 0,8 3,0 6" fill="#818cf8" opacity="0.85"/></marker></defs>';}function spawnNode(node, canvas) {const el = document.createElement('div');el.className = 'diagram-node';el.style.cssText = `left:${node.x}px;top:${node.y}px;cursor:grab;`;el.dataset.nid = node.id;el.innerHTML = `<div class="node-badge nt-${node.type}">${node.type}</div><div class="node-name">${node.name}</div><div class="node-prov">${node.provider}</div>`;node.el = el;canvas.appendChild(el);// dragel.addEventListener('mousedown', ev => {if (builderMode !== 'drag') return;ev.preventDefault();const r = canvas.getBoundingClientRect();const ox = ev.clientX - r.left - node.x, oy = ev.clientY - r.top - node.y;const mv = e2 => {node.x = Math.max(0, Math.min(canvas.clientWidth - 128, e2.clientX - r.left - ox));node.y = Math.max(0, Math.min(canvas.clientHeight - 72, e2.clientY - r.top - oy));el.style.left = node.x + 'px'; el.style.top = node.y + 'px';redrawEdges();};const up = () => { document.removeEventListener('mousemove', mv); document.removeEventListener('mouseup', up); };document.addEventListener('mousemove', mv);document.addEventListener('mouseup', up);});// connectel.addEventListener('click', ev => {if (builderMode !== 'connect') return;ev.stopPropagation();if (!connectSrc) {connectSrc = node; el.classList.add('connect-source');} else if (connectSrc.id !== node.id) {const dup = builderEdges.some(e => e.source === connectSrc.id && e.target === node.id);if (!dup) { builderEdges.push({source: connectSrc.id, target: node.id}); redrawEdges(); refreshCanvasSugg(); }connectSrc.el.classList.remove('connect-source'); connectSrc = null;}});}function setMode(mode) {builderMode = mode;if (connectSrc) { connectSrc.el.classList.remove('connect-source'); connectSrc = null; }document.getElementById('modeDrag').classList.toggle('active', mode === 'drag');document.getElementById('modeConnect').classList.toggle('active', mode === 'connect');document.getElementById('modeHint').textContent = mode === 'drag'? 'Drag nodes to arrange your architecture': 'Click a service, then click another to draw a connection';builderNodes.forEach(n => {n.el.classList.toggle('connect-mode', mode === 'connect');n.el.style.cursor = mode === 'drag' ? 'grab' : 'pointer';});}function removeLastEdge() {if (builderEdges.length > 0) { builderEdges.pop(); redrawEdges(); refreshCanvasSugg(); }}function redrawEdges() {const svg = document.getElementById('canvasSvg');svg.innerHTML = svgDefs();const nW = 118, nH = 64;builderEdges.forEach(edge => {const s = builderNodes.find(n => n.id === edge.source);const t = builderNodes.find(n => n.id === edge.target);if (!s || !t) return;const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');line.setAttribute('x1', s.x + nW/2); line.setAttribute('y1', s.y + nH/2);line.setAttribute('x2', t.x + nW/2); line.setAttribute('y2', t.y + nH/2);line.setAttribute('stroke', '#818cf8'); line.setAttribute('stroke-width', '2');line.setAttribute('stroke-opacity', '0.75'); line.setAttribute('marker-end', 'url(#ah)');svg.appendChild(line);});}function refreshCanvasSugg() {const types = new Set(builderNodes.map(n => n.type));renderSuggestions(types, builderEdges, 'canvasSuggList', builderNodes);}async function runBuilderAnalysis() {const btn = document.getElementById('builderAnalyzeBtn');const loader = document.getElementById('loader');const errorBox = document.getElementById('errorBox');errorBox.style.display = 'none';document.getElementById('results').style.display = 'none';loader.style.display = 'block';btn.disabled = true;try {const res = await fetch('/analyze-interactive', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({name: 'Interactive Diagram',components: builderNodes.map(n => ({id:n.id, name:n.name, type:n.type, provider:n.provider, service:n.service})),connections: builderEdges.map(e => ({source_id:e.source, target_id:e.target, label:''}))})});const data = await res.json();if (!res.ok) throw new Error(data.detail || 'Analysis failed');renderResults(data);} catch (err) {errorBox.textContent = err.message; errorBox.style.display = 'block';} finally {loader.style.display = 'none'; btn.disabled = false;}}// ===================== END BUILDER =====================function findingCard(f) {const card = document.createElement('div');card.className = 'finding-card ' + f.severity;
web/app.py+35-1
web/static/index.html+507-8