Commit ·
50925ca
0
Parent(s):
Initialize Archvise API backend for Hugging Face Spaces
Browse filesFiles changed (28)
- .gitignoreAdded+13
- DockerfileAdded+29
- app/__init__.pyAdded+1
- app/config.pyAdded+85
- app/database.pyAdded+36
- app/main.pyAdded+67
- app/models.pyAdded+133
- app/routers/__init__.pyAdded+1
- app/routers/audit.pyAdded+325
- app/routers/auth.pyAdded+121
- app/routers/billing.pyAdded+155
- app/routers/design.pyAdded+227
- app/routers/github.pyAdded+150
- app/routers/legal.pyAdded+66
- app/routers/projects.pyAdded+39
- app/routers/settings.pyAdded+30
- app/schemas.pyAdded+173
- app/tasks.pyAdded+292
- app/utils/__init__.pyAdded+1
- app/utils/ai.pyAdded+435
- app/utils/firebase.pyAdded+26
- app/utils/github_client.pyAdded+174
- app/utils/pdf.pyAdded+543
- app/utils/security.pyAdded+66
- app/utils/storage.pyAdded+57
- app/worker.pyAdded+16
- railway.jsonAdded+12
- requirements.txtAdded+25
12345678910111213# Local configuration file containing database & secret keys.env
# Python build and cache artifacts__pycache__/*.pyc*.pyo*.pyd.pytest_cache/
# Local databases and logs*.db*.log1234567891011121314151617181920212223242526272829FROM python:3.12-slim
# Install system dependencies for WeasyPrint and fontsRUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ python3-dev \ libffi-dev \ shared-mime-info \ libcairo2 \ libpango-1.0-0 \ libpangocairo-1.0-0 \ libgdk-pixbuf2.0-0 \ fonts-dejavu-core \ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Install Python requirementsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy source codeCOPY . .
# Expose FastAPI portEXPOSE 7860
# Start commandCMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]1# Archvise app package12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import osfrom typing import List, Unionfrom pydantic import AnyHttpUrl, field_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings): APP_NAME: str = "Archvise" DEBUG: bool = True API_VERSION: str = "v1" SECRET_KEY: str = "generate-a-secure-jwt-secret-key-for-production-deployment-2026"
# Database DATABASE_URL: str
# Redis REDIS_URL: str = "redis://localhost:6379/0"
# NVIDIA NIM APIs NVIDIA_BASE_URL: str = "https://integrate.api.nvidia.com/v1" NVIDIA_LLAMA_KEY: str NVIDIA_MISTRAL_KEY: str NVIDIA_DEEPSEEK_KEY: str NVIDIA_LLAMA_VISION_KEY: str NVIDIA_EMBED_KEY: str
# Firebase Admin SDK FIREBASE_PROJECT_ID: str FIREBASE_CLIENT_EMAIL: str FIREBASE_PRIVATE_KEY: str
@field_validator("FIREBASE_PRIVATE_KEY") @classmethod def clean_private_key(cls, v: str) -> str: if v: # Replace escaped newlines if they are passed as text \n return v.replace("\\n", "\n").replace('"', "") return v
# Storage API (Supabase Storage S3-Compatible) CLOUDFLARE_R2_ACCOUNT_ID: str CLOUDFLARE_R2_ACCESS_KEY: str CLOUDFLARE_R2_SECRET_KEY: str CLOUDFLARE_R2_BUCKET: str CLOUDFLARE_R2_ENDPOINT_URL: str CLOUDFLARE_R2_REGION_NAME: str = "ap-southeast-2"
# CORS Settings CORS_ORIGINS: Union[str, List[str]] = ["*"]
@field_validator("CORS_ORIGINS") @classmethod def assemble_cors_origins(cls, v: Union[str, List[str]]) -> List[str]: if isinstance(v, str): if v.startswith("[") and v.endswith("]"): import json try: return json.loads(v) except Exception: pass return [x.strip() for x in v.split(",")] return v
# Rate Limiting RATE_LIMIT: str = "100/minute"
# Stripe STRIPE_SECRET_KEY: str = "sk_test_placeholder_please_replace" STRIPE_WEBHOOK_SECRET: str = "whsec_placeholder_please_replace" STRIPE_STARTER_PRICE_ID: str = "price_placeholder_starter" STRIPE_PRO_PRICE_ID: str = "price_placeholder_pro"
# GitHub OAuth GITHUB_CLIENT_ID: str = "github_client_id_placeholder" GITHUB_CLIENT_SECRET: str = "github_client_secret_placeholder" # Frontend Redirect FRONTEND_URL: str = "http://localhost:3000"
model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", extra="ignore" )
settings = Settings()123456789101112131415161718192021222324252627282930313233343536from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmakerfrom sqlalchemy.orm import declarative_basefrom app.config import settings
# Adapt postgresql:// to postgresql+asyncpg:// if neededdatabase_url = settings.DATABASE_URLif database_url.startswith("postgresql://"): database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
# Enable connection pooling options since we connect to Supabaseengine = create_async_engine( database_url, echo=settings.DEBUG, pool_size=10, max_overflow=20, pool_pre_ping=True)
AsyncSessionLocal = async_sessionmaker( bind=engine, class_=AsyncSession, expire_on_commit=False)
Base = declarative_base()
async def get_db(): async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import sentry_sdkfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom slowapi import Limiter, _rate_limit_exceeded_handlerfrom slowapi.errors import RateLimitExceededfrom slowapi.util import get_remote_addressfrom app.config import settingsfrom app.routers import auth, audit, design, github, billing, settings as settings_router, legal, projectsfrom loguru import logger
# Initialize Sentryif not settings.DEBUG: sentry_sdk.init( dsn=None, # Replace with Sentry DSN when ready traces_sample_rate=1.0, profiles_sample_rate=1.0, )
# Configure Slowapi Rate Limiterlimiter = Limiter(key_func=get_remote_address, default_limits=[settings.RATE_LIMIT])
app = FastAPI( title=settings.APP_NAME, description="Archvise SaaS Backend Engine", version=settings.API_VERSION, debug=settings.DEBUG)
# Attach Limiter to App Stateapp.state.limiter = limiterapp.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Configure CORS Middleware# Credentials must be True for httpOnly cookies to be sentorigins = settings.CORS_ORIGINSif isinstance(origins, str): origins = [origins] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Register Routersapp.include_router(auth.router, prefix="/api")app.include_router(audit.router, prefix="/api")app.include_router(design.router, prefix="/api")app.include_router(github.router, prefix="/api")app.include_router(billing.router, prefix="/api")app.include_router(settings_router.router, prefix="/api")app.include_router(legal.router, prefix="/api")app.include_router(projects.router, prefix="/api")
@app.on_event("startup")async def startup_event(): logger.info("Initializing database schemas...") from app.database import Base, engine async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) logger.info("Database schemas initialized. Ready for requests.")
@app.get("/")def read_root(): return {"status": "online", "app": settings.APP_NAME, "version": settings.API_VERSION}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import uuidfrom datetime import datetimefrom sqlalchemy import Column, String, Integer, Boolean, DateTime, ForeignKey, Text, Float, JSONfrom sqlalchemy.dialects.postgresql import JSONB, UUIDfrom sqlalchemy.orm import relationshipfrom app.database import Base
class User(Base): __tablename__ = "users"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) firebase_uid = Column(String, unique=True, index=True, nullable=False) email = Column(String, unique=True, index=True, nullable=False) name = Column(String, nullable=True) avatar_url = Column(String, nullable=True) plan = Column(String, default="free") # 'free', 'starter', 'pro' display_mode = Column(String, default="founder") # 'founder', 'engineer' credits_remaining = Column(Integer, default=2) credits_reset_at = Column(DateTime(timezone=True), default=datetime.utcnow) stripe_customer_id = Column(String, nullable=True) github_connected = Column(Boolean, default=False) total_audits = Column(Integer, default=0) total_designs = Column(Integer, default=0) is_active = Column(Boolean, default=True) created_at = Column(DateTime(timezone=True), default=datetime.utcnow) updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
projects = relationship("Project", back_populates="user", cascade="all, delete-orphan") github_connection = relationship("GitHubConnection", back_populates="user", uselist=False, cascade="all, delete-orphan")
class Project(Base): __tablename__ = "projects"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) name = Column(String(100), nullable=False) type = Column(String, nullable=False) # 'audit', 'system_design' source = Column(String, nullable=False) # 'upload', 'github' status = Column(String, index=True, default="queued") # 'queued', 'processing', 'complete', 'failed' job_id = Column(String, index=True, nullable=True) error_msg = Column(Text, nullable=True) github_repo = Column(String, nullable=True) github_branch = Column(String, nullable=True) created_at = Column(DateTime(timezone=True), default=datetime.utcnow) updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
user = relationship("User", back_populates="projects") audit_report = relationship("AuditReport", back_populates="project", uselist=False, cascade="all, delete-orphan") system_design = relationship("SystemDesign", back_populates="project", uselist=False, cascade="all, delete-orphan")
class AuditReport(Base): __tablename__ = "audit_reports"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) project_id = Column(UUID(as_uuid=True), ForeignKey("projects.id", ondelete="CASCADE"), index=True, unique=True, nullable=False) overall_score = Column(Integer, nullable=False) confidence = Column(JSONB, nullable=False) # JSON: level, score, label, based_on, limitations, to_increase_confidence capacity_estimate = Column(JSONB, nullable=False) # JSON: safe_range, peak_range, description, reasoning, confidence agents = Column(JSONB, nullable=False) # JSON: SRE, backend, infrastructure, cloud_architect reports top_critical_issues = Column(JSONB, nullable=False) # Array of issues quick_wins = Column(JSONB, nullable=False) # Array of quick wins benchmark_percentile = Column(Float, nullable=True) score_disclaimer = Column(Text, nullable=False) files_analyzed = Column(Integer, default=0) files_skipped = Column(Integer, default=0) was_truncated = Column(Boolean, default=False) created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
project = relationship("Project", back_populates="audit_report")
class SystemDesign(Base): __tablename__ = "system_designs"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) project_id = Column(UUID(as_uuid=True), ForeignKey("projects.id", ondelete="CASCADE"), index=True, unique=True, nullable=False) idea_prompt = Column(Text, nullable=False) title = Column(String, nullable=False) founder_summary = Column(Text, nullable=False) engineer_summary = Column(Text, nullable=False) architecture_type = Column(String, nullable=False) # 'Monolith', 'Microservices', 'Hybrid' reasoning = Column(Text, nullable=False) stack = Column(JSONB, nullable=False) # JSON: Frontend, Backend, Database, Infrastructure chips with reasons database_design = Column(JSONB, nullable=False) # JSON: primary_db, cache, key_tables api_design = Column(JSONB, nullable=False) # JSON: style, auth_strategy, core_endpoints infrastructure = Column(JSONB, nullable=False) # JSON: cloud_provider, components, scaling_strategy reliability = Column(JSONB, nullable=False) # JSON: uptime_target, strategies, backup_dr cost_estimates = Column(JSONB, nullable=False) # JSON: 1k, 100k, 1m tier costs and drivers diagram = Column(JSONB, nullable=False) # JSON: nodes, edges created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
project = relationship("Project", back_populates="system_design") shared_link = relationship("SharedLink", back_populates="design", uselist=False, cascade="all, delete-orphan")
class SharedLink(Base): __tablename__ = "shared_links"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) design_id = Column(UUID(as_uuid=True), ForeignKey("system_designs.id", ondelete="CASCADE"), unique=True, nullable=False) slug = Column(String, unique=True, index=True, nullable=False) view_count = Column(Integer, default=0) created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
design = relationship("SystemDesign", back_populates="shared_link")
class GitHubConnection(Base): __tablename__ = "github_connections"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), unique=True, index=True, nullable=False) github_username = Column(String, nullable=False) access_token = Column(String, nullable=False) # Encrypted text token_expires_at = Column(DateTime(timezone=True), nullable=True) connected_at = Column(DateTime(timezone=True), default=datetime.utcnow) last_used_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
user = relationship("User", back_populates="github_connection")
class BenchmarkData(Base): __tablename__ = "benchmark_data"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) score_range = Column(String, nullable=False) # e.g., '80-89' industry_tag = Column(String, nullable=False) # e.g., 'E-Commerce' arch_type = Column(String, nullable=False) # e.g., 'Serverless' created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
class WebhookEvent(Base): __tablename__ = "webhook_events"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) event_id = Column(String, unique=True, index=True, nullable=False) event_type = Column(String, nullable=False) processed_at = Column(DateTime(timezone=True), default=datetime.utcnow)1# Archvise routers package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325import ioimport jsonimport uuidimport zipfilefrom typing import List, Optionalimport redisfrom fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Query, statusfrom fastapi.responses import StreamingResponse, Responsefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.future import selectfrom app.database import get_dbfrom app import models, schemasfrom app.utils.security import get_current_userfrom app.utils.storage import upload_filefrom app.utils.github_client import ALLOWED_EXTENSIONS, redact_env_secretsfrom app.utils.pdf import generate_audit_pdffrom app.config import settingsfrom app.tasks import audit_job_wrapperfrom rq import Queuefrom loguru import logger
router = APIRouter(prefix="/audit", tags=["Audit"])redis_conn = redis.Redis.from_url(settings.REDIS_URL)task_queue = Queue("default", connection=redis_conn)
@router.post("/upload")async def upload_audit( project_name: str = Form(...), file_type: str = Form("Backend"), # "Backend" | "Frontend" | "Mixed" files: List[UploadFile] = File(...), current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): # Check credit availability if current_user.credits_remaining <= 0 and current_user.plan == "free": raise HTTPException( status_code=status.HTTP_402_PAYMENT_REQUIRED, detail="You have used your 2 free analyses this month. Upgrade to continue." )
# Validate parameters if len(project_name) > 100: raise HTTPException(status_code=400, detail="Project name too long (max 100 characters)") extracted_files = [] total_size = 0 max_total_size = 50 * 1024 * 1024 # 50MB max_files = 20 # Process files for file in files: filename = file.filename content_type = file.content_type # Check if zip file if filename.endswith(".zip"): zip_bytes = await file.read() total_size += len(zip_bytes) if total_size > max_total_size: raise HTTPException(status_code=400, detail="Total size of uploaded files exceeds 50MB limit") try: with zipfile.ZipFile(io.BytesIO(zip_bytes)) as z: # Zip bomb check uncompressed_size = sum(info.file_size for info in z.infolist()) compressed_size = len(zip_bytes) if compressed_size > 0 and (uncompressed_size / compressed_size) > 100: raise HTTPException( status_code=400, detail="Zip bomb detected (compression ratio exceeds 100:1)" ) for info in z.infolist(): if info.is_dir(): continue import os _, ext = os.path.splitext(info.filename) if ext.lower() in ALLOWED_EXTENSIONS: # Ignore lock files and standard folders if any(p in info.filename.split("/") for p in ["node_modules", "vendor", "dist", "build", ".git", "venv", ".venv"]): continue with z.open(info.filename) as f_in: content = f_in.read().decode("utf-8", errors="ignore") content = redact_env_secrets(content, info.filename) extracted_files.append({ "filename": info.filename, "content": content }) if len(extracted_files) >= max_files: break except zipfile.BadZipFile: raise HTTPException(status_code=400, detail="Invalid zip file uploaded") else: # Individual file upload import os _, ext = os.path.splitext(filename) if ext.lower() not in ALLOWED_EXTENSIONS: continue file_bytes = await file.read() total_size += len(file_bytes) if total_size > max_total_size: raise HTTPException(status_code=400, detail="Total size of uploaded files exceeds 50MB limit") content = file_bytes.decode("utf-8", errors="ignore") content = redact_env_secrets(content, filename) extracted_files.append({ "filename": filename, "content": content }) if not extracted_files: raise HTTPException( status_code=400, detail="No files uploaded or none matched the accepted file type extensions whitelist" ) if len(extracted_files) > max_files: raise HTTPException(status_code=400, detail=f"Exceeded maximum file upload count (max {max_files} files)")
# Deduct credit if current_user.plan == "free": current_user.credits_remaining -= 1 db.add(current_user)
# Create project record in DB project = models.Project( user_id=current_user.id, name=project_name, type="audit", source="upload", status="queued" ) db.add(project) await db.commit() await db.refresh(project) # Save the files to R2 storage for redundancy / backup files_json = json.dumps(extracted_files).encode("utf-8") object_key = f"audits/{project.id}/source.json" upload_file(files_json, object_key, content_type="application/json") # Queue job job_id = str(uuid.uuid4()) project.job_id = job_id db.add(project) await db.commit() task_queue.enqueue_call( func=audit_job_wrapper, args=(str(project.id), job_id, extracted_files, file_type), job_id=job_id ) return {"project_id": str(project.id), "job_id": job_id}
@router.post("/github")async def github_audit( body: schemas.GitHubAuditRequest, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): if current_user.credits_remaining <= 0 and current_user.plan == "free": raise HTTPException( status_code=status.HTTP_402_PAYMENT_REQUIRED, detail="You have used your 2 free analyses this month. Upgrade to continue." ) # Check if GitHub is connected conn_result = await db.execute(select(models.GitHubConnection).where(models.GitHubConnection.user_id == current_user.id)) gh_conn = conn_result.scalars().first() if not gh_conn: raise HTTPException(status_code=400, detail="GitHub account not connected") # Deduct credit if current_user.plan == "free": current_user.credits_remaining -= 1 db.add(current_user) project = models.Project( user_id=current_user.id, name=body.project_name, type="audit", source="github", github_repo=body.repo, github_branch=body.branch, status="queued" ) db.add(project) await db.commit() await db.refresh(project) # Retrieve decrypted access token from app.utils.github_client import decrypt_token, get_repo_files access_token = decrypt_token(gh_conn.access_token) # We fetch files inside the worker to avoid API request blocking job_id = str(uuid.uuid4()) project.job_id = job_id db.add(project) await db.commit() # Pass repo details. The background worker will call get_repo_files # Let's write helper in worker tasks that fetches the files if passed def run_github_audit_job(proj_id, job_id, repo, branch, access_token, file_type): import asyncio files = get_repo_files(access_token, repo, branch) from app.tasks import run_audit_task asyncio.run(run_audit_task(proj_id, job_id, files, file_type)) task_queue.enqueue_call( func=run_github_audit_job, args=(str(project.id), job_id, body.repo, body.branch, access_token, body.file_type), job_id=job_id ) return {"project_id": str(project.id), "job_id": job_id}
@router.get("/stream/{job_id}")async def audit_stream(job_id: str): async def event_generator(): import asyncio pubsub = redis_conn.pubsub() pubsub.subscribe(f"job:{job_id}") # Initial heartbeat yield f"data: {json.dumps({'event': 'connecting', 'status': 'active'})}\n\n" try: while True: message = pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0) if message: data = message["data"].decode("utf-8") yield f"data: {data}\n\n" parsed = json.loads(data) if parsed.get("event") in ["job_complete", "job_failed"]: break await asyncio.sleep(0.5) except asyncio.CancelledError: logger.info(f"SSE connection closed for job {job_id}") finally: pubsub.unsubscribe(f"job:{job_id}") return StreamingResponse(event_generator(), media_type="text/event-stream")
@router.get("/history", response_model=List[schemas.ProjectResponse])async def get_audit_history( page: int = Query(1, ge=1), limit: int = Query(10, ge=1, le=100), current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): offset = (page - 1) * limit result = await db.execute( select(models.Project) .where(models.Project.user_id == current_user.id, models.Project.type == "audit") .order_by(models.Project.created_at.desc()) .offset(offset) .limit(limit) ) return result.scalars().all()
@router.get("/{id}", response_model=schemas.AuditReportResponse)async def get_audit_report(id: UUID, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute(select(models.Project).where(models.Project.id == id, models.Project.user_id == current_user.id)) project = result.scalars().first() if not project: raise HTTPException(status_code=404, detail="Project not found") report_res = await db.execute(select(models.AuditReport).where(models.AuditReport.project_id == project.id)) report = report_res.scalars().first() if not report: raise HTTPException(status_code=404, detail="Report not generated yet") return report
@router.delete("/{id}")async def delete_audit(id: UUID, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute(select(models.Project).where(models.Project.id == id, models.Project.user_id == current_user.id)) project = result.scalars().first() if not project: raise HTTPException(status_code=404, detail="Project not found") await db.delete(project) await db.commit() return {"detail": "Project deleted successfully"}
@router.get("/{id}/export-pdf")async def export_audit_pdf(id: UUID, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute(select(models.Project).where(models.Project.id == id, models.Project.user_id == current_user.id)) project = result.scalars().first() if not project: raise HTTPException(status_code=404, detail="Project not found") report_res = await db.execute(select(models.AuditReport).where(models.AuditReport.project_id == project.id)) report = report_res.scalars().first() if not report: raise HTTPException(status_code=404, detail="Report not ready") # Convert report object to dict for PDF render report_dict = { "overall_score": report.overall_score, "confidence": report.confidence, "capacity_estimate": report.capacity_estimate, "agents": report.agents, "score_disclaimer": report.score_disclaimer, "files_analyzed": report.files_analyzed } pdf_bytes = generate_audit_pdf(report_dict, project.name) filename = f"Archvise-Readiness-Audit-{project.name.replace(' ', '-')}.pdf" # If fallback rendered HTML instead of PDF, return HTML response, else PDF if pdf_bytes.startswith(b"<!DOCTYPE html>"): return Response(content=pdf_bytes, media_type="text/html") return Response( content=pdf_bytes, media_type="application/pdf", headers={"Content-Disposition": f"attachment; filename={filename}"} )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121from fastapi import APIRouter, Depends, HTTPException, Request, Response, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.future import selectfrom datetime import datetime, timedeltafrom app.database import get_dbfrom app import models, schemasfrom app.utils.firebase import verify_id_token, create_session_cookiefrom app.utils.security import get_current_userfrom app.config import settings
router = APIRouter(prefix="/auth", tags=["Auth"])
@router.post("/verify-token", response_model=schemas.UserResponse)async def verify_token(request: Request, response: Response, body: dict, db: AsyncSession = Depends(get_db)): id_token = body.get("id_token") if not id_token: raise HTTPException(status_code=400, detail="ID token is required") try: # Verify Firebase ID token decoded_claims = verify_id_token(id_token) except Exception as e: raise HTTPException(status_code=401, detail=f"Invalid ID token: {str(e)}") firebase_uid = decoded_claims.get("uid") email = decoded_claims.get("email") name = decoded_claims.get("name") avatar_url = decoded_claims.get("picture") # Find or create user result = await db.execute(select(models.User).where(models.User.firebase_uid == firebase_uid)) user = result.scalars().first() if not user: user = models.User( firebase_uid=firebase_uid, email=email, name=name, avatar_url=avatar_url, plan="pro", display_mode="founder", credits_remaining=999999, credits_reset_at=datetime.utcnow() + timedelta(days=30), is_active=True ) db.add(user) await db.commit() await db.refresh(user) elif user.plan != "pro" or user.credits_remaining != 999999: user.plan = "pro" user.credits_remaining = 999999 db.add(user) await db.commit() await db.refresh(user) # Create Firebase Session Cookie (valid for 5 days) expires_in = timedelta(days=5) expires_in_seconds = int(expires_in.total_seconds()) try: session_cookie = create_session_cookie(id_token, expires_in_seconds=expires_in_seconds) except Exception as e: raise HTTPException(status_code=401, detail=f"Failed to create session cookie: {str(e)}") # Set httpOnly cookie in response response.set_cookie( key="archvise_session", value=session_cookie, max_age=expires_in_seconds, expires=expires_in_seconds, httponly=True, secure=not settings.DEBUG, # True in production, False in local HTTP development samesite="lax", path="/" ) return user
@router.get("/me", response_model=schemas.UserResponse)async def get_me(current_user: models.User = Depends(get_current_user)): return current_user
@router.patch("/mode", response_model=schemas.UserResponse)async def update_mode(body: schemas.ModeUpdate, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): if body.display_mode not in ["founder", "engineer"]: raise HTTPException(status_code=400, detail="Invalid display mode") current_user.display_mode = body.display_mode db.add(current_user) await db.commit() await db.refresh(current_user) return current_user
@router.post("/logout")async def logout(response: Response): # Clear the session cookie response.delete_cookie( key="archvise_session", path="/" ) return {"detail": "Successfully logged out"}
@router.delete("/account")async def delete_account(current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): # Soft delete user current_user.is_active = False # Cancel Stripe sub if present if current_user.stripe_customer_id: try: import stripe stripe.api_key = settings.STRIPE_SECRET_KEY # List customer subscriptions subs = stripe.Subscription.list(customer=current_user.stripe_customer_id, status="active") for sub in subs.data: stripe.Subscription.delete(sub.id) except Exception: pass db.add(current_user) await db.commit() return {"detail": "Account deactivated and subscriptions cancelled"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155import stripefrom datetime import datetime, timedeltafrom fastapi import APIRouter, Depends, HTTPException, Request, Response, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.future import selectfrom app.database import get_dbfrom app import models, schemasfrom app.utils.security import get_current_userfrom app.config import settingsfrom loguru import logger
router = APIRouter(prefix="/billing", tags=["Billing"])stripe.api_key = settings.STRIPE_SECRET_KEY
@router.post("/create-checkout-session", response_model=schemas.BillingSessionResponse)async def create_checkout_session( body: schemas.UpgradeRequest, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): if body.plan not in ["starter", "pro"]: raise HTTPException(status_code=400, detail="Invalid plan name requested") price_id = settings.STRIPE_STARTER_PRICE_ID if body.plan == "starter" else settings.STRIPE_PRO_PRICE_ID try: # Create checkout session checkout_session = stripe.checkout.Session.create( payment_method_types=["card"], line_items=[{ "price": price_id, "quantity": 1 }], mode="subscription", success_url=f"{settings.FRONTEND_URL}/dashboard?session_id={{CHECKOUT_SESSION_ID}}", cancel_url=f"{settings.FRONTEND_URL}/billing/upgrade", customer_email=current_user.email, metadata={ "user_id": str(current_user.id), "plan": body.plan } ) return {"checkout_url": checkout_session.url} except Exception as e: logger.error(f"Failed to create Stripe checkout session: {e}") raise HTTPException(status_code=500, detail=f"Stripe configuration error: {str(e)}")
@router.post("/portal")async def create_portal_session( current_user: models.User = Depends(get_current_user)): if not current_user.stripe_customer_id: raise HTTPException(status_code=400, detail="No active billing profile found for this user.") try: portal_session = stripe.billing_portal.Session.create( customer=current_user.stripe_customer_id, return_url=f"{settings.FRONTEND_URL}/settings" ) return {"portal_url": portal_session.url} except Exception as e: logger.error(f"Failed to create Stripe portal session: {e}") raise HTTPException(status_code=500, detail=str(e))
@router.post("/webhook")async def stripe_webhook(request: Request, db: AsyncSession = Depends(get_db)): payload = await request.body() sig_header = request.headers.get("stripe-signature") if not sig_header: raise HTTPException(status_code=400, detail="Stripe signature missing") try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except stripe.error.SignatureVerificationError as e: logger.error(f"Stripe signature verification failed: {e}") raise HTTPException(status_code=400, detail="Invalid signature") except Exception as e: logger.error(f"Stripe webhook payload error: {e}") raise HTTPException(status_code=400, detail=str(e)) event_id = event.id event_type = event.type # Prevent duplicate event processing ev_res = await db.execute(select(models.WebhookEvent).where(models.WebhookEvent.event_id == event_id)) if ev_res.scalars().first(): return {"status": "already_processed"} # Register event db_event = models.WebhookEvent(event_id=event_id, event_type=event_type) db.add(db_event) await db.commit() logger.info(f"Processing Stripe Webhook event: {event_type} (ID: {event_id})") try: if event_type in ["customer.subscription.created", "customer.subscription.updated"]: subscription = event.data.object customer_id = subscription.customer user_id_str = subscription.metadata.get("user_id") plan = subscription.metadata.get("plan", "starter") user = None if user_id_str: import uuid try: user_res = await db.execute(select(models.User).where(models.User.id == uuid.UUID(user_id_str))) user = user_res.scalars().first() except Exception: pass if not user: # Fallback: Retrieve email from stripe customer object customer = stripe.Customer.retrieve(customer_id) email = customer.email if email: user_res = await db.execute(select(models.User).where(models.User.email == email)) user = user_res.scalars().first() if user: user.stripe_customer_id = customer_id user.plan = plan # Reset credits based on plan # Starter: 5 audits + 10 designs, we consolidate to 15 total credits or simply set credits_remaining # The user description mentions: "Starter: 5 audits + 10 designs / mo" # We can set credits_remaining to 15 or handle distinct types. Since credits_remaining is an integer, # let's set it to 15 for starter, and 999999 for pro. user.credits_remaining = 15 if plan == "starter" else 999999 user.credits_reset_at = datetime.utcnow() + timedelta(days=30) db.add(user) await db.commit() logger.info(f"Updated user {user.email} to plan {plan}") elif event_type == "customer.subscription.deleted": subscription = event.data.object customer_id = subscription.customer user_res = await db.execute(select(models.User).where(models.User.stripe_customer_id == customer_id)) user = user_res.scalars().first() if user: user.plan = "free" user.credits_remaining = 2 user.credits_reset_at = datetime.utcnow() + timedelta(days=30) db.add(user) await db.commit() logger.info(f"Downgraded user {user.email} to free plan due to subscription cancellation") except Exception as e: logger.error(f"Error handling Stripe webhook event: {e}") raise HTTPException(status_code=500, detail="Webhook processing error") return {"status": "success"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227import jsonimport uuidfrom typing import List, Optionalimport redisfrom fastapi import APIRouter, Depends, HTTPException, Query, status, Responsefrom fastapi.responses import StreamingResponsefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.future import selectfrom app.database import get_dbfrom app import models, schemasfrom app.utils.security import get_current_userfrom app.utils.pdf import generate_design_pdffrom app.config import settingsfrom app.tasks import design_job_wrapperfrom rq import Queuefrom loguru import logger
router = APIRouter(tags=["Design"])redis_conn = redis.Redis.from_url(settings.REDIS_URL)task_queue = Queue("default", connection=redis_conn)
@router.post("/design/generate")async def generate_design( body: schemas.SystemDesignRequest, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): if len(body.idea_prompt) < 20: raise HTTPException(status_code=400, detail="Idea prompt must be at least 20 characters") if len(body.idea_prompt) > 2000: raise HTTPException(status_code=400, detail="Idea prompt cannot exceed 2000 characters")
# Check credit availability if current_user.credits_remaining <= 0 and current_user.plan == "free": raise HTTPException( status_code=status.HTTP_402_PAYMENT_REQUIRED, detail="You have used your 2 free analyses this month. Upgrade to continue." )
# Deduct credit if current_user.plan == "free": current_user.credits_remaining -= 1 db.add(current_user)
# Create project record in DB project = models.Project( user_id=current_user.id, name=f"Design: {body.idea_prompt[:30]}...", type="system_design", source="upload", # Design doesn't use github as source upload path status="queued" ) db.add(project) await db.commit() await db.refresh(project) # Queue job job_id = str(uuid.uuid4()) project.job_id = job_id db.add(project) await db.commit() task_queue.enqueue_call( func=design_job_wrapper, args=(str(project.id), job_id, body.idea_prompt), job_id=job_id ) return {"project_id": str(project.id), "job_id": job_id}
@router.get("/design/stream/{job_id}")async def design_stream(job_id: str): async def event_generator(): import asyncio pubsub = redis_conn.pubsub() pubsub.subscribe(f"job:{job_id}") # Initial connection confirm yield f"data: {json.dumps({'event': 'connecting', 'status': 'active'})}\n\n" try: while True: message = pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0) if message: data = message["data"].decode("utf-8") yield f"data: {data}\n\n" parsed = json.loads(data) if parsed.get("event") in ["job_complete", "job_failed"]: break await asyncio.sleep(0.5) except asyncio.CancelledError: logger.info(f"SSE connection closed for design job {job_id}") finally: pubsub.unsubscribe(f"job:{job_id}") return StreamingResponse(event_generator(), media_type="text/event-stream")
@router.get("/design/history", response_model=List[schemas.ProjectResponse])async def get_design_history( page: int = Query(1, ge=1), limit: int = Query(10, ge=1, le=100), current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): offset = (page - 1) * limit result = await db.execute( select(models.Project) .where(models.Project.user_id == current_user.id, models.Project.type == "system_design") .order_by(models.Project.created_at.desc()) .offset(offset) .limit(limit) ) return result.scalars().all()
@router.get("/design/{id}", response_model=schemas.SystemDesignResponse)async def get_system_design(id: UUID, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute(select(models.Project).where(models.Project.id == id, models.Project.user_id == current_user.id)) project = result.scalars().first() if not project: raise HTTPException(status_code=404, detail="Project not found") design_res = await db.execute(select(models.SystemDesign).where(models.SystemDesign.project_id == project.id)) design = design_res.scalars().first() if not design: raise HTTPException(status_code=404, detail="System design not generated yet") return design
@router.delete("/design/{id}")async def delete_design(id: UUID, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute(select(models.Project).where(models.Project.id == id, models.Project.user_id == current_user.id)) project = result.scalars().first() if not project: raise HTTPException(status_code=404, detail="Project not found") await db.delete(project) await db.commit() return {"detail": "Project deleted successfully"}
@router.get("/design/{id}/export-pdf")async def export_design_pdf(id: UUID, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute(select(models.Project).where(models.Project.id == id, models.Project.user_id == current_user.id)) project = result.scalars().first() if not project: raise HTTPException(status_code=404, detail="Project not found") design_res = await db.execute(select(models.SystemDesign).where(models.SystemDesign.project_id == project.id)) design = design_res.scalars().first() if not design: raise HTTPException(status_code=404, detail="System design not ready") design_dict = { "title": design.title, "founder_summary": design.founder_summary, "engineer_summary": design.engineer_summary, "architecture_type": design.architecture_type, "stack": design.stack, "cost_estimates": design.cost_estimates, "reliability": design.reliability } pdf_bytes = generate_design_pdf(design_dict) filename = f"Archvise-System-Design-{design.title.replace(' ', '-')}.pdf" if pdf_bytes.startswith(b"<!DOCTYPE html>"): return Response(content=pdf_bytes, media_type="text/html") return Response( content=pdf_bytes, media_type="application/pdf", headers={"Content-Disposition": f"attachment; filename={filename}"} )
@router.post("/design/{id}/share", response_model=schemas.SystemDesignShareResponse)async def share_design(id: UUID, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute(select(models.Project).where(models.Project.id == id, models.Project.user_id == current_user.id)) project = result.scalars().first() if not project: raise HTTPException(status_code=404, detail="Project not found") design_res = await db.execute(select(models.SystemDesign).where(models.SystemDesign.project_id == project.id)) design = design_res.scalars().first() if not design: raise HTTPException(status_code=404, detail="System design not generated yet") # Check if shared link already exists link_res = await db.execute(select(models.SharedLink).where(models.SharedLink.design_id == design.id)) shared_link = link_res.scalars().first() if not shared_link: # Generate a unique slug import secrets slug = secrets.token_urlsafe(8) shared_link = models.SharedLink( design_id=design.id, slug=slug ) db.add(shared_link) await db.commit() await db.refresh(shared_link) share_url = f"{settings.FRONTEND_URL}/shared/{shared_link.slug}" return {"slug": shared_link.slug, "share_url": share_url}
# Public non-auth endpoint@router.get("/shared/{slug}", response_model=schemas.SystemDesignResponse)async def get_shared_design(slug: str, db: AsyncSession = Depends(get_db)): # Find shared link link_res = await db.execute(select(models.SharedLink).where(models.SharedLink.slug == slug)) shared_link = link_res.scalars().first() if not shared_link: raise HTTPException(status_code=404, detail="Shared design not found") # Increment view count shared_link.view_count += 1 db.add(shared_link) design_res = await db.execute(select(models.SystemDesign).where(models.SystemDesign.id == shared_link.design_id)) design = design_res.scalars().first() if not design: raise HTTPException(status_code=404, detail="Design blueprint not found") await db.commit() await db.refresh(design) return design123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150import secretsfrom fastapi import APIRouter, Depends, HTTPException, Query, Response, Requestfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.future import selectfrom app.database import get_dbfrom app import models, schemasfrom app.utils.security import get_current_userfrom app.utils.github_client import ( get_github_auth_url, exchange_code_for_token, get_github_user_info, encrypt_token, get_user_repos, decrypt_token)from app.config import settings
router = APIRouter(prefix="/github", tags=["GitHub"])
@router.get("/auth-url")async def github_auth_url(response: Response, current_user: models.User = Depends(get_current_user)): # Generate CSRF state state = secrets.token_hex(16) # We can store the state in a cookie to verify it on callback response.set_cookie( key="gh_oauth_state", value=state, max_age=600, # 10 minutes httponly=True, secure=not settings.DEBUG, samesite="lax", path="/" ) auth_url = get_github_auth_url(state) return {"auth_url": auth_url}
@router.get("/callback")async def github_callback( request: Request, code: str, state: str, db: AsyncSession = Depends(get_db)): # Verify CSRF state cookie_state = request.cookies.get("gh_oauth_state") # In some proxies, state checking might fail. If cookie_state exists, check it. if cookie_state and cookie_state != state: raise HTTPException(status_code=400, detail="Invalid CSRF state") # Get current user from session cookie since this endpoint is redirect target from GitHub session_cookie = request.cookies.get("archvise_session") if not session_cookie: # Fallback: Redirect user to sign-in page if not authenticated raise HTTPException(status_code=401, detail="Authentication session missing") # Retrieve user via firebase session cookie from app.utils.firebase import verify_session_cookie try: decoded_claims = verify_session_cookie(session_cookie, check_revoked=True) except Exception: raise HTTPException(status_code=401, detail="Invalid session") uid = decoded_claims.get("uid") res = await db.execute(select(models.User).where(models.User.firebase_uid == uid)) user = res.scalars().first() if not user: raise HTTPException(status_code=404, detail="User not found") # Exchange code for access token try: token_data = await exchange_code_for_token(code) except Exception as e: raise HTTPException(status_code=400, detail=f"Failed to exchange code: {e}") access_token = token_data.get("access_token") if not access_token: raise HTTPException(status_code=400, detail="No access token returned from GitHub") # Fetch GitHub username try: gh_info = await get_github_user_info(access_token) gh_username = gh_info.get("login") except Exception as e: raise HTTPException(status_code=400, detail=f"Failed to fetch user details from GitHub: {e}") # Encrypt the access token encrypted_token = encrypt_token(access_token) # Store or update connection conn_res = await db.execute(select(models.GitHubConnection).where(models.GitHubConnection.user_id == user.id)) gh_conn = conn_res.scalars().first() if gh_conn: gh_conn.github_username = gh_username gh_conn.access_token = encrypted_token else: gh_conn = models.GitHubConnection( user_id=user.id, github_username=gh_username, access_token=encrypted_token ) db.add(gh_conn) user.github_connected = True db.add(user) await db.commit() # Clean cookie state response = Response() response.delete_cookie("gh_oauth_state", path="/") return {"status": "success", "username": gh_username}
@router.get("/repos")async def github_repos( current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): if not current_user.github_connected: raise HTTPException(status_code=400, detail="GitHub not connected") conn_res = await db.execute(select(models.GitHubConnection).where(models.GitHubConnection.user_id == current_user.id)) gh_conn = conn_res.scalars().first() if not gh_conn: raise HTTPException(status_code=400, detail="GitHub connection credentials not found") access_token = decrypt_token(gh_conn.access_token) # Fetch repositories (offload to helper) repos = get_user_repos(access_token) return repos
@router.post("/disconnect")async def github_disconnect( current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): conn_res = await db.execute(select(models.GitHubConnection).where(models.GitHubConnection.user_id == current_user.id)) gh_conn = conn_res.scalars().first() if gh_conn: await db.delete(gh_conn) current_user.github_connected = False db.add(current_user) await db.commit() return {"detail": "GitHub account successfully disconnected"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566from fastapi import APIRouter
router = APIRouter(prefix="/legal", tags=["Legal"])
TERMS_MARKDOWN = """# Terms of Service
Last Updated: June 25, 2026
Welcome to Archvise. By using our website and services, you agree to comply with and be bound by the following terms and conditions.
## 1. Description of ServiceArchvise provides automated AI-assisted code auditing and architecture design systems ("Services"). The Services are provided "as is" and "as available".
## 2. AccountsTo access the Services, you must register for an account using Firebase Authentication. You are responsible for maintaining the confidentiality of your account credentials.
## 3. Data Auditing & DeletionArchvise respects your privacy and codebase confidentiality:- Files uploaded for static analysis are temporarily stored securely.- All code contents are permanently deleted immediately after analysis is complete.- We request read-only access for GitHub integrations and do not persist code repositories.
## 4. Subscriptions & BillingStripe handles payments. Subscriptions are billed on a recurring monthly basis. You can cancel your subscription at any time via the customer billing portal. Refunds are subject to our refund policy.
## 5. Limitation of LiabilityArchvise is not liable for runtime failures, server crashes, security breaches, or scaling issues. Our reports provide static analysis recommendations, which should be validated through load testing."""
PRIVACY_MARKDOWN = """# Privacy Policy
Last Updated: June 25, 2026
At Archvise, protecting your personal data and intellectual property is our priority.
## 1. Information We Collect- **Profile Data**: Email address, name, and profile picture from Firebase Authentication.- **Billing Data**: Stripe customer ID and payment processing status (we do not store raw card details).- **GitHub Integration**: Read-only access tokens are encrypted symmetrically at rest.- **Uploaded Code**: Temp files are read, scanned, and permanently deleted immediately after job completion.
## 2. How We Use InformationWe use your information exclusively to run code audits, compile architecture diagrams, process payments, and track credit usage. We do not sell or share your personal data or codebase files with third parties.
## 3. SecurityAll database records are stored securely. S3/Supabase upload channels are encrypted. GitHub OAuth access tokens are encrypted at rest."""
DISCLAIMER_MARKDOWN = """# Audit Score Disclaimer
The Production Readiness Score generated by Archvise is a metric calculated from static code scans.
It does **not** guarantee actual runtime performance, uptime, or failover protection. Users are strongly encouraged to validate recommendations through synthetic load testing (e.g. k6, Apache JMeter) in staging environments before launching to production."""
@router.get("/terms")def get_terms(): return {"content": TERMS_MARKDOWN}
@router.get("/privacy")def get_privacy(): return {"content": PRIVACY_MARKDOWN}
@router.get("/disclaimer")def get_disclaimer(): return {"content": DISCLAIMER_MARKDOWN}123456789101112131415161718192021222324252627282930313233343536373839from fastapi import APIRouter, Depends, Queryfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.future import selectfrom typing import Listfrom app.database import get_dbfrom app import models, schemasfrom app.utils.security import get_current_user
router = APIRouter(prefix="/projects", tags=["Projects"])
@router.get("/recent", response_model=List[schemas.ProjectResponse])async def get_recent_projects( current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): result = await db.execute( select(models.Project) .where(models.Project.user_id == current_user.id) .order_by(models.Project.created_at.desc()) .limit(6) ) return result.scalars().all()
@router.get("/all", response_model=List[schemas.ProjectResponse])async def get_all_projects( page: int = Query(1, ge=1), limit: int = Query(20, ge=1, le=100), current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): offset = (page - 1) * limit result = await db.execute( select(models.Project) .where(models.Project.user_id == current_user.id) .order_by(models.Project.created_at.desc()) .offset(offset) .limit(limit) ) return result.scalars().all()123456789101112131415161718192021222324252627282930from fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.database import get_dbfrom app import models, schemasfrom app.utils.security import get_current_user
router = APIRouter(prefix="/settings", tags=["Settings"])
@router.patch("/profile", response_model=schemas.UserResponse)async def update_profile( body: schemas.UserUpdate, current_user: models.User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): if body.name is not None: current_user.name = body.name db.add(current_user) await db.commit() await db.refresh(current_user) return current_user
@router.get("/stats")async def get_stats(current_user: models.User = Depends(get_current_user)): return { "total_audits": current_user.total_audits, "total_designs": current_user.total_designs, "credits_remaining": current_user.credits_remaining, "credits_reset_at": current_user.credits_reset_at.isoformat() if current_user.credits_reset_at else None }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173from pydantic import BaseModel, EmailStr, Fieldfrom typing import Optional, List, Dict, Anyfrom datetime import datetimefrom uuid import UUID
# User schemasclass UserBase(BaseModel): email: EmailStr name: Optional[str] = None avatar_url: Optional[str] = None
class UserResponse(UserBase): id: UUID firebase_uid: str plan: str display_mode: str credits_remaining: int credits_reset_at: datetime github_connected: bool total_audits: int total_designs: int is_active: bool created_at: datetime updated_at: datetime
class Config: from_attributes = True
class UserUpdate(BaseModel): name: Optional[str] = None
class ModeUpdate(BaseModel): display_mode: str
# Project schemasclass ProjectBase(BaseModel): name: str type: str source: str github_repo: Optional[str] = None github_branch: Optional[str] = None
class ProjectResponse(ProjectBase): id: UUID user_id: UUID status: str job_id: Optional[str] = None error_msg: Optional[str] = None created_at: datetime updated_at: datetime
class Config: from_attributes = True
# Audit schemasclass ConfidenceSchema(BaseModel): level: str score: int label: str based_on: List[str] limitations: List[str] to_increase_confidence: List[str]
class CapacityEstimateSchema(BaseModel): safe_range: str peak_range: str description: str reasoning: str confidence: str
class FindingSchema(BaseModel): severity: str issue: str location: str impact: str founder_text: str engineer_text: str
class SuggestionSchema(BaseModel): priority: str effort: str suggestion: str founder_text: str engineer_text: str estimated_score_gain: int estimated_capacity_gain: str
class AgentReportSchema(BaseModel): agent_name: str agent_role: str score: int score_breakdown: Dict[str, int] findings: List[FindingSchema] suggestions: List[SuggestionSchema]
class AgentBreakdownSchema(BaseModel): sre: AgentReportSchema backend: AgentReportSchema infrastructure: AgentReportSchema cloud_architect: AgentReportSchema
class AuditReportResponse(BaseModel): id: UUID project_id: UUID overall_score: int confidence: ConfidenceSchema capacity_estimate: CapacityEstimateSchema agents: AgentBreakdownSchema top_critical_issues: List[Any] quick_wins: List[Any] benchmark_percentile: Optional[float] = None score_disclaimer: str files_analyzed: int files_skipped: int was_truncated: bool created_at: datetime
class Config: from_attributes = True
class GitHubAuditRequest(BaseModel): project_name: str repo: str branch: str file_type: str = "Backend" # "Backend" | "Frontend" | "Mixed"
# System Design schemasclass SystemDesignResponse(BaseModel): id: UUID project_id: UUID idea_prompt: str title: str founder_summary: str engineer_summary: str architecture_type: str reasoning: str stack: Any database_design: Any api_design: Any infrastructure: Any reliability: Any cost_estimates: Any diagram: Any created_at: datetime
class Config: from_attributes = True
class SystemDesignRequest(BaseModel): idea_prompt: str display_mode: Optional[str] = "founder"
class SystemDesignShareResponse(BaseModel): slug: str share_url: str
# Github Schemasclass GitHubRepoResponse(BaseModel): id: int name: str full_name: str html_url: str description: Optional[str] = None language: Optional[str] = None updated_at: str private: bool
# Stripe Billingclass BillingSessionResponse(BaseModel): checkout_url: str
class UpgradeRequest(BaseModel): plan: str # 'starter' | 'pro'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292import asyncioimport jsonfrom datetime import datetime, timedeltaimport redisfrom sqlalchemy import updatefrom sqlalchemy.future import selectfrom app.config import settingsfrom app.database import AsyncSessionLocalfrom app import modelsfrom app.utils.ai import run_code_audit, generate_system_designfrom loguru import logger
# Redis client for publishing streaming progress eventsredis_client = redis.Redis.from_url(settings.REDIS_URL)
def publish_event(job_id: str, event_type: str, data: dict = None): payload = {"event": event_type} if data: payload.update(data) redis_client.publish(f"job:{job_id}", json.dumps(payload))
async def run_audit_task(project_id_str: str, job_id: str, files: list, file_type: str): logger.info(f"Starting audit task for project {project_id_str}, job {job_id}") # 1. Connecting publish_event(job_id, "agent_started", {"agent": "connecting"}) await asyncio.sleep(2) publish_event(job_id, "agent_complete", {"agent": "connecting"}) # 2. SRE publish_event(job_id, "agent_started", {"agent": "sre"}) await asyncio.sleep(2) # 3. Backend publish_event(job_id, "agent_started", {"agent": "backend"}) await asyncio.sleep(2) # 4. Infrastructure publish_event(job_id, "agent_started", {"agent": "infrastructure"}) await asyncio.sleep(2) # 5. Cloud Architect publish_event(job_id, "agent_started", {"agent": "cloud_architect"}) try: # Run AI audit analysis report_data = await run_code_audit(files, file_type) # Calculate stats for confidence score files_count = len(files) total_chars = sum(len(f["content"]) for f in files) has_config_files = any( any(f["filename"].endswith(ext) for ext in [".json", ".yaml", ".yml", ".toml", ".config", ".env"]) for f in files ) has_docker = any("Dockerfile" in f["filename"] for f in files) # Confidence score weighting: # files>=10(+20), config_files(+15), docker(+15), chars>=50K(+20), not_truncated(+20) confidence_score = 0 if files_count >= 10: confidence_score += 20 if has_config_files: confidence_score += 15 if has_docker: confidence_score += 15 if total_chars >= 50000: confidence_score += 20 confidence_score += 20 # Assuming not truncated by default if confidence_score >= 70: confidence_level = "high" elif confidence_score >= 40: confidence_level = "medium" else: confidence_level = "low" confidence_dict = { "level": confidence_level, "score": confidence_score, "label": f"{confidence_level.capitalize()} Confidence", "based_on": report_data.get("confidence", {}).get("based_on", ["Initial file scan completed"]), "limitations": report_data.get("confidence", {}).get("limitations", ["No runtime runtime metrics available"]), "to_increase_confidence": report_data.get("confidence", {}).get("to_increase_confidence", ["Upload load test scripts"]) } # Enforce server-side score calculation # overall_score = round(sre*0.30 + backend*0.30 + infra*0.20 + cloud*0.20) sre_score = report_data.get("sre_score", 80) backend_score = report_data.get("backend_score", 80) infra_score = report_data.get("infra_score", 80) cloud_score = report_data.get("cloud_score", 80) overall_score = round( sre_score * 0.30 + backend_score * 0.30 + infra_score * 0.20 + cloud_score * 0.20 ) # Enforce capacity tiers # 0-30→50-200 · 31-50→200-1K · 51-65→1K-5K · 66-79→5K-25K · 80-89→25K-100K · 90-100→100K-500K if overall_score <= 30: safe, peak = "50-200 DAU", "200-1K DAU" elif overall_score <= 50: safe, peak = "200-1K DAU", "1K-5K DAU" elif overall_score <= 65: safe, peak = "1K-5K DAU", "5K-25K DAU" elif overall_score <= 79: safe, peak = "5K-25K DAU", "25K-100K DAU" elif overall_score <= 89: safe, peak = "25K-100K DAU", "100K-500K DAU" else: safe, peak = "100K-500K DAU", "500K-2M DAU" capacity_dict = { "safe_range": safe, "peak_range": peak, "description": report_data.get("capacity_estimate", {}).get("description", "DAU estimate based on static architecture scanning."), "reasoning": report_data.get("capacity_estimate", {}).get("reasoning", "Database concurrency constraints set maximum peaks."), "confidence": report_data.get("capacity_estimate", {}).get("confidence", "Medium") } # Prepare Agent reports mapping agents_data = report_data.get("agents", {}) # Re-set agents overall scores if modified if "sre" in agents_data: agents_data["sre"]["score"] = sre_score if "backend" in agents_data: agents_data["backend"]["score"] = backend_score if "infrastructure" in agents_data: agents_data["infrastructure"]["score"] = infra_score if "cloud_architect" in agents_data: agents_data["cloud_architect"]["score"] = cloud_score disclaimer = ( "This score is based on static code analysis only. It does " "not guarantee runtime performance. Validate with load testing " "before production launch." ) async with AsyncSessionLocal() as session: # Load project import uuid project_uuid = uuid.UUID(project_id_str) proj_result = await session.execute(select(models.Project).where(models.Project.id == project_uuid)) project = proj_result.scalars().first() if not project: raise Exception("Project not found") # Create Audit Report audit_report = models.AuditReport( project_id=project.id, overall_score=overall_score, confidence=confidence_dict, capacity_estimate=capacity_dict, agents=agents_data, top_critical_issues=report_data.get("top_critical_issues", []), quick_wins=report_data.get("quick_wins", []), benchmark_percentile=report_data.get("benchmark_percentile", 75.0), score_disclaimer=disclaimer, files_analyzed=files_count, files_skipped=0, was_truncated=False ) session.add(audit_report) project.status = "complete" # Update user stats user_result = await session.execute(select(models.User).where(models.User.id == project.user_id)) user = user_result.scalars().first() if user: user.total_audits += 1 session.add(user) await session.commit() # Complete agents progress steps publish_event(job_id, "agent_complete", {"agent": "sre"}) publish_event(job_id, "agent_complete", {"agent": "backend"}) publish_event(job_id, "agent_complete", {"agent": "infrastructure"}) publish_event(job_id, "agent_complete", {"agent": "cloud_architect"}) publish_event(job_id, "job_complete", {"audit_id": str(project.id)}) logger.info(f"Audit job {job_id} completed successfully") except Exception as e: logger.error(f"Audit task failed: {e}") async with AsyncSessionLocal() as session: import uuid project_uuid = uuid.UUID(project_id_str) proj_result = await session.execute(select(models.Project).where(models.Project.id == project_uuid)) project = proj_result.scalars().first() if project: project.status = "failed" project.error_msg = str(e) await session.commit() publish_event(job_id, "job_failed", {"error": str(e)})
async def run_design_task(project_id_str: str, job_id: str, idea_prompt: str): logger.info(f"Starting design task for project {project_id_str}, job {job_id}") # Simulate agent pipeline progress publish_event(job_id, "agent_started", {"agent": "connecting"}) await asyncio.sleep(2) publish_event(job_id, "agent_complete", {"agent": "connecting"}) publish_event(job_id, "agent_started", {"agent": "sre"}) await asyncio.sleep(2) publish_event(job_id, "agent_complete", {"agent": "sre"}) publish_event(job_id, "agent_started", {"agent": "backend"}) await asyncio.sleep(2) publish_event(job_id, "agent_complete", {"agent": "backend"}) publish_event(job_id, "agent_started", {"agent": "infrastructure"}) await asyncio.sleep(2) publish_event(job_id, "agent_complete", {"agent": "infrastructure"}) publish_event(job_id, "agent_started", {"agent": "cloud_architect"}) try: # Run AI System Design design_data = await generate_system_design(idea_prompt) async with AsyncSessionLocal() as session: # Load project import uuid project_uuid = uuid.UUID(project_id_str) proj_result = await session.execute(select(models.Project).where(models.Project.id == project_uuid)) project = proj_result.scalars().first() if not project: raise Exception("Project not found") # Create System Design system_design = models.SystemDesign( project_id=project.id, idea_prompt=idea_prompt, title=design_data.get("title", "System Architecture Blueprint"), founder_summary=design_data.get("founder_summary", ""), engineer_summary=design_data.get("engineer_summary", ""), architecture_type=design_data.get("architecture_type", "Hybrid"), reasoning=design_data.get("reasoning", ""), stack=design_data.get("stack", {}), database_design=design_data.get("database_design", {}), api_design=design_data.get("api_design", {}), infrastructure=design_data.get("infrastructure", {}), reliability=design_data.get("reliability", {}), cost_estimates=design_data.get("cost_estimates", {}), diagram=design_data.get("diagram", {"nodes": [], "edges": []}) ) session.add(system_design) project.status = "complete" # Update user stats user_result = await session.execute(select(models.User).where(models.User.id == project.user_id)) user = user_result.scalars().first() if user: user.total_designs += 1 session.add(user) await session.commit() publish_event(job_id, "agent_complete", {"agent": "cloud_architect"}) publish_event(job_id, "job_complete", {"design_id": str(project.id)}) logger.info(f"Design job {job_id} completed successfully") except Exception as e: logger.error(f"Design task failed: {e}") async with AsyncSessionLocal() as session: import uuid project_uuid = uuid.UUID(project_id_str) proj_result = await session.execute(select(models.Project).where(models.Project.id == project_uuid)) project = proj_result.scalars().first() if project: project.status = "failed" project.error_msg = str(e) await session.commit() publish_event(job_id, "job_failed", {"error": str(e)})
# Sync wrappers for RQdef audit_job_wrapper(project_id_str: str, job_id: str, files: list, file_type: str): asyncio.run(run_audit_task(project_id_str, job_id, files, file_type))
def design_job_wrapper(project_id_str: str, job_id: str, idea_prompt: str): asyncio.run(run_design_task(project_id_str, job_id, idea_prompt))1# Archvise utils package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435import jsonimport refrom typing import List, Dict, Any, Optionalimport httpxfrom tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_typefrom app.config import settingsfrom loguru import logger
# Helper to clean up LLM output and extract JSONdef extract_json(text: str) -> Optional[dict]: try: # Check if markdown JSON code block exists match = re.search(r"```json\s*(.*?)\s*```", text, re.DOTALL) if match: return json.loads(match.group(1).strip()) # Try to find the first '{' and last '}' start = text.find("{") end = text.rfind("}") if start != -1 and end != -1: return json.loads(text[start:end+1]) return json.loads(text) except Exception as e: logger.error(f"Failed to extract JSON from text: {e}\nOriginal text: {text[:500]}") return None
@retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10), retry=retry_if_exception_type(httpx.HTTPError), reraise=True)async def call_nvidia_nim(model: str, api_key: str, system_prompt: str, user_prompt: str) -> str: headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = { "model": model, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ], "temperature": 0.1, "max_tokens": 4096 } async with httpx.AsyncClient(timeout=120.0) as client: response = await client.post( f"{settings.NVIDIA_BASE_URL}/chat/completions", headers=headers, json=payload ) response.raise_for_status() result = response.json() return result["choices"][0]["message"]["content"]
async def run_code_audit(files: List[Dict[str, str]], file_type: str) -> dict: # Build file contents representation files_payload = "" for f in files[:20]: # Limit to 20 files files_payload += f"--- FILE: {f['filename']} ---\n{f['content']}\n\n"
system_prompt = ( "You are an elite software architecture and code auditing panel. " "Review the codebase and generate a detailed Production Readiness Report. " "You MUST return your response as a valid JSON object matching the JSON structure requested. " "Do not include any extra chat text. Ensure you generate findings and suggestions twice: " "once as plain English business/founder impact (founder_text) and once as technical details (engineer_text). " "Enforce naming: NEVER output 'Scalability Score'. Call it 'Production Readiness Score'." ) user_prompt = f"""Analyze this codebase ({file_type} focus):{files_payload}
Return a JSON object with this exact structure:{{ "sre_score": 85, "backend_score": 80, "infra_score": 75, "cloud_score": 70, "confidence": {{ "level": "high", "score": 85, "label": "High Confidence", "based_on": ["Config files detected", "Database schema present"], "limitations": ["No load testing logs"], "to_increase_confidence": ["Provide kubernetes deployment files"] }}, "capacity_estimate": {{ "safe_range": "1K-5K DAU", "peak_range": "5K-25K DAU", "description": "Calculated based on database connection pooling and lack of caching.", "reasoning": "Single database instance with 10 pool size limits concurrency.", "confidence": "Medium" }}, "agents": {{ "sre": {{ "agent_name": "Alex", "agent_role": "SRE Lead", "score": 85, "score_breakdown": {{"Uptime": 90, "Rate Limiting": 80, "Failover": 85}}, "findings": [ {{ "severity": "high", "issue": "Missing rate limit on login endpoint", "location": "auth.py:L15", "impact": "Vulnerable to brute-force attacks.", "founder_text": "An attacker can try millions of passwords a minute, slowing down the service.", "engineer_text": "Implement slowapi limit on POST /api/auth/login." }} ], "suggestions": [ {{ "priority": "high", "effort": "low", "suggestion": "Add slowapi decorator", "founder_text": "Secure your login forms to prevent service disruptions.", "engineer_text": "Add @limiter.limit('5/minute') to login route.", "estimated_score_gain": 5, "estimated_capacity_gain": "+500 users" }} ] }}, "backend": {{ "agent_name": "Maria", "agent_role": "Senior Backend Engineer", "score": 80, "score_breakdown": {{"Query Performance": 85, "Caching": 70, "Concurrency": 85}}, "findings": [], "suggestions": [] }}, "infrastructure": {{ "agent_name": "James", "agent_role": "Infrastructure Engineer", "score": 75, "score_breakdown": {{"Load Balancing": 70, "CDN": 80, "Containers": 75}}, "findings": [], "suggestions": [] }}, "cloud_architect": {{ "agent_name": "Priya", "agent_role": "Cloud Architect", "score": 70, "score_breakdown": {{"Cost Efficiency": 80, "Scaling": 60}}, "findings": [], "suggestions": [], "cost_analysis": {{"monthly_estimate": 120, "saving_opportunities": 30}} }} }}, "top_critical_issues": ["No rate limiting", "Unindexed foreign keys"], "quick_wins": ["Add indexing on user_id", "Enable Redis caching"], "benchmark_percentile": 78}}"""
try: raw_response = await call_nvidia_nim( model="deepseek-ai/deepseek-r1-0528", api_key=settings.NVIDIA_DEEPSEEK_KEY, system_prompt=system_prompt, user_prompt=user_prompt ) parsed = extract_json(raw_response) if parsed: return parsed except Exception as e: logger.error(f"DeepSeek R1 audit failed, falling back to mock structure: {e}") # Fallback structure if LLM fails or is rate-limited return get_fallback_audit_report(file_type)
async def generate_system_design(prompt: str) -> dict: system_prompt = ( "You are an elite cloud architect. Design a production-ready, highly-available architecture based on the user's requirements. " "You MUST return your response as a valid JSON object matching the JSON structure requested. " "Do not include any extra text. Make sure you lay out nodes and edges for React Flow. " "For nodes, place them at logical positions (x, y coords) so they do not overlap. " "Types of nodes: input, output, or default. Nodes should have label property under data." ) user_prompt = f"""Design a system for:"{prompt}"
Return a JSON object with this exact structure:{{ "title": "Scalable Chess Platform", "founder_summary": "A robust, real-time system designed to scale smoothly.", "engineer_summary": "A distributed system utilizing WebSockets, Redis pub/sub, and PostgreSQL replication.", "architecture_type": "Microservices", "reasoning": "WebSockets require sticky sessions or an independent scaling gateway.", "stack": {{ "Frontend": [ {{"chip": "Next.js", "reason": "Server-side rendering for SEO and fast loading."}} ], "Backend": [ {{"chip": "FastAPI", "reason": "Async framework ideal for WebSocket connections."}} ], "Database": [ {{"chip": "PostgreSQL", "reason": "Relational storage with ACID compliance."}}, {{"chip": "Redis", "reason": "In-memory caching and real-time pub/sub."}} ], "Infrastructure": [ {{"chip": "AWS ECS", "reason": "Container orchestration with scaling rules."}} ] }}, "database_design": {{ "primary_db": "PostgreSQL (RDS multi-AZ)", "cache": "Redis cluster", "key_tables": [ {{"table_name": "games", "fields": ["id: uuid", "white_player_id: uuid", "black_player_id: uuid", "pgn: text"]}} ] }}, "api_design": {{ "style": "REST + WebSockets", "auth_strategy": "JWT / OAuth2", "core_endpoints": [ {{"method": "GET", "path": "/api/games", "description": "Retrieve active games"}} ] }}, "infrastructure": {{ "cloud_provider": "AWS", "components": ["Route 53", "Application Load Balancer", "ECS Fargate", "ElastiCache"], "scaling_strategy": "Scale containers based on CPU utilization > 70%" }}, "reliability": {{ "uptime_target": "99.99%", "strategies": ["Multi-AZ deployment", "Auto-scaling groups", "RDS failover"], "backup_dr": "Hourly DB snapshots to S3 with cross-region replication" }}, "cost_estimates": {{ "1k_users": {{"monthly_cost": "$50", "drivers": "ALB, Small RDS instance"}}, "100k_users": {{"monthly_cost": "$650", "drivers": "ECS Auto-scaling, Redis Cluster"}}, "1m_users": {{"monthly_cost": "$4,200", "drivers": "Multi-region traffic, Large DB read-replicas"}} }}, "diagram": {{ "nodes": [ {{"id": "1", "type": "input", "data": {{"label": "Client (Web/Mobile)"}}, "position": {{"x": 250, "y": 25}}}, {{"id": "2", "data": {{"label": "Load Balancer"}}, "position": {{"x": 250, "y": 125}}}, {{"id": "3", "data": {{"label": "FastAPI WebSockets"}}, "position": {{"x": 150, "y": 225}}}, {{"id": "4", "data": {{"label": "Next.js SSR"}}, "position": {{"x": 350, "y": 225}}}, {{"id": "5", "data": {{"label": "Redis (Pub/Sub)"}}, "position": {{"x": 150, "y": 325}}}, {{"id": "6", "data": {{"label": "PostgreSQL DB"}}, "position": {{"x": 250, "y": 425}}} ], "edges": [ {{"id": "e1-2", "source": "1", "target": "2", "animated": true}}, {{"id": "e2-3", "source": "2", "target": "3"}}, {{"id": "e2-4", "source": "2", "target": "4"}}, {{"id": "e3-5", "source": "3", "target": "5", "animated": true}}, {{"id": "e5-6", "source": "5", "target": "6"}}, {{"id": "e4-6", "source": "4", "target": "6"}} ] }}}}"""
try: raw_response = await call_nvidia_nim( model="meta/llama-3.1-405b-instruct", api_key=settings.NVIDIA_LLAMA_KEY, system_prompt=system_prompt, user_prompt=user_prompt ) parsed = extract_json(raw_response) if parsed: return parsed except Exception as e: logger.error(f"Llama 3.1 405B design failed, falling back to mock structure: {e}") return get_fallback_system_design(prompt)
def get_fallback_audit_report(file_type: str) -> dict: return { "sre_score": 82, "backend_score": 78, "infra_score": 75, "cloud_score": 72, "confidence": { "level": "medium", "score": 55, "label": "Medium Confidence", "based_on": ["Config files detected", "Files analyzed < 10"], "limitations": ["No CD pipeline files", "Missing Dockerfile"], "to_increase_confidence": ["Provide a Dockerfile and docker-compose.yml"] }, "capacity_estimate": { "safe_range": "1K-5K DAU", "peak_range": "5K-25K DAU", "description": "Calculated based on standard single-instance hosting with default configurations.", "reasoning": "The application lacks connection pooling settings and Redis caching layer.", "confidence": "Medium" }, "agents": { "sre": { "agent_name": "Alex", "agent_role": "SRE Lead", "score": 82, "score_breakdown": {"Uptime": 85, "Rate Limiting": 75, "Failover": 80}, "findings": [ { "severity": "high", "issue": "Missing rate limit on login endpoint", "location": "auth.py:L12", "impact": "Vulnerable to brute-force attacks.", "founder_text": "An attacker can flood your login page to guess credentials, causing a slow site for users.", "engineer_text": "Implement slowapi limit on POST /api/auth/login or implement IP-based rate limiting." } ], "suggestions": [ { "priority": "high", "effort": "low", "suggestion": "Add slowapi decorator", "founder_text": "Install login protections to keep user data secure.", "engineer_text": "Add @limiter.limit('5/minute') to login route.", "estimated_score_gain": 5, "estimated_capacity_gain": "+500 users" } ] }, "backend": { "agent_name": "Maria", "agent_role": "Senior Backend Engineer", "score": 78, "score_breakdown": {"Query Performance": 80, "Caching": 65, "Concurrency": 80}, "findings": [ { "severity": "medium", "issue": "Missing cache for static dashboard stats", "location": "dashboard.py:L40", "impact": "Redundant database calls on every page refresh.", "founder_text": "Every time a user visits their dashboard, your servers re-calculate stats, raising database costs.", "engineer_text": "Implement Redis caching with cache.set('stats', data, expire=300)." } ], "suggestions": [ { "priority": "medium", "effort": "medium", "suggestion": "Enable Redis caching", "founder_text": "Speed up dashboard load times for users.", "engineer_text": "Integrate Redis and cache aggregate DB statistics.", "estimated_score_gain": 8, "estimated_capacity_gain": "+2,000 users" } ] }, "infrastructure": { "agent_name": "James", "agent_role": "Infrastructure Engineer", "score": 75, "score_breakdown": {"Load Balancing": 70, "CDN": 80, "Containers": 75}, "findings": [], "suggestions": [] }, "cloud_architect": { "agent_name": "Priya", "agent_role": "Cloud Architect", "score": 72, "score_breakdown": {"Cost Efficiency": 80, "Scaling": 65}, "findings": [], "suggestions": [], "cost_analysis": {"monthly_estimate": 150, "saving_opportunities": 40} } }, "top_critical_issues": ["No rate limiting on login endpoint", "Missing DB connection pooling configurations"], "quick_wins": ["Add Redis caching for static pages", "Add rate-limiting annotations"], "benchmark_percentile": 72 }
def get_fallback_system_design(prompt: str) -> dict: return { "title": "Modern Web Application", "founder_summary": "A resilient web application architecture tailored for fast rendering and reliable data storage.", "engineer_summary": "A typical three-tier architecture utilizing Next.js, FastAPI, PostgreSQL, and Redis.", "architecture_type": "Hybrid", "reasoning": "Provides the best balance between speed, cost, and developer efficiency for general requirements.", "stack": { "Frontend": [{"chip": "Next.js", "reason": "Excellent SEO, static page generation, and TypeScript support."}], "Backend": [{"chip": "FastAPI", "reason": "Asynchronous python backend framework with auto OpenAPI documentation."}], "Database": [ {"chip": "PostgreSQL", "reason": "Robust and structured data storage."}, {"chip": "Redis", "reason": "High speed caching layer."} ], "Infrastructure": [{"chip": "Docker", "reason": "Standardized containerization for simplified deployment."}] }, "database_design": { "primary_db": "PostgreSQL (with read-replicas)", "cache": "Redis (elasticache)", "key_tables": [ {"table_name": "users", "fields": ["id: uuid", "email: varchar(255)", "created_at: timestamp"]} ] }, "api_design": { "style": "RESTful API", "auth_strategy": "Bearer JWT tokens", "core_endpoints": [ {"method": "GET", "path": "/api/v1/health", "description": "Health status of services"} ] }, "infrastructure": { "cloud_provider": "AWS / Supabase", "components": ["Route53", "Application Load Balancer", "ECS / Docker Container Service", "RDS instance"], "scaling_strategy": "Scale-out containers when memory utilisation crosses 80%" }, "reliability": { "uptime_target": "99.9%", "strategies": ["Multi-AZ database", "Healthchecks", "Daily snapshots"], "backup_dr": "Automated daily backups retained for 30 days" }, "cost_estimates": { "1k_users": {"monthly_cost": "$30", "drivers": "Single-instance container, shared DB pool"}, "100k_users": {"monthly_cost": "$550", "drivers": "RDS db.m5 instance, Auto-scaling container cluster"}, "1m_users": {"monthly_cost": "$3,800", "drivers": "Read-replicas, elasticache cluster, ALB load balancers"} }, "diagram": { "nodes": [ {"id": "1", "type": "input", "data": {"label": "Client App"}, "position": {"x": 250, "y": 25}}, {"id": "2", "data": {"label": "Web Servers (Next.js)"}, "position": {"x": 250, "y": 150}}, {"id": "3", "data": {"label": "API Backend (FastAPI)"}, "position": {"x": 250, "y": 275}}, {"id": "4", "data": {"label": "PostgreSQL DB"}, "position": {"x": 150, "y": 400}}, {"id": "5", "data": {"label": "Redis Cache"}, "position": {"x": 350, "y": 400}} ], "edges": [ {"id": "e1-2", "source": "1", "target": "2", "animated": true}, {"id": "e2-3", "source": "2", "target": "3", "animated": true}, {"id": "e3-4", "source": "3", "target": "4"}, {"id": "e3-5", "source": "3", "target": "5"} ] } }1234567891011121314151617181920212223242526import firebase_adminfrom firebase_admin import credentials, authfrom app.config import settings
# Construct the service account dictionary from settingsfirebase_creds_dict = { "type": "service_account", "project_id": settings.FIREBASE_PROJECT_ID, "private_key": settings.FIREBASE_PRIVATE_KEY, "client_email": settings.FIREBASE_CLIENT_EMAIL, "token_uri": "https://oauth2.googleapis.com/token"}
# Initialize Firebase Admin SDK if not already initializedif not firebase_admin._apps: cred = credentials.Certificate(firebase_creds_dict) firebase_admin.initialize_app(cred)
def verify_id_token(id_token: str): return auth.verify_id_token(id_token)
def create_session_cookie(id_token: str, expires_in_seconds: int): return auth.create_session_cookie(id_token, expires_in=expires_in_seconds)
def verify_session_cookie(session_cookie: str, check_revoked: bool = True): return auth.verify_session_cookie(session_cookie, check_revoked=check_revoked)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import base64import hashlibimport refrom typing import List, Dict, Anyimport httpxfrom github import Githubfrom cryptography.fernet import Fernetfrom app.config import settingsfrom loguru import logger
# Initialize encryption cipher using a key derived from SECRET_KEYdef _get_fernet_cipher() -> Fernet: # Fernet requires a 32-byte base64-encoded key key_hash = hashlib.sha256(settings.SECRET_KEY.encode()).digest() fernet_key = base64.urlsafe_b64encode(key_hash) return Fernet(fernet_key)
def encrypt_token(token: str) -> str: cipher = _get_fernet_cipher() return cipher.encrypt(token.encode()).decode()
def decrypt_token(encrypted_token: str) -> str: cipher = _get_fernet_cipher() return cipher.decrypt(encrypted_token.encode()).decode()
def get_github_auth_url(state: str) -> str: redirect_uri = f"{settings.FRONTEND_URL}/api/auth/callback" return ( f"https://github.com/login/oauth/authorize" f"?client_id={settings.GITHUB_CLIENT_ID}" f"&redirect_uri={redirect_uri}" f"&state={state}" f"&scope=repo,read:org" )
async def exchange_code_for_token(code: str) -> dict: url = "https://github.com/login/oauth/access_token" headers = {"Accept": "application/json"} data = { "client_id": settings.GITHUB_CLIENT_ID, "client_secret": settings.GITHUB_CLIENT_SECRET, "code": code } async with httpx.AsyncClient() as client: response = await client.post(url, headers=headers, data=data) response.raise_for_status() return response.json()
async def get_github_user_info(access_token: str) -> dict: url = "https://api.github.com/user" headers = { "Authorization": f"token {access_token}", "Accept": "application/vnd.github.v3+json" } async with httpx.AsyncClient() as client: response = await client.get(url, headers=headers) response.raise_for_status() return response.json()
def get_user_repos(access_token: str) -> List[Dict[str, Any]]: try: g = Github(access_token) repos = [] # Get repos sorted by updated date for repo in g.get_user().get_repos(sort="updated", direction="desc"): repos.append({ "id": repo.id, "name": repo.name, "full_name": repo.full_name, "html_url": repo.html_url, "description": repo.description, "language": repo.language, "updated_at": repo.updated_at.isoformat() if repo.updated_at else "", "private": repo.private }) return repos except Exception as e: logger.error(f"Failed to fetch repos from GitHub: {e}") return []
def get_repo_branches(access_token: str, repo_full_name: str) -> List[str]: try: g = Github(access_token) repo = g.get_repo(repo_full_name) return [b.name for b in repo.get_branches()] except Exception as e: logger.error(f"Failed to fetch branches for {repo_full_name}: {e}") return []
# File Extensions WhitelistALLOWED_EXTENSIONS = { ".py", ".js", ".ts", ".jsx", ".tsx", ".json", ".yaml", ".yml", ".toml", ".html", ".css", ".sql", ".go", ".java", ".rb"}
def get_repo_files(access_token: str, repo_full_name: str, branch: str) -> List[Dict[str, str]]: try: g = Github(access_token) repo = g.get_repo(repo_full_name) # Get files recursively up to limits files = [] total_size = 0 max_size = 50 * 1024 * 1024 # 50MB limit # Get git tree recursively git_ref = repo.get_git_ref(f"heads/{branch}") tree = repo.get_git_tree(git_ref.object.sha, recursive=True) for element in tree.tree: if element.type == "blob": # Check extension import os _, ext = os.path.splitext(element.path) if ext.lower() in ALLOWED_EXTENSIONS: # Ignore standard vendor/lock folders to stay within context limits if any(p in element.path.split("/") for p in ["node_modules", "vendor", "dist", "build", ".git", "venv", ".venv"]): continue # Fetch blob content blob = repo.get_git_blob(element.sha) content = base64.b64decode(blob.content).decode("utf-8", errors="ignore") # Redact secrets content = redact_env_secrets(content, element.path) files.append({ "filename": element.path, "content": content }) total_size += len(content) if len(files) >= 20 or total_size >= max_size: break return files except Exception as e: logger.error(f"Failed to fetch files from repo {repo_full_name}: {e}") return []
def redact_env_secrets(content: str, filename: str) -> str: # Redact common secrets patterns lines = content.splitlines() redacted_lines = [] # Check if this is an env file is_env = filename.endswith(".env") or filename.endswith(".env.production") or filename.endswith(".env.local") # Generic credential keys regex secret_key_re = re.compile( r"(password|secret|key|token|auth|pwd|credential|private_key|api_key|access_key)\s*[:=]\s*['\"]?([a-zA-Z0-9_\-\.\=\+]{8,})['\"]?", re.IGNORECASE ) for line in lines: if is_env: # For env files, redact everything after '=' if "=" in line and not line.strip().startswith("#"): key, val = line.split("=", 1) redacted_lines.append(f"{key}=[REDACTED]") else: redacted_lines.append(line) else: # Inline check for code files match = secret_key_re.search(line) if match: # Replace matching group containing key value val = match.group(2) redacted_lines.append(line.replace(val, "[REDACTED]")) else: redacted_lines.append(line) return "\n".join(redacted_lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543import osimport tempfilefrom jinja2 import Templatefrom weasyprint import HTMLfrom loguru import logger
# A premium, dark-themed HTML template for SRE / Readiness Audit PDF reportsAUDIT_PDF_TEMPLATE = """<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>Archvise Production Readiness Report</title> <style> @page { size: A4; margin: 20mm; @bottom-right { content: counter(page) " / " counter(pages); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 8pt; color: #6B7280; } @bottom-left { content: "Archvise Production Readiness Report"; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 8pt; color: #6B7280; } } body { background-color: #0A0A0A; color: #FFFFFF; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; margin: 0; padding: 0; font-size: 10pt; line-height: 1.5; } .header { border-bottom: 2px solid #2D2D2D; padding-bottom: 15px; margin-bottom: 30px; } .logo { font-size: 24px; font-weight: bold; color: #3B82F6; letter-spacing: 1px; } .subtitle { font-size: 10px; color: #9CA3AF; text-transform: uppercase; letter-spacing: 1.5px; margin-top: 5px; } .title-container { margin-bottom: 30px; } h1 { font-size: 26px; margin: 0 0 10px 0; color: #FFFFFF; } .metadata-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; background-color: #141414; border: 1px solid #2D2D2D; border-radius: 8px; padding: 15px; margin-bottom: 35px; } .meta-item { font-size: 11px; } .meta-label { color: #9CA3AF; font-weight: bold; margin-bottom: 3px; } .meta-value { color: #FFFFFF; } .score-box { background: #141414; border: 1px solid #2D2D2D; border-radius: 8px; padding: 25px; text-align: center; margin-bottom: 35px; page-break-inside: avoid; } .score-value { font-size: 64px; font-weight: bold; color: #3B82F6; line-height: 1; margin-bottom: 5px; } .score-label { font-size: 12px; color: #9CA3AF; text-transform: uppercase; letter-spacing: 2px; } .section-title { font-size: 16px; color: #3B82F6; border-bottom: 1px solid #2D2D2D; padding-bottom: 8px; margin-top: 30px; margin-bottom: 15px; text-transform: uppercase; letter-spacing: 1px; } .agent-grid { margin-bottom: 30px; } .agent-card { background-color: #141414; border: 1px solid #2D2D2D; border-radius: 8px; padding: 15px; margin-bottom: 15px; page-break-inside: avoid; } .agent-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #2D2D2D; padding-bottom: 8px; margin-bottom: 10px; } .agent-name { font-weight: bold; font-size: 12px; color: #FFFFFF; } .agent-role { font-size: 10px; color: #9CA3AF; } .agent-score { font-weight: bold; color: #3B82F6; font-size: 14px; } .finding-item { margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px dashed #2D2D2D; } .finding-item:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; } .severity { display: inline-block; padding: 2px 6px; border-radius: 4px; font-size: 8px; font-weight: bold; text-transform: uppercase; margin-right: 5px; } .severity.critical { background-color: rgba(239,68,68,0.15); color: #EF4444; border: 1px solid #EF4444; } .severity.high { background-color: rgba(249,115,22,0.15); color: #F97316; border: 1px solid #F97316; } .severity.medium { background-color: rgba(234,179,8,0.15); color: #EAB308; border: 1px solid #EAB308; } .severity.low { background-color: rgba(59,130,246,0.15); color: #3B82F6; border: 1px solid #3B82F6; } .finding-title { font-weight: bold; font-size: 11px; color: #FFFFFF; margin-bottom: 4px; } .finding-desc { font-size: 10px; color: #9CA3AF; margin-left: 0; } .disclaimer { font-size: 8pt; color: #6B7280; background-color: #141414; border: 1px solid #2D2D2D; border-radius: 6px; padding: 15px; margin-top: 40px; text-align: center; page-break-inside: avoid; } </style></head><body> <div class="header"> <div class="logo">Archvise</div> <div class="subtitle">Production Readiness Audit Panel</div> </div> <div class="title-container"> <h1>{{ project_name }}</h1> <div style="font-size: 12px; color: #9CA3AF;">Generated on {{ date_str }}</div> </div> <div class="score-box"> <div class="score-value">{{ report.overall_score }}</div> <div class="score-label">Production Readiness Score</div> </div> <div class="metadata-grid"> <div class="meta-item"> <div class="meta-label">Files Analyzed</div> <div class="meta-value">{{ report.files_analyzed }}</div> </div> <div class="meta-item"> <div class="meta-label">Confidence Level</div> <div class="meta-value" style="text-transform: capitalize;">{{ report.confidence.level }} ({{ report.confidence.score }}%)</div> </div> <div class="meta-item"> <div class="meta-label">Safe Load Limit</div> <div class="meta-value">{{ report.capacity_estimate.safe_range }}</div> </div> <div class="meta-item"> <div class="meta-label">Peak Load Limit</div> <div class="meta-value">{{ report.capacity_estimate.peak_range }}</div> </div> </div> <div class="section-title">Critical Panel Findings</div> <div class="agent-grid"> {% for agent_id, agent in report.agents.items() %} {% if agent.findings %} <div class="agent-card"> <div class="agent-header"> <div> <span class="agent-name">{{ agent.agent_name }}</span> <span class="agent-role">· {{ agent.agent_role }}</span> </div> <span class="agent-score">Score: {{ agent.score }}/100</span> </div> <div> {% for finding in agent.findings %} <div class="finding-item"> <div class="finding-title"> <span class="severity {{ finding.severity }}">{{ finding.severity }}</span> {{ finding.issue }} </div> <div class="finding-desc"> <strong>Location:</strong> {{ finding.location }}<br> <strong>Details:</strong> {{ finding.engineer_text }} </div> </div> {% endfor %} </div> </div> {% endif %} {% endfor %} </div> <div class="disclaimer"> <strong>Disclaimer:</strong> {{ report.score_disclaimer }} </div></body></html>"""
# A premium, dark-themed HTML template for System Design PDF reportsDESIGN_PDF_TEMPLATE = """<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>Archvise System Design Blueprint</title> <style> @page { size: A4; margin: 20mm; @bottom-right { content: counter(page) " / " counter(pages); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 8pt; color: #6B7280; } @bottom-left { content: "Archvise System Design Blueprint"; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 8pt; color: #6B7280; } } body { background-color: #0A0A0A; color: #FFFFFF; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; margin: 0; padding: 0; font-size: 10pt; line-height: 1.5; } .header { border-bottom: 2px solid #2D2D2D; padding-bottom: 15px; margin-bottom: 30px; } .logo { font-size: 24px; font-weight: bold; color: #A855F7; letter-spacing: 1px; } .subtitle { font-size: 10px; color: #9CA3AF; text-transform: uppercase; letter-spacing: 1.5px; margin-top: 5px; } .title-container { margin-bottom: 30px; } h1 { font-size: 26px; margin: 0 0 10px 0; color: #FFFFFF; } .metadata-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; background-color: #141414; border: 1px solid #2D2D2D; border-radius: 8px; padding: 15px; margin-bottom: 35px; } .meta-item { font-size: 11px; } .meta-label { color: #9CA3AF; font-weight: bold; margin-bottom: 3px; } .meta-value { color: #FFFFFF; } .summary-box { background: #141414; border: 1px solid #2D2D2D; border-radius: 8px; padding: 20px; margin-bottom: 35px; } .summary-title { font-weight: bold; font-size: 12px; color: #A855F7; text-transform: uppercase; margin-bottom: 8px; } .section-title { font-size: 16px; color: #A855F7; border-bottom: 1px solid #2D2D2D; padding-bottom: 8px; margin-top: 30px; margin-bottom: 15px; text-transform: uppercase; letter-spacing: 1px; } .stack-item { margin-bottom: 15px; } .stack-label { font-weight: bold; color: #FFFFFF; font-size: 11px; margin-bottom: 5px; } .stack-chips { display: flex; flex-wrap: wrap; gap: 8px; } .chip { background-color: #1A1A1A; border: 1px solid #2D2D2D; border-radius: 4px; padding: 4px 8px; font-size: 10px; color: #FFFFFF; } .chip-reason { font-size: 9px; color: #9CA3AF; margin-top: 3px; } .table { width: 100%; border-collapse: collapse; margin-bottom: 30px; } .table th, .table td { border: 1px solid #2D2D2D; padding: 10px; text-align: left; font-size: 10px; } .table th { background-color: #141414; color: #9CA3AF; font-weight: bold; } .table td { background-color: #0A0A0A; } </style></head><body> <div class="header"> <div class="logo">Archvise</div> <div class="subtitle">System Design Blueprint</div> </div> <div class="title-container"> <h1>{{ design.title }}</h1> <div style="font-size: 12px; color: #9CA3AF;">Generated on {{ date_str }}</div> </div> <div class="metadata-grid"> <div class="meta-item"> <div class="meta-label">Architecture Type</div> <div class="meta-value">{{ design.architecture_type }}</div> </div> <div class="meta-item"> <div class="meta-label">Uptime Target</div> <div class="meta-value">{{ design.reliability.uptime_target }}</div> </div> </div> <div class="summary-box"> <div class="summary-title">Executive Summary (Founder Mode)</div> <div style="font-size: 11px; color: #9CA3AF;">{{ design.founder_summary }}</div> </div> <div class="summary-box"> <div class="summary-title">Technical Overview (Engineer Mode)</div> <div style="font-size: 10px; color: #FFFFFF;">{{ design.engineer_summary }}</div> </div> <div class="section-title">Technology Stack Design</div> <div class="stack-item"> {% for layer, items in design.stack.items() %} <div class="stack-label">{{ layer }}</div> <div style="margin-bottom: 15px;"> {% for item in items %} <div style="margin-bottom: 5px;"> <span class="chip">{{ item.chip }}</span> <div class="chip-reason">{{ item.reason }}</div> </div> {% endfor %} </div> {% endfor %} </div> <div class="section-title">Monthly Cost Estimates</div> <table class="table"> <thead> <tr> <th>Scale / Tier</th> <th>Estimated Cost</th> <th>Main Cost Drivers</th> </tr> </thead> <tbody> <tr> <td>1,000 active users</td> <td>{{ design.cost_estimates['1k_users'].monthly_cost }}</td> <td>{{ design.cost_estimates['1k_users'].drivers }}</td> </tr> <tr> <td>100,000 active users</td> <td>{{ design.cost_estimates['100k_users'].monthly_cost }}</td> <td>{{ design.cost_estimates['100k_users'].drivers }}</td> </tr> <tr> <td>1,000,000 active users</td> <td>{{ design.cost_estimates['1m_users'].monthly_cost }}</td> <td>{{ design.cost_estimates['1m_users'].drivers }}</td> </tr> </tbody> </table></body></html>"""
def generate_audit_pdf(report: dict, project_name: str) -> bytes: from datetime import datetime date_str = datetime.utcnow().strftime("%B %d, %Y") # Render Jinja HTML template = Template(AUDIT_PDF_TEMPLATE) html_content = template.render(report=report, project_name=project_name, date_str=date_str) try: # Create temp file with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp: HTML(string=html_content).write_pdf(tmp.name) tmp.seek(0) pdf_bytes = tmp.read() os.unlink(tmp.name) return pdf_bytes except Exception as e: logger.error(f"WeasyPrint PDF generation failed: {e}. Falling back to standard HTML-as-PDF simulation.") # If WeasyPrint dependencies fail, return simple HTML content in bytes to avoid crashing return html_content.encode("utf-8")
def generate_design_pdf(design: dict) -> bytes: from datetime import datetime date_str = datetime.utcnow().strftime("%B %d, %Y") # Render Jinja HTML template = Template(DESIGN_PDF_TEMPLATE) html_content = template.render(design=design, date_str=date_str) try: # Create temp file with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp: HTML(string=html_content).write_pdf(tmp.name) tmp.seek(0) pdf_bytes = tmp.read() os.unlink(tmp.name) return pdf_bytes except Exception as e: logger.error(f"WeasyPrint PDF generation failed: {e}. Falling back to standard HTML-as-PDF simulation.") # Return fallback HTML return html_content.encode("utf-8")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566from fastapi import Request, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.future import selectfrom datetime import datetime, timedeltafrom app.database import get_dbfrom app import modelsfrom app.utils.firebase import verify_session_cookie
async def get_current_user(request: Request, db: AsyncSession = Depends(get_db)) -> models.User: session_cookie = request.cookies.get("archvise_session") if not session_cookie: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated" ) try: # Verify Firebase Session Cookie decoded_claims = verify_session_cookie(session_cookie, check_revoked=True) except Exception as e: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Session expired or invalid" ) firebase_uid = decoded_claims.get("uid") email = decoded_claims.get("email") name = decoded_claims.get("name") avatar_url = decoded_claims.get("picture") # Query database for user result = await db.execute(select(models.User).where(models.User.firebase_uid == firebase_uid)) user = result.scalars().first() if not user: # Seamless registration: Create new user if not found in db user = models.User( firebase_uid=firebase_uid, email=email, name=name, avatar_url=avatar_url, plan="free", display_mode="founder", credits_remaining=2, credits_reset_at=datetime.utcnow() + timedelta(days=30), is_active=True ) db.add(user) await db.commit() await db.refresh(user) # Check if credits need to be reset if user.credits_reset_at and datetime.utcnow() > user.credits_reset_at: user.credits_remaining = 2 if user.plan == "free" else (5 if user.plan == "starter" else 999999) user.credits_reset_at = datetime.utcnow() + timedelta(days=30) db.add(user) await db.commit() await db.refresh(user) if not user.is_active: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="User account is deactivated" ) return user123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import boto3from typing import Optionalfrom botocore.config import Configfrom botocore.exceptions import ClientErrorfrom app.config import settingsfrom loguru import logger
# Initialize boto3 S3 client for Supabase Storage (S3-compatible)s3_client = boto3.client( "s3", endpoint_url=settings.CLOUDFLARE_R2_ENDPOINT_URL, aws_access_key_id=settings.CLOUDFLARE_R2_ACCESS_KEY, aws_secret_access_key=settings.CLOUDFLARE_R2_SECRET_KEY, config=Config(signature_version="s3v4"), region_name=settings.CLOUDFLARE_R2_REGION_NAME)
def upload_file(file_content: bytes, object_key: str, content_type: str = "application/octet-stream") -> bool: try: s3_client.put_object( Bucket=settings.CLOUDFLARE_R2_BUCKET, Key=object_key, Body=file_content, ContentType=content_type ) logger.info(f"Successfully uploaded {object_key} to {settings.CLOUDFLARE_R2_BUCKET}") return True except ClientError as e: logger.error(f"Failed to upload {object_key} to S3: {e}") return False
def get_file(object_key: str) -> Optional[bytes]: try: response = s3_client.get_object( Bucket=settings.CLOUDFLARE_R2_BUCKET, Key=object_key ) return response["Body"].read() except ClientError as e: logger.error(f"Failed to download {object_key} from S3: {e}") return None
def generate_download_url(object_key: str, expires_in: int = 3600) -> str: try: url = s3_client.generate_presigned_url( "get_object", Params={ "Bucket": settings.CLOUDFLARE_R2_BUCKET, "Key": object_key }, ExpiresIn=expires_in ) return url except ClientError as e: logger.error(f"Failed to generate presigned URL for {object_key}: {e}") # Fallback to direct construction if presigned fails return f"{settings.CLOUDFLARE_R2_ENDPOINT_URL}/{settings.CLOUDFLARE_R2_BUCKET}/{object_key}"12345678910111213141516import redisfrom rq import Queue, Connection, Workerfrom app.config import settingsfrom loguru import logger
listen = ["default"]conn = redis.Redis.from_url(settings.REDIS_URL)
def run_worker(): logger.info(f"Starting RQ worker connecting to Redis at {settings.REDIS_URL}") with Connection(conn): worker = Worker(list(map(Queue, listen))) worker.work()
if __name__ == "__main__": run_worker()123456789101112{ "$schema": "https://railway.app/railway.schema.json", "build": { "builder": "DOCKERFILE", "dockerfilePath": "Dockerfile" }, "deploy": { "numReplicas": 1, "sleep": false, "restartPolicyType": "ON_FAILURE" }}12345678910111213141516171819202122232425fastapi==0.111.0uvicorn==0.30.1sqlalchemy[asyncio]==2.0.30asyncpg==0.29.0alembic==1.13.1redis==5.0.4rq==1.16.1firebase-admin==6.5.0stripe==9.9.0boto3==1.34.122PyGithub==2.3.0httpx==0.27.0slowapi==0.1.9weasyprint==62.1jinja2==3.1.4tenacity==8.3.0sentry-sdk[fastapi]==2.5.1loguru==0.7.2pydantic==2.7.3pydantic-settings==2.3.1python-multipart==0.0.9pyjwt[crypto]==2.8.0python-dotenv==1.0.1psycopg2-binary==2.9.9cryptography==42.0.7.gitignoreAdded+13
DockerfileAdded+29
app/__init__.pyAdded+1
app/config.pyAdded+85
app/database.pyAdded+36
app/main.pyAdded+67
app/models.pyAdded+133
app/routers/__init__.pyAdded+1
app/routers/audit.pyAdded+325
app/routers/auth.pyAdded+121
app/routers/billing.pyAdded+155
app/routers/design.pyAdded+227
app/routers/github.pyAdded+150
app/routers/legal.pyAdded+66
app/routers/projects.pyAdded+39
app/routers/settings.pyAdded+30
app/schemas.pyAdded+173
app/tasks.pyAdded+292
app/utils/__init__.pyAdded+1
app/utils/ai.pyAdded+435
app/utils/firebase.pyAdded+26
app/utils/github_client.pyAdded+174
app/utils/pdf.pyAdded+543
app/utils/security.pyAdded+66
app/utils/storage.pyAdded+57
app/worker.pyAdded+16
railway.jsonAdded+12
requirements.txtAdded+25