Files
Nexus/server/infrastructure/database/script_repo.py
T
Your Name 752a24497c feat: Phase 2 security audit fixes + script execution platform
Security (P0/P1/P2):
- WebSSH: dedicated short-lived token, server_id binding, 4003 close code
- Remove /api/agent/exec from control plane (RCE surface eliminated)
- Global JWT middleware (JwtAuthMiddleware) with install-mode bypass
- decrypt_value: failure returns None, never leaks ciphertext
- Telegram: sanitize_external_message strips sensitive fields
- Agent auth: startup enforces non-empty API key, compare_digest
- Credentials: password_set bool flag, no plaintext in API responses
- audit_log: writes admin_username + ip_address on all CUD ops
- Install lock: all /api/install/* except GET /status return 403 post-install
- WebSocket dedup: publish once, subscribers deliver locally

Script execution platform:
- script_jobs.py / script_job_callback.py: async batching and callback
- script_execution_store.py / script_callback_rate.py: Redis-backed state
- script_execution_flush.py: background flusher to MySQL
- scripts.html / script-executions.html: full execution UI
- agent_url.py: centralised URL builder

Frontend:
- All 13 pages migrated from CDN to /app/vendor/ (no external deps)
- vendor/: alpinejs, tailwindcss-browser, xterm, xterm-addon-*, qrious
- Dashboard WebSocket real-time alerts; 8h JWT session timeout

Tests:
- test_security_unit.py: 15 unit tests (JWT, sanitize, vendor, install 403)
- test_api.py: env-configurable admin credentials

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 15:26:56 +08:00

94 lines
3.4 KiB
Python

"""Nexus — Script & ScriptExecution Repository (Async SQLAlchemy)"""
from typing import Optional, List, Tuple
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from server.domain.models import Script, ScriptExecution
class ScriptRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def get_by_id(self, id: int) -> Optional[Script]:
result = await self.session.execute(select(Script).where(Script.id == id))
return result.scalar_one_or_none()
async def get_all(self) -> List[Script]:
result = await self.session.execute(select(Script).order_by(Script.id))
return list(result.scalars().all())
async def get_by_category(self, category: str) -> List[Script]:
result = await self.session.execute(
select(Script).where(Script.category == category).order_by(Script.id)
)
return list(result.scalars().all())
async def create(self, script: Script) -> Script:
self.session.add(script)
await self.session.commit()
await self.session.refresh(script)
return script
async def update(self, script: Script) -> Script:
await self.session.commit()
await self.session.refresh(script)
return script
async def delete(self, id: int) -> bool:
script = await self.get_by_id(id)
if script:
await self.session.delete(script)
await self.session.commit()
return True
return False
class ScriptExecutionRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def get_by_id(self, id: int) -> Optional[ScriptExecution]:
result = await self.session.execute(
select(ScriptExecution).where(ScriptExecution.id == id)
)
return result.scalar_one_or_none()
async def create(self, execution: ScriptExecution) -> ScriptExecution:
self.session.add(execution)
await self.session.commit()
await self.session.refresh(execution)
return execution
async def list_recent(
self,
limit: int = 50,
offset: int = 0,
status: Optional[str] = None,
) -> Tuple[List[ScriptExecution], int]:
filters = []
if status:
filters.append(ScriptExecution.status == status)
count_stmt = select(func.count(ScriptExecution.id))
if filters:
count_stmt = count_stmt.where(*filters)
total = int((await self.session.execute(count_stmt)).scalar() or 0)
stmt = select(ScriptExecution).order_by(ScriptExecution.started_at.desc())
if filters:
stmt = stmt.where(*filters)
result = await self.session.execute(stmt.limit(limit).offset(offset))
return list(result.scalars().all()), total
async def update_status(self, id: int, status: str, results: str) -> Optional[ScriptExecution]:
from datetime import datetime, timezone
execution = await self.session.get(ScriptExecution, id)
if execution:
execution.status = status
execution.results = results
if status != "running" and execution.completed_at is None:
execution.completed_at = datetime.now(timezone.utc)
await self.session.commit()
await self.session.refresh(execution)
return execution