Add browser Python editor with Pyodide, user auth, and workspace API
- FastAPI serves static UI, file CRUD under code/ and read-only lib/ - Pyodide worker runs Python and Jedi completions in the browser - SQLite accounts: login/register, session cookies, superuser user management - Optional EDITOR_API_KEY, AUTH_* env vars, .env.example - Pipenv, pytest, Selenium smoke test, README Made-with: Cursor
This commit is contained in:
7
src/app.py
Normal file
7
src/app.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from editor_app.main import app
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host="0.0.0.0", port=8080)
|
||||
0
src/editor_app/__init__.py
Normal file
0
src/editor_app/__init__.py
Normal file
30
src/editor_app/config.py
Normal file
30
src/editor_app/config.py
Normal file
@@ -0,0 +1,30 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# Application package lives under `src/`; repo root is one level up (for `.env`, default workspace).
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
PROJECT_ROOT = BASE_DIR.parent
|
||||
STATIC_DIR = BASE_DIR / "static"
|
||||
|
||||
|
||||
def load_env_file(env_path: Path) -> None:
|
||||
"""Load KEY=VALUE entries from a local .env file (does not override existing os.environ)."""
|
||||
if not env_path.exists():
|
||||
return
|
||||
|
||||
for line in env_path.read_text(encoding="utf-8").splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("#") or "=" not in stripped:
|
||||
continue
|
||||
key, value = stripped.split("=", 1)
|
||||
key = key.strip()
|
||||
value = value.strip().strip('"').strip("'")
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
load_env_file(PROJECT_ROOT / ".env")
|
||||
|
||||
_default_workspace = PROJECT_ROOT / "workspace"
|
||||
WORKSPACE_ROOT = Path(os.environ.get("WORKSPACE_ROOT", str(_default_workspace))).resolve()
|
||||
0
src/editor_app/db/__init__.py
Normal file
0
src/editor_app/db/__init__.py
Normal file
40
src/editor_app/db/models.py
Normal file
40
src/editor_app/db/models.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
|
||||
|
||||
def _utc_naive() -> dt.datetime:
|
||||
return dt.datetime.now(dt.UTC).replace(tzinfo=None)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(256))
|
||||
is_superuser: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=_utc_naive)
|
||||
|
||||
sessions: Mapped[list[AuthSession]] = relationship(
|
||||
"AuthSession", back_populates="user", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
|
||||
class AuthSession(Base):
|
||||
__tablename__ = "auth_sessions"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
token: Mapped[str] = mapped_column(String(128), unique=True, index=True)
|
||||
expires_at: Mapped[dt.datetime] = mapped_column(DateTime)
|
||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=_utc_naive)
|
||||
|
||||
user: Mapped[User] = relationship("User", back_populates="sessions")
|
||||
55
src/editor_app/db/session.py
Normal file
55
src/editor_app/db/session.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from editor_app.config import PROJECT_ROOT
|
||||
|
||||
_engine = None
|
||||
_SessionLocal: sessionmaker[Session] | None = None
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
path = os.environ.get("AUTH_DATABASE_PATH", str(PROJECT_ROOT / "data" / "editor.db"))
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
return f"sqlite:///{path}"
|
||||
|
||||
|
||||
def reset_engine() -> None:
|
||||
"""Test helper: clear cached engine after env change."""
|
||||
global _engine, _SessionLocal
|
||||
if _engine is not None:
|
||||
_engine.dispose()
|
||||
_engine = None
|
||||
_SessionLocal = None
|
||||
|
||||
|
||||
def get_engine():
|
||||
global _engine, _SessionLocal
|
||||
if _engine is None:
|
||||
_engine = create_engine(
|
||||
_database_url(),
|
||||
connect_args={"check_same_thread": False},
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
_SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=_engine)
|
||||
return _engine
|
||||
|
||||
|
||||
def get_session_factory() -> sessionmaker[Session]:
|
||||
get_engine()
|
||||
assert _SessionLocal is not None
|
||||
return _SessionLocal
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
factory = get_session_factory()
|
||||
db = factory()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
63
src/editor_app/deps.py
Normal file
63
src/editor_app/deps.py
Normal file
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from fastapi import Cookie, Depends, Header, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.session import get_db
|
||||
from editor_app.db.models import User
|
||||
from editor_app.services import accounts
|
||||
|
||||
|
||||
def api_key_valid(authorization: str | None) -> bool:
|
||||
expected = (os.environ.get("EDITOR_API_KEY") or "").strip()
|
||||
if not expected:
|
||||
return False
|
||||
return (authorization or "").strip() == f"Bearer {expected}"
|
||||
|
||||
|
||||
async def require_api_access(
|
||||
db: Session = Depends(get_db),
|
||||
authorization: str | None = Header(None),
|
||||
editor_session: str | None = Cookie(None),
|
||||
) -> None:
|
||||
"""API key, or (when auth off) open access, or (when auth on) valid session — see README."""
|
||||
if api_key_valid(authorization):
|
||||
return
|
||||
key_configured = bool((os.environ.get("EDITOR_API_KEY") or "").strip())
|
||||
if key_configured:
|
||||
if accounts.auth_enabled():
|
||||
user = accounts.get_session_user(db, editor_session)
|
||||
if user:
|
||||
return
|
||||
raise HTTPException(status_code=401, detail="Invalid or missing API key")
|
||||
if not accounts.auth_enabled():
|
||||
return
|
||||
user = accounts.get_session_user(db, editor_session)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
|
||||
|
||||
async def get_current_user_optional(
|
||||
db: Session = Depends(get_db),
|
||||
authorization: str | None = Header(None),
|
||||
editor_session: str | None = Cookie(None),
|
||||
) -> User | None:
|
||||
if api_key_valid(authorization):
|
||||
return None
|
||||
if not accounts.auth_enabled():
|
||||
return None
|
||||
return accounts.get_session_user(db, editor_session)
|
||||
|
||||
|
||||
async def require_superuser(
|
||||
user: User | None = Depends(get_current_user_optional),
|
||||
) -> User:
|
||||
if not accounts.auth_enabled():
|
||||
raise HTTPException(status_code=400, detail="User management requires AUTH_ENABLED=true")
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
if not user.is_superuser:
|
||||
raise HTTPException(status_code=403, detail="Superuser required")
|
||||
return user
|
||||
47
src/editor_app/main.py
Normal file
47
src/editor_app/main.py
Normal file
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from editor_app.config import STATIC_DIR, WORKSPACE_ROOT
|
||||
from editor_app.db.models import Base
|
||||
from editor_app.db.session import get_engine
|
||||
from editor_app.deps import require_api_access
|
||||
from editor_app.routers.auth_routes import router as auth_router
|
||||
from editor_app.routers.files import router as files_router
|
||||
from editor_app.routers.frontend import router as frontend_router
|
||||
from editor_app.routers.users_admin import router as users_admin_router
|
||||
from editor_app.services import accounts
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
(WORKSPACE_ROOT / "lib").mkdir(parents=True, exist_ok=True)
|
||||
engine = get_engine()
|
||||
Base.metadata.create_all(bind=engine)
|
||||
factory = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
db = factory()
|
||||
try:
|
||||
if accounts.auth_enabled():
|
||||
bu = os.environ.get("BOOTSTRAP_ADMIN_USERNAME", "").strip()
|
||||
bp = os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "").strip()
|
||||
if bu and bp and accounts.count_users(db) == 0:
|
||||
accounts.create_user(db, bu, bp, is_superuser=True)
|
||||
finally:
|
||||
db.close()
|
||||
yield
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
||||
app.include_router(frontend_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(users_admin_router)
|
||||
app.include_router(files_router, dependencies=[Depends(require_api_access)])
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
22
src/editor_app/models.py
Normal file
22
src/editor_app/models.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class FileContent(BaseModel):
|
||||
content: str
|
||||
|
||||
|
||||
class FileInfo(BaseModel):
|
||||
name: str
|
||||
is_directory: bool
|
||||
size: Optional[int] = None
|
||||
|
||||
|
||||
class FolderOperation(BaseModel):
|
||||
path: str
|
||||
|
||||
|
||||
class MoveFileRequest(BaseModel):
|
||||
source_path: str
|
||||
destination_folder: str = ""
|
||||
0
src/editor_app/routers/__init__.py
Normal file
0
src/editor_app/routers/__init__.py
Normal file
95
src/editor_app/routers/auth_routes.py
Normal file
95
src/editor_app/routers/auth_routes.py
Normal file
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.session import get_db
|
||||
from editor_app.schemas.users import AuthStatusResponse, LoginRequest, RegisterRequest, UserPublic
|
||||
from editor_app.services import accounts
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _set_session_cookie(response: Response, request: Request, token: str) -> None:
|
||||
max_age = accounts.session_ttl_days() * 86400
|
||||
secure = request.url.scheme == "https"
|
||||
response.set_cookie(
|
||||
key=accounts.SESSION_COOKIE_NAME,
|
||||
value=token,
|
||||
max_age=max_age,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=secure,
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
def _clear_session_cookie(response: Response, request: Request) -> None:
|
||||
secure = request.url.scheme == "https"
|
||||
response.delete_cookie(accounts.SESSION_COOKIE_NAME, path="/", samesite="lax", secure=secure)
|
||||
|
||||
|
||||
@router.get("/status", response_model=AuthStatusResponse)
|
||||
async def auth_status() -> AuthStatusResponse:
|
||||
return AuthStatusResponse(auth_enabled=accounts.auth_enabled(), register_open=accounts.register_open())
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def auth_me(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
if not accounts.auth_enabled():
|
||||
return {"auth_enabled": False, "user": None}
|
||||
token = request.cookies.get(accounts.SESSION_COOKIE_NAME)
|
||||
user = accounts.get_session_user(db, token)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
return {"auth_enabled": True, "user": UserPublic.model_validate(user).model_dump()}
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserPublic)
|
||||
async def register(
|
||||
body: RegisterRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> UserPublic:
|
||||
if not accounts.auth_enabled():
|
||||
raise HTTPException(status_code=400, detail="Set AUTH_ENABLED=true to use accounts")
|
||||
if not accounts.register_open():
|
||||
raise HTTPException(status_code=403, detail="Registration is disabled (AUTH_REGISTER_OPEN=false)")
|
||||
try:
|
||||
user = accounts.register_user(db, body.username, body.password)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
return UserPublic.model_validate(user)
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(
|
||||
request: Request,
|
||||
response: Response,
|
||||
body: LoginRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> UserPublic:
|
||||
if not accounts.auth_enabled():
|
||||
raise HTTPException(status_code=400, detail="Set AUTH_ENABLED=true to use accounts")
|
||||
user = accounts.authenticate(db, body.username, body.password)
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Invalid username or password")
|
||||
sess = accounts.create_session(db, user)
|
||||
_set_session_cookie(response, request, sess.token)
|
||||
return UserPublic.model_validate(user)
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(
|
||||
request: Request,
|
||||
response: Response,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
token = request.cookies.get(accounts.SESSION_COOKIE_NAME)
|
||||
accounts.delete_session(db, token)
|
||||
_clear_session_cookie(response, request)
|
||||
return {"message": "Logged out"}
|
||||
56
src/editor_app/routers/files.py
Normal file
56
src/editor_app/routers/files.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from editor_app.models import FileContent, FolderOperation, MoveFileRequest
|
||||
from editor_app.services import filesystem
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
|
||||
@router.get("/files")
|
||||
async def list_files(path: str = ""):
|
||||
files = filesystem.list_files(path)
|
||||
return {"files": files}
|
||||
|
||||
|
||||
@router.get("/workspace/py-sources")
|
||||
async def workspace_python_sources():
|
||||
return {"files": filesystem.collect_python_sources()}
|
||||
|
||||
|
||||
@router.get("/file/{file_path:path}")
|
||||
async def read_file(file_path: str):
|
||||
content, filename = filesystem.read_text_file(file_path)
|
||||
return {"content": content, "filename": filename}
|
||||
|
||||
|
||||
@router.post("/file/{file_path:path}")
|
||||
async def save_file(file_path: str, file_data: FileContent):
|
||||
filename = filesystem.save_text_file(file_path, file_data.content)
|
||||
return {"message": "File saved successfully", "filename": filename}
|
||||
|
||||
|
||||
@router.post("/file-move")
|
||||
async def move_file(move_data: MoveFileRequest):
|
||||
new_path, moved_type = filesystem.move_path(
|
||||
source_path=move_data.source_path,
|
||||
destination_folder=move_data.destination_folder,
|
||||
)
|
||||
return {"message": "Path moved successfully", "new_path": new_path, "moved_type": moved_type}
|
||||
|
||||
|
||||
@router.delete("/file/{file_path:path}")
|
||||
async def delete_file(file_path: str):
|
||||
filesystem.delete_file(file_path)
|
||||
return {"message": "File deleted successfully"}
|
||||
|
||||
|
||||
@router.post("/folder/new/{folder_path:path}")
|
||||
async def create_folder(folder_path: str, folder_data: FolderOperation):
|
||||
folder_name = filesystem.create_folder(folder_path)
|
||||
return {"message": "Folder created successfully", "folder": folder_name}
|
||||
|
||||
|
||||
@router.delete("/folder/{folder_path:path}")
|
||||
async def delete_folder(folder_path: str):
|
||||
filesystem.delete_folder(folder_path)
|
||||
return {"message": "Folder deleted successfully"}
|
||||
26
src/editor_app/routers/frontend.py
Normal file
26
src/editor_app/routers/frontend.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from editor_app.config import STATIC_DIR
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def serve_home():
|
||||
return FileResponse(STATIC_DIR / "home.html")
|
||||
|
||||
|
||||
@router.get("/editor")
|
||||
async def serve_frontend():
|
||||
return FileResponse(STATIC_DIR / "index.html")
|
||||
|
||||
|
||||
@router.get("/login")
|
||||
async def serve_login():
|
||||
return FileResponse(STATIC_DIR / "login.html")
|
||||
|
||||
|
||||
@router.get("/register")
|
||||
async def serve_register():
|
||||
return FileResponse(STATIC_DIR / "register.html")
|
||||
50
src/editor_app/routers/users_admin.py
Normal file
50
src/editor_app/routers/users_admin.py
Normal file
@@ -0,0 +1,50 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.session import get_db
|
||||
from editor_app.db.models import User
|
||||
from editor_app.deps import require_superuser
|
||||
from editor_app.schemas.users import UserCreateAdmin, UserPublic
|
||||
from editor_app.services import accounts
|
||||
|
||||
router = APIRouter(prefix="/api/users", tags=["users"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserPublic])
|
||||
async def list_users(
|
||||
_admin: User = Depends(require_superuser),
|
||||
db: Session = Depends(get_db),
|
||||
) -> list[UserPublic]:
|
||||
return [UserPublic.model_validate(u) for u in accounts.list_users(db)]
|
||||
|
||||
|
||||
@router.post("", response_model=UserPublic)
|
||||
async def create_user_admin(
|
||||
body: UserCreateAdmin,
|
||||
admin: User = Depends(require_superuser),
|
||||
db: Session = Depends(get_db),
|
||||
) -> UserPublic:
|
||||
if accounts.get_user_by_username(db, body.username):
|
||||
raise HTTPException(status_code=409, detail="Username already taken")
|
||||
user = accounts.create_user(
|
||||
db,
|
||||
body.username,
|
||||
body.password,
|
||||
is_superuser=body.is_superuser,
|
||||
)
|
||||
return UserPublic.model_validate(user)
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user_admin(
|
||||
user_id: int,
|
||||
admin: User = Depends(require_superuser),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
if user_id == admin.id:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete your own account")
|
||||
if not accounts.delete_user(db, user_id):
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {"message": "User deleted"}
|
||||
46
src/editor_app/schemas/users.py
Normal file
46
src/editor_app/schemas/users.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
username: str = Field(min_length=3, max_length=64)
|
||||
password: str = Field(min_length=8, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_chars(cls, v: str) -> str:
|
||||
s = v.strip()
|
||||
if not s.replace("_", "").isalnum():
|
||||
raise ValueError("Username may only contain letters, numbers, and underscores")
|
||||
return s
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
is_superuser: bool
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class UserCreateAdmin(BaseModel):
|
||||
username: str = Field(min_length=3, max_length=64)
|
||||
password: str = Field(min_length=8, max_length=128)
|
||||
is_superuser: bool = False
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_chars(cls, v: str) -> str:
|
||||
s = v.strip()
|
||||
if not s.replace("_", "").isalnum():
|
||||
raise ValueError("Username may only contain letters, numbers, and underscores")
|
||||
return s
|
||||
|
||||
|
||||
class AuthStatusResponse(BaseModel):
|
||||
auth_enabled: bool
|
||||
register_open: bool
|
||||
0
src/editor_app/services/__init__.py
Normal file
0
src/editor_app/services/__init__.py
Normal file
128
src/editor_app/services/accounts.py
Normal file
128
src/editor_app/services/accounts.py
Normal file
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import os
|
||||
import secrets
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import bcrypt
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from editor_app.db.models import AuthSession, User
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
SESSION_COOKIE_NAME = "editor_session"
|
||||
SESSION_DAYS_DEFAULT = 14
|
||||
|
||||
|
||||
def auth_enabled() -> bool:
|
||||
return os.environ.get("AUTH_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def register_open() -> bool:
|
||||
return os.environ.get("AUTH_REGISTER_OPEN", "true").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def session_ttl_days() -> int:
|
||||
try:
|
||||
return max(1, min(365, int(os.environ.get("AUTH_SESSION_DAYS", str(SESSION_DAYS_DEFAULT)))))
|
||||
except ValueError:
|
||||
return SESSION_DAYS_DEFAULT
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("ascii")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("ascii"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def get_user_by_username(db: Session, username: str) -> User | None:
|
||||
return db.scalars(select(User).where(User.username == username)).one_or_none()
|
||||
|
||||
|
||||
def get_user_by_id(db: Session, user_id: int) -> User | None:
|
||||
return db.scalars(select(User).where(User.id == user_id)).one_or_none()
|
||||
|
||||
|
||||
def count_users(db: Session) -> int:
|
||||
return int(db.scalar(select(func.count()).select_from(User)) or 0)
|
||||
|
||||
|
||||
def create_user(db: Session, username: str, password: str, *, is_superuser: bool = False) -> User:
|
||||
user = User(
|
||||
username=username,
|
||||
password_hash=hash_password(password),
|
||||
is_superuser=is_superuser,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def register_user(db: Session, username: str, password: str) -> User:
|
||||
if get_user_by_username(db, username):
|
||||
raise ValueError("Username already taken")
|
||||
first = count_users(db) == 0
|
||||
return create_user(db, username, password, is_superuser=first)
|
||||
|
||||
|
||||
def authenticate(db: Session, username: str, password: str) -> User | None:
|
||||
user = get_user_by_username(db, username.strip())
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def _utc_naive() -> dt.datetime:
|
||||
return dt.datetime.now(dt.UTC).replace(tzinfo=None)
|
||||
|
||||
|
||||
def create_session(db: Session, user: User) -> AuthSession:
|
||||
token = secrets.token_urlsafe(48)
|
||||
expires = _utc_naive() + dt.timedelta(days=session_ttl_days())
|
||||
row = AuthSession(user_id=user.id, token=token, expires_at=expires)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
def get_session_user(db: Session, token: str | None) -> User | None:
|
||||
if not token:
|
||||
return None
|
||||
now = _utc_naive()
|
||||
row = db.scalars(select(AuthSession).where(AuthSession.token == token)).one_or_none()
|
||||
if not row or row.expires_at < now:
|
||||
return None
|
||||
return get_user_by_id(db, row.user_id)
|
||||
|
||||
|
||||
def delete_session(db: Session, token: str | None) -> None:
|
||||
if not token:
|
||||
return
|
||||
row = db.scalars(select(AuthSession).where(AuthSession.token == token)).one_or_none()
|
||||
if row:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
def list_users(db: Session) -> list[User]:
|
||||
return list(db.scalars(select(User).order_by(User.username)).all())
|
||||
|
||||
|
||||
def delete_user(db: Session, user_id: int) -> bool:
|
||||
user = get_user_by_id(db, user_id)
|
||||
if not user:
|
||||
return False
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return True
|
||||
202
src/editor_app/services/filesystem.py
Normal file
202
src/editor_app/services/filesystem.py
Normal file
@@ -0,0 +1,202 @@
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from editor_app import config
|
||||
from editor_app.models import FileInfo
|
||||
|
||||
LIB_DIR_NAME = "lib"
|
||||
WRITABLE_ROOTS = {"code"}
|
||||
|
||||
|
||||
def normalize_relative_path(relative_path: str) -> str:
|
||||
cleaned = (relative_path or "").strip().lstrip("/")
|
||||
if not cleaned:
|
||||
return ""
|
||||
|
||||
parts = [segment for segment in cleaned.split("/") if segment]
|
||||
if len(parts) >= 2 and parts[0] == "code":
|
||||
while len(parts) >= 2 and parts[0] == parts[1] == "code":
|
||||
parts.pop(1)
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def resolve_workspace_path(relative_path: str) -> Path:
|
||||
relative_path = normalize_relative_path(relative_path)
|
||||
target_path = (config.WORKSPACE_ROOT / relative_path).resolve()
|
||||
try:
|
||||
target_path.relative_to(config.WORKSPACE_ROOT.resolve())
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Path escapes workspace") from exc
|
||||
return target_path
|
||||
|
||||
|
||||
def _is_path_in_lib(target_path: Path) -> bool:
|
||||
workspace = config.WORKSPACE_ROOT.resolve()
|
||||
lib_root = (workspace / LIB_DIR_NAME).resolve()
|
||||
try:
|
||||
target_path.resolve().relative_to(lib_root)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_not_lib_path(target_path: Path) -> None:
|
||||
if _is_path_in_lib(target_path):
|
||||
raise HTTPException(status_code=403, detail="lib is read-only")
|
||||
|
||||
|
||||
def _is_writable_path(target_path: Path) -> bool:
|
||||
workspace = config.WORKSPACE_ROOT.resolve()
|
||||
resolved = target_path.resolve()
|
||||
try:
|
||||
relative = resolved.relative_to(workspace)
|
||||
except ValueError:
|
||||
return False
|
||||
if not relative.parts:
|
||||
return False
|
||||
return relative.parts[0] in WRITABLE_ROOTS
|
||||
|
||||
|
||||
def _ensure_writable_path(target_path: Path) -> None:
|
||||
if not _is_writable_path(target_path):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Only code/ is writable (lib is read-only)",
|
||||
)
|
||||
|
||||
|
||||
def list_files(path: str = "") -> list[FileInfo]:
|
||||
path = normalize_relative_path(path)
|
||||
target_path = config.WORKSPACE_ROOT / path if path else config.WORKSPACE_ROOT
|
||||
if not target_path.exists() or not target_path.is_dir():
|
||||
raise HTTPException(status_code=404, detail="Directory not found")
|
||||
|
||||
files = []
|
||||
for item in sorted(target_path.iterdir()):
|
||||
if item.name.startswith("."):
|
||||
continue
|
||||
files.append(
|
||||
FileInfo(
|
||||
name=item.name,
|
||||
is_directory=item.is_dir(),
|
||||
size=item.stat().st_size if item.is_file() else None,
|
||||
)
|
||||
)
|
||||
return files
|
||||
|
||||
|
||||
def read_text_file(file_path: str) -> tuple[str, str]:
|
||||
target_path = resolve_workspace_path(file_path)
|
||||
if not target_path.exists():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
if target_path.is_dir():
|
||||
raise HTTPException(status_code=400, detail="Path is a directory")
|
||||
try:
|
||||
content = target_path.read_text(encoding="utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise HTTPException(status_code=400, detail="File is not a text file") from exc
|
||||
return content, target_path.name
|
||||
|
||||
|
||||
def save_text_file(file_path: str, content: str) -> str:
|
||||
target_path = resolve_workspace_path(file_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
target_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
target_path.write_text(content, encoding="utf-8")
|
||||
return target_path.name
|
||||
|
||||
|
||||
def delete_file(file_path: str) -> None:
|
||||
target_path = resolve_workspace_path(file_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
if not target_path.exists():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
if target_path.is_dir():
|
||||
raise HTTPException(status_code=400, detail="Cannot delete directories")
|
||||
target_path.unlink()
|
||||
|
||||
|
||||
def move_path(source_path: str, destination_folder: str) -> tuple[str, str]:
|
||||
source = resolve_workspace_path(source_path)
|
||||
_ensure_not_lib_path(source)
|
||||
_ensure_writable_path(source)
|
||||
if not source.exists():
|
||||
raise HTTPException(status_code=404, detail="Source path not found")
|
||||
|
||||
destination_dir = (
|
||||
resolve_workspace_path(destination_folder)
|
||||
if destination_folder
|
||||
else config.WORKSPACE_ROOT
|
||||
)
|
||||
_ensure_not_lib_path(destination_dir)
|
||||
_ensure_writable_path(destination_dir)
|
||||
if not destination_dir.exists() or not destination_dir.is_dir():
|
||||
raise HTTPException(status_code=404, detail="Destination folder not found")
|
||||
|
||||
destination = destination_dir / source.name
|
||||
source_resolved = source.resolve()
|
||||
destination_resolved = destination.resolve()
|
||||
if destination_resolved == source_resolved:
|
||||
raise HTTPException(status_code=400, detail="Path is already in that folder")
|
||||
if source.is_dir():
|
||||
source_prefix = str(source_resolved) + "/"
|
||||
if str(destination_dir.resolve()).startswith(source_prefix):
|
||||
raise HTTPException(
|
||||
status_code=400, detail="Cannot move a folder into itself or its child"
|
||||
)
|
||||
if destination.exists():
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="A path with that name already exists in destination",
|
||||
)
|
||||
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
source.rename(destination)
|
||||
moved_type = "folder" if destination.is_dir() else "file"
|
||||
return str(destination.relative_to(config.WORKSPACE_ROOT)), moved_type
|
||||
|
||||
|
||||
def create_folder(folder_path: str) -> str:
|
||||
target_path = resolve_workspace_path(folder_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
if target_path.exists():
|
||||
raise HTTPException(status_code=400, detail="Folder already exists")
|
||||
target_path.mkdir(parents=True, exist_ok=False)
|
||||
return target_path.name
|
||||
|
||||
|
||||
def delete_folder(folder_path: str) -> None:
|
||||
target_path = resolve_workspace_path(folder_path)
|
||||
_ensure_not_lib_path(target_path)
|
||||
_ensure_writable_path(target_path)
|
||||
if not target_path.exists():
|
||||
raise HTTPException(status_code=404, detail="Folder not found")
|
||||
if not target_path.is_dir():
|
||||
raise HTTPException(status_code=400, detail="Path is not a directory")
|
||||
shutil.rmtree(target_path)
|
||||
|
||||
|
||||
def collect_python_sources() -> dict[str, str]:
|
||||
"""Return all UTF-8 .py files under the workspace for browser-side Pyodide sync."""
|
||||
result: dict[str, str] = {}
|
||||
workspace = config.WORKSPACE_ROOT.resolve()
|
||||
if not workspace.exists():
|
||||
return result
|
||||
for path in workspace.rglob("*.py"):
|
||||
try:
|
||||
rel = path.relative_to(workspace)
|
||||
except ValueError:
|
||||
continue
|
||||
if any(part.startswith(".") for part in rel.parts):
|
||||
continue
|
||||
try:
|
||||
key = str(rel).replace("\\", "/")
|
||||
result[key] = path.read_text(encoding="utf-8")
|
||||
except (UnicodeDecodeError, OSError):
|
||||
continue
|
||||
return result
|
||||
14
src/static/codemirror.bundle.mjs
Normal file
14
src/static/codemirror.bundle.mjs
Normal file
File diff suppressed because one or more lines are too long
143
src/static/home.html
Normal file
143
src/static/home.html
Normal file
@@ -0,0 +1,143 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #0f172a, #1e293b);
|
||||
color: #e2e8f0;
|
||||
}
|
||||
.home-card {
|
||||
width: min(560px, 92vw);
|
||||
background: rgba(15, 23, 42, 0.78);
|
||||
border: 1px solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 14px;
|
||||
padding: 2rem;
|
||||
box-shadow: 0 20px 45px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
h1 { margin: 0 0 0.75rem 0; font-size: 1.8rem; color: #f8fafc; }
|
||||
p { margin: 0 0 1rem 0; color: #cbd5e1; line-height: 1.5; }
|
||||
.btn {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
border-radius: 8px;
|
||||
padding: 0.65rem 1rem;
|
||||
font-weight: 600;
|
||||
border: 1px solid transparent;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
}
|
||||
.btn-primary { background: #3b82f6; color: #ffffff; }
|
||||
.btn-ghost { background: transparent; border-color: #64748b; color: #e2e8f0; }
|
||||
label { display: block; font-size: 0.85rem; color: #94a3b8; margin-bottom: 0.35rem; }
|
||||
input[type="password"] {
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #64748b;
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.note { font-size: 0.8rem; color: #94a3b8; margin-top: 1rem; }
|
||||
.nav { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1rem; align-items: center; }
|
||||
.nav span { color: #94a3b8; font-size: 0.9rem; }
|
||||
.hidden { display: none !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="home-card">
|
||||
<h1>Python Editor</h1>
|
||||
<div id="auth-nav" class="nav">
|
||||
<span id="auth-greeting" class="hidden"></span>
|
||||
<a class="btn btn-ghost hidden" id="link-login" href="/login">Sign in</a>
|
||||
<a class="btn btn-ghost hidden" id="link-register" href="/register">Register</a>
|
||||
<button type="button" class="btn btn-ghost hidden" id="btn-logout">Sign out</button>
|
||||
</div>
|
||||
<p>Edit and store files on the server. Python runs in your browser with <a href="https://pyodide.org/" style="color:#93c5fd">Pyodide</a>.</p>
|
||||
<div id="optional-api-key">
|
||||
<p>If you use <code style="color:#fcd34d">EDITOR_API_KEY</code> (without user login), store it here for API calls from this browser tab:</p>
|
||||
<label for="api-key">API key (optional)</label>
|
||||
<input id="api-key" type="password" autocomplete="off" placeholder="Leave blank if not used" />
|
||||
<p class="note">The key is kept in <code>sessionStorage</code>. You can also use <code>?api_key=…</code> on the editor URL.</p>
|
||||
</div>
|
||||
<a class="btn btn-primary" href="/editor" id="open-editor">Open Editor</a>
|
||||
</main>
|
||||
<script>
|
||||
const storageKey = 'python-editor.api_key';
|
||||
const input = document.getElementById('api-key');
|
||||
const openLink = document.getElementById('open-editor');
|
||||
|
||||
async function refreshAuthNav() {
|
||||
const st = await fetch('/api/auth/status');
|
||||
const status = await st.json();
|
||||
const loginEl = document.getElementById('link-login');
|
||||
const regEl = document.getElementById('link-register');
|
||||
const outEl = document.getElementById('btn-logout');
|
||||
const greet = document.getElementById('auth-greeting');
|
||||
const optionalKey = document.getElementById('optional-api-key');
|
||||
if (!status.auth_enabled) {
|
||||
loginEl.classList.add('hidden');
|
||||
regEl.classList.add('hidden');
|
||||
outEl.classList.add('hidden');
|
||||
greet.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
loginEl.classList.remove('hidden');
|
||||
if (status.register_open) {
|
||||
regEl.classList.remove('hidden');
|
||||
}
|
||||
const me = await fetch('/api/auth/me', { credentials: 'include' });
|
||||
if (me.ok) {
|
||||
const j = await me.json();
|
||||
greet.textContent = `Signed in as ${j.user.username}`;
|
||||
greet.classList.remove('hidden');
|
||||
loginEl.classList.add('hidden');
|
||||
regEl.classList.add('hidden');
|
||||
outEl.classList.remove('hidden');
|
||||
if (optionalKey) optionalKey.classList.add('hidden');
|
||||
} else {
|
||||
outEl.classList.add('hidden');
|
||||
greet.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('btn-logout').addEventListener('click', async () => {
|
||||
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const fromQuery = params.get('api_key');
|
||||
if (fromQuery) {
|
||||
sessionStorage.setItem(storageKey, fromQuery);
|
||||
}
|
||||
const existing = sessionStorage.getItem(storageKey);
|
||||
if (existing) {
|
||||
input.value = existing;
|
||||
}
|
||||
} catch (_e) {}
|
||||
openLink.addEventListener('click', () => {
|
||||
try {
|
||||
const v = input.value.trim();
|
||||
if (v) {
|
||||
sessionStorage.setItem(storageKey, v);
|
||||
} else {
|
||||
sessionStorage.removeItem(storageKey);
|
||||
}
|
||||
} catch (_e) {}
|
||||
});
|
||||
refreshAuthNav();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
72
src/static/index.html
Normal file
72
src/static/index.html
Normal file
@@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<link rel="stylesheet" href="/static/styles.css?v=6">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="sidebar">
|
||||
<div class="sidebar-header">
|
||||
<h3>Files</h3>
|
||||
<div class="sidebar-actions">
|
||||
<button id="new-file-btn" title="New File">📄</button>
|
||||
<button id="new-folder-btn" title="New Folder">📁+</button>
|
||||
<button id="delete-selected-btn" title="Delete Selected">🗑️</button>
|
||||
<button id="refresh-btn" title="Refresh">🔄</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="file-tree" id="file-tree">
|
||||
<div class="loading">Loading files...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="main-content">
|
||||
<div class="editor-header">
|
||||
<div class="file-info">
|
||||
<span id="save-status" class="save-status"></span>
|
||||
<span class="runtime-hint" title="Python runs locally in your browser via Pyodide; completions use Jedi in the same runtime.">Browser · Pyodide</span>
|
||||
</div>
|
||||
<div class="mode-toggle">
|
||||
<a id="home-btn" class="mode-btn active" href="/">Home</a>
|
||||
</div>
|
||||
<div class="editor-actions">
|
||||
<button id="run-btn" disabled>Run Python</button>
|
||||
<button id="stop-btn" disabled>Stop</button>
|
||||
<select id="run-file-select" title="Script to run">
|
||||
<option value="">Run active file</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="tabs" class="tabs"></div>
|
||||
|
||||
<div class="editor-container">
|
||||
<div id="editor"></div>
|
||||
<div id="completion-dropdown" class="completion-dropdown"></div>
|
||||
</div>
|
||||
|
||||
<div class="console-container">
|
||||
<div class="console-header">Console Output</div>
|
||||
<pre id="console-output" class="console-output"></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="new-file-modal" class="modal">
|
||||
<div class="modal-content">
|
||||
<h3>Create New File</h3>
|
||||
<input type="text" id="new-filename" placeholder="Enter filename (e.g., example.txt)" />
|
||||
<div class="modal-actions">
|
||||
<button id="create-file-btn">Create</button>
|
||||
<button id="cancel-create-btn">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="/static/script.js?v=10"></script>
|
||||
</body>
|
||||
</html>
|
||||
120
src/static/login.html
Normal file
120
src/static/login.html
Normal file
@@ -0,0 +1,120 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Sign in — Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #0f172a, #1e293b);
|
||||
color: #e2e8f0;
|
||||
}
|
||||
.card {
|
||||
width: min(400px, 92vw);
|
||||
background: rgba(15, 23, 42, 0.85);
|
||||
border: 1px solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 14px;
|
||||
padding: 2rem;
|
||||
}
|
||||
h1 { margin: 0 0 1rem 0; font-size: 1.4rem; }
|
||||
label { display: block; font-size: 0.85rem; color: #94a3b8; margin-bottom: 0.35rem; }
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #64748b;
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 0.65rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: #3b82f6;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
button:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
.err { color: #fca5a5; font-size: 0.9rem; margin-bottom: 0.75rem; min-height: 1.2em; }
|
||||
a { color: #93c5fd; }
|
||||
.links { font-size: 0.9rem; margin-top: 1rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<h1>Sign in</h1>
|
||||
<div id="err" class="err"></div>
|
||||
<form id="form">
|
||||
<label for="username">Username</label>
|
||||
<input id="username" name="username" autocomplete="username" required />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" type="password" name="password" autocomplete="current-password" required />
|
||||
<button type="submit" id="submit">Sign in</button>
|
||||
</form>
|
||||
<div class="links">
|
||||
<a href="/">Home</a>
|
||||
· <a id="register-link" href="/register">Create account</a>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const next = params.get("next") || "/editor";
|
||||
|
||||
(async function checkStatus() {
|
||||
try {
|
||||
const r = await fetch("/api/auth/status");
|
||||
const s = await r.json();
|
||||
if (!s.auth_enabled) {
|
||||
document.getElementById("err").textContent = "Sign-in is disabled (AUTH_ENABLED is not set).";
|
||||
document.getElementById("form").style.display = "none";
|
||||
}
|
||||
if (!s.register_open) {
|
||||
const link = document.getElementById("register-link");
|
||||
link.style.display = "none";
|
||||
}
|
||||
} catch (_e) {}
|
||||
})();
|
||||
|
||||
document.getElementById("form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const err = document.getElementById("err");
|
||||
const btn = document.getElementById("submit");
|
||||
err.textContent = "";
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const body = {
|
||||
username: document.getElementById("username").value.trim(),
|
||||
password: document.getElementById("password").value,
|
||||
};
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const j = await res.json().catch(() => ({}));
|
||||
err.textContent = j.detail || res.statusText || "Login failed";
|
||||
return;
|
||||
}
|
||||
window.location.href = next.startsWith("/") ? next : "/editor";
|
||||
} catch (ex) {
|
||||
err.textContent = String(ex.message || ex);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
122
src/static/pyodide-worker.js
Normal file
122
src/static/pyodide-worker.js
Normal file
@@ -0,0 +1,122 @@
|
||||
/* global importScripts, loadPyodide, self */
|
||||
importScripts('https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.js');
|
||||
|
||||
const PYODIDE_INDEX_URL = 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/';
|
||||
|
||||
let pyodide = null;
|
||||
let loadingPromise = null;
|
||||
|
||||
async function ensurePyodide() {
|
||||
if (pyodide) {
|
||||
return pyodide;
|
||||
}
|
||||
if (!loadingPromise) {
|
||||
loadingPromise = (async () => {
|
||||
const p = await loadPyodide({ indexURL: PYODIDE_INDEX_URL });
|
||||
p.setStdout({
|
||||
batched: (txt) => self.postMessage({ type: 'io', stream: 'stdout', text: txt }),
|
||||
});
|
||||
p.setStderr({
|
||||
batched: (txt) => self.postMessage({ type: 'io', stream: 'stderr', text: txt }),
|
||||
});
|
||||
await p.loadPackage('micropip');
|
||||
await p.runPythonAsync(`
|
||||
import micropip
|
||||
await micropip.install("jedi")
|
||||
`);
|
||||
return p;
|
||||
})();
|
||||
}
|
||||
pyodide = await loadingPromise;
|
||||
return pyodide;
|
||||
}
|
||||
|
||||
self.onmessage = async (event) => {
|
||||
const { id, type, payload } = event.data || {};
|
||||
try {
|
||||
if (type === 'init') {
|
||||
await ensurePyodide();
|
||||
self.postMessage({ id, type: 'init', ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const p = await ensurePyodide();
|
||||
|
||||
if (type === 'complete') {
|
||||
const rel = String(payload.path || 'scratch.py').replace(/^\/+/, '');
|
||||
const vpath = `/workspace/${rel}`;
|
||||
p.globals.set('__cm_code', String(payload.content ?? ''));
|
||||
p.globals.set('__cm_path', vpath);
|
||||
p.globals.set('__cm_line', Number(payload.line) || 1);
|
||||
p.globals.set('__cm_col', Number(payload.column) || 0);
|
||||
p.globals.set('__cm_max', Math.min(100, Math.max(1, Number(payload.max_results) || 20)));
|
||||
p.globals.set('__cm_extra_json', JSON.stringify(payload.extra_files || {}));
|
||||
const raw = p.runPython(`
|
||||
import json, os
|
||||
import jedi
|
||||
|
||||
extra = json.loads(__cm_extra_json)
|
||||
os.makedirs("/workspace", exist_ok=True)
|
||||
for rel_path, body in extra.items():
|
||||
rel_path = str(rel_path).lstrip("/")
|
||||
full = os.path.join("/workspace", rel_path)
|
||||
os.makedirs(os.path.dirname(full), exist_ok=True)
|
||||
with open(full, "w", encoding="utf-8") as fh:
|
||||
fh.write(str(body))
|
||||
os.makedirs(os.path.dirname(__cm_path), exist_ok=True)
|
||||
with open(__cm_path, "w", encoding="utf-8") as fh:
|
||||
fh.write(__cm_code)
|
||||
proj = jedi.Project("/workspace")
|
||||
s = jedi.Script(code=__cm_code, path=__cm_path, project=proj)
|
||||
items = s.complete(line=__cm_line, column=__cm_col)
|
||||
out = [{"name": i.name, "type": i.type, "complete": i.complete} for i in items[:__cm_max]]
|
||||
json.dumps(out)
|
||||
`);
|
||||
const completions = JSON.parse(String(raw));
|
||||
self.postMessage({ id, type: 'complete', ok: true, completions });
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'run') {
|
||||
const files = payload.files && typeof payload.files === 'object' ? payload.files : {};
|
||||
const mainRel = String(payload.mainPath || '').replace(/^\/+/, '');
|
||||
const argsList = Array.isArray(payload.args) ? payload.args.map(String) : [];
|
||||
p.globals.set('__run_files_json', JSON.stringify(files));
|
||||
p.globals.set('__run_main', `/workspace/${mainRel}`);
|
||||
p.globals.set('__run_args', p.toPy(argsList));
|
||||
await p.runPythonAsync(`
|
||||
import json, os, shutil, sys, runpy
|
||||
|
||||
files = json.loads(__run_files_json)
|
||||
shutil.rmtree('/workspace', ignore_errors=True)
|
||||
os.makedirs('/workspace', exist_ok=True)
|
||||
for rel, body in files.items():
|
||||
rel = str(rel).lstrip("/")
|
||||
full = os.path.join("/workspace", rel)
|
||||
os.makedirs(os.path.dirname(full), exist_ok=True)
|
||||
with open(full, "w", encoding="utf-8") as fh:
|
||||
fh.write(str(body))
|
||||
|
||||
for entry in ("/workspace/lib", "/workspace"):
|
||||
if entry not in sys.path:
|
||||
sys.path.insert(0, entry)
|
||||
|
||||
os.chdir("/workspace")
|
||||
main = __run_main
|
||||
sys.argv = [main] + list(__run_args)
|
||||
runpy.run_path(main, run_name="__main__")
|
||||
`);
|
||||
self.postMessage({ id, type: 'run', ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
self.postMessage({ id, type, ok: false, error: `Unknown message type: ${type}` });
|
||||
} catch (err) {
|
||||
self.postMessage({
|
||||
id,
|
||||
type,
|
||||
ok: false,
|
||||
error: err && err.message ? String(err.message) : String(err),
|
||||
});
|
||||
}
|
||||
};
|
||||
113
src/static/register.html
Normal file
113
src/static/register.html
Normal file
@@ -0,0 +1,113 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Register — Python Editor</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #0f172a, #1e293b);
|
||||
color: #e2e8f0;
|
||||
}
|
||||
.card {
|
||||
width: min(400px, 92vw);
|
||||
background: rgba(15, 23, 42, 0.85);
|
||||
border: 1px solid rgba(148, 163, 184, 0.25);
|
||||
border-radius: 14px;
|
||||
padding: 2rem;
|
||||
}
|
||||
h1 { margin: 0 0 1rem 0; font-size: 1.4rem; }
|
||||
label { display: block; font-size: 0.85rem; color: #94a3b8; margin-bottom: 0.35rem; }
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #64748b;
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 0.65rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: #3b82f6;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
button:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
.err { color: #fca5a5; font-size: 0.9rem; margin-bottom: 0.75rem; min-height: 1.2em; }
|
||||
.hint { font-size: 0.8rem; color: #94a3b8; margin-bottom: 1rem; }
|
||||
a { color: #93c5fd; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<h1>Create account</h1>
|
||||
<p class="hint">Username: letters, numbers, underscore (3–64). Password: at least 8 characters.</p>
|
||||
<div id="err" class="err"></div>
|
||||
<form id="form">
|
||||
<label for="username">Username</label>
|
||||
<input id="username" name="username" autocomplete="username" required />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" type="password" name="password" autocomplete="new-password" required />
|
||||
<button type="submit" id="submit">Register</button>
|
||||
</form>
|
||||
<p><a href="/login">Sign in</a> · <a href="/">Home</a></p>
|
||||
</main>
|
||||
<script>
|
||||
(async function checkStatus() {
|
||||
try {
|
||||
const r = await fetch("/api/auth/status");
|
||||
const s = await r.json();
|
||||
if (!s.auth_enabled) {
|
||||
document.getElementById("err").textContent = "Registration is disabled (AUTH_ENABLED is not set).";
|
||||
document.getElementById("form").style.display = "none";
|
||||
} else if (!s.register_open) {
|
||||
document.getElementById("err").textContent = "Public registration is closed. Ask an administrator.";
|
||||
document.getElementById("form").style.display = "none";
|
||||
}
|
||||
} catch (_e) {}
|
||||
})();
|
||||
|
||||
document.getElementById("form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const err = document.getElementById("err");
|
||||
const btn = document.getElementById("submit");
|
||||
err.textContent = "";
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const body = {
|
||||
username: document.getElementById("username").value.trim(),
|
||||
password: document.getElementById("password").value,
|
||||
};
|
||||
const res = await fetch("/api/auth/register", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const j = await res.json().catch(() => ({}));
|
||||
err.textContent = typeof j.detail === "string" ? j.detail : JSON.stringify(j.detail) || res.statusText;
|
||||
return;
|
||||
}
|
||||
window.location.href = "/login?next=/editor";
|
||||
} catch (ex) {
|
||||
err.textContent = String(ex.message || ex);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
1505
src/static/script.js
Normal file
1505
src/static/script.js
Normal file
File diff suppressed because it is too large
Load Diff
475
src/static/styles.css
Normal file
475
src/static/styles.css
Normal file
@@ -0,0 +1,475 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background-color: #f5f5f5;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
/* Sidebar */
|
||||
.sidebar {
|
||||
width: 300px;
|
||||
background-color: #2d3748;
|
||||
color: white;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid #4a5568;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.sidebar-header h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sidebar-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sidebar-actions button {
|
||||
background: none;
|
||||
border: none;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
padding: 0.25rem;
|
||||
border-radius: 4px;
|
||||
font-size: 1rem;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.sidebar-actions button:hover {
|
||||
background-color: #4a5568;
|
||||
}
|
||||
|
||||
.file-tree {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.file-item {
|
||||
padding: 0.5rem;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 2px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.file-item:hover {
|
||||
background-color: #4a5568;
|
||||
}
|
||||
|
||||
.file-item.selected {
|
||||
background-color: #3182ce;
|
||||
}
|
||||
|
||||
.file-item.drag-target {
|
||||
background-color: #2b6cb0;
|
||||
outline: 1px dashed #90cdf4;
|
||||
}
|
||||
|
||||
.file-item.dragging-file {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.file-item.directory {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.file-item.root-drop {
|
||||
border: 1px dashed #4a5568;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.loading {
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
color: #a0aec0;
|
||||
}
|
||||
|
||||
/* Main Content */
|
||||
.main-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
.editor-header {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background-color: #f7fafc;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.runtime-hint {
|
||||
font-size: 0.75rem;
|
||||
color: #718096;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
padding: 0.2rem 0.45rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#current-file {
|
||||
font-weight: 600;
|
||||
color: #2d3748;
|
||||
}
|
||||
|
||||
.save-status {
|
||||
font-size: 0.875rem;
|
||||
color: #718096;
|
||||
}
|
||||
|
||||
.save-status.saved {
|
||||
color: #38a169;
|
||||
}
|
||||
|
||||
.save-status.unsaved {
|
||||
color: #e53e3e;
|
||||
}
|
||||
|
||||
.mode-toggle {
|
||||
display: inline-flex;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.mode-btn {
|
||||
border: none;
|
||||
background: #edf2f7;
|
||||
color: #4a5568;
|
||||
padding: 0.45rem 0.8rem;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mode-btn + .mode-btn {
|
||||
border-left: 1px solid #cbd5e0;
|
||||
}
|
||||
|
||||
.mode-btn.active {
|
||||
background: #3182ce;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.editor-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
#run-file-select {
|
||||
min-width: 220px;
|
||||
padding: 0.5rem 0.65rem;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.editor-actions button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
background-color: white;
|
||||
color: #4a5568;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.editor-actions button:hover:not(:disabled) {
|
||||
background-color: #f7fafc;
|
||||
border-color: #cbd5e0;
|
||||
}
|
||||
|
||||
.editor-actions button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.editor-actions button:not(:disabled):active {
|
||||
background-color: #edf2f7;
|
||||
}
|
||||
|
||||
.editor-container {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.completion-dropdown {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
display: none;
|
||||
min-width: 220px;
|
||||
max-width: 420px;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
background: #ffffff;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.18);
|
||||
}
|
||||
|
||||
.completion-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.4rem 0.6rem;
|
||||
cursor: pointer;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.completion-item:hover,
|
||||
.completion-item.active {
|
||||
background: #ebf8ff;
|
||||
}
|
||||
|
||||
.completion-name {
|
||||
color: #1a202c;
|
||||
}
|
||||
|
||||
.completion-type {
|
||||
color: #718096;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
background: #f8fafc;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.tab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.35rem 0.6rem;
|
||||
border: 1px solid #cbd5e0;
|
||||
border-radius: 6px;
|
||||
background: white;
|
||||
color: #2d3748;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
border-color: #3182ce;
|
||||
background: #ebf8ff;
|
||||
}
|
||||
|
||||
.tab-title {
|
||||
max-width: 260px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.tab-close {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #718096;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.tab-close:hover {
|
||||
color: #e53e3e;
|
||||
}
|
||||
|
||||
#editor {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
outline: none;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
padding: 1rem;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
/* CodeMirror 6 styling */
|
||||
.cm-editor {
|
||||
height: 100%;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.cm-focused {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.console-container {
|
||||
height: 220px;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #0f172a;
|
||||
}
|
||||
|
||||
.console-header {
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
color: #cbd5e1;
|
||||
border-bottom: 1px solid #1e293b;
|
||||
}
|
||||
|
||||
.console-output {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
padding: 0.75rem;
|
||||
overflow: auto;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
color: #e2e8f0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: white;
|
||||
margin: 15% auto;
|
||||
padding: 2rem;
|
||||
border-radius: 8px;
|
||||
width: 400px;
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.modal-content h3 {
|
||||
margin-bottom: 1rem;
|
||||
color: #2d3748;
|
||||
}
|
||||
|
||||
.modal-content input {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.modal-content input:focus {
|
||||
outline: none;
|
||||
border-color: #3182ce;
|
||||
box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.1);
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.modal-actions button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
background-color: white;
|
||||
color: #4a5568;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.modal-actions button:hover {
|
||||
background-color: #f7fafc;
|
||||
border-color: #cbd5e0;
|
||||
}
|
||||
|
||||
.modal-actions button:first-child {
|
||||
background-color: #3182ce;
|
||||
color: white;
|
||||
border-color: #3182ce;
|
||||
}
|
||||
|
||||
.modal-actions button:first-child:hover {
|
||||
background-color: #2c5aa0;
|
||||
border-color: #2c5aa0;
|
||||
}
|
||||
|
||||
/* Responsive design */
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
width: 90%;
|
||||
margin: 20% auto;
|
||||
}
|
||||
}
|
||||
|
||||
/* Scrollbar styling */
|
||||
.file-tree::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.file-tree::-webkit-scrollbar-track {
|
||||
background: #2d3748;
|
||||
}
|
||||
|
||||
.file-tree::-webkit-scrollbar-thumb {
|
||||
background: #4a5568;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.file-tree::-webkit-scrollbar-thumb:hover {
|
||||
background: #718096;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user