From 232b9bf507ea8cf5f87d819c184f15dfcd3d019f Mon Sep 17 00:00:00 2001 From: Eli Date: Sun, 19 Apr 2026 19:22:45 -0400 Subject: [PATCH 1/7] Harden auth and stream security; update local hosting/deploy workflow --- .env.example | 2 +- Bash-Scripts/run-front.sh | 8 +- INSTRUCTIONS.md | 63 +- README.md | 7 +- backend/.env.example | 18 +- backend/api/internal/handlers/auth_routes.go | 127 ++++ .../handlers/direct_message_routes.go | 52 +- backend/api/main.go | 31 +- backend/deploy/systemd/devbits-api.service | 17 - backend/docker-compose.yml | 37 +- backend/docs/AWS_TRANSFER_NO_NGINX.md | 90 --- backend/nginx/nginx.conf | 579 ++++++++++++++++++ backend/scripts/README.md | 211 ++++--- backend/scripts/backup-deployment-db.sh | 50 +- backend/scripts/build-backend-linux.sh | 26 - backend/scripts/deploy-aws-native.sh | 27 - .../scripts/install-aws-systemd-service.sh | 61 -- backend/scripts/issue-letsencrypt-cert.sh | 99 +++ backend/scripts/reset-deployment-db.sh | 41 +- backend/scripts/restore-deployment-db.sh | 52 +- backend/scripts/update-live.ps1 | 108 ++++ backend/scripts/update-live.sh | 57 +- .../uploads/u1_1a5534ccca23297b1a89c65a.jpg | Bin 58053 -> 0 bytes frontend/RELEASE_CHECKLIST.md | 106 ++++ frontend/app.config.js | 81 ++- frontend/app.json | 80 --- frontend/app/_layout.tsx | 17 - frontend/app/conversation/[username].tsx | 4 +- frontend/app/settings/about.tsx | 2 +- frontend/eas.json | 7 +- frontend/services/api.ts | 14 +- 31 files changed, 1513 insertions(+), 561 deletions(-) delete mode 100644 backend/deploy/systemd/devbits-api.service delete mode 100644 backend/docs/AWS_TRANSFER_NO_NGINX.md create mode 100644 backend/nginx/nginx.conf delete mode 100644 backend/scripts/build-backend-linux.sh delete mode 100644 backend/scripts/deploy-aws-native.sh delete mode 100644 backend/scripts/install-aws-systemd-service.sh create mode 100644 backend/scripts/issue-letsencrypt-cert.sh create mode 100644 backend/scripts/update-live.ps1 delete mode 100644 backend/uploads/u1_1a5534ccca23297b1a89c65a.jpg create mode 100644 frontend/RELEASE_CHECKLIST.md delete mode 100644 frontend/app.json diff --git a/.env.example b/.env.example index a2ef39b..6ccf5ec 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,6 @@ EXPO_PUBLIC_USE_LOCAL_API=1 EXPO_PUBLIC_LOCAL_API_URL=http://192.168.76.129:8080 -EXPO_PUBLIC_API_URL=https://devbits.app +EXPO_PUBLIC_API_URL=https://devbits.ddns.net EXPO_PUBLIC_LOCAL_API_PORT=8080 POSTGRES_DB=devbits_dev POSTGRES_USER=devbits_dev diff --git a/Bash-Scripts/run-front.sh b/Bash-Scripts/run-front.sh index e5c0e99..a296734 100644 --- a/Bash-Scripts/run-front.sh +++ b/Bash-Scripts/run-front.sh @@ -77,7 +77,7 @@ if [[ -z "$LAN_IP" ]]; then fi if [[ -z "$MODE" ]]; then - echo "Select backend: 1) Live (devbits.app) 2) Local (LAN IP:8080)" + echo "Select backend: 1) Live (devbits.ddns.net) 2) Local (LAN IP:8080)" read -r -p "Choose [1/2]: " selection case "$selection" in 1) MODE="production" ;; @@ -96,8 +96,8 @@ else unset REACT_NATIVE_PACKAGER_HOSTNAME || true unset EXPO_PACKAGER_HOSTNAME || true fi -export EXPO_PUBLIC_API_URL="https://devbits.app" -export EXPO_PUBLIC_API_FALLBACK_URL="https://devbits.app" +export EXPO_PUBLIC_API_URL="https://devbits.ddns.net" +export EXPO_PUBLIC_API_FALLBACK_URL="https://devbits.ddns.net" if [[ "$MODE" == "local" ]]; then LOCAL_API_PORT="${EXPO_PUBLIC_LOCAL_API_PORT:-8080}" @@ -119,7 +119,7 @@ if [[ "$MODE" == "local" ]]; then else export EXPO_PUBLIC_USE_LOCAL_API=0 unset EXPO_PUBLIC_LOCAL_API_URL || true - echo "Using live backend: https://devbits.app" + echo "Using live backend: https://devbits.ddns.net" fi cd "$FRONTEND_DIR" diff --git a/INSTRUCTIONS.md b/INSTRUCTIONS.md index b0aa2aa..78865ec 100644 --- a/INSTRUCTIONS.md +++ b/INSTRUCTIONS.md @@ -2,57 +2,29 @@ ## Backend -> **AWS EC2 (Amazon Linux) Native Deploy** +> **Live/Deployed Stack** > > ```bash -> # On your EC2 instance -> sudo dnf update -y -> sudo dnf install -y git tar +> cd /path/to/DevBits/backend +> docker compose up -d +> docker compose logs -f db > ``` -> -> Install Go 1.24.x (required by `backend/go.mod`): -> -> ```bash -> curl -LO https://go.dev/dl/go1.24.2.linux-amd64.tar.gz -> sudo rm -rf /usr/local/go -> sudo tar -C /usr/local -xzf go1.24.2.linux-amd64.tar.gz -> echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc -> source ~/.bashrc -> go version -> ``` -> -> Clone and deploy: -> -> ```bash -> sudo mkdir -p /opt/devbits -> sudo chown -R "$USER":"$USER" /opt/devbits -> cd /opt/devbits -> git clone https://github.com/devbits-go/DevBits.git . -> git checkout aws-ready-main -> cd backend -> cp .env.example .env -> # edit .env with production values (DATABASE_URL, secrets, CORS, etc.) -> ./scripts/deploy-aws-native.sh -> ``` -> -> Verify service: + +> Rebuild and restart: > > ```bash -> sudo systemctl status devbits-api --no-pager -> sudo journalctl -u devbits-api -n 120 --no-pager -> curl -i http://127.0.0.1:8080/health +> docker compose up -d --build > ``` -> + > [!TIP] -> AWS deploy uses native `systemd` (no Docker or nginx required in production). -> See `backend/docs/AWS_TRANSFER_NO_NGINX.md` for full runbook. +> Check `backend/scripts/README.md` for database operations. ## Build > **Android Production Build** > > ```bash -> npx eas build -p android --profile production +> npx --yes eas-cli build -p android --profile production > ``` > [!NOTE] @@ -63,11 +35,12 @@ > Replace `android` with `ios` and fill out proper credentials. > > ```bash -> npx eas build -p ios --profile production +> npx --yes eas-cli build -p ios --profile production > ``` > [!NOTE] -> Currently requires MY credentials. Need to add team credentials. +> If iOS build fails with Apple 403 / PLA message, accept the latest Apple Developer Program License Agreement first: +> https://developer.apple.com/account ## Submit @@ -76,14 +49,18 @@ > Copy file out of expo and create new release on Google Play Console. > [!NOTE] -> `npx eas submit -p android` failed, so manual submission is required until fix is in place. Im not sure what is happening. +> Use: +> ```bash +> npx --yes eas-cli submit -p android --latest --profile production +> ``` +> If it fails, verify the service account key path in `frontend/eas.json` points to `../devbits-play-service-account.json` and that Google Play API access is enabled for the linked service account. > **iOS to App Store** > > ```bash -> npx eas submit -p ios --latest --profile production +> npx --yes eas-cli submit -p ios --latest --profile production > ``` --- -`Workflow: AWS Backend Deploy → EAS Build → EAS Submit` +`Workflow: Backend Setup → EAS Build → EAS Submit` diff --git a/README.md b/README.md index d6fdc26..f3f24b3 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Expo TypeScript PostgreSQL - AWS + Docker

--- @@ -113,7 +113,7 @@ Anyone can react, follow, comment, and join the conversation. - Go + Gin REST backend with JWT auth and middleware-protected routes. - PostgreSQL production database and SQLite-friendly test workflows. - React Native + Expo mobile client for Android and iOS. -- AWS-hosted backend deployment path. +- Docker Compose + nginx backend deployment path. @@ -123,7 +123,7 @@ Anyone can react, follow, comment, and join the conversation. Backend: Go (Gin API, JWT auth, DB query layer) Frontend: TypeScript (React Native + Expo Router) Database: PostgreSQL (production), SQLite (test mode) -Infra: AWS EC2 + AWS RDS +Infra: Docker Compose + nginx ``` ## Architecture at a Glance @@ -154,4 +154,3 @@ Instead of posting polished outcomes only, builders can share: - Product and deployment runbook: [INSTRUCTIONS.md](INSTRUCTIONS.md) - Backend structure and scripts: [backend/scripts/README.md](backend/scripts/README.md) -- AWS deployment notes: [docs/AWS_TRANSFER_NO_NGINX.md](docs/AWS_TRANSFER_NO_NGINX.md) diff --git a/backend/.env.example b/backend/.env.example index b7acfbc..5983a92 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -5,21 +5,21 @@ DEVBITS_ADMIN_KEY=replace-with-strong-admin-key DEVBITS_JWT_SECRET=replace-with-64-plus-char-random-secret -# Preferred for AWS (RDS/Postgres) -# Replace user/password/endpoint/db name with your real RDS values. -# URL-encode special characters in password (for example ! -> %21). -DATABASE_URL=postgres://postgres:replace-with-strong-password@your-rds-endpoint:5432/postgres?sslmode=require +# Docker/Postgres values used by backend/docker-compose.yml +# Keep sslmode=disable for the internal Docker network. +DATABASE_URL=postgres://devbits:replace-with-strong-password@db:5432/devbits?sslmode=disable -# Optional local fallback values (used only when DATABASE_URL is unset) +# Docker database bootstrap values POSTGRES_DB=devbits POSTGRES_USER=devbits POSTGRES_PASSWORD=replace-with-strong-password # Optional: comma-separated CORS origins for browser clients. -DEVBITS_CORS_ORIGINS=https://devbits.app,https://www.devbits.app +DEVBITS_CORS_ORIGINS=https://devbits.ddns.net -# AWS/ALB runtime settings +# Runtime settings for Docker + nginx reverse proxy +DEVBITS_DEBUG=0 DEVBITS_API_ADDR=0.0.0.0:8080 -DEVBITS_ADMIN_LOCAL_ONLY=0 -# Set true only when running behind a trusted proxy (ALB/nginx) that sets X-Forwarded-Proto. +DEVBITS_ADMIN_LOCAL_ONLY=1 +# Set true only when running behind a trusted proxy (nginx) that sets X-Forwarded-Proto. DEVBITS_TRUST_PROXY=true diff --git a/backend/api/internal/handlers/auth_routes.go b/backend/api/internal/handlers/auth_routes.go index 5a3a520..3c8ee72 100644 --- a/backend/api/internal/handlers/auth_routes.go +++ b/backend/api/internal/handlers/auth_routes.go @@ -4,6 +4,7 @@ import ( "fmt" "net/http" "strings" + "sync" "time" "backend/api/internal/auth" @@ -31,6 +32,121 @@ type AuthResponse struct { User database.ApiUser `json:"user"` } +type loginFailureState struct { + failures int + firstFailure time.Time + blockedUntil time.Time +} + +var loginFailureMu sync.Mutex +var loginFailuresByKey = make(map[string]loginFailureState) + +const ( + loginFailureWindow = 10 * time.Minute + loginFailureBlockFor = 5 * time.Minute + maxLoginFailuresByUser = 8 + maxLoginFailuresByIP = 20 +) + +func loginUserKey(username string) string { + normalized := strings.ToLower(strings.TrimSpace(username)) + if normalized == "" { + normalized = "_" + } + return "user:" + normalized +} + +func loginIPKey(ip string) string { + normalized := strings.TrimSpace(ip) + if normalized == "" { + normalized = "unknown" + } + return "ip:" + normalized +} + +func resetLoginFailureLocked(key string, now time.Time) { + state := loginFailuresByKey[key] + if state.failures == 0 && state.blockedUntil.IsZero() { + return + } + if now.Sub(state.firstFailure) > loginFailureWindow { + delete(loginFailuresByKey, key) + return + } + state.failures = 0 + state.firstFailure = time.Time{} + state.blockedUntil = time.Time{} + loginFailuresByKey[key] = state +} + +func checkLoginRateLimit(ip, username string) (bool, int) { + now := time.Now() + keys := []string{loginUserKey(username), loginIPKey(ip)} + + loginFailureMu.Lock() + defer loginFailureMu.Unlock() + + for _, key := range keys { + state, ok := loginFailuresByKey[key] + if !ok { + continue + } + if !state.blockedUntil.IsZero() { + if now.Before(state.blockedUntil) { + remaining := int(time.Until(state.blockedUntil).Seconds()) + if remaining < 1 { + remaining = 1 + } + return true, remaining + } + state.blockedUntil = time.Time{} + state.failures = 0 + state.firstFailure = time.Time{} + loginFailuresByKey[key] = state + } + } + + return false, 0 +} + +func recordLoginFailure(ip, username string) { + now := time.Now() + keys := []string{loginUserKey(username), loginIPKey(ip)} + + loginFailureMu.Lock() + defer loginFailureMu.Unlock() + + for _, key := range keys { + state := loginFailuresByKey[key] + if state.firstFailure.IsZero() || now.Sub(state.firstFailure) > loginFailureWindow { + state = loginFailureState{failures: 0, firstFailure: now} + } + + state.failures++ + limit := maxLoginFailuresByIP + if strings.HasPrefix(key, "user:") { + limit = maxLoginFailuresByUser + } + if state.failures >= limit { + state.blockedUntil = now.Add(loginFailureBlockFor) + } + + loginFailuresByKey[key] = state + } +} + +func clearLoginFailures(ip, username string) { + now := time.Now() + keys := []string{loginUserKey(username), loginIPKey(ip)} + + loginFailureMu.Lock() + defer loginFailureMu.Unlock() + + for _, key := range keys { + resetLoginFailureLocked(key, now) + } +} + func Register(context *gin.Context) { var request RegisterRequest if err := context.BindJSON(&request); err != nil { @@ -114,23 +230,32 @@ func Login(context *gin.Context) { return } + if blocked, retryAfter := checkLoginRateLimit(context.ClientIP(), request.Username); blocked { + context.Header("Retry-After", fmt.Sprintf("%d", retryAfter)) + RespondWithError(context, http.StatusTooManyRequests, "Too many login attempts. Please try again later.") + return + } + loginInfo, err := database.GetUserLoginInfo(request.Username) if err != nil { RespondWithError(context, http.StatusInternalServerError, fmt.Sprintf("Failed to login: %v", err)) return } if loginInfo == nil { + recordLoginFailure(context.ClientIP(), request.Username) RespondWithError(context, http.StatusUnauthorized, "Invalid credentials") return } if err := bcrypt.CompareHashAndPassword([]byte(loginInfo.PasswordHash), []byte(request.Password)); err != nil { + recordLoginFailure(context.ClientIP(), request.Username) RespondWithError(context, http.StatusUnauthorized, "Invalid credentials") return } user, err := database.GetUserByUsername(request.Username) if err != nil || user == nil { + recordLoginFailure(context.ClientIP(), request.Username) RespondWithError(context, http.StatusUnauthorized, "Invalid credentials") return } @@ -161,6 +286,8 @@ func Login(context *gin.Context) { return } + clearLoginFailures(context.ClientIP(), request.Username) + context.JSON(http.StatusOK, AuthResponse{Token: token, User: *user}) } diff --git a/backend/api/internal/handlers/direct_message_routes.go b/backend/api/internal/handlers/direct_message_routes.go index 6473c66..c3c3b40 100644 --- a/backend/api/internal/handlers/direct_message_routes.go +++ b/backend/api/internal/handlers/direct_message_routes.go @@ -18,7 +18,7 @@ import ( ) type directMessageStreamEvent struct { - Type string `json:"type"` + Type string `json:"type"` DirectMessage database.DirectMessage `json:"direct_message"` } @@ -107,11 +107,46 @@ func normalizeUsername(value string) string { return strings.ToLower(strings.TrimSpace(strings.TrimPrefix(value, "@"))) } +func extractTokenFromWebSocketProtocol(headerValue string) string { + if strings.TrimSpace(headerValue) == "" { + return "" + } + + parts := strings.Split(headerValue, ",") + for _, raw := range parts { + part := strings.TrimSpace(raw) + if part == "" { + continue + } + + if strings.HasPrefix(strings.ToLower(part), "bearer.") { + candidate := strings.TrimSpace(part[len("bearer."):]) + if candidate != "" { + return candidate + } + } + + if strings.HasPrefix(strings.ToLower(part), "devbits.jwt.") { + candidate := strings.TrimSpace(part[len("devbits.jwt."):]) + if candidate != "" { + return candidate + } + } + } + + return "" +} + func extractToken(context *gin.Context) string { authorization := strings.TrimSpace(context.GetHeader("Authorization")) if strings.HasPrefix(strings.ToLower(authorization), "bearer ") { return strings.TrimSpace(authorization[7:]) } + + if protocolToken := extractTokenFromWebSocketProtocol(context.GetHeader("Sec-WebSocket-Protocol")); protocolToken != "" { + return protocolToken + } + return strings.TrimSpace(context.Query("token")) } @@ -235,20 +270,21 @@ func StreamDirectMessages(context *gin.Context) { "connection": context.GetHeader("Connection"), "user_agent": context.GetHeader("User-Agent"), }).Warn("Direct message stream request missing websocket upgrade headers") - RespondWithError(context, http.StatusBadRequest, "Failed to establish stream") + context.Header("Upgrade", "websocket") + RespondWithError(context, http.StatusUpgradeRequired, "WebSocket upgrade required") return } connection, err := wsUpgrader.Upgrade(context.Writer, context.Request, nil) if err != nil { logger.Log.WithFields(map[string]interface{}{ - "path": context.Request.URL.Path, - "upgrade": context.GetHeader("Upgrade"), - "connection": context.GetHeader("Connection"), - "sec_websocket_key": context.GetHeader("Sec-WebSocket-Key") != "", + "path": context.Request.URL.Path, + "upgrade": context.GetHeader("Upgrade"), + "connection": context.GetHeader("Connection"), + "sec_websocket_key": context.GetHeader("Sec-WebSocket-Key") != "", "sec_websocket_version": context.GetHeader("Sec-WebSocket-Version"), - "user_agent": context.GetHeader("User-Agent"), - "error": err.Error(), + "user_agent": context.GetHeader("User-Agent"), + "error": err.Error(), }).Warn("Direct message stream websocket upgrade failed") RespondWithError(context, http.StatusBadRequest, "Failed to establish stream") return diff --git a/backend/api/main.go b/backend/api/main.go index a90cf78..0e6b380 100644 --- a/backend/api/main.go +++ b/backend/api/main.go @@ -1,11 +1,14 @@ package main import ( - "github.com/joho/godotenv" + "fmt" "log" "os" "path/filepath" "strings" + "time" + + "github.com/joho/godotenv" "backend/api/internal/database" "backend/api/internal/handlers" @@ -42,8 +45,7 @@ func getAllowedOrigins() []string { } return []string{ - "https://devbits.app", - "https://www.devbits.app", + "https://devbits.ddns.net", "http://localhost:8081", "http://localhost:19006", "http://127.0.0.1:8081", @@ -98,7 +100,28 @@ func main() { router := gin.New() router.MaxMultipartMemory = 64 << 20 - router.Use(gin.Logger(), gin.Recovery()) + router.Use(gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string { + // Never log query strings to avoid leaking credentials/tokens. + path := params.Path + if path == "" && params.Request != nil && params.Request.URL != nil { + path = params.Request.URL.Path + } + + userAgent := "" + if params.Request != nil { + userAgent = params.Request.UserAgent() + } + + return fmt.Sprintf("[%s] %d | %13v | %15s | %-7s %s | ua=%q\n", + params.TimeStamp.Format(time.RFC3339), + params.StatusCode, + params.Latency, + params.ClientIP, + params.Method, + path, + userAgent, + ) + }), gin.Recovery()) router.Use(func(context *gin.Context) { path := context.Request.URL.Path if strings.HasPrefix(path, "/uploads/") { diff --git a/backend/deploy/systemd/devbits-api.service b/backend/deploy/systemd/devbits-api.service deleted file mode 100644 index 17a18b0..0000000 --- a/backend/deploy/systemd/devbits-api.service +++ /dev/null @@ -1,17 +0,0 @@ -[Unit] -Description=DevBits API Service -After=network.target - -[Service] -Type=simple -User=__SERVICE_USER__ -Group=__SERVICE_USER__ -WorkingDirectory=__WORKDIR__ -EnvironmentFile=__ENV_FILE__ -ExecStart=__BINARY_PATH__ -Restart=always -RestartSec=3 -LimitNOFILE=65535 - -[Install] -WantedBy=multi-user.target diff --git a/backend/docker-compose.yml b/backend/docker-compose.yml index dd96c6f..2e63deb 100644 --- a/backend/docker-compose.yml +++ b/backend/docker-compose.yml @@ -16,6 +16,8 @@ services: interval: 5s timeout: 5s retries: 20 + networks: + - app-network backend: build: @@ -27,9 +29,11 @@ services: # Mount the uploads directory to persist data - ./uploads:/root/uploads ports: - - "8080:8080" + - "127.0.0.1:8080:8080" security_opt: - no-new-privileges:true + networks: + - app-network depends_on: db: condition: service_healthy @@ -37,7 +41,36 @@ services: - DATABASE_URL=postgres://${POSTGRES_USER:-devbits}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}@db:5432/${POSTGRES_DB:-devbits}?sslmode=disable - DEVBITS_ADMIN_KEY=${DEVBITS_ADMIN_KEY} - DEVBITS_ADMIN_LOCAL_ONLY=${DEVBITS_ADMIN_LOCAL_ONLY:-0} - - DEVBITS_CORS_ORIGINS=${DEVBITS_CORS_ORIGINS:-https://devbits.app,https://www.devbits.app} + - DEVBITS_CORS_ORIGINS=${DEVBITS_CORS_ORIGINS:-https://devbits.ddns.net} + - DEVBITS_JWT_SECRET=${DEVBITS_JWT_SECRET} + - DEVBITS_TRUST_PROXY=${DEVBITS_TRUST_PROXY:-true} + - DEVBITS_DEBUG=${DEVBITS_DEBUG:-0} + - DEVBITS_API_ADDR=${DEVBITS_API_ADDR:-0.0.0.0:8080} + + nginx: + image: nginx:1.27-alpine + container_name: devbits-nginx + restart: unless-stopped + ports: + - "80:80" + - "443:443" + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + # Mount volumes for Let's Encrypt certificates + - ./nginx/certs:/etc/letsencrypt + # Serve static site assets (public pages + screenshots) + - ../frontend/public:/usr/share/nginx/html:ro + depends_on: + backend: + condition: service_started + security_opt: + - no-new-privileges:true + networks: + - app-network + +networks: + app-network: + driver: bridge volumes: postgres-data: diff --git a/backend/docs/AWS_TRANSFER_NO_NGINX.md b/backend/docs/AWS_TRANSFER_NO_NGINX.md deleted file mode 100644 index db3a01f..0000000 --- a/backend/docs/AWS_TRANSFER_NO_NGINX.md +++ /dev/null @@ -1,90 +0,0 @@ -# DevBits AWS Transfer (Native Backend, No Docker, No Nginx) - -This runbook deploys the Go backend as a native Linux service on EC2. - -## Target architecture - -- Route 53 (`devbits.app`, optional `www.devbits.app`) -- ACM certificate -- Application Load Balancer (HTTPS 443) -- EC2 instance running `devbits-api` via `systemd` -- PostgreSQL on AWS RDS (recommended) or another managed Postgres - -## What changed in this branch - -- `devbits.ddns.net` defaults moved to `devbits.app`. -- nginx runtime dependency removed from deployment path. -- Backend serves: - - `/apple-app-site-association` - - `/.well-known/assetlinks.json` - - `/privacy-policy` - - `/account-deletion` -- Upload absolute URLs now honor `X-Forwarded-Proto` (correct behind ALB). -- Added native deploy scripts: - - `backend/scripts/build-backend-linux.sh` - - `backend/scripts/install-aws-systemd-service.sh` - - `backend/scripts/deploy-aws-native.sh` - - `backend/scripts/update-live.sh` (wrapper) - -## What you give the AWS account owner - -1. Repo URL + branch name. -2. Domain: `devbits.app` (+ optional `www.devbits.app`). -3. Region (example: `us-east-1`). -4. These env values for `backend/.env`: - - `DATABASE_URL=postgres://...` (RDS endpoint, db, user, password, sslmode=require) - - `DEVBITS_JWT_SECRET` - - `DEVBITS_ADMIN_KEY` - - `DEVBITS_ADMIN_LOCAL_ONLY=0` (or `1` for localhost-only admin) - - `DEVBITS_CORS_ORIGINS=https://devbits.app,https://www.devbits.app` - - `DEVBITS_API_ADDR=0.0.0.0:8080` -5. Optional data migration files: - - DB dump (`devbits-db-*.sql`) - - uploads archive - -## AWS setup steps (admin) - -1. Create Route 53 records for `devbits.app` and `www.devbits.app`. -2. Request ACM cert for both names. -3. Create ALB: - - Listener `80` -> redirect to `443` - - Listener `443` -> target group on EC2 `:8080` - - Health check path `/health` -4. Create EC2 (Amazon Linux 2023 recommended). -5. Security groups: - - ALB SG: inbound `80/443` from internet - - EC2 SG: inbound `8080` from ALB SG only, `22` from admin IP only -6. Provision EC2: - - Install `git` and `tar`: `sudo dnf install -y git tar` - - Install Go `1.24.x` from `go.dev` tarball to `/usr/local/go` - - Clone repo to `/opt/devbits` (typically as `ec2-user`) - - `cd /opt/devbits/backend` - - `cp .env.example .env` and fill real values - - `./scripts/deploy-aws-native.sh` -7. Verify: - - `https://devbits.app/health` - - `https://devbits.app/privacy-policy` - - `https://devbits.app/account-deletion` - - `https://devbits.app/apple-app-site-association` - - `https://devbits.app/.well-known/assetlinks.json` - -## Updating backend after code changes - -On EC2: - -```bash -cd /opt/devbits -git pull origin -cd backend -./scripts/update-live.sh -``` - -Amazon Linux notes: - -- Default SSH user is usually `ec2-user`. -- Use `dnf` (not `apt`) for packages. -- Keep `/opt/devbits` owned by the deploy user so build/deploy scripts can run without permission issues. - -## Notes - -- Docker is still available in this repo for local workflows, but AWS deployment in this runbook is native (`systemd`) and does not require Docker or nginx. diff --git a/backend/nginx/nginx.conf b/backend/nginx/nginx.conf new file mode 100644 index 0000000..7a9ed39 --- /dev/null +++ b/backend/nginx/nginx.conf @@ -0,0 +1,579 @@ +worker_processes 1; + +events { + worker_connections 1024; +} + +http { + upstream backend_upstream { + server backend:8080; + keepalive 64; + } + + map $http_upgrade $connection_upgrade { + default upgrade; + '' close; + } + + map "$request_method $request_uri" $loggable { + default 1; + "GET /favicon.ico" 0; + "GET /apple-touch-icon.png" 0; + "GET /apple-touch-icon-precomposed.png" 0; + "POST /" 0; + } + + map $request_uri $honeypot_hit { + default 0; + ~*^/(wp-admin|wp-login\.php|xmlrpc\.php|phpmyadmin|pma|\.git|\.env|cgi-bin|boaform|actuator|manager/html|server-status|vendor/phpunit|\.well-known/pki-validation) 1; + } + + map $honeypot_hit $honeypot_loggable { + default 0; + 1 1; + } + + access_log /dev/stdout combined if=$loggable; + access_log /dev/stdout combined if=$honeypot_loggable; + error_log /dev/stderr warn; + + limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=10r/m; + limit_req_zone $binary_remote_addr zone=api_limit:10m rate=30r/s; + + sendfile on; + tcp_nopush on; + tcp_nodelay on; + keepalive_timeout 30; + keepalive_requests 1000; + types_hash_max_size 2048; + + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_comp_level 6; + gzip_types + text/plain + text/css + text/xml + application/xml + application/json + application/javascript + image/svg+xml; + + include /etc/nginx/mime.types; + default_type application/octet-stream; + client_max_body_size 64m; + proxy_set_header Authorization $http_authorization; + server_tokens off; + + # HTTP server for local development and health checks + server { + listen 80 default_server; + server_name _; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Referrer-Policy "same-origin" always; + + location ~* ^/(wp-admin|wp-login\.php|xmlrpc\.php|phpmyadmin|pma|\.git|\.env|cgi-bin|boaform|actuator|manager/html|server-status|vendor/phpunit|\.well-known/pki-validation) { + return 444; + } + + location ~* ^/(media/upload|users/.+/(profile-picture|update))$ { + client_max_body_size 64m; + client_body_timeout 30s; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + proxy_request_buffering on; + proxy_buffering on; + proxy_read_timeout 30s; + proxy_send_timeout 30s; + add_header Cache-Control "no-store" always; + } + + location ~* ^/users/[^/]+$ { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + proxy_request_buffering on; + proxy_buffering on; + proxy_read_timeout 30s; + proxy_send_timeout 30s; + add_header Cache-Control "no-store" always; + } + + location ~ ^/(auth|feed|users|projects|posts|comments|notifications|messages|media|health)(/|$) { + limit_req zone=api_limit burst=120 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location ^~ /uploads/ { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + add_header Cache-Control "no-cache, max-age=0, must-revalidate" always; + } + + location ~* \.(png|jpg|jpeg|gif|webp|svg|ico)$ { + root /usr/share/nginx/html; + try_files $uri =404; + add_header Cache-Control "public, max-age=86400" always; + } + + location = /Cards.svg { + default_type image/svg+xml; + alias /usr/share/nginx/html/Cards.svg; + add_header Cache-Control "public, max-age=86400" always; + } + + location = /cards.svg { + default_type image/svg+xml; + alias /usr/share/nginx/html/Cards.svg; + add_header Cache-Control "public, max-age=86400" always; + } + + location / { + root /usr/share/nginx/html; + try_files $uri $uri/ @backend; + } + + location @backend { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + # Serve Apple App Site Association for Universal Links + location = /apple-app-site-association { + default_type application/json; + alias /usr/share/nginx/html/apple-app-site-association; + } + + # Serve Android assetlinks (App Links) + location = /.well-known/assetlinks.json { + default_type application/json; + alias /usr/share/nginx/html/.well-known/assetlinks.json; + } + + location /api/ { + limit_req zone=api_limit burst=120 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location = /admin { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location ^~ /admin/ { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location = /api/auth/login { + limit_req zone=auth_limit burst=40 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location = /api/auth/register { + limit_req zone=auth_limit burst=40 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + } + + # Redirect all HTTP traffic to HTTPS for production domain + server { + listen 80; + server_name devbits.ddns.net; + return 301 https://$host$request_uri; + } + + # HTTPS server + server { + listen 443 ssl http2; + server_name devbits.ddns.net; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Referrer-Policy "same-origin" always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + + location ~* ^/(wp-admin|wp-login\.php|xmlrpc\.php|phpmyadmin|pma|\.git|\.env|cgi-bin|boaform|actuator|manager/html|server-status|vendor/phpunit|\.well-known/pki-validation) { + return 444; + } + + # SSL Certificate + ssl_certificate /etc/letsencrypt/live/devbits.ddns.net/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/devbits.ddns.net/privkey.pem; + + # Improve SSL security + ssl_protocols TLSv1.2 TLSv1.3; + ssl_prefer_server_ciphers on; + ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; + + # Session / ticket settings + ssl_session_cache shared:SSL:50m; + ssl_session_timeout 1d; + ssl_session_tickets on; + + # OCSP stapling disabled because current certificate chain has no responder URL. + ssl_stapling off; + ssl_stapling_verify off; + resolver 1.1.1.1 8.8.8.8 8.8.4.4 ipv6=off valid=300s; + resolver_timeout 5s; + ssl_trusted_certificate /etc/letsencrypt/live/devbits.ddns.net/chain.pem; + + # Disable gzip on TLS endpoint to mitigate BREACH risk for sensitive responses + gzip off; + + location ~* ^/(media/upload|users/.+/(profile-picture|update))$ { + client_max_body_size 64m; + client_body_timeout 180s; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + proxy_request_buffering on; + proxy_buffering on; + proxy_read_timeout 180s; + proxy_send_timeout 180s; + add_header Cache-Control "no-store" always; + } + + location ~* ^/users/[^/]+$ { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + proxy_request_buffering on; + proxy_buffering on; + proxy_read_timeout 180s; + proxy_send_timeout 180s; + add_header Cache-Control "no-store" always; + } + + location ~ ^/(auth|feed|users|projects|posts|comments|notifications|messages|media|health)(/|$) { + limit_req zone=api_limit burst=120 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location ^~ /uploads/ { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + add_header Cache-Control "no-cache, max-age=0, must-revalidate" always; + } + + location ~* \.(png|jpg|jpeg|gif|webp|svg|ico)$ { + root /usr/share/nginx/html; + try_files $uri =404; + add_header Cache-Control "public, max-age=86400" always; + } + + location = /Cards.svg { + default_type image/svg+xml; + alias /usr/share/nginx/html/Cards.svg; + add_header Cache-Control "public, max-age=86400" always; + } + + location = /cards.svg { + default_type image/svg+xml; + alias /usr/share/nginx/html/Cards.svg; + add_header Cache-Control "public, max-age=86400" always; + } + + location / { + root /usr/share/nginx/html; + try_files $uri $uri/ @backend; + } + + # Serve Apple App Site Association for Universal Links + location = /apple-app-site-association { + default_type application/json; + alias /usr/share/nginx/html/apple-app-site-association; + } + + # Serve Android assetlinks (App Links) + location = /.well-known/assetlinks.json { + default_type application/json; + alias /usr/share/nginx/html/.well-known/assetlinks.json; + } + + location @backend { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + # Serve static pages directly from nginx + location = /account-deletion { + default_type text/html; + alias /usr/share/nginx/html/account-deletion.html; + } + + location = /account-deletion.html { + default_type text/html; + alias /usr/share/nginx/html/account-deletion.html; + } + + # Serve the Privacy Policy page required by store listings + location = /privacy-policy { + default_type text/html; + alias /usr/share/nginx/html/privacy-policy.html; + } + + location = /privacy-policy.html { + default_type text/html; + alias /usr/share/nginx/html/privacy-policy.html; + } + + location = /api/auth/login { + limit_req zone=auth_limit burst=20 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location = /api/auth/register { + limit_req zone=auth_limit burst=20 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location /api/ { + limit_req zone=api_limit burst=120 nodelay; + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location = /admin { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + location ^~ /admin/ { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache off; + proxy_cache_bypass 1; + proxy_no_cache 1; + add_header Cache-Control "no-store" always; + } + + # Serve the CSAE (Child Sexual Abuse & Exploitation) standards page + location = /csae-standards { + default_type text/html; + alias /usr/share/nginx/html/csae-standards.html; + } + + location = /csae-standards.html { + default_type text/html; + alias /usr/share/nginx/html/csae-standards.html; + } + + # Serve the tester application page + location = /tester-application { + default_type text/html; + alias /usr/share/nginx/html/tester-application.html; + } + + location = /tester-application.html { + default_type text/html; + alias /usr/share/nginx/html/tester-application.html; + } + + # Serve features page + location = /features { + default_type text/html; + alias /usr/share/nginx/html/features.html; + } + + location = /features.html { + default_type text/html; + alias /usr/share/nginx/html/features.html; + } + + # Serve about page + location = /about { + default_type text/html; + alias /usr/share/nginx/html/about.html; + } + + location = /about.html { + default_type text/html; + alias /usr/share/nginx/html/about.html; + } + + } +} diff --git a/backend/scripts/README.md b/backend/scripts/README.md index 7748d6c..099fe88 100644 --- a/backend/scripts/README.md +++ b/backend/scripts/README.md @@ -1,118 +1,183 @@ -# DevBits Backend Scripts +# DevBits Database Scripts -Run scripts from `backend/`. +All deployment database scripts are in this folder. -## 1) Update backend on AWS +## Environment separation (important) -Build locally, then copy binary to EC2 (recommended): +### Local DB (development machine) -```bash -# local machine -cd /home/ws-73/OldFiles/projects/DevBits/backend -TARGET_GOOS=linux TARGET_GOARCH=amd64 ./scripts/build-backend-linux.sh -scp -i ./bin/devbits-api ec2-user@:/tmp/devbits-api +Run from project root: + +```powershell +cd c:\Users\eligf\DevBits +``` + +Use compose file path explicitly: + +```powershell +docker compose -f backend/docker-compose.yml up -d +docker compose -f backend/docker-compose.yml logs -f db ``` -On the EC2 host: +### Live DB (deployed server) + +Run on server in backend directory: ```bash -cd /opt/devbits -# Save any local EC2 edits before pulling -git stash push -u -m "ec2-local-before-pull-$(date +%Y%m%d-%H%M%S)" -git pull origin aws-ready-main +cd /path/to/DevBits/backend +docker compose up -d +docker compose logs -f db +``` + +Only run reset/restore in the environment you mean to modify. + +## Script location + +Run script commands from `backend`: + +```powershell cd backend -sudo mv /tmp/devbits-api ./bin/devbits-api -sudo chown ec2-user:ec2-user ./bin/devbits-api -sudo chmod +x ./bin/devbits-api -sudo ./scripts/install-aws-systemd-service.sh ``` -If you intentionally want to discard local EC2 changes instead: +## Required env file + +Before running deploy/reset/update scripts, ensure `backend/.env` exists: + +```powershell +Copy-Item .env.example .env +``` + +Set a strong `POSTGRES_PASSWORD` value in `.env`. + +## Scripts + +- `scripts/reset-deployment-db.ps1` / `scripts/reset-deployment-db.sh` +- `scripts/backup-deployment-db.ps1` / `scripts/backup-deployment-db.sh` +- `scripts/restore-deployment-db.ps1` / `scripts/restore-deployment-db.sh` +- `scripts/issue-letsencrypt-cert.sh` +- `scripts/setup-daily-backup-task.ps1` +- `scripts/disable-daily-backup-task.ps1` + +## HTTPS certificate issuance (Let's Encrypt) + +Run from `backend` on your live host after DNS and router forwarding are ready: ```bash -cd /opt/devbits -git reset --hard -git clean -fd -git pull origin aws-ready-main -cd backend -./scripts/deploy-aws-native.sh +./scripts/issue-letsencrypt-cert.sh --email you@example.com --domain devbits.ddns.net ``` -Verify: +Staging mode (safe test against Let's Encrypt staging): ```bash -sudo systemctl status devbits-api --no-pager -curl -i http://127.0.0.1:8080/health +./scripts/issue-letsencrypt-cert.sh --email you@example.com --domain devbits.ddns.net --staging ``` -## 1.1) Extra AWS checks +The script stops nginx briefly, requests/renews the certificate, restarts nginx, +and verifies `fullchain.pem`, `privkey.pem`, and `chain.pem` are present and non-empty. -Run on EC2: +## 1) Reset DB (blank slate) -```bash -# Service state -sudo systemctl is-active devbits-api -sudo systemctl status devbits-api --no-pager +Warning: this wipes all app data in that environment. -# Process is listening on 8080 -sudo ss -ltnp | grep ':8080' +PowerShell: -# Recent service logs -sudo journalctl -u devbits-api -n 150 --no-pager +```powershell +./scripts/reset-deployment-db.ps1 +``` + +Keep uploads while resetting only DB volume: -# Follow logs live while testing app traffic -sudo journalctl -u devbits-api -f +```powershell +./scripts/reset-deployment-db.ps1 -KeepUploads ``` -Database connectivity check (from EC2): +Bash: ```bash -# Ensure PostgreSQL client tools are installed -sudo dnf install -y postgresql15 +./scripts/reset-deployment-db.sh +./scripts/reset-deployment-db.sh --keep-uploads +``` -# Uses DATABASE_URL from backend/.env -cd /opt/devbits/backend -set -a; . ./.env; set +a -psql "$DATABASE_URL" -c "select current_user, current_database();" +## 2) Backup DB (single-backup retention) + +Safe for both local and live. Run it in the target environment. + +PowerShell: + +```powershell +./scripts/backup-deployment-db.ps1 ``` -DNS/public checks (from local machine or EC2): +Bash: ```bash -dig +short devbits.app -curl -i https://devbits.app/health -curl -i https://devbits.app/privacy-policy -curl -i https://devbits.app/.well-known/assetlinks.json -curl -i https://devbits.app/apple-app-site-association +./scripts/backup-deployment-db.sh +``` + +Backup location: + +- `backend/backups/db` + +Retention policy: + +- keeps only the newest `devbits-*.sql` +- deletes older backup files automatically + +Backup type: + +- Logical SQL dump created with `pg_dump` from the running DB container +- Not a Docker volume snapshot/image snapshot + +## 3) Restore DB from latest backup + +Warning: restore terminates sessions and recreates DB in that environment. + +PowerShell: + +```powershell +./scripts/restore-deployment-db.ps1 ``` -Target group health check path should return 200: +Bash: ```bash -curl -i http://127.0.0.1:8080/health +./scripts/restore-deployment-db.sh +``` + +Restore behavior: + +- picks latest backup file from `backend/backups/db` +- terminates active DB sessions +- drops and recreates `devbits` +- applies SQL dump + +## 4) Enable daily auto backup (Windows) + +Create a scheduled task at 03:00 daily: + +```powershell +./scripts/setup-daily-backup-task.ps1 ``` -## 2) Script usage +Custom time: + +```powershell +./scripts/setup-daily-backup-task.ps1 -RunAt "01:30" +``` -Deploy/build: +Notes: -- `scripts/build-backend-linux.sh` - - Build backend binary to `bin/devbits-api`. -- `scripts/install-aws-systemd-service.sh` - - Install/restart `devbits-api` systemd service. -- `scripts/deploy-aws-native.sh` - - Build + install/restart in one command. -- `scripts/update-live.sh` - - Wrapper for `deploy-aws-native.sh`. +- Script tries `SYSTEM` first. +- If shell is not elevated, it falls back to current-user mode. -Database scripts (use `DATABASE_URL` in `backend/.env`): +Verify task: -- `scripts/reset-deployment-db.sh` -- `--keep-uploads` to keep uploads. -- `scripts/backup-deployment-db.sh` -- `scripts/restore-deployment-db.sh` -- restores latest `devbits-db-*.sql` and matching uploads archive if present. +```powershell +schtasks /Query /TN DevBitsDailyDbBackup /V /FO LIST +``` -Required tools for DB scripts: +## 5) Disable daily auto backup (Windows) -- Linux: `postgresql` client package (`psql`, `pg_dump`) +```powershell +./scripts/disable-daily-backup-task.ps1 +``` diff --git a/backend/scripts/backup-deployment-db.sh b/backend/scripts/backup-deployment-db.sh index ce10b0d..2463bed 100644 --- a/backend/scripts/backup-deployment-db.sh +++ b/backend/scripts/backup-deployment-db.sh @@ -1,32 +1,28 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" -cd "$ROOT_DIR" +if [ "$EUID" -ne 0 ]; then + echo "Please run as root" + sudo "$0" "$@" + exit +fi BACKUP_DIR="${1:-backups/db}" echo "Creating deployment database backup..." -if [[ ! -f ".env" ]]; then - echo "Missing $ROOT_DIR/.env. Create it from backend/.env.example and set DATABASE_URL." >&2 - exit 1 -fi - -set -a -. ./.env -set +a +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +cd "$ROOT_DIR" -if [[ -z "${DATABASE_URL:-}" ]]; then - echo "Missing DATABASE_URL in $ROOT_DIR/.env" >&2 - exit 1 +if [[ -f ".env" ]]; then + set -a + . ./.env + set +a fi -if ! command -v pg_dump >/dev/null 2>&1; then - echo "pg_dump is required. Install PostgreSQL client tools first." >&2 - exit 1 -fi +DB_USER="${POSTGRES_USER:-devbits}" +DB_NAME="${POSTGRES_DB:-devbits}" mkdir -p "$BACKUP_DIR" @@ -34,34 +30,42 @@ TIMESTAMP="$(date +"%Y%m%d-%H%M%S")" DB_BACKUP_FILE_NAME="devbits-db-${TIMESTAMP}.sql" DB_OUTPUT_FILE="${BACKUP_DIR}/${DB_BACKUP_FILE_NAME}" -pg_dump "$DATABASE_URL" --no-owner --no-privileges > "$DB_OUTPUT_FILE" +docker compose exec -T db pg_dump -U "$DB_USER" -d "$DB_NAME" --no-owner --no-privileges > "$DB_OUTPUT_FILE" if [[ ! -s "$DB_OUTPUT_FILE" ]]; then echo "Database backup file is empty or missing. Aborting." >&2 exit 1 fi - echo "Database backup created: $DB_OUTPUT_FILE" UPLOADS_DIR="uploads" UPLOADS_BACKUP_FILE_NAME="devbits-uploads-${TIMESTAMP}.tar.gz" UPLOADS_OUTPUT_FILE="${BACKUP_DIR}/${UPLOADS_BACKUP_FILE_NAME}" -if [[ -d "$UPLOADS_DIR" ]]; then +if [ -d "$UPLOADS_DIR" ]; then tar -czf "$UPLOADS_OUTPUT_FILE" -C "$UPLOADS_DIR" . echo "Uploads backup created: $UPLOADS_OUTPUT_FILE" else echo "Uploads directory not found, skipping backup." fi -# Retention: keep only the latest DB backup and latest uploads backup. +# Retention: keep only the latest db backup and the latest uploads backup find "$BACKUP_DIR" -maxdepth 1 -type f -name 'devbits-db-*.sql' | sort | head -n -1 | xargs -r rm find "$BACKUP_DIR" -maxdepth 1 -type f -name 'devbits-uploads-*.tar.gz' | sort | head -n -1 | xargs -r rm echo "Retention applied: only latest backup of each type is kept." +live_backend_state="unavailable" +if backend_status_output="$(docker compose ps backend 2>/dev/null)"; then + if echo "$backend_status_output" | grep -q "Up"; then + live_backend_state="running" + else + live_backend_state="not running" + fi +fi + echo echo "===== Summary =====" echo "Action: Deployment backup created" echo "Updated: Latest DB + uploads backup files retained" -echo "Database backup target: DATABASE_URL" +echo "Live backend: $live_backend_state" diff --git a/backend/scripts/build-backend-linux.sh b/backend/scripts/build-backend-linux.sh deleted file mode 100644 index 95883f8..0000000 --- a/backend/scripts/build-backend-linux.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" - -cd "$ROOT_DIR" - -mkdir -p bin uploads - -TARGET_GOOS="${TARGET_GOOS:-linux}" -if [[ -n "${TARGET_GOARCH:-}" ]]; then - TARGET_GOARCH="${TARGET_GOARCH}" -else - case "$(uname -m)" in - x86_64) TARGET_GOARCH="amd64" ;; - aarch64|arm64) TARGET_GOARCH="arm64" ;; - *) TARGET_GOARCH="amd64" ;; - esac -fi -OUTPUT_PATH="${OUTPUT_PATH:-$ROOT_DIR/bin/devbits-api}" - -echo "Building DevBits backend for ${TARGET_GOOS}/${TARGET_GOARCH}..." -CGO_ENABLED=0 GOOS="$TARGET_GOOS" GOARCH="$TARGET_GOARCH" go build -trimpath -ldflags="-s -w" -o "$OUTPUT_PATH" ./api - -echo "Build complete: $OUTPUT_PATH" diff --git a/backend/scripts/deploy-aws-native.sh b/backend/scripts/deploy-aws-native.sh deleted file mode 100644 index a15eb8f..0000000 --- a/backend/scripts/deploy-aws-native.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" - -cd "$ROOT_DIR" - -if [[ ! -f ".env" ]]; then - echo "Missing $ROOT_DIR/.env. Create it from backend/.env.example and set real values." >&2 - exit 1 -fi - -echo "Building backend binary..." -"$ROOT_DIR/scripts/build-backend-linux.sh" - -if [[ "$EUID" -eq 0 ]]; then - "$ROOT_DIR/scripts/install-aws-systemd-service.sh" -else - sudo "$ROOT_DIR/scripts/install-aws-systemd-service.sh" -fi - -echo -echo "===== Summary =====" -echo "Action: Native AWS deploy completed" -echo "Binary: $ROOT_DIR/bin/devbits-api" -echo "Service: ${DEVBITS_SERVICE_NAME:-devbits-api}" diff --git a/backend/scripts/install-aws-systemd-service.sh b/backend/scripts/install-aws-systemd-service.sh deleted file mode 100644 index e666325..0000000 --- a/backend/scripts/install-aws-systemd-service.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -if [[ "$EUID" -ne 0 ]]; then - echo "Please run as root" - sudo "$0" "$@" - exit -fi - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" - -SERVICE_NAME="${DEVBITS_SERVICE_NAME:-devbits-api}" -SERVICE_USER="${DEVBITS_SERVICE_USER:-${SUDO_USER:-ec2-user}}" -WORK_DIR="${DEVBITS_WORKDIR:-$ROOT_DIR}" -ENV_FILE="${DEVBITS_ENV_FILE:-$WORK_DIR/.env}" -BINARY_PATH="${DEVBITS_BINARY_PATH:-$WORK_DIR/bin/devbits-api}" -TEMPLATE_PATH="$ROOT_DIR/deploy/systemd/devbits-api.service" -SERVICE_PATH="/etc/systemd/system/${SERVICE_NAME}.service" - -if [[ ! -f "$ENV_FILE" ]]; then - echo "Missing env file: $ENV_FILE" >&2 - echo "Create it from backend/.env.example before installing service." >&2 - exit 1 -fi - -if [[ ! -x "$BINARY_PATH" ]]; then - echo "Missing executable binary: $BINARY_PATH" >&2 - echo "Run ./scripts/build-backend-linux.sh first." >&2 - exit 1 -fi - -if [[ ! -f "$TEMPLATE_PATH" ]]; then - echo "Missing systemd service template: $TEMPLATE_PATH" >&2 - echo "Ensure the deploy/systemd/devbits-api.service template is present." >&2 - exit 1 -fi - -if ! id "$SERVICE_USER" >/dev/null 2>&1; then - echo "Service user does not exist: $SERVICE_USER" >&2 - exit 1 -fi - -tmp_service="$(mktemp)" -trap 'rm -f "$tmp_service"' EXIT - -sed \ - -e "s|__SERVICE_USER__|$SERVICE_USER|g" \ - -e "s|__WORKDIR__|$WORK_DIR|g" \ - -e "s|__ENV_FILE__|$ENV_FILE|g" \ - -e "s|__BINARY_PATH__|$BINARY_PATH|g" \ - "$TEMPLATE_PATH" > "$tmp_service" - -install -m 0644 "$tmp_service" "$SERVICE_PATH" - -systemctl daemon-reload -systemctl enable "$SERVICE_NAME" -systemctl restart "$SERVICE_NAME" - -echo "Service installed: $SERVICE_PATH" -systemctl --no-pager --full status "$SERVICE_NAME" | sed -n '1,25p' diff --git a/backend/scripts/issue-letsencrypt-cert.sh b/backend/scripts/issue-letsencrypt-cert.sh new file mode 100644 index 0000000..899e17d --- /dev/null +++ b/backend/scripts/issue-letsencrypt-cert.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Issues or renews a Let's Encrypt certificate for the public domain used by nginx. +# This script stops nginx briefly so certbot can bind to :80 for HTTP-01 validation. + +DOMAIN="devbits.ddns.net" +EMAIL="" +STAGING="0" + +while [[ $# -gt 0 ]]; do + case "$1" in + --domain) + DOMAIN="${2:-}" + shift 2 + ;; + --email) + EMAIL="${2:-}" + shift 2 + ;; + --staging) + STAGING="1" + shift + ;; + *) + echo "Unknown argument: $1" >&2 + echo "Usage: $0 --email you@example.com [--domain devbits.ddns.net] [--staging]" >&2 + exit 1 + ;; + esac +done + +if [[ -z "$EMAIL" ]]; then + echo "Missing required --email argument." >&2 + echo "Usage: $0 --email you@example.com [--domain devbits.ddns.net] [--staging]" >&2 + exit 1 +fi + +if ! command -v docker >/dev/null 2>&1; then + echo "docker is required but was not found." >&2 + exit 1 +fi + +if ! docker compose version >/dev/null 2>&1; then + echo "docker compose v2 is required but was not found." >&2 + exit 1 +fi + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BACKEND_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +CERT_DIR="$BACKEND_DIR/nginx/certs/live/$DOMAIN" + +CERTBOT_FLAGS=( + certonly + --standalone + --preferred-challenges http + --agree-tos + --non-interactive + --keep-until-expiring + --email "$EMAIL" + -d "$DOMAIN" +) + +if [[ "$STAGING" == "1" ]]; then + CERTBOT_FLAGS+=(--staging) +fi + +echo "Issuing/renewing Let's Encrypt certificate for $DOMAIN ..." +cd "$BACKEND_DIR" + +# Free port 80 so certbot standalone can complete HTTP-01 validation. +docker compose stop nginx >/dev/null 2>&1 || true + +docker run --rm \ + -p 80:80 \ + -v "$BACKEND_DIR/nginx/certs:/etc/letsencrypt" \ + -v "$BACKEND_DIR/nginx/certs/lib:/var/lib/letsencrypt" \ + certbot/certbot "${CERTBOT_FLAGS[@]}" + +# Bring nginx back online. +docker compose up -d nginx >/dev/null + +missing=0 +for file in fullchain.pem privkey.pem chain.pem; do + path="$CERT_DIR/$file" + if [[ ! -s "$path" ]]; then + echo "Missing or empty: $path" >&2 + missing=1 + fi +done + +if [[ "$missing" -ne 0 ]]; then + echo "Certificate issuance completed with missing files. Check certbot output above." >&2 + exit 1 +fi + +echo "Certificate files verified:" +ls -l "$CERT_DIR/fullchain.pem" "$CERT_DIR/privkey.pem" "$CERT_DIR/chain.pem" +echo "Done." diff --git a/backend/scripts/reset-deployment-db.sh b/backend/scripts/reset-deployment-db.sh index db7c2b8..868dbfe 100644 --- a/backend/scripts/reset-deployment-db.sh +++ b/backend/scripts/reset-deployment-db.sh @@ -3,6 +3,12 @@ set -euo pipefail KEEP_UPLOADS="${1:-}" +if [ "$EUID" -ne 0 ]; then + echo "Please run as root" + sudo "$0" "$@" + exit +fi + echo "Resetting DevBits deployment database to a blank slate..." SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -14,22 +20,7 @@ if [[ ! -f ".env" ]]; then exit 1 fi -set -a -. ./.env -set +a - -if [[ -z "${DATABASE_URL:-}" ]]; then - echo "Missing DATABASE_URL in $ROOT_DIR/.env" >&2 - exit 1 -fi - -if ! command -v psql >/dev/null 2>&1; then - echo "psql is required. Install PostgreSQL client tools first." >&2 - exit 1 -fi - -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "DROP SCHEMA IF EXISTS public CASCADE;" -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "CREATE SCHEMA public;" +docker compose down -v --remove-orphans if [[ "$KEEP_UPLOADS" != "--keep-uploads" ]]; then if [[ -d "uploads" ]]; then @@ -37,15 +28,21 @@ if [[ "$KEEP_UPLOADS" != "--keep-uploads" ]]; then fi fi -if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q '^devbits-api\.service'; then - echo "Restarting devbits-api service to recreate schema and warm startup..." - sudo systemctl restart devbits-api -fi +docker compose up -d --build echo "Database reset complete. All users and app data are removed." +live_backend_state="unavailable" +if backend_status_output="$(docker compose ps backend 2>/dev/null)"; then + if echo "$backend_status_output" | grep -q "Up"; then + live_backend_state="running" + else + live_backend_state="not running" + fi +fi + echo echo "===== Summary =====" echo "Action: Deployment DB reset executed" -echo "Updated: Public schema recreated (blank state)" -echo "Database reset target: DATABASE_URL" +echo "Updated: Database recreated and services rebuilt" +echo "Live backend: $live_backend_state" diff --git a/backend/scripts/restore-deployment-db.sh b/backend/scripts/restore-deployment-db.sh index 85c4190..d1e304b 100644 --- a/backend/scripts/restore-deployment-db.sh +++ b/backend/scripts/restore-deployment-db.sh @@ -9,23 +9,19 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" cd "$ROOT_DIR" -if [[ ! -f ".env" ]]; then - echo "Missing $ROOT_DIR/.env. Create it from backend/.env.example and set real values." >&2 - exit 1 +if [[ -f ".env" ]]; then + set -a + . ./.env + set +a fi -set -a -. ./.env -set +a - -if [[ -z "${DATABASE_URL:-}" ]]; then - echo "Missing DATABASE_URL in $ROOT_DIR/.env" >&2 - exit 1 -fi +DB_USER="${POSTGRES_USER:-devbits}" +DB_NAME="${POSTGRES_DB:-devbits}" -if ! command -v psql >/dev/null 2>&1; then - echo "psql is required. Install PostgreSQL client tools first." >&2 - exit 1 +if [ "$EUID" -ne 0 ]; then + echo "Please run as root" + sudo "$0" "$@" + exit fi if [[ ! -d "$BACKUP_DIR" ]]; then @@ -43,9 +39,10 @@ RESOLVED_BACKUP="$LATEST_FILE" echo "Using backup: $RESOLVED_BACKUP" -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "DROP SCHEMA IF EXISTS public CASCADE;" -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "CREATE SCHEMA public;" -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 < "$RESOLVED_BACKUP" +docker compose exec -T db psql -U "$DB_USER" -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${DB_NAME}' AND pid <> pg_backend_pid();" +docker compose exec -T db psql -U "$DB_USER" -d postgres -c "DROP DATABASE IF EXISTS \"${DB_NAME}\";" +docker compose exec -T db psql -U "$DB_USER" -d postgres -c "CREATE DATABASE \"${DB_NAME}\";" +docker compose exec -T db psql -U "$DB_USER" -d "$DB_NAME" < "$RESOLVED_BACKUP" db_file_name="$(basename "$RESOLVED_BACKUP")" db_timestamp="${db_file_name#devbits-db-}" @@ -68,15 +65,22 @@ else echo "No matching uploads backup found for timestamp $db_timestamp, keeping current uploads directory." fi -if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q '^devbits-api\.service'; then - echo "Restarting devbits-api service..." - sudo systemctl restart devbits-api -fi +echo "Restore complete. Rebuilding deployment services..." +docker compose up -d --build -echo "Restore complete." +echo "Restore complete and services rebuilt." + +live_backend_state="unavailable" +if backend_status_output="$(docker compose ps backend 2>/dev/null)"; then + if echo "$backend_status_output" | grep -q "Up"; then + live_backend_state="running" + else + live_backend_state="not running" + fi +fi echo echo "===== Summary =====" echo "Action: Deployment DB restore executed" -echo "Updated: Database restored and matching uploads restored when available" -echo "Database restore target: DATABASE_URL" +echo "Updated: Database restored and matching uploads restored when available; services rebuilt" +echo "Live backend: $live_backend_state" diff --git a/backend/scripts/update-live.ps1 b/backend/scripts/update-live.ps1 new file mode 100644 index 0000000..9db9f95 --- /dev/null +++ b/backend/scripts/update-live.ps1 @@ -0,0 +1,108 @@ +param( + [switch]$NoPause +) + +if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + $arguments = "& '" + $myinvocation.mycommand.definition + "'" + Start-Process powershell -Verb runAs -ArgumentList $arguments + exit +} + +$ErrorActionPreference = "Stop" + +Write-Host "Updating the live application by rebuilding and restarting the backend service..." -ForegroundColor Yellow + +$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$root = Resolve-Path (Join-Path $scriptDir "..") +Push-Location $root + +try { + $hostsPath = "C:\Windows\System32\drivers\etc\hosts" + if (Test-Path $hostsPath) { + $hostOverride = Select-String -Path $hostsPath -Pattern "(?im)^\s*127\.0\.0\.1\s+devbits\.app(\s|$)" -ErrorAction SilentlyContinue + if ($hostOverride) { + Write-Host "WARNING: hosts file maps devbits.app to 127.0.0.1. This can cause domain/API connection failures and slow first loads." -ForegroundColor Yellow + Write-Host "Remove that hosts override from $hostsPath (run editor as Administrator) if you want real domain routing." -ForegroundColor Yellow + } + } + + $envFile = Join-Path $root ".env" + if (-not (Test-Path $envFile)) { + throw "Missing $envFile. Create it from backend/.env.example and set strong credentials before deploying." + } + + $envContent = Get-Content -Path $envFile -Raw + if ($envContent -notmatch "(?m)^POSTGRES_PASSWORD=.+$") { + throw "POSTGRES_PASSWORD is not set in $envFile." + } + if ($envContent -match "(?m)^POSTGRES_PASSWORD=(password|changeme|devbits)$") { + throw "POSTGRES_PASSWORD in $envFile is weak/default. Set a strong random value before deploying." + } + + # Ensure DB is started first so we can sync credentials to avoid auth mismatches. + docker compose up -d db + + # Wait for DB health (up to ~60s) + $dbHealthy = $false + for ($attempt = 0; $attempt -lt 30; $attempt++) { + $statusOutput = docker compose ps db 2>$null | Out-String + if ($statusOutput -match "Up" -and $statusOutput -match "healthy") { + $dbHealthy = $true + break + } + Start-Sleep -Seconds 2 + } + + if (-not $dbHealthy) { + Write-Host "Warning: DB did not reach healthy state in time; proceeding to attempt password sync anyway." -ForegroundColor Yellow + } + + # Sync the POSTGRES_PASSWORD from .env into the Postgres role to keep credentials consistent. + try { + $envRaw = Get-Content -Path $envFile -Raw + if ($envRaw -match "(?m)^POSTGRES_PASSWORD=(.+)$") { + $dbPass = $Matches[1].Trim() + if ($dbPass -and $dbPass -notmatch "^(password|changeme|devbits)$") { + $tmpFile = Join-Path $env:TEMP "sync-devbits-password.sql" + $safe = $dbPass.Replace("'", "''") + Set-Content -Path $tmpFile -Value "ALTER ROLE devbits WITH PASSWORD '$safe';" -NoNewline + try { + Get-Content $tmpFile -Raw | docker compose exec -T db sh -lc "psql -U devbits -d postgres" | Out-Null + Write-Host "Synchronized Postgres role password to match .env" -ForegroundColor Green + } + catch { + Write-Host "Warning: Could not run password sync command inside DB container: $_" -ForegroundColor Yellow + } + Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue + } + } + } + catch { + Write-Host "Warning: Failed to read .env or sync password: $_" -ForegroundColor Yellow + } + + docker compose up -d --build backend nginx + Write-Host "Backend and nginx services have been updated." -ForegroundColor Green +} +finally { + Pop-Location +} + +$liveBackendState = "unavailable" +try { + $statusOutput = docker compose -f (Join-Path $root "docker-compose.yml") ps backend 2>$null + if ($LASTEXITCODE -eq 0) { + $liveBackendState = if (($statusOutput | Out-String) -match "Up") { "running" } else { "not running" } + } +} +catch {} + +Write-Host "" +Write-Host "===== Summary =====" -ForegroundColor Cyan +Write-Host "Action: Live backend update executed" +Write-Host "Updated: Backend rebuilt; nginx refreshed" +Write-Host "Live backend: $liveBackendState" + +if (-not $NoPause -and [Environment]::UserInteractive -and $Host.Name -eq "ConsoleHost") { + Read-Host "Press Enter to close" +} diff --git a/backend/scripts/update-live.sh b/backend/scripts/update-live.sh index 7c24965..8ae65b5 100644 --- a/backend/scripts/update-live.sh +++ b/backend/scripts/update-live.sh @@ -1,8 +1,53 @@ -#!/usr/bin/env bash -set -euo pipefail +#!/bin/bash -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +if [ "$EUID" -ne 0 ]; then + echo "Please run as root" + sudo "$0" "$@" + exit +fi -echo "Updating live backend (native binary + systemd)..." -"$ROOT_DIR/scripts/deploy-aws-native.sh" +set -e + +echo "Updating the live application by rebuilding and restarting the backend service..." + +# Get the directory of the script +script_dir=$(dirname "$(readlink -f "$0")") +root_dir=$(realpath "$script_dir/..") + +# Change to the root directory of the backend +cd "$root_dir" + +env_file="$root_dir/.env" +if [[ ! -f "$env_file" ]]; then + echo "Missing $env_file. Create it from backend/.env.example and set strong credentials before deploying." >&2 + exit 1 +fi + +postgres_password="$(grep -E '^POSTGRES_PASSWORD=' "$env_file" | tail -n 1 | cut -d '=' -f2- || true)" +if [[ -z "$postgres_password" ]]; then + echo "POSTGRES_PASSWORD is not set in $env_file" >&2 + exit 1 +fi +if [[ "$postgres_password" == "password" || "$postgres_password" == "changeme" || "$postgres_password" == "devbits" ]]; then + echo "POSTGRES_PASSWORD in $env_file is weak/default. Set a strong random value before deploying." >&2 + exit 1 +fi + +docker compose up -d --build backend nginx + +echo "Backend and nginx services have been updated." + +live_backend_state="unavailable" +if backend_status_output="$(docker compose ps backend 2>/dev/null)"; then + if echo "$backend_status_output" | grep -q "Up"; then + live_backend_state="running" + else + live_backend_state="not running" + fi +fi + +echo +echo "===== Summary =====" +echo "Action: Live backend update executed" +echo "Updated: Backend rebuilt; nginx refreshed" +echo "Live backend: $live_backend_state" diff --git a/backend/uploads/u1_1a5534ccca23297b1a89c65a.jpg b/backend/uploads/u1_1a5534ccca23297b1a89c65a.jpg deleted file mode 100644 index d760285bf7d52806bb32c4acf0e2ed4ec7afbc4b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 58053 zcmbTd1yEc~*DktohXBDfL4yXj0YVZyK(OEzEXd&Q?hLL$LU4C?cPGf;?lO4L!~6dK z`M*=Q>Q>F(8gp68#}fLAgS(h>k18~{kY9KiEB;3Mv0W&!|m zasU$m0H^>G93Fu1!r)#G0FD$u`j-QM3>?}2a3wg#|F(e#fM7EK@xN^}U&?>*68RtR z|1RNw!T)ayxaeO9|Kb0bJ|6@8Uw>FTSlj=wwxQ-?dk^q`l$JyMC*lkK<#hkjS2Gk5 z3sFE7;=T`B^3m-_ujdVTM(IzV^u8)7NJxJX|5p?|v4M?^5}H0wXH{!{;d#n6q6?G0ZnA70M)hBkH% zFAc%+!oNB@*!;siUifRfmxp@c(f@GM|Kd6S@bCY{8~(LXQTp^^GxEZz4SyIIz3`(K z&hq{Ls5kvTIM~whpU?dV|Fk@&v6ZUwOZoccBnLhNW`I3l16TqEfGa=^dSRFECE1=)pG}c ziwYMF7mWb-7J$cvL%@Z5?g6M?S_%p7U;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S;MfO{TZ?nphZ9MHDkVmNR_|=Iml>zhbu|qgGObq^2b{8nSTwsc% z2SaZll>#^31M{eEB2``Ew`$LhVyqcYHL{GiaS%TCITdM=(TQ)Fq}n=))No4(BINfq zOHGZDWsnT9VxaZ_cQvp3yHv;VcRsYlF=37s=aXMbcq+tc{s)F_pgq}X+th+^zxe3l zzEzu0GfuY90?x-ASK4>BiEE)-+e8Wop+p0?3Nc=0GI}VUjt)Ax68KV6G&7(X!~Xy= z{{Ysf>X!au=N$Fm%sRO zkKKI)6Ik@1)%*LHT-A#TMAMapae5=dEbQrb*QYbJI0e z50ye=AEj&Q>UX^4U?&x;(HU;YHL1i31wrEE0lakU-k5a|}^eQPtV-bW zN+01rO7kBS_=OIH3aQ9bQwx4vi4;XcS zxhUaC9Gvwafz58NpwXN;$I~CJRJghmxR;Hq(4Ls}=y>(|R%=ZSn&#Am%1_N9`BWZr z(Ek80sP*k!lHNY8sC}iSD;#8`cw@lmPj0n)RhtogjSd=q8`KW`^Mj9n=Tz-UHNW8PI^$IFHHE#ix;n@ly7g2}ScBUjaqnLjN)B^L?%Dg!CbFYKQd%Ux zBkNlT8rIGWe=o`j8m`Rl+kw+}e0tU7#_VuOr8o)~91b|+^`{NM7RLvS3j5iuEPp)3 z-MKNczo*JE)3to%@$bazW#Qz|;cQ8$xI@n(Bsp)-fnN82aJJC1u>$~;U!9&j@iTa@ z#h03heb6I$PUG9&gUihB& zOWo$)!V|DcM=~D!2Sblq<~%9k$vjV~c}zB0z*NrN*dB^)={aw3do33k} z`yRipPvl$1*gtwkI7J@h*QiW%i$Rkb$o@Z6tmy(@cr!3IJ5v~N{j{P#7~+Wc45^r<%4n3)vtu7QR> zA6oJo{aRVrmTctIx>l2SsIVk92^;`PIsEIcSZFoPh}83aysybYSo%*$_~{ { - const base = appJson.expo || {}; const extras = { - ...(base.extra || {}), + router: {}, + eas: { + projectId: "2286e55a-f086-446f-bcb5-3e36b65a79f6", + }, EXPO_PUBLIC_API_URL: process.env.EXPO_PUBLIC_API_URL || process.env.API_URL || null, EXPO_PUBLIC_USE_LOCAL_API: - typeof process.env.EXPO_PUBLIC_USE_LOCAL_API !== 'undefined' + typeof process.env.EXPO_PUBLIC_USE_LOCAL_API !== "undefined" ? process.env.EXPO_PUBLIC_USE_LOCAL_API : undefined, EXPO_PUBLIC_LOCAL_API_URL: process.env.EXPO_PUBLIC_LOCAL_API_URL || undefined, @@ -14,7 +14,76 @@ module.exports = () => { return { expo: { - ...base, + name: "DevBits", + slug: "frontend", + version: "1.0.3", + orientation: "portrait", + icon: "./assets/images/Devbits_Icons.png", + scheme: "myapp", + userInterfaceStyle: "automatic", + newArchEnabled: true, + ios: { + supportsTablet: true, + icon: "./assets/images/Devbits_Icons.png", + bundleIdentifier: "com.devbits.frontend", + buildNumber: "18", + infoPlist: { + ITSAppUsesNonExemptEncryption: false, + NSPhotoLibraryUsageDescription: + "DevBits requests access to your photo library to let you pick images to attach to posts or save images from the app. Example: selecting a photo to upload when creating a byte.", + NSPhotoLibraryAddUsageDescription: + "DevBits may save images you create or download (for example, saving a snapshot of a post) to your photo library when you choose to do so.", + NSCameraUsageDescription: + "DevBits requests access to the camera so you can capture photos or videos to attach to posts. Example: taking a photo while creating a byte.", + NSMicrophoneUsageDescription: + "DevBits requests access to the microphone to record audio for posts or streams. Example: recording a short audio clip when creating content.", + }, + associatedDomains: ["applinks:devbits.ddns.net"], + }, + android: { + icon: "./assets/images/Devbits_Icons1.png", + versionCode: 18, + adaptiveIcon: { + foregroundImage: "./assets/images/adaptive-icon.png", + backgroundColor: "#000000", + }, + permissions: ["android.permission.RECORD_AUDIO"], + package: "com.devbits.frontend", + }, + web: { + bundler: "metro", + output: "static", + favicon: "./assets/images/favicon.png", + }, + splash: { + image: "./assets/images/splash-icon.png", + resizeMode: "contain", + backgroundColor: "#000000", + }, + plugins: [ + "expo-router", + "expo-notifications", + [ + "expo-image-picker", + { + photosPermission: "Allow DevBits to access your photos.", + }, + ], + [ + "expo-splash-screen", + { + image: "./assets/images/splash-icon.png", + imageWidth: 200, + resizeMode: "contain", + backgroundColor: "#000000", + }, + ], + "expo-secure-store", + "expo-video", + ], + experiments: { + typedRoutes: true, + }, extra: extras, }, }; diff --git a/frontend/app.json b/frontend/app.json deleted file mode 100644 index 132bf87..0000000 --- a/frontend/app.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "expo": { - "name": "DevBits", - "slug": "frontend", - "version": "1.0.3", - "orientation": "portrait", - "icon": "./assets/images/Devbits_Icons.png", - "scheme": "myapp", - "userInterfaceStyle": "automatic", - "newArchEnabled": true, - "ios": { - "supportsTablet": true, - "icon": "./assets/images/Devbits_Icons.png", - "bundleIdentifier": "com.devbits.frontend", - "buildNumber": "16", - "infoPlist": { - "ITSAppUsesNonExemptEncryption": false, - "NSPhotoLibraryUsageDescription": "DevBits requests access to your photo library to let you pick images to attach to posts or save images from the app. Example: selecting a photo to upload when creating a byte.", - "NSPhotoLibraryAddUsageDescription": "DevBits may save images you create or download (for example, saving a snapshot of a post) to your photo library when you choose to do so.", - "NSCameraUsageDescription": "DevBits requests access to the camera so you can capture photos or videos to attach to posts. Example: taking a photo while creating a byte.", - "NSMicrophoneUsageDescription": "DevBits requests access to the microphone to record audio for posts or streams. Example: recording a short audio clip when creating content." - }, - "associatedDomains": [ - "applinks:devbits.app" - ] - }, - "android": { - "icon": "./assets/images/Devbits_Icons1.png", - "versionCode": 16, - "adaptiveIcon": { - "foregroundImage": "./assets/images/adaptive-icon.png", - "backgroundColor": "#000000" - }, - "permissions": [ - "android.permission.RECORD_AUDIO" - ], - "package": "com.devbits.frontend" - }, - "web": { - "bundler": "metro", - "output": "static", - "favicon": "./assets/images/favicon.png" - }, - "splash": { - "image": "./assets/images/splash-icon.png", - "resizeMode": "contain", - "backgroundColor": "#000000" - }, - "plugins": [ - "expo-router", - "expo-notifications", - [ - "expo-image-picker", - { - "photosPermission": "Allow DevBits to access your photos." - } - ], - [ - "expo-splash-screen", - { - "image": "./assets/images/splash-icon.png", - "imageWidth": 200, - "resizeMode": "contain", - "backgroundColor": "#000000" - } - ], - "expo-secure-store", - "expo-video" - ], - "experiments": { - "typedRoutes": true - }, - "extra": { - "router": {}, - "eas": { - "projectId": "2286e55a-f086-446f-bcb5-3e36b65a79f6" - } - } - } -} diff --git a/frontend/app/_layout.tsx b/frontend/app/_layout.tsx index b332dcb..31bc509 100644 --- a/frontend/app/_layout.tsx +++ b/frontend/app/_layout.tsx @@ -29,7 +29,6 @@ import { useColorScheme } from "@/hooks/useColorScheme"; import { HyprBackdrop } from "@/components/HyprBackdrop"; import { BootScreen } from "@/components/BootScreen"; import { InAppNotificationBanner } from "@/components/InAppNotificationBanner"; -import { API_BASE_URL } from "@/services/api"; // Prevent the splash screen from auto-hiding before asset loading is complete SplashScreen.preventAutoHideAsync(); @@ -214,22 +213,6 @@ function RootLayoutNav() { } }, [fontsReady]); - useEffect(() => { - // Debug: print resolved API base URL and expo extras so we can confirm - // the JS runtime is seeing the intended backend when running via Expo. - try { - // eslint-disable-next-line no-console - console.log("Resolved API_BASE_URL:", API_BASE_URL); - // eslint-disable-next-line no-console - console.log( - "Expo extras:", - Constants.expoConfig?.extra ?? Constants.manifest?.extra ?? null, - ); - } catch (e) { - // ignore - } - }, []); - useEffect(() => { if (!fontsReady || isLoading) { return; diff --git a/frontend/app/conversation/[username].tsx b/frontend/app/conversation/[username].tsx index f629144..e68990d 100644 --- a/frontend/app/conversation/[username].tsx +++ b/frontend/app/conversation/[username].tsx @@ -125,7 +125,7 @@ export default function ConversationScreen() { const wsBase = getWebSocketBaseUrl(API_BASE_URL); const wsUrl = `${wsBase}/messages/${encodeURIComponent( user.username, - )}/stream?token=${encodeURIComponent(token)}`; + )}/stream`; const connect = () => { if (!isActive) { return; @@ -141,7 +141,7 @@ export default function ConversationScreen() { wsRef.current.close(); } - const ws = new WebSocket(wsUrl); + const ws = new WebSocket(wsUrl, [`devbits.jwt.${token}`]); wsRef.current = ws; ws.onopen = () => { diff --git a/frontend/app/settings/about.tsx b/frontend/app/settings/about.tsx index 8b4be32..0fdcb4f 100644 --- a/frontend/app/settings/about.tsx +++ b/frontend/app/settings/about.tsx @@ -8,7 +8,7 @@ import { useAppColors } from "@/hooks/useAppColors"; import { SettingsPageShell, settingsStyles } from "@/features/settings/shared"; const SITE_BASE_URL = ( - process.env.EXPO_PUBLIC_SITE_URL?.trim() || "https://devbits.app" + process.env.EXPO_PUBLIC_SITE_URL?.trim() || "https://devbits.ddns.net" ).replace(/\/+$/, ""); const publicLinks = [ diff --git a/frontend/eas.json b/frontend/eas.json index 763fcd5..c5408be 100644 --- a/frontend/eas.json +++ b/frontend/eas.json @@ -12,11 +12,10 @@ "distribution": "internal" }, "production": { - "autoIncrement": true, "env": { - "EXPO_PUBLIC_API_URL": "https://devbits.app", - "EXPO_PUBLIC_API_FALLBACK_URL": "https://devbits.app", - "EXPO_PUBLIC_SITE_URL": "https://devbits.app" + "EXPO_PUBLIC_API_URL": "https://devbits.ddns.net", + "EXPO_PUBLIC_API_FALLBACK_URL": "https://devbits.ddns.net", + "EXPO_PUBLIC_SITE_URL": "https://devbits.ddns.net" } , "credentialsSource": "remote" diff --git a/frontend/services/api.ts b/frontend/services/api.ts index 899fdc0..c180ed4 100644 --- a/frontend/services/api.ts +++ b/frontend/services/api.ts @@ -259,7 +259,7 @@ const getDefaultBaseUrl = () => { // If the developer explicitly disables using the local API in dev, use // the production endpoint even when __DEV__ is true. if (!useLocal) { - return "https://devbits.app"; + return "https://devbits.ddns.net"; } } catch { // ignore and fall back to defaults below @@ -294,7 +294,7 @@ const getDefaultBaseUrl = () => { } // Production: use live server - return "https://devbits.app"; + return "https://devbits.ddns.net"; }; const normalizeBaseUrl = (url: string) => url.replace(/\/+$/, ""); @@ -327,21 +327,21 @@ function getValidatedBaseUrl(): string { const checkUrl = new URL(raw); if (!checkUrl.hostname) { // eslint-disable-next-line no-console - console.error("Invalid API_BASE_URL resolved; falling back to https://devbits.app", raw); - return normalizeBaseUrl("https://devbits.app"); + console.error("Invalid API_BASE_URL resolved; falling back to https://devbits.ddns.net", raw); + return normalizeBaseUrl("https://devbits.ddns.net"); } return raw; } catch (e) { // eslint-disable-next-line no-console - console.error("Failed to parse API_BASE_URL; falling back to https://devbits.app", raw, String(e)); - return normalizeBaseUrl("https://devbits.app"); + console.error("Failed to parse API_BASE_URL; falling back to https://devbits.ddns.net", raw, String(e)); + return normalizeBaseUrl("https://devbits.ddns.net"); } } export const API_BASE_URL = getValidatedBaseUrl(); const API_FALLBACK_URL = normalizeBaseUrl( - __DEV__ ? "" : "https://devbits.app", + __DEV__ ? "" : "https://devbits.ddns.net", ); const API_REQUEST_BASE_URLS = buildBaseUrlList(API_BASE_URL, API_FALLBACK_URL); From f548013e9349c330d4884136e5c404be7753d5e1 Mon Sep 17 00:00:00 2001 From: Eli Date: Sun, 19 Apr 2026 19:25:03 -0400 Subject: [PATCH 2/7] fixed error in frontend tsconfig.json --- frontend/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json index 7164bec..25f4cc4 100644 --- a/frontend/tsconfig.json +++ b/frontend/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "expo/tsconfig.base", "compilerOptions": { + "ignoreDeprecations": "6.0", "baseUrl": ".", "paths": { "@/*": ["./*"] From a56cc974f5e8c2f385750c6348e1837b1b1c0dc8 Mon Sep 17 00:00:00 2001 From: Eli Date: Thu, 23 Apr 2026 01:11:45 -0400 Subject: [PATCH 3/7] broken admin and stuff --- SECURITY_NEEDS.txt | 89 +++ TODO.md | 7 + backend/api/admin/console.html | 305 +-------- backend/api/admin/index.html | 182 +++--- backend/api/admin/static/admin-icons.js | 60 ++ backend/api/admin/static/admin.css | 634 ++++++++++++++++++ backend/api/admin/static/admin.js | 828 +++++++++++++----------- backend/api/admin/static/login.js | 174 ++--- backend/api/main.go | 2 +- backend/nginx/nginx.conf | 223 +------ 10 files changed, 1463 insertions(+), 1041 deletions(-) create mode 100644 SECURITY_NEEDS.txt create mode 100644 TODO.md create mode 100644 backend/api/admin/static/admin-icons.js create mode 100644 backend/api/admin/static/admin.css diff --git a/SECURITY_NEEDS.txt b/SECURITY_NEEDS.txt new file mode 100644 index 0000000..9620511 --- /dev/null +++ b/SECURITY_NEEDS.txt @@ -0,0 +1,89 @@ +DevBits Security Setup (Cloudflare Domain + Cloudflare Tunnel) + +0) Before you start +0.1) Keep current DNS and router setup unchanged until Step 8 verification passes. +0.2) Keep current domain live during migration (no cutover yet). +0.3) Have access to: Cloudflare account, domain registrar account, server SSH/root, router admin panel. + +1) Cloudflare domain onboarding +1.1) In Cloudflare, click Add a site. +1.2) Enter your owned domain (not a shared ddns.net hostname). +1.3) Select Free plan and continue. +1.4) Copy the two Cloudflare nameservers shown. + +2) Registrar nameserver change +2.1) Open registrar panel for your owned domain. +2.2) Go to Nameservers. +2.3) Replace existing nameservers with the two Cloudflare nameservers. +2.4) Save changes. +2.5) If DNSSEC is enabled at registrar, disable it temporarily. +2.6) Wait until Cloudflare zone status is Active. + +3) Create Cloudflare Tunnel +3.1) In Cloudflare dashboard, open Zero Trust. +3.2) Go to Networks -> Tunnels. +3.3) Click Create a tunnel. +3.4) Select Cloudflared. +3.5) Set tunnel name: devbits-home. +3.6) Keep installation/auth command page open. + +4) Install cloudflared connector on server +4.1) SSH into server. +4.2) Run the exact install/auth command from Cloudflare tunnel page. +4.3) Confirm tunnel connector shows Healthy/Connected in Cloudflare. + +5) Public hostname route for backend +5.1) In Cloudflare tunnel page, open Public Hostnames. +5.2) Click Add a public hostname. +5.3) Subdomain: api (or preferred label). +5.4) Domain: your owned Cloudflare domain. +5.5) Service Type: HTTP. +5.6) URL: localhost:80. +5.7) Save. + +6) Cloudflare edge security controls +6.1) SSL/TLS -> Overview: set mode to Full (strict). +6.2) SSL/TLS -> Edge Certificates: enable Always Use HTTPS. +6.3) Security -> WAF: enable managed rules. +6.4) Security -> Bots: enable Bot Fight Mode. +6.5) Security -> Rate Limiting Rules: add +6.5.1) /auth/login strict limit. +6.5.2) /auth/register strict limit. +6.5.3) /api/* moderate limit. + +7) Server config updates (before cutover) +7.1) In backend/.env set DEVBITS_ADMIN_LOCAL_ONLY=1. +7.2) In backend/.env set DEVBITS_CORS_ORIGINS to the new Cloudflare URL (example: https://api.yourdomain.com). +7.3) Keep DEVBITS_TRUST_PROXY=true. +7.4) Rebuild/restart services: cd backend && docker compose up -d --build backend nginx. +7.5) Check status: docker compose ps. +7.6) Check logs: docker compose logs --tail=200 nginx. + +8) Validate new path before closing ports +8.1) Open https://api.yourdomain.com and confirm app/backend responses. +8.2) Verify tunnel is Healthy in Cloudflare Zero Trust. +8.3) Verify Cloudflare analytics show requests to hostname. +8.4) Verify login/API rules trigger under burst testing. + +9) Close public origin exposure +9.1) Router: remove/disable port forwarding for 80 and 443. +9.2) Host firewall: deny inbound 80/443 from internet. +9.3) Keep only tunnel-based ingress path. + +10) Host hardening +10.1) Disable SSH password auth (key-only). +10.2) Disable SSH root login. +10.3) Install and configure fail2ban. +10.4) Enable unattended security updates. +10.5) Disable UPnP on router. + +11) Post-cutover verification +11.1) Cloudflare hostname works from external network. +11.2) Direct home IP on 80/443 is closed. +11.3) Bot/WAF/rate-limit events appear in Cloudflare dashboard. +11.4) No DNS record leaks direct home IP for app hostname. + +12) Rollback (if emergency) +12.1) Re-enable 80/443 port forward on router. +12.2) Temporarily point clients back to previous hostname. +12.3) Keep investigating tunnel failure via cloudflared logs and Cloudflare tunnel status. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..4d07d86 --- /dev/null +++ b/TODO.md @@ -0,0 +1,7 @@ +# DevBits Admin Console Fix/Build TODO + +## [✓] 1. Fix admin.css (@extend → explicit, add nav-bottom-list) +## [✓] 2. Full rewrite admin.js (FlatButton, API, pages, etc.) +## [✓] 3. Verify/update console.html & index.html +## [ ] 4. Test locally +## [ ] 5. Complete ✓ diff --git a/backend/api/admin/console.html b/backend/api/admin/console.html index 432c821..0889fac 100644 --- a/backend/api/admin/console.html +++ b/backend/api/admin/console.html @@ -4,293 +4,34 @@ DevBits Admin Console - - - -
-
-
-
DevBits Admin Console
-
- Moderation panel with ultimate key or delegated admin login. -
-
-
- - -
-
-
+ + + + + -
-
-
Users
-
-
-
-
-
Posts
-
-
-
-
-
Streams
-
-
-
-
-
Comments
-
-
-
-
-
+ + +

Users

-
- - - -
-
- + + -
-

Posts (Bytes)

-
- - - -
-
-
-
-
-

Projects (Streams)

-
- - - -
-
-
-
-
-

Comments

-
- - - -
-
-
-
-
+
- + + + + diff --git a/backend/api/admin/index.html b/backend/api/admin/index.html index 3e7440b..fe10b16 100644 --- a/backend/api/admin/index.html +++ b/backend/api/admin/index.html @@ -4,105 +4,91 @@ DevBits Admin Sign In - + + + + + + - -
-

DevBits

-

- Sign in as Administrator (password = ultimate key) or with an admin user - account. -

- - - -
-
+ + + + + +
+ +
+ diff --git a/backend/api/admin/static/admin-icons.js b/backend/api/admin/static/admin-icons.js new file mode 100644 index 0000000..8788fb1 --- /dev/null +++ b/backend/api/admin/static/admin-icons.js @@ -0,0 +1,60 @@ +// SVG Icons for UntitledUI-style sidebar (React components) +const Icons = { + HomeLine: ({ className = 'w-5 h-5' }) => ( + + + + + ), + BarChartSquare02: ({ className = 'w-5 h-5' }) => ( + + + + + + + ), + Users01: ({ className = 'w-5 h-5' }) => ( + + + + + + + ), + Rows01: ({ className = 'w-5 h-5' }) => ( + + + + + + ), + CheckDone01: ({ className = 'w-5 h-5' }) => ( + + + + ), + PieChart03: ({ className = 'w-5 h-5' }) => ( + + + + + ), + Settings01: ({ className = 'w-5 h-5' }) => ( + + + + + ), + LifeBuoy01: ({ className = 'w-5 h-5' }) => ( + + + + + + + ) +}; + +// Usage: + diff --git a/backend/api/admin/static/admin.css b/backend/api/admin/static/admin.css new file mode 100644 index 0000000..c5ec7f4 --- /dev/null +++ b/backend/api/admin/static/admin.css @@ -0,0 +1,634 @@ +/* DevBits Admin CSS - Floating Buttons v2 - No borders/shadows, typewriter text, smooth tint->green */ + +:root { + color-scheme: dark; + --db-bg: #05070a; + --db-surface: #10141a; + --db-surface-alt: #0c1016; + --db-text: #f0f3f7; + --db-muted: #94a0af; + --db-tint: #00f329; + --db-border: #1f2732; + --db-danger: #ef4444; + --db-success: #00f329; + --db-on-tint: #0b0d10; + --db-radius-card: 14px; + --db-radius-button: 12px; + --db-radius-input: 12px; + --db-space-card-x: 12px; + --db-space-card-y: 11px; + --ease-enter: cubic-bezier(0.25, 0.46, 0.45, 0.94); + --ease-exit: cubic-bezier(0.55, 0, 1, 0.45); + --ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1); + --dur-micro: 100ms; + --dur-standard: 220ms; + --dur-emphasis: 380ms; + --dur-counter: 1200ms; + --typewriter-step: 0.08s; +} + +* { + box-sizing: border-box; +} + +html, body { + min-height: 100%; + margin: 0; +} + +body { + font-family: "Space Mono", ui-monospace, Menlo, Monaco, "Cascadia Mono", "Segoe UI Mono", monospace; + color: var(--db-text); + background: var(--db-bg); + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; +} + +.admin-root, .admin-bottom-nav, .toast-stack, .record-overlay { + position: relative; + z-index: 3; +} + +.sr-only { + border: 0; + clip: rect(0, 0, 0, 0); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} + +h1, h2, h3, p { + margin: 0; +} + +button, input, textarea { + font: inherit; +} + +/* DevBits Floating Buttons - Clean, borderless, typewriter text */ +.btn { + position: relative; + background: var(--db-surface); + color: var(--db-text); + border: none; + border-radius: var(--db-radius-button); + padding: 12px 24px; + font-weight: 600; + font-size: 15px; + line-height: 1.2; + cursor: pointer; + transition: all var(--dur-standard) var(--ease-spring); + overflow: hidden; + min-height: 48px; + display: inline-flex; + align-items: center; + justify-content: center; + text-decoration: none; + box-shadow: none; + white-space: nowrap; +} + +.btn:focus-visible { + outline: none; +} + +.btn::before { + content: ''; + position: absolute; + inset: 0; + background: var(--db-tint); + opacity: 0; + transition: opacity var(--dur-standard) var(--ease-spring); + z-index: -1; +} + +.btn:hover::before, +.btn:focus::before, +.btn:active::before { + opacity: 0.15; +} + +.btn:active { + transform: scale(0.97); + transition-duration: var(--dur-micro); +} + +.btn span { + position: relative; + background: linear-gradient(90deg, transparent 0%, currentColor 0%, currentColor 100%, transparent 100%); + background-repeat: no-repeat; + background-size: 0% 100%; + background-position: left center; + transition: background-size var(--typewriter-step) linear; +} + +.btn:hover span, +.btn:focus span { + background-size: 100% 100%; + background-position: right center; +} + +/* Button variants by context/size */ +.btn--sidebar { + padding: 12px; + font-size: 14px; + min-height: 44px; + border-radius: 8px; + width: 100%; +} + +.btn--action { + padding: 10px 20px; + font-size: 14px; + flex: 1; + min-width: 100px; + min-height: 40px; +} + +.btn--primary { + padding: 14px 28px; + font-size: 16px; + min-height: 52px; +} + +.btn--small { + padding: 8px 16px; + font-size: 13px; + min-height: 36px; +} + +.btn.danger { + color: var(--db-danger); +} + +.btn.danger::before { + background: color-mix(in srgb, var(--db-danger) 50%, transparent); +} + +.btn.is-loading::after { + content: ''; + position: absolute; + width: 18px; + height: 18px; + border: 2px solid rgba(255,255,255,0.3); + border-top-color: currentColor; + border-radius: 50%; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + animation: spin 1s linear infinite; + z-index: 1; +} + +.btn.is-loading span { + opacity: 0; +} + +/* Sidebar nav-items as buttons */ +.nav-item { +position: relative; + background: var(--db-surface); + color: var(--db-text); + border: 1px solid transparent; + border-radius: 8px; + padding: 12px; + font-weight: 600; + font-size: 14px; + line-height: 1.2; + cursor: pointer; + transition: all var(--dur-standard) ease; + overflow: hidden; + min-height: 44px; + display: inline-flex; + align-items: center; + justify-content: center; + text-decoration: none; + box-shadow: none; + white-space: nowrap; + width: 100%; + text-align: center; + text-align: center; + position: relative; + overflow: visible; + transition: all var(--dur-standard) ease; +} + +.nav-item::before { + opacity: 0.08; +} + +.nav-item.active { + background: color-mix(in srgb, var(--db-surface-alt), var(--db-tint) 20%); + color: var(--db-tint); +} + +.nav-item:hover { + transform: none; +} + +/* Inputs */ +.admin-input { + width: 100%; + background: var(--db-surface); + border: 1px solid var(--db-border); + border-radius: var(--db-radius-input); + color: var(--db-text); + padding: 12px 16px; + font-size: 16px; + transition: all var(--dur-standard); +} + +.admin-input:focus-visible { + outline: none; + border-color: var(--db-tint); + background: color-mix(in srgb, var(--db-surface), var(--db-tint) 5%); + box-shadow: 0 0 0 3px color-mix(in srgb, transparent, var(--db-tint) 15%); +} + +/* Login */ +.admin-login-page { + overflow: hidden; +} + +.login-shell { + min-height: 100vh; + display: grid; + place-items: center; + padding: 2rem; +} + +.login-card { + width: min(420px, 100%); + background: var(--db-surface); + border: 1px solid var(--db-border); + border-radius: 20px; + padding: 2rem; + display: grid; + gap: 1rem; +} + +.login-logo { + width: 72px; + height: 72px; + border-radius: 16px; + border: 1px solid var(--db-border); + margin: 0 auto; +} + +.login-title { + font-size: 28px; + line-height: 1.2; + font-weight: 700; + text-align: center; +} + +.login-caption { + font-size: 14px; + color: var(--db-muted); + text-align: center; +} + +.login-form { + display: grid; + gap: 1rem; +} + +.password-row { + display: grid; + grid-template-columns: 1fr auto; + gap: 0.5rem; + align-items: end; +} + +.login-status { + min-height: 1.25rem; + font-size: 14px; + color: var(--db-muted); + text-align: center; +} + +.login-status.error { + color: var(--db-danger); +} + +/* Layout */ +.admin-root { + min-height: 100vh; + display: grid; + grid-template-columns: 72px 1fr; + gap: 0; +} + +.admin-sidebar { + position: sticky; + top: 0; + height: 100vh; + background: var(--db-bg); + padding: 1rem 0.5rem; + display: flex; + flex-direction: column; + gap: 1rem; + border-right: 1px solid var(--db-border); + overflow: hidden; +} + +.sidebar-brand { + display: flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + padding: 0.5rem; +} + +.sidebar-brand img { + width: 32px; + height: 32px; + border-radius: 8px; + border: 1px solid var(--db-border); +} + +.nav-list { + flex: 1; + display: grid; + gap: 0.5rem; + padding: 0 0.25rem; +} + +.admin-main { + padding: 1.5rem; + min-width: 0; +} + +.admin-topbar { + position: sticky; + top: 0; + z-index: 100; + height: 4rem; + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 1rem; + border-bottom: 1px solid var(--db-border); + background: var(--db-bg); + margin-bottom: 1rem; +} + +.topbar-left { + display: flex; + align-items: center; + gap: 0.75rem; +} + +.topbar-left img { + width: 28px; + height: 28px; + border-radius: 8px; +} + +.topbar-actions { + display: flex; + align-items: center; + gap: 0.5rem; + min-width: 120px; +} + +.search-wrap { + flex: 1; + max-width: 32rem; + position: relative; +} + +.search-input { + height: 2.5rem; + border-radius: 999px; + background: var(--db-surface); + border: 1px solid var(--db-border); + padding: 0 1rem; + width: 100%; + font-size: 16px; + color: var(--db-text); + transition: all var(--dur-standard); +} + +.search-input:focus { + border-color: var(--db-tint); + background: color-mix(in srgb, var(--db-surface), var(--db-tint) 5%); +} + +.search-dropdown { + position: absolute; + top: calc(100% + 0.5rem); + left: 0; + right: 0; + background: var(--db-surface); + border: 1px solid var(--db-border); + border-radius: var(--db-radius-card); + max-height: 28rem; + overflow: auto; + z-index: 200; + box-shadow: 0 10px 25px rgba(0,0,0,0.3); +} + +.mobile-search-toggle { + display: none; +} + +/* Cards & Content */ +.page { + margin-top: 1rem; +} + +.section-card { + background: var(--db-surface); + border: 1px solid var(--db-border); + border-radius: var(--db-radius-card); + padding: 1rem; + margin-bottom: 1rem; +} + +.section-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + margin-bottom: 0.75rem; +} + +.section-head h2 { + font-size: 1.25rem; + font-weight: 700; +} + +.counter-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); + gap: 1rem; +} + +.entity-card { + background: var(--db-surface); + border: 1px solid var(--db-border); + border-radius: var(--db-radius-card); + padding: 1rem; + display: grid; + gap: 0.75rem; + transition: all var(--dur-standard); + cursor: pointer; +} + +.entity-card:hover { + border-color: var(--db-tint); + transform: translateY(-1px); +} + +.entity-actions { + display: flex; + gap: 0.5rem; +} + +.list-search-row { + display: flex; + gap: 0.5rem; + margin-bottom: 1rem; +} + +.load-more-row { + display: flex; + justify-content: center; + margin-top: 1rem; +} + +/* Responsive */ +@media (max-width: 1024px) { + .nav-item span:last-child { + display: none; + } + + .sidebar-brand strong { + display: none; + } +} + +@media (max-width: 900px) { + .admin-root { + grid-template-columns: 0 1fr; + } + + .admin-sidebar { + position: fixed; + inset: 0; + z-index: 300; + transform: translateX(-100%); + transition: transform var(--dur-standard); + } + + .admin-sidebar:hover { + transform: translateX(0); + } + + .admin-main { + padding-left: 1rem; + } +} + +@media (max-width: 768px) { + .admin-root { + grid-template-columns: 1fr; + } + + .admin-sidebar { + display: none; + } + + .admin-main { + padding: 1rem; + } + + .admin-topbar { + padding: 0 1rem; + } + + .mobile-search-toggle { + display: flex; + } + + .search-wrap { + display: none; + } + +.admin-bottom-nav { + display: block; + position: fixed; + bottom: 0; + left: 0; + right: 0; + height: 4rem; + background: var(--db-surface); + border-top: 1px solid var(--db-border); + z-index: 200; + } + + .nav-bottom-list { + display: flex; + height: 100%; + align-items: center; + justify-content: space-around; + } + + .counter-grid { + grid-template-columns: 1fr; + } +} + +@keyframes spin { + to { transform: rotate(360deg); } +} + +@keyframes typewriter { + from { background-size: 0% 100%; } + to { background-size: 100% 100%; } +} + +/* Toast & Modal */ +.toast-stack { + position: fixed; + top: 5rem; + right: 1rem; + z-index: 999; + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.toast { + background: var(--db-surface); + border: 1px solid var(--db-border); + border-left: 4px solid var(--db-tint); + border-radius: var(--db-radius-card); + padding: 1rem; + animation: slideIn 0.3s ease; +} + +.record-overlay { + position: fixed; + inset: 0; + background: rgba(0,0,0,0.5); + z-index: 500; + display: grid; + place-items: center; + padding: 1rem; +} + +.record-modal { + background: var(--db-surface); + border: 1px solid var(--db-border); + border-radius: var(--db-radius-card); + max-width: 36rem; + max-height: 80vh; + overflow: auto; + width: 100%; +} diff --git a/backend/api/admin/static/admin.js b/backend/api/admin/static/admin.js index aaade56..19c52aa 100644 --- a/backend/api/admin/static/admin.js +++ b/backend/api/admin/static/admin.js @@ -1,414 +1,488 @@ -function getStoredAdminKey() { - return sessionStorage.getItem('devbits_admin_key') || '' +/** @jsxRuntime classic */ +/** @jsx React.createElement */ +const { useState, useEffect, useRef, useMemo, useCallback, useId } = React; + +// FlatButton - CRITICAL: Define FIRST +function FlatButton({ children, onClick, busy, danger, className = "", size }) { + const classes = ["btn", danger ? "danger" : "", busy ? "is-loading" : "", size ? `btn--${size}` : "", className] + .filter(Boolean).join(" "); + return ( + + ); } -function getStoredAdminToken() { - return sessionStorage.getItem('devbits_admin_token') || '' -} +// Icons available globally from admin-icons.js -function setStoredAdminKey(value) { - const trimmed = (value || '').trim() - if (!trimmed) { - sessionStorage.removeItem('devbits_admin_key') - return '' - } - sessionStorage.setItem('devbits_admin_key', trimmed) - return trimmed -} +// NAV_CONFIG +const NAV_CONFIG = [ + { label: "Dashboard", href: "#/dashboard", icon: Icons.BarChartSquare02, match: "dashboard" }, + { label: "Users", href: "#/users", icon: Icons.Users01, match: "users" }, + { label: "Bytes", href: "#/bytes", icon: Icons.Package, match: "bytes" }, + { label: "Streams", href: "#/streams", icon: Icons.Rows01, match: "streams" }, + { label: "Bits", href: "#/bits", icon: Icons.PieChart03, match: "bits" }, +]; + +const PAGES = ["dashboard", "users", "bytes", "streams", "bits"]; -function setStoredAdminToken(value) { - const trimmed = (value || '').trim() - if (!trimmed) { - sessionStorage.removeItem('devbits_admin_token') - return '' +// API Layer + Cache +const cache = new Map(); +function getCached(key) { + return cache.get(key); +} +function setCached(key, value, ttl = 5 * 60 * 1000) { + cache.set(key, { value, expires: Date.now() + ttl }); +} +function invalidateCache(...prefixes) { + for (let [key] of cache) { + if (prefixes.some(prefix => key.startsWith(prefix))) { + cache.delete(key); + } } - sessionStorage.setItem('devbits_admin_token', trimmed) - return trimmed } -async function api(path, method = 'GET', body = null) { - const key = getStoredAdminKey() - const token = getStoredAdminToken() - if (!key && !token) { - window.location.href = '/admin' - throw new Error('admin authentication required') - } +async function api(path, options = {}) { + const key = getStoredAuth() + path + JSON.stringify(options?.body || {}); + const cached = getCached(key); + if (cached && cached.expires > Date.now()) return cached.value; - const opts = { method, headers: {} } - if (key) { - opts.headers['X-Admin-Key'] = key - } else if (token) { - opts.headers.Authorization = `Bearer ${token}` + const auth = getStoredAuth(); + if (!auth) { + window.location.href = "/admin"; + throw new Error("Not authenticated"); } - if (body) { - opts.body = JSON.stringify(body) - opts.headers['Content-Type'] = 'application/json' + const headers = { "Content-Type": "application/json", ...options.headers }; + if (auth.startsWith("Bearer ")) headers.Authorization = auth; + else headers["X-Admin-Key"] = auth; + + const resp = await fetch(path, { ...options, headers }); + const data = await resp.clone().json().catch(() => null); + + if (resp.status === 401 || resp.status === 403) { + sessionStorage.clear(); + window.location.href = "/admin"; + throw new Error("Session expired"); } - const res = await fetch(path, opts) - if (!res.ok) { - const text = await res.text() - throw new Error(`${res.status} ${res.statusText}: ${text}`) + if (!resp.ok) throw new Error(data?.message || data?.error || `HTTP ${resp.status}`); + + if (resp.ok && options.method !== "POST" && options.method !== "DELETE") { + setCached(key, data); } - return res.json().catch(() => null) + return data; } -function setText(id, value) { - const node = document.getElementById(id) - if (node) node.textContent = value +function getStoredAuth() { + return sessionStorage.getItem("devbits_admin_token") || sessionStorage.getItem("devbits_admin_key") || ""; } -function toText(value) { - if (value === null || typeof value === 'undefined') return '' - return String(value) +// ToastStack +function ToastStack({ toasts, onDismiss }) { + return ( +
+ {toasts.map(({ id, message, type = "info" }) => ( +
+ {message} + +
+ ))} +
+ ); } -function asArray(value) { - return Array.isArray(value) ? value : [] +// EntityModal +function EntityModal({ entity, type, isOpen, onClose }) { + if (!isOpen) return null; + const fields = Object.entries(entity || {}).map(([k, v]) => ( +
+ {k}: {String(v)} +
+ )); + + return ( +
+
e.stopPropagation()}> +
+

{type} Expanded view

+ Close +
+
{fields}
+
+
+ ); } -function renderTable(containerId, columns, rows, getActions) { - const container = document.getElementById(containerId) - if (!container) return - - const table = document.createElement('table') - const thead = document.createElement('thead') - const headRow = document.createElement('tr') - - columns.forEach(col => { - const th = document.createElement('th') - th.textContent = col.label - headRow.appendChild(th) - }) - - const actionTh = document.createElement('th') - actionTh.textContent = 'Actions' - headRow.appendChild(actionTh) - thead.appendChild(headRow) - table.appendChild(thead) - - const tbody = document.createElement('tbody') - rows.forEach(row => { - const tr = document.createElement('tr') - - columns.forEach(col => { - const td = document.createElement('td') - const rawValue = typeof col.value === 'function' ? col.value(row) : row[col.value] - td.textContent = toText(rawValue) - if (col.truncate) td.className = 'cell-truncate' - tr.appendChild(td) - }) - - const actionTd = document.createElement('td') - const actions = typeof getActions === 'function' ? getActions(row) : [] - actions.forEach((action, index) => { - const button = document.createElement('button') - button.textContent = action.label - button.className = action.className || '' - button.onclick = action.onClick - actionTd.appendChild(button) - if (index < actions.length - 1) { - const spacer = document.createElement('span') - spacer.textContent = ' ' - actionTd.appendChild(spacer) - } - }) - tr.appendChild(actionTd) - - tbody.appendChild(tr) - }) - - table.appendChild(tbody) - container.innerHTML = '' - container.appendChild(table) +// GenericCard +function GenericCard({ entity, type, onDelete, onClick }) { + const [showConfirm, setShowConfirm] = useState(false); + return ( +
+
{entity.title || entity.username || entity.id}
+
+ by {entity.owner} + {new Date(entity.created_at || entity.updated_at).toLocaleDateString()} +
+
{(entity.content || entity.bio || "").slice(0, 120)}...
+
+ {e.stopPropagation(); onDelete(entity.id || entity.username);}}> + Delete + +
+
+ ); } -async function refreshOverview() { - try { - const data = await api('/admin/overview') - setText('stat-users', data?.counts?.users ?? '-') - setText('stat-posts', data?.counts?.posts ?? '-') - setText('stat-projects', data?.counts?.projects ?? '-') - setText('stat-comments', data?.counts?.comments ?? '-') - setText('overview-status', `Server: ${data?.server_time ?? '-'} DB: ${data?.db_time ?? 'n/a'}`) - } catch (error) { - setText('overview-status', `Overview error: ${error.message}`) - } +// UserCard (extends Generic) +function UserCard({ user, onAction }) { + const initials = user.username ? user.username.slice(0,2).toUpperCase() : '?'; + const isAdmin = user.is_admin; + const isBanned = user.ban_expires_at; + + const handleAdminToggle = () => onAction(user.username, 'admin', !isAdmin); + const handleBanToggle = () => onAction(user.username, 'ban', !isBanned); + + return ( +
+
+
{initials}
+
+
{user.username}
+
{user.bio?.slice(0,80)}...
+
+
+
+ handleAdminToggle()}>{isAdmin ? 'Revoke Admin' : 'Grant Admin'} + handleBanToggle()}>{isBanned ? 'Unban' : 'Ban'} + onAction(user.username, 'delete')}>Delete +
+
+ ); } -async function updateAuthStatus() { - const hasKey = !!getStoredAdminKey() - const hasToken = !!getStoredAdminToken() - if (!hasKey && !hasToken) { - setText('auth-status', 'Not signed in.') - return - } - - try { - const me = await api('/admin/me') - if (me?.mode === 'key') { - setText('auth-status', 'Signed in with ultimate admin key.') - return +// Page: Data list (users/bytes/etc) +function DataPage({ page }) { + const [query, setQuery] = useState(''); + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(false); + const [pageNum, setPageNum] = useState(1); + const [hasMore, setHasMore] = useState(true); + const [selected, setSelected] = useState(null); + + const endpoint = `/admin/${page}s?q=${encodeURIComponent(query)}&page=${pageNum}&limit=12`; + + const refresh = useCallback(async () => { + setLoading(true); + try { + const data = await api(endpoint); + setItems(data.items || []); + setHasMore(data.has_more !== false); + } catch (e) { + toasts.current.push({id: Date.now(), message: e.message, type: 'error'}); + } finally { + setLoading(false); } - const label = me?.username ? `Signed in as admin user: ${me.username}.` : 'Signed in with admin account.' - setText('auth-status', label) - } catch (error) { - setText('auth-status', `Auth status error: ${error.message}`) - } -} - -async function refreshUsers() { - try { - const q = document.getElementById('user-search').value || '' - const path = q ? `/admin/users?q=${encodeURIComponent(q)}` : '/admin/users' - const usersResponse = asArray(await api(path)) - const users = Array.isArray(usersResponse) ? usersResponse : [] - renderTable( - 'users', - [ - { label: 'ID', value: 'id' }, - { label: 'Username', value: 'username' }, - { label: 'Admin', value: (u) => (u.is_admin ? 'Yes' : 'No') }, - { label: 'Ban Until', value: (u) => u.ban_until || '' }, - { label: 'Ban Reason', value: (u) => u.ban_reason || '', truncate: true }, - { label: 'Bio', value: (u) => u.bio || '', truncate: true }, - { label: 'Created', value: 'creation_date' }, - ], - users, - (u) => { - const actions = [] - - actions.push({ - label: u.is_admin ? 'Remove Admin' : 'Make Admin', - className: 'secondary', - onClick: async () => { - try { - const res = await api(`/admin/users/${encodeURIComponent(u.username)}/admin`, 'POST', { - is_admin: !u.is_admin, - }) - alert(res.message || 'Admin status updated') - await refreshUsers() - } catch (e) { - alert('Error: ' + e.message) - } - } - }) - - if (u.ban_until) { - actions.push({ - label: 'Unban', - className: 'secondary', - onClick: async () => { - try { - const res = await api(`/admin/users/${encodeURIComponent(u.username)}/unban`, 'POST') - alert(res.message || 'User unbanned') - await refreshUsers() - } catch (e) { - alert('Error: ' + e.message) - } - } - }) - } else { - actions.push({ - label: 'Ban', - className: 'secondary', - onClick: async () => { - const reason = (prompt(`Ban reason for ${u.username}:`, 'Violation of community guidelines') || '').trim() - if (!reason) { - alert('Ban reason is required.') - return - } - - const minutesText = (prompt('Ban duration (minutes):', '60') || '').trim() - const durationMinutes = Number.parseInt(minutesText, 10) - if (!Number.isFinite(durationMinutes) || durationMinutes <= 0) { - alert('Duration must be a positive whole number of minutes.') - return - } - - try { - const res = await api(`/admin/users/${encodeURIComponent(u.username)}/ban`, 'POST', { - reason, - duration_minutes: durationMinutes, - }) - alert(res.message || 'User banned') - await refreshUsers() - } catch (e) { - alert('Error: ' + e.message) - } - } - }) - } - - actions.push({ - label: 'Delete', - className: 'danger', - onClick: async () => { - if (!confirm('Delete user ' + u.username + '?')) return - try { - const res = await api(`/admin/users/${encodeURIComponent(u.username)}`, 'DELETE') - alert(res.message || 'deleted') - await refreshUsers() - await refreshOverview() - } catch (e) { - alert('Error: ' + e.message) - } - } - }) - - return actions - } - ) - setText('overview-status', `Loaded ${users.length} user row(s)`) - } catch (e) { - alert('Error: ' + e.message) - } + }, [endpoint]); + + useEffect(() => { + refresh(); + }, [query, pageNum]); + + const handleAction = async (id, action, value) => { + try { + if (action === 'delete') await api(`/admin/${page}s/${id}`, {method: 'DELETE'}); + else if (action === 'admin') await api(`/admin/${page}s/${id}/admin`, {method: 'POST', body: {is_admin: value}}); + else if (action === 'ban') await api(`/admin/${page}s/${id}/ban`, {method: 'POST', body: {reason: 'Admin action', duration_minutes: value ? 0 : 60*24*7}}); + else if (action === 'unban') await api(`/admin/${page}s/${id}/unban`, {method: 'POST'}); + invalidateCache(`/admin/${page}`); + refresh(); + toasts.current.push({id: Date.now(), message: 'Action completed', type: 'success'}); + } catch (e) { + toasts.current.push({id: Date.now(), message: e.message, type: 'error'}); + } + }; + + const CardComponent = page === 'users' ? UserCard : GenericCard; + + const skeletons = Array(6).fill().map((_,i) => ( +
+ )); + + return ( +
+
+
+

{page.charAt(0).toUpperCase() + page.slice(1)}

+
+ setQuery(e.target.value)} style={{flex:1, minWidth:'200px'}}/> + Search +
+
+
+ {loading && !items.length ? skeletons : items.map(item => ( + setSelected(item)} /> + ))} +
+ {hasMore &&
setPageNum(p => p+1)}>Load more
} +
+ setSelected(null)} /> +
+ ); } -document.getElementById('refresh-users').onclick = refreshUsers -document.getElementById('clear-search').onclick = () => { document.getElementById('user-search').value = ''; refreshUsers() } -document.getElementById('refresh-overview').onclick = refreshOverview -document.getElementById('reset-key').onclick = () => { - setStoredAdminKey('') - setStoredAdminToken('') - window.location.href = '/admin' +// DashboardPage +function DashboardPage() { + const [overview, setOverview] = useState({}); + const [snapshots, setSnapshots] = useState({}); + const [loading, setLoading] = useState(true); + const [selected, setSelected] = useState(null); + + useEffect(() => { + api('/admin/overview').then(data => { + setOverview(data); + setSnapshots({ + streams: data.recent_streams?.slice(0,6) || [], + bytes: data.recent_bytes?.slice(0,6) || [], + bits: data.recent_bits?.slice(0,6) || [] + }); + setLoading(false); + }).catch(e => { + toasts.current.push({id: Date.now(), message: e.message, type: 'error'}); + setLoading(false); + }); + }, []); + + if (loading) return
Loading...
; + + const stats = [ + { label: 'Users', value: overview.user_count, icon: Icons.Users01 }, + { label: 'Bytes', value: overview.byte_count, icon: Icons.Package }, + { label: 'Streams', value: overview.stream_count, icon: Icons.Rows01 }, + { label: 'Bits', value: overview.bit_count, icon: Icons.PieChart03 } + ]; + + const snapshotSections = [ + { title: 'Live Streams', items: snapshots.streams, type: 'streams' }, + { title: 'Recent Bytes', items: snapshots.bytes, type: 'bytes' }, + { title: 'Latest Bits', items: snapshots.bits, type: 'bits' } + ]; + + return ( +
+
+

Overview

+
+ {stats.map(({label, value, icon: Icon}) => ( +
+
+ +
+
{value || 0}
+
{label}
+
+
+
+ ))} +
+
+ {snapshotSections.map(({title, items, type}) => ( +
+

{title}

+
+ {items.map(item => setSelected(item)} />)} +
+
+ ))} + setSelected(null)}} /> +
+ ); } -async function searchPosts() { - const q = document.getElementById('post-search').value || '' - try { - const path = q ? `/admin/posts?q=${encodeURIComponent(q)}` : '/admin/posts' - const postsResponse = asArray(await api(path)) - const posts = Array.isArray(postsResponse) ? postsResponse : [] - renderTable( - 'posts', - [ - { label: 'ID', value: 'id' }, - { label: 'User ID', value: 'user' }, - { label: 'Stream ID', value: 'project' }, - { label: 'Content', value: (p) => p.content || '', truncate: true }, - { label: 'Created', value: 'creation_date' }, - ], - posts, - (p) => ([{ - label: 'Delete', - className: 'danger', - onClick: async () => { - if (!confirm('Delete post ' + p.id + '?')) return - try { - const res = await api(`/admin/posts/${encodeURIComponent(p.id)}`, 'DELETE') - setText('post-result', res.message || 'deleted') - await searchPosts() - await refreshOverview() - } catch (e) { - alert('Error: ' + e.message) - } - } - }]) - ) - setText('post-result', `${posts.length} result(s)`) - } catch (e) { - setText('post-result', 'Error: ' + e.message) +// Topbar Search +function TopSearch({ onSearch }) { + const [query, setQuery] = useState(''); + const [results, setResults] = useState({}); + const [showDropdown, setShowDropdown] = useState(false); + const timeoutRef = useRef(); + + const debouncedSearch = useCallback(debounce(async (q) => { + if (!q) return setResults({}); + const [users, bytes, streams, bits] = await Promise.all([ + api(`/admin/users?q=${q}`).catch(() => []), + api(`/admin/posts?q=${q}`).catch(() => []), + api(`/admin/projects?q=${q}`).catch(() => []), + api(`/admin/comments?q=${q}`).catch(() => []) + ]); + setResults({ users, bytes: bytes, streams, bits }); + setShowDropdown(true); + }, 220), []); + + useEffect(() => { + clearTimeout(timeoutRef.current); + timeoutRef.current = setTimeout(() => debouncedSearch(query), 220); + return () => clearTimeout(timeoutRef.current); + }, [query]); + + function debounce(fn, ms) { + return (...args) => { + clearTimeout(timeoutRef.current); + timeoutRef.current = setTimeout(() => fn(...args), ms); + }; } -} -document.getElementById('search-posts').onclick = searchPosts -document.getElementById('clear-post-search').onclick = () => { document.getElementById('post-search').value = ''; searchPosts() } - -async function searchProjects() { - const q = document.getElementById('project-search').value || '' - try { - const path = q ? `/admin/projects?q=${encodeURIComponent(q)}` : '/admin/projects' - const projectsResponse = asArray(await api(path)) - const projects = Array.isArray(projectsResponse) ? projectsResponse : [] - renderTable( - 'projects', - [ - { label: 'ID', value: 'id' }, - { label: 'Owner ID', value: 'owner' }, - { label: 'Name', value: (p) => p.name || '' }, - { label: 'Description', value: (p) => p.description || '', truncate: true }, - { label: 'Created', value: 'creation_date' }, - ], - projects, - (p) => ([{ - label: 'Delete', - className: 'danger', - onClick: async () => { - if (!confirm('Delete project ' + p.id + '?')) return - try { - const res = await api(`/admin/projects/${encodeURIComponent(p.id)}`, 'DELETE') - setText('project-result', res.message || 'deleted') - await searchProjects() - await refreshOverview() - } catch (e) { - alert('Error: ' + e.message) - } - } - }]) - ) - setText('project-result', `${projects.length} result(s)`) - } catch (e) { - setText('project-result', 'Error: ' + e.message) - } + const sections = [ + { label: 'Users', items: results.users || [] }, + { label: 'Bytes', items: results.bytes || [] }, + { label: 'Streams', items: results.streams || [] }, + { label: 'Bits', items: results.bits || [] } + ]; + + return ( +
+ setQuery(e.target.value)} + onFocus={() => setShowDropdown(true)} + /> + {showDropdown && Object.values(results).some(arr => arr.length) && ( +
+ {sections.map(({label, items}) => items?.length ? ( +
+
{label}
+ {items.slice(0,5).map(item => ( +
{ + setSelectedGlobal(item); setShowDropdown(false); + }}> + {item.username || item.title || item.content?.slice(0,50)} +
+ ))} +
+ ) : null)} +
+ )} +
+ ); } -document.getElementById('search-projects').onclick = searchProjects -document.getElementById('clear-project-search').onclick = () => { document.getElementById('project-search').value = ''; searchProjects() } - -async function searchComments() { - const q = document.getElementById('comment-search').value || '' - try { - const path = q ? `/admin/comments?q=${encodeURIComponent(q)}` : '/admin/comments' - const commentsResponse = asArray(await api(path)) - const comments = Array.isArray(commentsResponse) ? commentsResponse : [] - renderTable( - 'comments', - [ - { label: 'ID', value: 'id' }, - { label: 'User ID', value: 'user' }, - { label: 'Content', value: (c) => c.content || '', truncate: true }, - { label: 'Created', value: 'created_on' }, - ], - comments, - (c) => ([{ - label: 'Delete', - className: 'danger', - onClick: async () => { - if (!confirm('Delete comment ' + c.id + '?')) return - try { - const res = await api(`/admin/comments/${encodeURIComponent(c.id)}`, 'DELETE') - setText('comment-result', res.message || 'deleted') - await searchComments() - await refreshOverview() - } catch (e) { - setText('comment-result', 'Error: ' + e.message) - } - } - }]) - ) - setText('comment-result', `${comments.length} result(s)`) - } catch (e) { - setText('comment-result', 'Error: ' + e.message) - } +// SidebarNavigationSlim +function SidebarNavigationSlim({ activePage, onNavigate, authLabel, onRefresh, onSignOut }) { + return ( + + ); } -document.getElementById('search-comments').onclick = searchComments -document.getElementById('clear-comment-search').onclick = () => { document.getElementById('comment-search').value = ''; searchComments() } - -window.addEventListener('load', async () => { - const existingKey = getStoredAdminKey() - const existingToken = getStoredAdminToken() - if (!existingKey && !existingToken) { - window.location.href = '/admin' - return - } +// Main App +function App() { + const [activePage, setActivePage] = useState('dashboard'); + const [user, setUser] = useState(null); + const toasts = useRef([]); + const [selectedGlobal, setSelectedGlobal] = useState(null); + + const navigate = useCallback((hash) => { + const page = hash.split('/')[1] || 'dashboard'; + if (PAGES.includes(page)) setActivePage(page); + window.location.hash = hash; + }, []); + + useEffect(() => { + const me = async () => { + try { + const data = await api('/admin/me'); + setUser(data); + } catch {} + }; + me(); + }, []); + + useEffect(() => { + const handler = () => { + const page = window.location.hash.split('/')[1] || 'dashboard'; + if (PAGES.includes(page)) setActivePage(page); + }; + window.addEventListener('hashchange', handler); + handler(); + return () => window.removeEventListener('hashchange', handler); + }, []); + + const PageComponent = activePage === 'dashboard' ? DashboardPage : () => ; + + const dismissToast = useCallback(id => { + toasts.current = toasts.current.filter(t => t.id !== id); + // Force re-render via key + }, []); + + return ( + <> +
+ window.location.reload()} + onSignOut={() => { + sessionStorage.clear(); + window.location.href = '/admin'; + }} + /> +
+
+
+ DevBits +
{activePage.charAt(0).toUpperCase() + activePage.slice(1)}
+
+
+ + window.location.reload()}> + + +
+
+ +
+
+ + setSelectedGlobal(null)} /> + + ); +} - await updateAuthStatus() - await refreshOverview() - await refreshUsers() - await searchPosts() - await searchProjects() - await searchComments() -}) +// Mount +const root = ReactDOM.createRoot(document.getElementById('admin-app')); +root.render(); diff --git a/backend/api/admin/static/login.js b/backend/api/admin/static/login.js index cc0abc3..a9e3cd6 100644 --- a/backend/api/admin/static/login.js +++ b/backend/api/admin/static/login.js @@ -1,123 +1,143 @@ function setStoredAdminKey(value) { - const trimmed = (value || '').trim() + const trimmed = (value || "").trim(); if (!trimmed) { - sessionStorage.removeItem('devbits_admin_key') - return '' + sessionStorage.removeItem("devbits_admin_key"); + return ""; } - sessionStorage.setItem('devbits_admin_key', trimmed) - return trimmed + sessionStorage.setItem("devbits_admin_key", trimmed); + return trimmed; } function setStoredAdminToken(value) { - const trimmed = (value || '').trim() + const trimmed = (value || "").trim(); if (!trimmed) { - sessionStorage.removeItem('devbits_admin_token') - return '' + sessionStorage.removeItem("devbits_admin_token"); + return ""; } - sessionStorage.setItem('devbits_admin_token', trimmed) - return trimmed + sessionStorage.setItem("devbits_admin_token", trimmed); + return trimmed; } async function verifyKey(key) { - const res = await fetch('/admin/overview', { - method: 'GET', - headers: { 'X-Admin-Key': key } - }) - return res.ok + const response = await fetch("/admin/overview", { + method: "GET", + headers: { "X-Admin-Key": key }, + }); + return response.ok; } async function loginWithCredentials(username, password) { - const res = await fetch('/auth/login', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ username, password }) - }) + const response = await fetch("/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username, password }), + }); - let payload = null + let payload = null; try { - payload = await res.json() + payload = await response.json(); } catch (_) { - payload = null + payload = null; } - if (!res.ok) { - const msg = payload?.message || payload?.error || 'Invalid credentials' - throw new Error(msg) + if (!response.ok) { + const message = payload?.message || payload?.error || "Invalid credentials"; + throw new Error(message); } - const token = payload?.token + const token = payload?.token; if (!token) { - throw new Error('Login succeeded but token is missing') + throw new Error("Login succeeded but token is missing"); } - const meRes = await fetch('/admin/me', { - method: 'GET', - headers: { Authorization: `Bearer ${token}` } - }) + const meResponse = await fetch("/admin/me", { + method: "GET", + headers: { Authorization: `Bearer ${token}` }, + }); - if (!meRes.ok) { - if (meRes.status === 403) { - throw new Error('This account is not an admin') + if (!meResponse.ok) { + if (meResponse.status === 403) { + throw new Error("This account is not an admin"); } - throw new Error('Failed to verify admin access') + throw new Error("Failed to verify admin access"); } - return token + return token; } -const statusEl = document.getElementById('status') -const usernameInput = document.getElementById('username-input') -const passwordInput = document.getElementById('password-input') -const signInBtn = document.getElementById('sign-in') +const statusEl = document.getElementById("status"); +const usernameInput = document.getElementById("username-input"); +const passwordInput = document.getElementById("password-input"); +const passwordToggle = document.getElementById("password-toggle"); +const signInButton = document.getElementById("sign-in"); +const form = document.getElementById("signin-form"); + +function setSignInVisualState(state) { + if (!signInButton) return; + signInButton.classList.remove("is-loading", "is-success", "is-error"); + if (state) { + signInButton.classList.add(state); + } +} -async function signIn() { - const username = (usernameInput.value || '').trim() - const password = (passwordInput.value || '').trim() +function setStatus(message, isError) { + if (!statusEl) return; + statusEl.textContent = message || ""; + statusEl.classList.toggle("error", !!isError); +} + +function wait(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function handleSignIn(event) { + event.preventDefault(); + const username = (usernameInput?.value || "").trim(); + const password = (passwordInput?.value || "").trim(); if (!username || !password) { - statusEl.textContent = 'Enter username and password.' - return + setStatus("Enter username and password.", true); + return; } - statusEl.textContent = 'Signing in...' - signInBtn.disabled = true + setStatus("Signing in...", false); + setSignInVisualState("is-loading"); + try { - if (username.toLowerCase() === 'administrator') { - const ok = await verifyKey(password) + if (username.toLowerCase() === "administrator") { + const ok = await verifyKey(password); if (!ok) { - statusEl.textContent = 'Invalid Administrator password.' - return + throw new Error("Invalid Administrator password."); } - - setStoredAdminToken('') - setStoredAdminKey(password) + setStoredAdminToken(""); + setStoredAdminKey(password); } else { - const token = await loginWithCredentials(username, password) - setStoredAdminKey('') - setStoredAdminToken(token) + const token = await loginWithCredentials(username, password); + setStoredAdminKey(""); + setStoredAdminToken(token); } - statusEl.textContent = 'Success. Redirecting...' - window.location.href = '/admin/console' + setSignInVisualState("is-success"); + setStatus("Success. Redirecting...", false); + await wait(280); + window.location.href = "/admin/console#/dashboard"; } catch (error) { - statusEl.textContent = `Sign in failed: ${error.message || 'network error'}` - } finally { - signInBtn.disabled = false + setSignInVisualState("is-error"); + setStatus(`Sign in failed: ${error?.message || "network error"}`, true); + await wait(420); + setSignInVisualState(""); } } -signInBtn.addEventListener('click', signIn) - -usernameInput.addEventListener('keydown', (event) => { - if (event.key === 'Enter') { - event.preventDefault() - signIn() - } -}) +if (passwordToggle && passwordInput) { + passwordToggle.addEventListener("click", () => { + const reveal = passwordInput.type === "password"; + passwordInput.type = reveal ? "text" : "password"; + passwordToggle.textContent = reveal ? "Hide" : "Show"; + passwordToggle.setAttribute("aria-label", reveal ? "Hide password" : "Show password"); + }); +} -passwordInput.addEventListener('keydown', (event) => { - if (event.key === 'Enter') { - event.preventDefault() - signIn() - } -}) +if (form) { + form.addEventListener("submit", handleSignIn); +} diff --git a/backend/api/main.go b/backend/api/main.go index 0e6b380..e1c8d6f 100644 --- a/backend/api/main.go +++ b/backend/api/main.go @@ -269,7 +269,7 @@ func main() { router.GET("/messages/:username/threads", handlers.RequireAuth(), handlers.RequireSameUser(), handlers.GetDirectMessageThreads) router.GET("/messages/:username/with/:other", handlers.RequireAuth(), handlers.RequireSameUser(), handlers.GetDirectMessages) router.POST("/messages/:username/with/:other", handlers.RequireAuth(), handlers.RequireSameUser(), handlers.CreateDirectMessage) - router.GET("/messages/:username/stream", handlers.StreamDirectMessages) + router.GET("/messages/:username/stream", handlers.RequireAuth(), handlers.RequireSameUser(), handlers.StreamDirectMessages) router.GET("/projects/:project_id", handlers.GetProjectById) router.POST("/projects", handlers.RequireAuth(), handlers.CreateProject) diff --git a/backend/nginx/nginx.conf b/backend/nginx/nginx.conf index 7a9ed39..f138d09 100644 --- a/backend/nginx/nginx.conf +++ b/backend/nginx/nginx.conf @@ -66,210 +66,11 @@ http { proxy_set_header Authorization $http_authorization; server_tokens off; - # HTTP server for local development and health checks + # Default sink for unknown hosts on :80 server { listen 80 default_server; server_name _; - add_header X-Content-Type-Options "nosniff" always; - add_header X-Frame-Options "DENY" always; - add_header Referrer-Policy "same-origin" always; - - location ~* ^/(wp-admin|wp-login\.php|xmlrpc\.php|phpmyadmin|pma|\.git|\.env|cgi-bin|boaform|actuator|manager/html|server-status|vendor/phpunit|\.well-known/pki-validation) { - return 444; - } - - location ~* ^/(media/upload|users/.+/(profile-picture|update))$ { - client_max_body_size 64m; - client_body_timeout 30s; - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - proxy_request_buffering on; - proxy_buffering on; - proxy_read_timeout 30s; - proxy_send_timeout 30s; - add_header Cache-Control "no-store" always; - } - - location ~* ^/users/[^/]+$ { - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - proxy_request_buffering on; - proxy_buffering on; - proxy_read_timeout 30s; - proxy_send_timeout 30s; - add_header Cache-Control "no-store" always; - } - - location ~ ^/(auth|feed|users|projects|posts|comments|notifications|messages|media|health)(/|$) { - limit_req zone=api_limit burst=120 nodelay; - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - add_header Cache-Control "no-store" always; - } - - location ^~ /uploads/ { - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - add_header Cache-Control "no-cache, max-age=0, must-revalidate" always; - } - - location ~* \.(png|jpg|jpeg|gif|webp|svg|ico)$ { - root /usr/share/nginx/html; - try_files $uri =404; - add_header Cache-Control "public, max-age=86400" always; - } - - location = /Cards.svg { - default_type image/svg+xml; - alias /usr/share/nginx/html/Cards.svg; - add_header Cache-Control "public, max-age=86400" always; - } - - location = /cards.svg { - default_type image/svg+xml; - alias /usr/share/nginx/html/Cards.svg; - add_header Cache-Control "public, max-age=86400" always; - } - - location / { - root /usr/share/nginx/html; - try_files $uri $uri/ @backend; - } - - location @backend { - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - add_header Cache-Control "no-store" always; - } - - # Serve Apple App Site Association for Universal Links - location = /apple-app-site-association { - default_type application/json; - alias /usr/share/nginx/html/apple-app-site-association; - } - - # Serve Android assetlinks (App Links) - location = /.well-known/assetlinks.json { - default_type application/json; - alias /usr/share/nginx/html/.well-known/assetlinks.json; - } - - location /api/ { - limit_req zone=api_limit burst=120 nodelay; - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - add_header Cache-Control "no-store" always; - } - - location = /admin { - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - add_header Cache-Control "no-store" always; - } - - location ^~ /admin/ { - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - add_header Cache-Control "no-store" always; - } - - location = /api/auth/login { - limit_req zone=auth_limit burst=40 nodelay; - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - add_header Cache-Control "no-store" always; - } - - location = /api/auth/register { - limit_req zone=auth_limit burst=40 nodelay; - proxy_pass http://backend_upstream; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache off; - proxy_cache_bypass 1; - proxy_no_cache 1; - add_header Cache-Control "no-store" always; - } + return 444; } # Redirect all HTTP traffic to HTTPS for production domain @@ -279,6 +80,12 @@ http { return 301 https://$host$request_uri; } + server { + listen 443 ssl default_server; + server_name _; + ssl_reject_handshake on; + } + # HTTPS server server { listen 443 ssl http2; @@ -292,6 +99,10 @@ http { return 444; } + location ~ /\.(?!well-known/) { + return 444; + } + # SSL Certificate ssl_certificate /etc/letsencrypt/live/devbits.ddns.net/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/devbits.ddns.net/privkey.pem; @@ -318,7 +129,7 @@ http { location ~* ^/(media/upload|users/.+/(profile-picture|update))$ { client_max_body_size 64m; - client_body_timeout 180s; + client_body_timeout 30s; proxy_pass http://backend_upstream; proxy_http_version 1.1; proxy_set_header Connection ""; @@ -331,8 +142,8 @@ http { proxy_no_cache 1; proxy_request_buffering on; proxy_buffering on; - proxy_read_timeout 180s; - proxy_send_timeout 180s; + proxy_read_timeout 30s; + proxy_send_timeout 30s; add_header Cache-Control "no-store" always; } @@ -349,8 +160,8 @@ http { proxy_no_cache 1; proxy_request_buffering on; proxy_buffering on; - proxy_read_timeout 180s; - proxy_send_timeout 180s; + proxy_read_timeout 30s; + proxy_send_timeout 30s; add_header Cache-Control "no-store" always; } From e6440297ee19184c163df74136f319732d949970 Mon Sep 17 00:00:00 2001 From: Eli Date: Thu, 23 Apr 2026 01:32:59 -0400 Subject: [PATCH 4/7] fixed --- backend/api/admin/console.html | 21 +- backend/api/admin/index.html | 61 +-- backend/api/admin/static/admin.css | 795 ++++++++--------------------- backend/api/admin/static/admin.js | 751 ++++++++++++++------------- backend/api/admin/static/login.js | 3 +- 5 files changed, 623 insertions(+), 1008 deletions(-) diff --git a/backend/api/admin/console.html b/backend/api/admin/console.html index 0889fac..2c1a7de 100644 --- a/backend/api/admin/console.html +++ b/backend/api/admin/console.html @@ -7,26 +7,13 @@ - - - + - - - - +
@@ -34,4 +21,4 @@ - + \ No newline at end of file diff --git a/backend/api/admin/index.html b/backend/api/admin/index.html index fe10b16..7d77dcc 100644 --- a/backend/api/admin/index.html +++ b/backend/api/admin/index.html @@ -7,80 +7,47 @@ - - - + - -
-
); } -// Topbar Search -function TopSearch({ onSearch }) { - const [query, setQuery] = useState(''); - const [results, setResults] = useState({}); - const [showDropdown, setShowDropdown] = useState(false); - const timeoutRef = useRef(); - - const debouncedSearch = useCallback(debounce(async (q) => { - if (!q) return setResults({}); - const [users, bytes, streams, bits] = await Promise.all([ - api(`/admin/users?q=${q}`).catch(() => []), - api(`/admin/posts?q=${q}`).catch(() => []), - api(`/admin/projects?q=${q}`).catch(() => []), - api(`/admin/comments?q=${q}`).catch(() => []) - ]); - setResults({ users, bytes: bytes, streams, bits }); - setShowDropdown(true); - }, 220), []); +function TopSearch({ onPick, addToast }) { + const [query, setQuery] = useState(""); + const [results, setResults] = useState({ users: [], posts: [], projects: [], comments: [] }); + const [open, setOpen] = useState(false); useEffect(() => { - clearTimeout(timeoutRef.current); - timeoutRef.current = setTimeout(() => debouncedSearch(query), 220); - return () => clearTimeout(timeoutRef.current); - }, [query]); - - function debounce(fn, ms) { - return (...args) => { - clearTimeout(timeoutRef.current); - timeoutRef.current = setTimeout(() => fn(...args), ms); - }; - } + const cleaned = query.trim(); + if (!cleaned) { + setResults({ users: [], posts: [], projects: [], comments: [] }); + return; + } - const sections = [ - { label: 'Users', items: results.users || [] }, - { label: 'Bytes', items: results.bytes || [] }, - { label: 'Streams', items: results.streams || [] }, - { label: 'Bits', items: results.bits || [] } - ]; + const timer = setTimeout(async () => { + try { + const [users, posts, projects, comments] = await Promise.all([ + api(`/admin/users?q=${encodeURIComponent(cleaned)}`).catch(() => []), + api(`/admin/posts?q=${encodeURIComponent(cleaned)}`).catch(() => []), + api(`/admin/projects?q=${encodeURIComponent(cleaned)}`).catch(() => []), + api(`/admin/comments?q=${encodeURIComponent(cleaned)}`).catch(() => []), + ]); + setResults({ + users: normalizeListPayload(users), + posts: normalizeListPayload(posts), + projects: normalizeListPayload(projects), + comments: normalizeListPayload(comments), + }); + } catch (error) { + addToast(error.message, "error"); + } + }, 240); + + return () => clearTimeout(timer); + }, [query, addToast]); + + const groups = useMemo( + () => [ + { label: "Users", key: "users" }, + { label: "Bytes", key: "posts" }, + { label: "Streams", key: "projects" }, + { label: "Bits", key: "comments" }, + ], + [] + ); + + const hasResults = groups.some((group) => (results[group.key] || []).length); return (
- setQuery(e.target.value)} - onFocus={() => setShowDropdown(true)} + setQuery(e.target.value)} + onFocus={() => setOpen(true)} + onBlur={() => { + window.setTimeout(() => setOpen(false), 120); + }} /> - {showDropdown && Object.values(results).some(arr => arr.length) && ( -
- {sections.map(({label, items}) => items?.length ? ( -
-
{label}
- {items.slice(0,5).map(item => ( -
{ - setSelectedGlobal(item); setShowDropdown(false); - }}> - {item.username || item.title || item.content?.slice(0,50)} -
- ))} -
- ) : null)} + {open && query.trim() && hasResults ? ( +
setOpen(false)}> + {groups.map((group) => { + const items = results[group.key] || []; + if (!items.length) return null; + return ( +
+
{group.label}
+ {items.slice(0, 5).map((item) => ( +
onPick(item)}> + {item.username || item.title || item.content || `ID ${item.id}`} +
+ ))} +
+ ); + })}
- )} + ) : null}
); } -// SidebarNavigationSlim -function SidebarNavigationSlim({ activePage, onNavigate, authLabel, onRefresh, onSignOut }) { - return ( - - ); -} - -// Main App function App() { - const [activePage, setActivePage] = useState('dashboard'); - const [user, setUser] = useState(null); - const toasts = useRef([]); - const [selectedGlobal, setSelectedGlobal] = useState(null); - - const navigate = useCallback((hash) => { - const page = hash.split('/')[1] || 'dashboard'; - if (PAGES.includes(page)) setActivePage(page); - window.location.hash = hash; + const [activePage, setActivePage] = useState("dashboard"); + const [adminMe, setAdminMe] = useState(null); + const [toasts, setToasts] = useState([]); + const [modalEntity, setModalEntity] = useState(null); + const [sidebarOpen, setSidebarOpen] = useState(false); + + const addToast = useCallback((message, type = "info") => { + const id = Date.now() + Math.random(); + setToasts((prev) => [...prev, { id, message, type }]); + window.setTimeout(() => { + setToasts((prev) => prev.filter((t) => t.id !== id)); + }, 4000); }, []); useEffect(() => { - const me = async () => { - try { - const data = await api('/admin/me'); - setUser(data); - } catch {} + api("/admin/me") + .then((data) => setAdminMe(data)) + .catch(() => {}); + + const syncHash = () => { + const rawPage = window.location.hash.replace("#/", "") || "dashboard"; + const page = PAGE_ALIASES[rawPage] || rawPage; + if (NAV_ITEMS.includes(page)) setActivePage(page); + else { + setActivePage("dashboard"); + window.location.hash = "#/dashboard"; + } }; - me(); - }, []); - useEffect(() => { - const handler = () => { - const page = window.location.hash.split('/')[1] || 'dashboard'; - if (PAGES.includes(page)) setActivePage(page); - }; - window.addEventListener('hashchange', handler); - handler(); - return () => window.removeEventListener('hashchange', handler); - }, []); - - const PageComponent = activePage === 'dashboard' ? DashboardPage : () => ; + window.addEventListener("hashchange", syncHash); + syncHash(); - const dismissToast = useCallback(id => { - toasts.current = toasts.current.filter(t => t.id !== id); - // Force re-render via key + return () => window.removeEventListener("hashchange", syncHash); }, []); + const navigate = (page) => { + setActivePage(page); + window.location.hash = `#/${page}`; + setSidebarOpen(false); + }; + return ( <> -
- window.location.reload()} - onSignOut={() => { - sessionStorage.clear(); - window.location.href = '/admin'; - }} - /> +
+ +
+ setSidebarOpen((v) => !v)} className="mobile-nav-toggle"> + Menu + DevBits -
{activePage.charAt(0).toUpperCase() + activePage.slice(1)}
+ {activePage === "posts" ? "Bytes" : activePage === "projects" ? "Streams" : activePage === "comments" ? "Bits" : activePage.charAt(0).toUpperCase() + activePage.slice(1)}
- - window.location.reload()}> - - + + window.location.reload()}>↻
- + + {activePage === "dashboard" ? ( + + ) : ( + + )}
- - setSelectedGlobal(null)} /> + + setToasts((prev) => prev.filter((t) => t.id !== id))} /> + setModalEntity(null)} + /> ); } -// Mount -const root = ReactDOM.createRoot(document.getElementById('admin-app')); -root.render(); +const root = ReactDOM.createRoot(document.getElementById("admin-app")); +root.render(); \ No newline at end of file diff --git a/backend/api/admin/static/login.js b/backend/api/admin/static/login.js index a9e3cd6..49a0e78 100644 --- a/backend/api/admin/static/login.js +++ b/backend/api/admin/static/login.js @@ -84,6 +84,7 @@ function setStatus(message, isError) { if (!statusEl) return; statusEl.textContent = message || ""; statusEl.classList.toggle("error", !!isError); + statusEl.classList.toggle("success", !!message && !isError); } function wait(ms) { @@ -140,4 +141,4 @@ if (passwordToggle && passwordInput) { if (form) { form.addEventListener("submit", handleSignIn); -} +} \ No newline at end of file From 4c0fb3d4b551ee863c8c64d72d6795709f96d9d8 Mon Sep 17 00:00:00 2001 From: Eli Date: Thu, 23 Apr 2026 01:59:34 -0400 Subject: [PATCH 5/7] pERfect --- backend/api/admin/static/admin-icons.js | 60 -- backend/api/admin/static/admin.css | 782 ++++++++++++++++++------ backend/api/admin/static/admin.js | 478 ++++++++++----- 3 files changed, 928 insertions(+), 392 deletions(-) delete mode 100644 backend/api/admin/static/admin-icons.js diff --git a/backend/api/admin/static/admin-icons.js b/backend/api/admin/static/admin-icons.js deleted file mode 100644 index 8788fb1..0000000 --- a/backend/api/admin/static/admin-icons.js +++ /dev/null @@ -1,60 +0,0 @@ -// SVG Icons for UntitledUI-style sidebar (React components) -const Icons = { - HomeLine: ({ className = 'w-5 h-5' }) => ( - - - - - ), - BarChartSquare02: ({ className = 'w-5 h-5' }) => ( - - - - - - - ), - Users01: ({ className = 'w-5 h-5' }) => ( - - - - - - - ), - Rows01: ({ className = 'w-5 h-5' }) => ( - - - - - - ), - CheckDone01: ({ className = 'w-5 h-5' }) => ( - - - - ), - PieChart03: ({ className = 'w-5 h-5' }) => ( - - - - - ), - Settings01: ({ className = 'w-5 h-5' }) => ( - - - - - ), - LifeBuoy01: ({ className = 'w-5 h-5' }) => ( - - - - - - - ) -}; - -// Usage: - diff --git a/backend/api/admin/static/admin.css b/backend/api/admin/static/admin.css index b449332..0e14ce2 100644 --- a/backend/api/admin/static/admin.css +++ b/backend/api/admin/static/admin.css @@ -1,277 +1,707 @@ :root { color-scheme: dark; - --bg: #060b12; - --bg-elev: #0e1522; - --bg-card: #111a2a; - --bg-soft: #172236; - --text: #edf2ff; - --muted: #94a3b8; - --line: #24324a; - --brand: #34d399; - --brand-strong: #10b981; - --danger: #fb7185; - --warn: #fbbf24; - --shadow: 0 14px 40px rgba(0, 0, 0, 0.35); - --radius: 14px; + --db-text: #F0F3F7; + --db-background: #05070A; + --db-surface: #10141A; + --db-surface-alt: #0C1016; + --db-tint: #00F329; + --db-on-tint: #0B0D10; + --db-muted: #94A0AF; + --db-border: #1F2732; + --db-danger: #EF4444; + --db-danger-soft: rgba(239, 68, 68, 0.18); + --db-shadow: 0 14px 34px rgba(0, 0, 0, 0.32); + --db-radius-sm: 10px; + --db-radius-md: 12px; + --db-radius-lg: 16px; + --db-duration: 180ms; + --db-duration-slow: 260ms; } * { box-sizing: border-box; } -html, body { margin: 0; min-height: 100%; } + +html, +body { + margin: 0; + min-height: 100%; +} + body { font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; - background: radial-gradient(1200px circle at 10% -5%, rgba(52,211,153,.12), transparent 40%), var(--bg); - color: var(--text); + font-size: 15px; + line-height: 1.45; + color: var(--db-text); + background: var(--db-background); } -h1,h2,h3,p { margin: 0; } -button,input { font: inherit; } +h1, h2, h3, p { margin: 0; } +button, input { font: inherit; } .sr-only { - border: 0; clip: rect(0, 0, 0, 0); height: 1px; margin: -1px; - overflow: hidden; padding: 0; position: absolute; width: 1px; + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; } .admin-atmosphere { - position: fixed; inset: 0; pointer-events: none; - background: - radial-gradient(500px circle at 80% 8%, rgba(59,130,246,.15), transparent 48%), - radial-gradient(600px circle at 20% 100%, rgba(52,211,153,.14), transparent 55%); + position: fixed; + inset: 0; + pointer-events: none; z-index: 0; + background: + radial-gradient(600px circle at 4% -10%, rgba(0, 243, 41, 0.13), transparent 52%), + radial-gradient(500px circle at 88% 6%, rgba(148, 160, 175, 0.09), transparent 45%); } -/* Login */ +/* LOGIN (mirrors mobile sign-in hierarchy, adapted for desktop) */ .admin-login-page { overflow: hidden; } -.login-shell { min-height: 100vh; display: grid; place-items: center; padding: 24px; position: relative; z-index: 1; } + +.login-shell { + min-height: 100vh; + display: grid; + place-items: center; + padding: 24px; + position: relative; + z-index: 1; +} + .login-card { width: min(460px, 100%); - background: rgba(17, 26, 42, 0.9); - border: 1px solid var(--line); - border-radius: 20px; - box-shadow: var(--shadow); - padding: 28px; display: grid; gap: 12px; + padding: 24px; + border: 1px solid var(--db-border); + border-radius: var(--db-radius-lg); + background: color-mix(in srgb, var(--db-surface), transparent 4%); + box-shadow: var(--db-shadow); +} + +.login-logo { + width: 72px; + height: 72px; + border-radius: 16px; + border: 1px solid var(--db-border); + margin-bottom: 4px; +} + +.login-title { + font-size: 28px; + line-height: 32px; + font-weight: 700; } -.login-logo { width: 72px; height: 72px; border-radius: 16px; border: 1px solid var(--line); margin: 0 auto 4px; } -.login-title { text-align: center; font-family: "Space Mono", monospace; font-size: 28px; } -.login-caption { text-align: center; color: var(--brand); font-weight: 600; } -.login-subtitle { text-align: center; color: var(--muted); font-size: 14px; margin-bottom: 8px; } -.login-form { display: grid; gap: 12px; } -.password-row { display: grid; grid-template-columns: 1fr auto; gap: 8px; } -.login-status { min-height: 20px; font-size: 14px; color: var(--muted); text-align: center; } -.login-status.error { color: var(--danger); } -.login-status.success { color: var(--brand); } - -/* Controls */ -.admin-input, .search-input { + +.login-caption, +.login-subtitle, +.login-status { + font-size: 12px; + line-height: 16px; + color: var(--db-muted); +} + +.login-form { + display: grid; + gap: 12px; + margin-top: 6px; +} + +.password-row { + display: grid; + grid-template-columns: 1fr auto; + gap: 8px; +} + +.login-status { + min-height: 16px; +} + +.login-status.error { color: #FB7185; } +.login-status.success { color: var(--db-tint); } + +/* COMMON CONTROLS */ +.admin-input, +.search-input { width: 100%; - border-radius: 12px; - border: 1px solid var(--line); - background: var(--bg-elev); - color: var(--text); - padding: 12px 14px; - transition: border-color .2s ease, transform .2s ease, background .2s ease; -} -.admin-input:focus, .search-input:focus { + border: 1px solid var(--db-border); + border-radius: var(--db-radius-md); + background: var(--db-surface); + color: var(--db-text); + padding: 10px 12px; + font-size: 15px; + line-height: 22px; + font-family: "Space Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, monospace; + transition: border-color var(--db-duration) ease, transform var(--db-duration) ease; +} + +.admin-input::placeholder, +.search-input::placeholder { + color: var(--db-muted); +} + +.admin-input:focus, +.search-input:focus { outline: none; - border-color: var(--brand); - background: #102033; + border-color: var(--db-tint); } -.flat-btn, .btn { - border: 1px solid var(--line); - color: var(--text); - background: var(--bg-elev); - border-radius: 12px; - padding: 10px 14px; - cursor: pointer; +.btn, +.flat-btn { + appearance: none; + border: 1px solid var(--db-border); + background: var(--db-surface); + color: var(--db-text); + border-radius: var(--db-radius-md); + padding: 10px 12px; font-weight: 600; - transition: transform .2s ease, border-color .2s ease, background .2s ease; + cursor: pointer; + transition: + transform var(--db-duration) ease, + border-color var(--db-duration) ease, + background-color var(--db-duration) ease, + box-shadow var(--db-duration) ease; +} + +.btn:hover, +.flat-btn:hover { + transform: translateY(-1px); + border-color: color-mix(in srgb, var(--db-border), var(--db-tint) 40%); +} + +.btn:active, +.flat-btn:active { + transform: translateY(0) scale(0.985); +} + +.btn:focus-visible, +.flat-btn:focus-visible, +.nav-item:focus-visible, +.search-result:focus-visible { + outline: 2px solid color-mix(in srgb, var(--db-tint), white 10%); + outline-offset: 1px; +} + +.btn--primary { + background: var(--db-tint); + color: var(--db-on-tint); + border-color: transparent; +} + +.btn--small { + padding: 8px 10px; + font-size: 13px; + line-height: 16px; +} + +.btn.danger { + color: #FFD9DF; + border-color: color-mix(in srgb, var(--db-danger), var(--db-border) 40%); + background: var(--db-danger-soft); +} + +.btn.is-loading { + opacity: 0.82; + pointer-events: none; +} + +/* LAYOUT */ +.admin-root { + position: relative; + z-index: 1; + min-height: 100vh; + display: grid; + grid-template-columns: 272px 1fr; } -.flat-btn:hover, .btn:hover { transform: translateY(-1px); border-color: var(--brand); } -.btn--primary { background: linear-gradient(180deg, var(--brand), var(--brand-strong)); color: #042014; border: none; } -.btn--small { padding: 8px 10px; font-size: 13px; } -.btn.danger { border-color: rgba(251,113,133,.55); color: #ffd9df; background: rgba(127,29,29,.25); } -.btn.is-loading { opacity: .8; pointer-events: none; } -/* Console layout */ -.admin-root { position: relative; z-index: 1; min-height: 100vh; display: grid; grid-template-columns: 270px 1fr; } .admin-sidebar { - border-right: 1px solid var(--line); - background: rgba(10, 17, 30, 0.96); - backdrop-filter: blur(6px); - padding: 18px; + border-right: 1px solid var(--db-border); + background: color-mix(in srgb, var(--db-background), black 4%); + padding: 16px; display: flex; flex-direction: column; gap: 12px; } -.sidebar-brand { display: flex; align-items: center; gap: 10px; font-family: "Space Mono", monospace; font-weight: 700; } -.sidebar-brand img { width: 36px; height: 36px; border-radius: 10px; border: 1px solid var(--line); } -.sidebar-user { border: 1px solid var(--line); border-radius: 12px; padding: 10px; color: var(--muted); } -.sidebar-user strong { color: var(--text); display: block; margin-top: 4px; font-size: 14px; } -.nav-list { display: grid; gap: 8px; } -.nav-item { + +.sidebar-brand { display: flex; align-items: center; gap: 10px; - padding: 10px 12px; - border-radius: 12px; + font-family: "Space Mono", ui-monospace, monospace; + font-weight: 700; +} + +.sidebar-brand img { + width: 34px; + height: 34px; + border-radius: 10px; + border: 1px solid var(--db-border); +} + +.sidebar-user { + border: 1px solid var(--db-border); + border-radius: var(--db-radius-md); + padding: 10px; + color: var(--db-muted); + font-size: 13px; +} + +.sidebar-user strong { + margin-top: 4px; + display: block; + color: var(--db-text); +} + +.nav-list { + display: grid; + gap: 8px; +} + +.nav-item { + appearance: none; border: 1px solid transparent; background: transparent; - color: #d8e3f4; + color: var(--db-text); + border-radius: var(--db-radius-md); + padding: 10px; + display: flex; + align-items: center; + gap: 10px; cursor: pointer; text-align: left; + transition: all var(--db-duration) ease; +} + +.nav-item:hover { + border-color: var(--db-border); + background: var(--db-surface-alt); +} + +.nav-item.active { + border-color: color-mix(in srgb, var(--db-tint), var(--db-border) 55%); + background: color-mix(in srgb, var(--db-surface-alt), var(--db-tint) 10%); +} + +.nav-icon { + width: 17px; + height: 17px; + flex-shrink: 0; +} + +.sidebar-footer { + margin-top: auto; + display: grid; + gap: 8px; +} + +.admin-main { + min-width: 0; + padding: 16px; } -.nav-item:hover { border-color: var(--line); background: var(--bg-elev); } -.nav-item.active { border-color: rgba(52,211,153,.45); background: rgba(52,211,153,.15); color: #b8ffe2; } -.sidebar-footer { margin-top: auto; display: grid; gap: 8px; } -.admin-main { padding: 20px; min-width: 0; } .admin-topbar { - border: 1px solid var(--line); - background: rgba(14, 21, 34, 0.9); - border-radius: var(--radius); - padding: 12px 14px; + border: 1px solid var(--db-border); + border-radius: var(--db-radius-lg); + background: color-mix(in srgb, var(--db-surface), black 8%); + padding: 10px 12px; + position: sticky; + top: 10px; + z-index: 4; display: flex; align-items: center; justify-content: space-between; - gap: 12px; - position: sticky; - top: 12px; - z-index: 5; + gap: 10px; +} + +.topbar-left { + display: flex; + align-items: center; + gap: 10px; + font-weight: 600; +} + +.topbar-left img { + width: 26px; + height: 26px; + border-radius: 8px; +} + +.topbar-actions { + width: min(600px, 100%); + display: flex; + align-items: center; + gap: 8px; +} + +.search-wrap { + position: relative; + flex: 1; } -.topbar-left { display: flex; align-items: center; gap: 10px; font-weight: 700; } -.topbar-left img { width: 28px; height: 28px; border-radius: 8px; } -.topbar-actions { display: flex; align-items: center; gap: 8px; width: min(560px, 100%); } -.search-wrap { position: relative; flex: 1; } + .search-dropdown { - position: absolute; left: 0; right: 0; top: calc(100% + 8px); - border: 1px solid var(--line); border-radius: 12px; background: var(--bg-card); - max-height: 360px; overflow: auto; box-shadow: var(--shadow); + position: absolute; + left: 0; + right: 0; + top: calc(100% + 8px); + border: 1px solid var(--db-border); + border-radius: var(--db-radius-md); + background: color-mix(in srgb, var(--db-surface), black 8%); + box-shadow: var(--db-shadow); + max-height: 350px; + overflow-y: auto; + z-index: 14; +} + +.search-group-title { + padding: 7px 10px; + font-size: 11px; + color: var(--db-muted); + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.search-result { + width: 100%; + border: 0; + border-top: 1px solid color-mix(in srgb, var(--db-border), transparent 42%); + background: transparent; + color: var(--db-text); + text-align: left; + padding: 9px 10px; + cursor: pointer; +} + +.search-result:hover { + background: var(--db-surface-alt); +} + +/* CONTENT */ +.page { + margin-top: 12px; + display: grid; + gap: 12px; } -.search-group-title { padding: 8px 12px; color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .08em; } -.search-result { padding: 10px 12px; border-top: 1px solid rgba(148,163,184,.12); cursor: pointer; } -.search-result:hover { background: var(--bg-soft); } -.page { margin-top: 14px; display: grid; gap: 14px; } .section-card { - background: rgba(17, 26, 42, 0.9); - border: 1px solid var(--line); - border-radius: var(--radius); - box-shadow: var(--shadow); - padding: 14px; - animation: fadeSlide .3s ease; + border: 1px solid var(--db-border); + border-radius: var(--db-radius-lg); + background: color-mix(in srgb, var(--db-surface), black 5%); + box-shadow: var(--db-shadow); + padding: 12px; +} + +.section-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 10px; +} + +.section-head h2 { + font-size: 24px; + line-height: 28px; +} + +.list-search-row { + display: flex; + align-items: center; + gap: 8px; +} + +.counter-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); + gap: 10px; +} + +.stat-card, +.gauge-card, +.entity-card { + border: 1px solid var(--db-border); + border-radius: var(--db-radius-md); + background: var(--db-surface-alt); } -.section-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; } -.section-head h2 { font-size: 18px; } -.list-search-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } -.counter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 10px; } .stat-card { - border: 1px solid var(--line); - border-radius: 12px; + padding: 10px; +} + +.stat-label { + font-size: 12px; + color: var(--db-muted); + margin-bottom: 6px; +} + +.stat-value { + font-size: 28px; + line-height: 32px; + font-family: "Space Mono", ui-monospace, monospace; +} + +.gauge-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); + gap: 10px; +} + +.gauge-card { padding: 12px; - background: var(--bg-elev); + display: flex; + align-items: center; + gap: 10px; +} + +.gauge-ring { + --gauge: 0%; + width: 64px; + height: 64px; + border-radius: 50%; + background: conic-gradient(var(--db-tint) var(--gauge), color-mix(in srgb, var(--db-border), transparent 30%) 0); + padding: 5px; + transition: background var(--db-duration-slow) ease; +} + +.gauge-inner { + width: 100%; + height: 100%; + border-radius: 50%; + background: var(--db-background); + display: grid; + place-items: center; + font-size: 11px; + font-weight: 700; +} + +.gauge-meta { + display: grid; + gap: 2px; +} + +.gauge-meta strong { + font-size: 13px; +} + +.gauge-meta span { + color: var(--db-muted); + font-size: 12px; +} + +.cards-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 10px; } -.stat-label { color: var(--muted); font-size: 13px; margin-bottom: 6px; } -.stat-value { font-size: 30px; font-weight: 700; font-family: "Space Mono", monospace; } -.cards-grid { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); } .entity-card { - border: 1px solid var(--line); - border-radius: 12px; padding: 12px; - background: var(--bg-elev); display: grid; gap: 8px; - transition: transform .22s ease, border-color .22s ease; + cursor: pointer; + transition: transform var(--db-duration) ease, border-color var(--db-duration) ease; +} + +.entity-card:hover { + transform: translateY(-2px); + border-color: color-mix(in srgb, var(--db-border), var(--db-tint) 35%); +} + +.card-title { + font-weight: 700; + word-break: break-word; +} + +.card-meta { + color: var(--db-muted); + font-size: 12px; + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.card-preview { + color: var(--db-text); + font-size: 14px; + opacity: 0.92; + word-break: break-word; +} + +.entity-actions, +.modal-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.badge { + border: 1px solid var(--db-border); + border-radius: 999px; + padding: 2px 8px; +} + +.badge.success { + border-color: color-mix(in srgb, var(--db-tint), var(--db-border) 56%); + color: color-mix(in srgb, var(--db-tint), white 18%); +} + +.badge.warn { + border-color: color-mix(in srgb, #FBBF24, var(--db-border) 40%); + color: #FBBF24; } -.entity-card:hover { transform: translateY(-2px); border-color: rgba(52,211,153,.5); } -.card-title { font-weight: 700; word-break: break-word; } -.card-meta { color: var(--muted); font-size: 12px; display: flex; flex-wrap: wrap; gap: 8px; } -.card-preview { color: #d9e4f4; font-size: 14px; line-height: 1.4; word-break: break-word; } -.entity-actions { display: flex; gap: 6px; flex-wrap: wrap; } -.badge { border: 1px solid var(--line); border-radius: 999px; padding: 2px 8px; font-size: 12px; color: var(--muted); } -.badge.success { color: #9ff2cf; border-color: rgba(52,211,153,.4); } -.badge.warn { color: #ffdfa0; border-color: rgba(251,191,36,.4); } .empty-state { - border: 1px dashed var(--line); - border-radius: 12px; - padding: 22px; + border: 1px dashed var(--db-border); + border-radius: var(--db-radius-md); + padding: 20px; text-align: center; - color: var(--muted); + color: var(--db-muted); } +/* TOAST + MODAL */ .toast-stack { position: fixed; - right: 16px; - top: 16px; - z-index: 50; + top: 14px; + right: 14px; + z-index: 30; display: grid; gap: 8px; } + .toast { min-width: 280px; - max-width: 400px; - border: 1px solid var(--line); - border-radius: 12px; - background: var(--bg-card); - padding: 10px 12px; + max-width: 420px; + border: 1px solid var(--db-border); + border-radius: var(--db-radius-md); + background: color-mix(in srgb, var(--db-surface), black 6%); display: flex; align-items: center; - gap: 10px; - box-shadow: var(--shadow); + gap: 8px; + padding: 10px; } -.toast--error { border-left: 4px solid var(--danger); } -.toast--success { border-left: 4px solid var(--brand); } + +.toast-message { flex: 1; } + +.toast--error { border-left: 4px solid #FB7185; } +.toast--success { border-left: 4px solid var(--db-tint); } .record-overlay { - position: fixed; inset: 0; z-index: 45; - background: rgba(2, 8, 20, 0.68); - display: grid; place-items: center; - padding: 16px; + position: fixed; + inset: 0; + z-index: 26; + background: rgba(0, 0, 0, 0.64); + display: grid; + place-items: center; + padding: 14px; } + .record-modal { - width: min(900px, 100%); - max-height: 80vh; + width: min(960px, 100%); + max-height: 82vh; overflow: auto; - border: 1px solid var(--line); - border-radius: 16px; - background: var(--bg-card); + border: 1px solid var(--db-border); + border-radius: var(--db-radius-lg); + background: color-mix(in srgb, var(--db-surface), black 5%); } -.modal-header { padding: 12px; border-bottom: 1px solid var(--line); display: flex; align-items: center; justify-content: space-between; } -.modal-fields { padding: 12px; font-family: "Space Mono", monospace; font-size: 13px; white-space: pre-wrap; word-break: break-word; } -.mobile-nav-toggle { display: none; } +.modal-header { + position: sticky; + top: 0; + border-bottom: 1px solid var(--db-border); + background: color-mix(in srgb, var(--db-surface), black 5%); + padding: 12px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} -.reveal { animation: fadeSlide .42s cubic-bezier(.2,.8,.2,1) both; } -.reveal-1 { animation-delay: .05s; } +.modal-actions { + padding: 10px 12px; + border-bottom: 1px solid var(--db-border); +} + +.modal-fields { + margin: 0; + padding: 12px; + color: var(--db-text); + font-family: "Space Mono", ui-monospace, monospace; + font-size: 13px; + line-height: 19px; + white-space: pre-wrap; + word-break: break-word; +} + +.mobile-nav-toggle { + display: none; +} -@keyframes fadeSlide { - from { opacity: 0; transform: translateY(8px) scale(.99); } - to { opacity: 1; transform: translateY(0) scale(1); } +.reveal { + animation: revealIn var(--db-duration-slow) cubic-bezier(.22,.61,.36,1) both; +} + +@keyframes revealIn { + from { + opacity: 0; + transform: translateY(8px); + } + to { + opacity: 1; + transform: translateY(0); + } } @media (max-width: 980px) { - .admin-root { grid-template-columns: 1fr; } + .admin-root { + grid-template-columns: 1fr; + } + .admin-sidebar { position: fixed; - left: 0; top: 0; + left: 0; bottom: 0; - width: 270px; + width: 272px; + z-index: 18; transform: translateX(-100%); - transition: transform .25s ease; - z-index: 10; + transition: transform var(--db-duration-slow) ease; + } + + .admin-root.sidebar-open .admin-sidebar { + transform: translateX(0); + } + + .mobile-nav-toggle { + display: inline-flex; } - .admin-root.sidebar-open .admin-sidebar { transform: translateX(0); } - .mobile-nav-toggle { display: inline-flex; } } @media (max-width: 768px) { - .admin-main { padding: 12px; } - .admin-topbar { flex-wrap: wrap; } - .topbar-actions { width: 100%; } - .cards-grid { grid-template-columns: 1fr; } + .admin-main { + padding: 12px; + } + + .admin-topbar { + flex-wrap: wrap; + } + + .topbar-actions { + width: 100%; + } + + .list-search-row { + width: 100%; + } + + .cards-grid, + .counter-grid, + .gauge-grid { + grid-template-columns: 1fr; + } + + .toast { + min-width: 0; + width: min(90vw, 420px); + } } \ No newline at end of file diff --git a/backend/api/admin/static/admin.js b/backend/api/admin/static/admin.js index e8fd52f..77570b1 100644 --- a/backend/api/admin/static/admin.js +++ b/backend/api/admin/static/admin.js @@ -1,38 +1,109 @@ /** @jsxRuntime classic */ /** @jsx React.createElement */ -const { useState, useEffect, useMemo, useCallback } = React; +const { useCallback, useEffect, useMemo, useRef, useState } = React; const ENTITY_CONFIG = { users: { title: "Users", listPath: "/admin/users", deletePath: (entity) => `/admin/users/${encodeURIComponent(entity.username)}`, + key: (entity) => entity.username || entity.id, + preview: (entity) => entity.bio || "No bio.", }, posts: { title: "Bytes", listPath: "/admin/posts", deletePath: (entity) => `/admin/posts/${entity.id}`, + key: (entity) => entity.id, + preview: (entity) => entity.content || "No content.", }, projects: { title: "Streams", listPath: "/admin/projects", deletePath: (entity) => `/admin/projects/${entity.id}`, + key: (entity) => entity.id, + preview: (entity) => entity.description || entity.content || "No description.", }, comments: { title: "Bits", listPath: "/admin/comments", deletePath: (entity) => `/admin/comments/${entity.id}`, + key: (entity) => entity.id, + preview: (entity) => entity.content || "No comment text.", }, }; -const NAV_ITEMS = ["dashboard", "users", "posts", "projects", "comments"]; +const NAV_ITEMS = [ + { key: "dashboard", label: "Dashboard", icon: IconDashboard }, + { key: "users", label: "Users", icon: IconUsers }, + { key: "posts", label: "Bytes", icon: IconPosts }, + { key: "projects", label: "Streams", icon: IconProjects }, + { key: "comments", label: "Bits", icon: IconComments }, +]; + const PAGE_ALIASES = { bytes: "posts", streams: "projects", bits: "comments", }; +function SvgIcon({ children, className = "" }) { + return ( + + ); +} + +function IconDashboard() { + return ( + + + + + + ); +} + +function IconUsers() { + return ( + + + + + + + ); +} + +function IconPosts() { + return ( + + + + + + ); +} + +function IconProjects() { + return ( + + + + + ); +} + +function IconComments() { + return ( + + + + ); +} + function getStoredAuth() { return sessionStorage.getItem("devbits_admin_token") || sessionStorage.getItem("devbits_admin_key") || ""; } @@ -52,14 +123,14 @@ async function api(path, options = {}) { throw new Error("Not authenticated"); } - const payload = options.body ? JSON.stringify(options.body) : undefined; const response = await fetch(path, { ...options, - body: payload, + body: options.body ? JSON.stringify(options.body) : undefined, headers: { ...authHeaders(), ...(options.headers || {}) }, }); const data = await response.clone().json().catch(() => null); + if (response.status === 401 || response.status === 403) { sessionStorage.clear(); window.location.href = "/admin"; @@ -79,23 +150,13 @@ function normalizeListPayload(data) { return []; } -function iconFor(page) { - const map = { - dashboard: "📊", - users: "👥", - posts: "🧩", - projects: "🚀", - comments: "💬", - }; - return map[page] || "•"; -} - -function FlatButton({ children, onClick, danger, busy, size = "", className = "" }) { - const cls = ["btn", danger ? "danger" : "", busy ? "is-loading" : "", size ? `btn--${size}` : "", className] +function FlatButton({ children, onClick, danger, busy, size = "", className = "", type = "button" }) { + const classes = ["btn", size ? `btn--${size}` : "", danger ? "danger" : "", busy ? "is-loading" : "", className] .filter(Boolean) .join(" "); + return ( - ); @@ -103,10 +164,10 @@ function FlatButton({ children, onClick, danger, busy, size = "", className = "" function ToastStack({ toasts, onDismiss }) { return ( -
+
{toasts.map((toast) => (
- {toast.message} +
{toast.message}
onDismiss(toast.id)}>Dismiss
))} @@ -114,15 +175,121 @@ function ToastStack({ toasts, onDismiss }) { ); } -function EntityModal({ title, entity, onClose }) { +function AnimatedCount({ value }) { + const [displayValue, setDisplayValue] = useState(0); + + useEffect(() => { + const target = Number(value) || 0; + const start = displayValue; + const duration = 600; + const started = performance.now(); + let frame = 0; + + const tick = (now) => { + const elapsed = Math.min((now - started) / duration, 1); + const eased = 1 - Math.pow(1 - elapsed, 3); + setDisplayValue(Math.round(start + (target - start) * eased)); + if (elapsed < 1) frame = requestAnimationFrame(tick); + }; + + frame = requestAnimationFrame(tick); + return () => cancelAnimationFrame(frame); + }, [value]); + + return {displayValue.toLocaleString()}; +} + +function Gauge({ label, value, total }) { + const safeTotal = Math.max(total || 0, 1); + const clampedValue = Math.max(0, Math.min(value || 0, safeTotal)); + const percent = Math.round((clampedValue / safeTotal) * 100); + + return ( +
+
+
{percent}%
+
+
+ {label} + {clampedValue} / {safeTotal} +
+
+ ); +} + +function EntityModal({ entityType, entity, onClose, onActionDone, addToast }) { + const [busy, setBusy] = useState(false); + if (!entity) return null; + + const config = ENTITY_CONFIG[entityType]; + + const runDelete = async () => { + if (!window.confirm("Delete this record permanently?")) return; + setBusy(true); + try { + await api(config.deletePath(entity), { method: "DELETE" }); + addToast(`${config.title.slice(0, -1)} deleted`, "success"); + onActionDone(); + onClose(); + } catch (error) { + addToast(error.message, "error"); + } finally { + setBusy(false); + } + }; + + const runUserAction = async (action) => { + setBusy(true); + try { + if (action === "toggle-admin") { + await api(`/admin/users/${encodeURIComponent(entity.username)}/admin`, { + method: "POST", + body: { is_admin: !entity.is_admin }, + }); + } + if (action === "toggle-ban") { + if (entity.ban_until) { + await api(`/admin/users/${encodeURIComponent(entity.username)}/unban`, { method: "POST" }); + } else { + await api(`/admin/users/${encodeURIComponent(entity.username)}/ban`, { + method: "POST", + body: { reason: "Admin moderation action", duration_minutes: 60 * 24 * 7 }, + }); + } + } + addToast("Action completed", "success"); + onActionDone(); + onClose(); + } catch (error) { + addToast(error.message, "error"); + } finally { + setBusy(false); + } + }; + return (
-
e.stopPropagation()}> +
event.stopPropagation()}>
-

{title} details

+

{config.title.slice(0, -1)} details

Close
+ +
+ {entityType === "users" ? ( + <> + runUserAction("toggle-admin")}> + {entity.is_admin ? "Revoke Admin" : "Grant Admin"} + + runUserAction("toggle-ban")}> + {entity.ban_until ? "Unban" : "Ban 7d"} + + + ) : null} + Delete +
+
{JSON.stringify(entity, null, 2)}
@@ -130,14 +297,23 @@ function EntityModal({ title, entity, onClose }) { } function DashboardPage({ addToast }) { - const [overview, setOverview] = useState(null); const [busy, setBusy] = useState(true); + const [overview, setOverview] = useState(null); + const [derived, setDerived] = useState({ userAdmins: 0, userBanned: 0 }); - const fetchOverview = useCallback(async () => { + const loadDashboard = useCallback(async () => { setBusy(true); try { - const data = await api("/admin/overview"); - setOverview(data); + const [overviewData, users] = await Promise.all([ + api("/admin/overview"), + api("/admin/users").then(normalizeListPayload), + ]); + + const userAdmins = users.filter((user) => user?.is_admin).length; + const userBanned = users.filter((user) => !!user?.ban_until).length; + + setOverview(overviewData); + setDerived({ userAdmins, userBanned }); } catch (error) { addToast(error.message, "error"); } finally { @@ -146,27 +322,38 @@ function DashboardPage({ addToast }) { }, [addToast]); useEffect(() => { - fetchOverview(); - }, [fetchOverview]); + loadDashboard(); + }, [loadDashboard]); const counts = overview?.counts || { users: 0, posts: 0, projects: 0, comments: 0 }; return (
-
+

Platform overview

- Refresh + Refresh
+
-
Users
{counts.users}
-
Bytes (posts)
{counts.posts}
-
Streams (projects)
{counts.projects}
-
Bits (comments)
{counts.comments}
+ + + +
-
+
+

Live admin health

+
+ + + + +
+
+ +

System timestamps

Server: {overview?.server_time || "-"} @@ -177,51 +364,16 @@ function DashboardPage({ addToast }) { ); } -function UserActions({ user, onDone, addToast }) { - const isBanned = !!user.ban_until; - const isAdmin = !!user.is_admin; - - const runAction = async (fn, successMessage) => { - try { - await fn(); - addToast(successMessage, "success"); - onDone(); - } catch (error) { - addToast(error.message, "error"); - } - }; - +function StatCard({ label, value }) { return ( -
- runAction( - () => api(`/admin/users/${encodeURIComponent(user.username)}/admin`, { method: "POST", body: { is_admin: !isAdmin } }), - isAdmin ? "Admin access revoked" : "Admin access granted" - )} - > - {isAdmin ? "Revoke Admin" : "Grant Admin"} - - runAction( - () => isBanned - ? api(`/admin/users/${encodeURIComponent(user.username)}/unban`, { method: "POST" }) - : api(`/admin/users/${encodeURIComponent(user.username)}/ban`, { - method: "POST", - body: { reason: "Admin moderation action", duration_minutes: 60 * 24 * 7 }, - }), - isBanned ? "User unbanned" : "User banned for 7 days" - )} - danger={isBanned} - > - {isBanned ? "Unban" : "Ban 7d"} - +
+
{label}
+
); } -function DataPage({ type, addToast, setModalEntity }) { +function DataPage({ type, addToast, onSelectEntity }) { const config = ENTITY_CONFIG[type]; const [query, setQuery] = useState(""); const [busy, setBusy] = useState(false); @@ -245,20 +397,9 @@ function DataPage({ type, addToast, setModalEntity }) { load(); }, [load]); - const handleDelete = async (entity) => { - if (!window.confirm("Delete this record permanently?")) return; - try { - await api(config.deletePath(entity), { method: "DELETE" }); - addToast(`${config.title.slice(0, -1)} deleted`, "success"); - load(); - } catch (error) { - addToast(error.message, "error"); - } - }; - return (
-
+

{config.title}

@@ -266,8 +407,8 @@ function DataPage({ type, addToast, setModalEntity }) { className="admin-input" placeholder={`Search ${config.title.toLowerCase()}...`} value={query} - onChange={(e) => setQuery(e.target.value)} - onKeyDown={(e) => e.key === "Enter" && load()} + onChange={(event) => setQuery(event.target.value)} + onKeyDown={(event) => event.key === "Enter" && load()} /> Search
@@ -278,23 +419,16 @@ function DataPage({ type, addToast, setModalEntity }) { ) : (
{items.map((entity) => ( -
+
onSelectEntity(entity, type)}>
{entity.title || entity.username || `ID ${entity.id}`}
{entity.creation_date ? Created {entity.creation_date} : null} {entity.ban_until ? Banned until {entity.ban_until} : null} {entity.is_admin ? Admin : null}
-
- {entity.bio || entity.content || entity.description || entity.subtitle || "No preview text."} -
- +
{config.preview(entity)}
- setModalEntity(entity)}>View - {type === "users" ? ( - - ) : null} - handleDelete(entity)}>Delete + Open details
))} @@ -307,8 +441,9 @@ function DataPage({ type, addToast, setModalEntity }) { function TopSearch({ onPick, addToast }) { const [query, setQuery] = useState(""); - const [results, setResults] = useState({ users: [], posts: [], projects: [], comments: [] }); const [open, setOpen] = useState(false); + const [results, setResults] = useState({ users: [], posts: [], projects: [], comments: [] }); + const blurTimer = useRef(0); useEffect(() => { const cleaned = query.trim(); @@ -317,7 +452,7 @@ function TopSearch({ onPick, addToast }) { return; } - const timer = setTimeout(async () => { + const timer = window.setTimeout(async () => { try { const [users, posts, projects, comments] = await Promise.all([ api(`/admin/users?q=${encodeURIComponent(cleaned)}`).catch(() => []), @@ -325,6 +460,7 @@ function TopSearch({ onPick, addToast }) { api(`/admin/projects?q=${encodeURIComponent(cleaned)}`).catch(() => []), api(`/admin/comments?q=${encodeURIComponent(cleaned)}`).catch(() => []), ]); + setResults({ users: normalizeListPayload(users), posts: normalizeListPayload(posts), @@ -334,20 +470,17 @@ function TopSearch({ onPick, addToast }) { } catch (error) { addToast(error.message, "error"); } - }, 240); + }, 250); - return () => clearTimeout(timer); + return () => window.clearTimeout(timer); }, [query, addToast]); - const groups = useMemo( - () => [ - { label: "Users", key: "users" }, - { label: "Bytes", key: "posts" }, - { label: "Streams", key: "projects" }, - { label: "Bits", key: "comments" }, - ], - [] - ); + const groups = [ + { label: "Users", key: "users", type: "users" }, + { label: "Bytes", key: "posts", type: "posts" }, + { label: "Streams", key: "projects", type: "projects" }, + { label: "Bits", key: "comments", type: "comments" }, + ]; const hasResults = groups.some((group) => (results[group.key] || []).length); @@ -357,24 +490,34 @@ function TopSearch({ onPick, addToast }) { className="search-input" placeholder="Global search users, bytes, streams, bits..." value={query} - onChange={(e) => setQuery(e.target.value)} + onChange={(event) => setQuery(event.target.value)} onFocus={() => setOpen(true)} onBlur={() => { - window.setTimeout(() => setOpen(false), 120); + blurTimer.current = window.setTimeout(() => setOpen(false), 140); }} /> + {open && query.trim() && hasResults ? ( -
setOpen(false)}> +
window.clearTimeout(blurTimer.current)}> {groups.map((group) => { - const items = results[group.key] || []; - if (!items.length) return null; + const groupItems = results[group.key] || []; + if (!groupItems.length) return null; + return (
{group.label}
- {items.slice(0, 5).map((item) => ( -
onPick(item)}> + {groupItems.slice(0, 5).map((item) => ( +
+ ))}
); @@ -388,27 +531,28 @@ function TopSearch({ onPick, addToast }) { function App() { const [activePage, setActivePage] = useState("dashboard"); const [adminMe, setAdminMe] = useState(null); - const [toasts, setToasts] = useState([]); - const [modalEntity, setModalEntity] = useState(null); const [sidebarOpen, setSidebarOpen] = useState(false); + const [toasts, setToasts] = useState([]); + const [selectedEntity, setSelectedEntity] = useState(null); + const [selectedEntityType, setSelectedEntityType] = useState("users"); + const [dataRefreshTick, setDataRefreshTick] = useState(0); const addToast = useCallback((message, type = "info") => { const id = Date.now() + Math.random(); - setToasts((prev) => [...prev, { id, message, type }]); + setToasts((current) => [...current, { id, message, type }]); window.setTimeout(() => { - setToasts((prev) => prev.filter((t) => t.id !== id)); - }, 4000); + setToasts((current) => current.filter((toast) => toast.id !== id)); + }, 4200); }, []); useEffect(() => { - api("/admin/me") - .then((data) => setAdminMe(data)) - .catch(() => {}); + api("/admin/me").then(setAdminMe).catch(() => {}); const syncHash = () => { const rawPage = window.location.hash.replace("#/", "") || "dashboard"; const page = PAGE_ALIASES[rawPage] || rawPage; - if (NAV_ITEMS.includes(page)) setActivePage(page); + const allowed = NAV_ITEMS.map((item) => item.key); + if (allowed.includes(page)) setActivePage(page); else { setActivePage("dashboard"); window.location.hash = "#/dashboard"; @@ -421,12 +565,30 @@ function App() { return () => window.removeEventListener("hashchange", syncHash); }, []); - const navigate = (page) => { + const handleNavigate = (page) => { setActivePage(page); window.location.hash = `#/${page}`; setSidebarOpen(false); }; + const handleSelectEntity = (entity, type) => { + setSelectedEntity(entity); + setSelectedEntityType(type); + }; + + const Page = activePage === "dashboard" ? ( + + ) : ( + + ); + + const currentTitle = NAV_ITEMS.find((item) => item.key === activePage)?.label || "Dashboard"; + return ( <>
@@ -435,27 +597,31 @@ function App() { DevBits DevBits Admin
+
Signed in as {adminMe?.username || "Administrator"}
- window.location.reload()}>Refresh + setDataRefreshTick((value) => value + 1)}>Refresh data { @@ -471,31 +637,31 @@ function App() {
- setSidebarOpen((v) => !v)} className="mobile-nav-toggle"> + setSidebarOpen((value) => !value)}> Menu DevBits - {activePage === "posts" ? "Bytes" : activePage === "projects" ? "Streams" : activePage === "comments" ? "Bits" : activePage.charAt(0).toUpperCase() + activePage.slice(1)} + {currentTitle}
+
- - window.location.reload()}>↻ + + setDataRefreshTick((value) => value + 1)}>Refresh
- {activePage === "dashboard" ? ( - - ) : ( - - )} + {Page}
- setToasts((prev) => prev.filter((t) => t.id !== id))} /> + setToasts((current) => current.filter((toast) => toast.id !== id))} /> + setModalEntity(null)} + entityType={selectedEntityType} + entity={selectedEntity} + onClose={() => setSelectedEntity(null)} + onActionDone={() => setDataRefreshTick((value) => value + 1)} + addToast={addToast} /> ); From af256bd92311667ffdbecf31d80a97a1f82cc0af Mon Sep 17 00:00:00 2001 From: Eli Date: Thu, 23 Apr 2026 02:33:16 -0400 Subject: [PATCH 6/7] update to admin consol --- .codex | 0 backend/api/admin/static/admin.css | 68 +++- backend/api/admin/static/admin.js | 578 +++++++++++++++++------------ 3 files changed, 399 insertions(+), 247 deletions(-) create mode 100644 .codex diff --git a/.codex b/.codex new file mode 100644 index 0000000..e69de29 diff --git a/backend/api/admin/static/admin.css b/backend/api/admin/static/admin.css index 0e14ce2..e0d5a41 100644 --- a/backend/api/admin/static/admin.css +++ b/backend/api/admin/static/admin.css @@ -591,21 +591,32 @@ button, input { font: inherit; } inset: 0; z-index: 26; background: rgba(0, 0, 0, 0.64); - display: grid; - place-items: center; + display: flex; + align-items: center; padding: 14px; + overflow-x: auto; +} + +.inspector-stack { + width: 100%; + display: flex; + gap: 12px; + align-items: stretch; + min-height: min(82vh, 760px); } -.record-modal { - width: min(960px, 100%); +.inspector-panel { + width: min(520px, 92vw); + min-width: 360px; max-height: 82vh; overflow: auto; border: 1px solid var(--db-border); border-radius: var(--db-radius-lg); background: color-mix(in srgb, var(--db-surface), black 5%); + animation: panelSlideIn var(--db-duration-slow) cubic-bezier(.2,.8,.2,1) both; } -.modal-header { +.inspector-header { position: sticky; top: 0; border-bottom: 1px solid var(--db-border); @@ -617,6 +628,40 @@ button, input { font: inherit; } gap: 8px; } +.inspector-header h3 { + font-size: 18px; +} + +.inspector-header p { + margin-top: 2px; + font-size: 12px; + color: var(--db-muted); +} + +.linked-users-row { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 10px 12px 0; +} + +.linked-user-chip { + border: 1px solid color-mix(in srgb, var(--db-tint), var(--db-border) 46%); + background: color-mix(in srgb, var(--db-surface-alt), var(--db-tint) 10%); + color: color-mix(in srgb, var(--db-tint), white 20%); + border-radius: 999px; + padding: 6px 10px; + font-size: 12px; + cursor: pointer; + box-shadow: 0 0 0 rgba(0, 243, 41, 0.25); + transition: transform var(--db-duration) ease, box-shadow var(--db-duration) ease; +} + +.linked-user-chip:hover { + transform: translateY(-1px); + box-shadow: 0 0 14px rgba(0, 243, 41, 0.3); +} + .modal-actions { padding: 10px 12px; border-bottom: 1px solid var(--db-border); @@ -641,6 +686,17 @@ button, input { font: inherit; } animation: revealIn var(--db-duration-slow) cubic-bezier(.22,.61,.36,1) both; } +@keyframes panelSlideIn { + from { + opacity: 0; + transform: translateX(14px); + } + to { + opacity: 1; + transform: translateX(0); + } +} + @keyframes revealIn { from { opacity: 0; @@ -704,4 +760,4 @@ button, input { font: inherit; } min-width: 0; width: min(90vw, 420px); } -} \ No newline at end of file +} diff --git a/backend/api/admin/static/admin.js b/backend/api/admin/static/admin.js index 77570b1..d5595f4 100644 --- a/backend/api/admin/static/admin.js +++ b/backend/api/admin/static/admin.js @@ -9,28 +9,63 @@ const ENTITY_CONFIG = { listPath: "/admin/users", deletePath: (entity) => `/admin/users/${encodeURIComponent(entity.username)}`, key: (entity) => entity.username || entity.id, - preview: (entity) => entity.bio || "No bio.", + summary: (entity) => ({ + primary: entity.username, + secondary: entity.bio || "No bio", + meta: [ + `ID: ${entity.id}`, + entity.creation_date ? `Created: ${entity.creation_date}` : null, + entity.is_admin ? "Admin" : null, + entity.ban_until ? `Banned until: ${entity.ban_until}` : null, + ].filter(Boolean), + }), }, posts: { title: "Bytes", listPath: "/admin/posts", deletePath: (entity) => `/admin/posts/${entity.id}`, key: (entity) => entity.id, - preview: (entity) => entity.content || "No content.", + summary: (entity, getUsername) => ({ + primary: `Byte #${entity.id}`, + secondary: trimText(entity.content, 160), + meta: [ + `By: ${getUsername(entity.user)}`, + `Likes: ${entity.likes || 0}`, + `Saves: ${entity.saves || 0}`, + entity.created_on ? `Created: ${formatDate(entity.created_on)}` : null, + ].filter(Boolean), + }), }, projects: { title: "Streams", listPath: "/admin/projects", deletePath: (entity) => `/admin/projects/${entity.id}`, key: (entity) => entity.id, - preview: (entity) => entity.description || entity.content || "No description.", + summary: (entity, getUsername) => ({ + primary: entity.name || `Stream #${entity.id}`, + secondary: trimText(entity.description || "No description", 160), + meta: [ + `By: ${getUsername(entity.owner)}`, + `Status: ${entity.status ?? "-"}`, + `Likes: ${entity.likes || 0}`, + `Saves: ${entity.saves || 0}`, + ].filter(Boolean), + }), }, comments: { title: "Bits", listPath: "/admin/comments", deletePath: (entity) => `/admin/comments/${entity.id}`, key: (entity) => entity.id, - preview: (entity) => entity.content || "No comment text.", + summary: (entity, getUsername) => ({ + primary: `Bit #${entity.id}`, + secondary: trimText(entity.content || "No content", 160), + meta: [ + `By: ${getUsername(entity.user)}`, + `Likes: ${entity.likes || 0}`, + entity.created_on ? `Created: ${formatDate(entity.created_on)}` : null, + ].filter(Boolean), + }), }, }; @@ -42,66 +77,43 @@ const NAV_ITEMS = [ { key: "comments", label: "Bits", icon: IconComments }, ]; -const PAGE_ALIASES = { - bytes: "posts", - streams: "projects", - bits: "comments", -}; +const PAGE_ALIASES = { bytes: "posts", streams: "projects", bits: "comments" }; + +function trimText(text, max = 120) { + const value = String(text || "").trim(); + if (value.length <= max) return value; + return `${value.slice(0, max).trimEnd()}…`; +} -function SvgIcon({ children, className = "" }) { +function formatDate(input) { + if (!input) return "-"; + const date = new Date(input); + if (Number.isNaN(date.getTime())) return String(input); + return date.toLocaleString(); +} + +function SvgIcon({ children }) { return ( - {displayValue.toLocaleString()}; + return <>{display.toLocaleString()}; } function Gauge({ label, value, total }) { - const safeTotal = Math.max(total || 0, 1); - const clampedValue = Math.max(0, Math.min(value || 0, safeTotal)); - const percent = Math.round((clampedValue / safeTotal) * 100); + const max = Math.max(total || 1, 1); + const clamped = Math.max(0, Math.min(value || 0, max)); + const percent = Math.round((clamped / max) * 100); return (
@@ -211,109 +217,29 @@ function Gauge({ label, value, total }) {
{label} - {clampedValue} / {safeTotal} + {clamped} / {max}
); } -function EntityModal({ entityType, entity, onClose, onActionDone, addToast }) { - const [busy, setBusy] = useState(false); - - if (!entity) return null; - - const config = ENTITY_CONFIG[entityType]; - - const runDelete = async () => { - if (!window.confirm("Delete this record permanently?")) return; - setBusy(true); - try { - await api(config.deletePath(entity), { method: "DELETE" }); - addToast(`${config.title.slice(0, -1)} deleted`, "success"); - onActionDone(); - onClose(); - } catch (error) { - addToast(error.message, "error"); - } finally { - setBusy(false); - } - }; - - const runUserAction = async (action) => { - setBusy(true); - try { - if (action === "toggle-admin") { - await api(`/admin/users/${encodeURIComponent(entity.username)}/admin`, { - method: "POST", - body: { is_admin: !entity.is_admin }, - }); - } - if (action === "toggle-ban") { - if (entity.ban_until) { - await api(`/admin/users/${encodeURIComponent(entity.username)}/unban`, { method: "POST" }); - } else { - await api(`/admin/users/${encodeURIComponent(entity.username)}/ban`, { - method: "POST", - body: { reason: "Admin moderation action", duration_minutes: 60 * 24 * 7 }, - }); - } - } - addToast("Action completed", "success"); - onActionDone(); - onClose(); - } catch (error) { - addToast(error.message, "error"); - } finally { - setBusy(false); - } - }; - +function StatCard({ label, value }) { return ( -
-
event.stopPropagation()}> -
-

{config.title.slice(0, -1)} details

- Close -
- -
- {entityType === "users" ? ( - <> - runUserAction("toggle-admin")}> - {entity.is_admin ? "Revoke Admin" : "Grant Admin"} - - runUserAction("toggle-ban")}> - {entity.ban_until ? "Unban" : "Ban 7d"} - - - ) : null} - Delete -
- -
{JSON.stringify(entity, null, 2)}
-
+
+
{label}
+
); } -function DashboardPage({ addToast }) { +function DashboardPage({ addToast, userLookup }) { const [busy, setBusy] = useState(true); const [overview, setOverview] = useState(null); - const [derived, setDerived] = useState({ userAdmins: 0, userBanned: 0 }); - const loadDashboard = useCallback(async () => { + const load = useCallback(async () => { setBusy(true); try { - const [overviewData, users] = await Promise.all([ - api("/admin/overview"), - api("/admin/users").then(normalizeListPayload), - ]); - - const userAdmins = users.filter((user) => user?.is_admin).length; - const userBanned = users.filter((user) => !!user?.ban_until).length; - - setOverview(overviewData); - setDerived({ userAdmins, userBanned }); + setOverview(await api("/admin/overview")); } catch (error) { addToast(error.message, "error"); } finally { @@ -322,19 +248,21 @@ function DashboardPage({ addToast }) { }, [addToast]); useEffect(() => { - loadDashboard(); - }, [loadDashboard]); + load(); + }, [load]); const counts = overview?.counts || { users: 0, posts: 0, projects: 0, comments: 0 }; + const allUsers = Object.values(userLookup); + const adminUsers = allUsers.filter((user) => user?.is_admin).length; + const bannedUsers = allUsers.filter((user) => !!user?.ban_until).length; return (

Platform overview

- Refresh + Refresh
-
@@ -346,34 +274,35 @@ function DashboardPage({ addToast }) {

Live admin health

- - + +
- -
-

System timestamps

-
- Server: {overview?.server_time || "-"} - Database: {overview?.db_time || "-"} -
-
); } -function StatCard({ label, value }) { +function SummaryCard({ entity, type, getUsername, onOpen }) { + const config = ENTITY_CONFIG[type]; + const summary = config.summary(entity, getUsername); + return ( -
-
{label}
-
-
+
onOpen(entity, type)}> +
{summary.primary}
+
{summary.secondary}
+
+ {summary.meta.map((entry, index) => {entry})} +
+
+ Open details +
+
); } -function DataPage({ type, addToast, onSelectEntity }) { +function DataPage({ type, addToast, onOpenEntity, getUsername }) { const config = ENTITY_CONFIG[type]; const [query, setQuery] = useState(""); const [busy, setBusy] = useState(false); @@ -384,8 +313,7 @@ function DataPage({ type, addToast, onSelectEntity }) { try { const q = query.trim(); const path = q ? `${config.listPath}?q=${encodeURIComponent(q)}` : config.listPath; - const data = await api(path); - setItems(normalizeListPayload(data)); + setItems(normalizeListPayload(await api(path))); } catch (error) { addToast(error.message, "error"); } finally { @@ -419,18 +347,13 @@ function DataPage({ type, addToast, onSelectEntity }) { ) : (
{items.map((entity) => ( -
onSelectEntity(entity, type)}> -
{entity.title || entity.username || `ID ${entity.id}`}
-
- {entity.creation_date ? Created {entity.creation_date} : null} - {entity.ban_until ? Banned until {entity.ban_until} : null} - {entity.is_admin ? Admin : null} -
-
{config.preview(entity)}
-
- Open details -
-
+ ))}
)} @@ -439,7 +362,132 @@ function DataPage({ type, addToast, onSelectEntity }) { ); } -function TopSearch({ onPick, addToast }) { +function InspectorPanel({ panel, index, getUsername, resolveUserByAnyRef, onOpenEntity, onClosePanel, onActionDone, addToast }) { + const { entity, type } = panel; + const [busy, setBusy] = useState(false); + const config = ENTITY_CONFIG[type]; + const title = type === "users" ? entity.username : config.summary(entity, getUsername).primary; + + const userRefs = useMemo(() => { + if (type === "users") return []; + const refs = []; + if (entity.user != null) refs.push(entity.user); + if (entity.owner != null) refs.push(entity.owner); + return [...new Set(refs)]; + }, [entity, type]); + + const runDelete = async () => { + if (!window.confirm("Delete this record permanently?")) return; + setBusy(true); + try { + await api(config.deletePath(entity), { method: "DELETE" }); + addToast(`${config.title.slice(0, -1)} deleted`, "success"); + onActionDone(); + onClosePanel(index); + } catch (error) { + addToast(error.message, "error"); + } finally { + setBusy(false); + } + }; + + const runUserAction = async (action) => { + setBusy(true); + try { + if (action === "toggle-admin") { + await api(`/admin/users/${encodeURIComponent(entity.username)}/admin`, { method: "POST", body: { is_admin: !entity.is_admin } }); + } + if (action === "toggle-ban") { + if (entity.ban_until) { + await api(`/admin/users/${encodeURIComponent(entity.username)}/unban`, { method: "POST" }); + } else { + await api(`/admin/users/${encodeURIComponent(entity.username)}/ban`, { + method: "POST", + body: { reason: "Admin moderation action", duration_minutes: 60 * 24 * 7 }, + }); + } + } + addToast("Action completed", "success"); + onActionDone(); + onClosePanel(index); + } catch (error) { + addToast(error.message, "error"); + } finally { + setBusy(false); + } + }; + + return ( +
+
+
+

{title}

+

{type === "users" ? `Tracked by username: ${entity.username}` : `${config.title.slice(0, -1)} details`}

+
+ onClosePanel(index)}>Close +
+ + {userRefs.length ? ( +
+ {userRefs.map((ref) => { + const user = resolveUserByAnyRef(ref); + const username = user?.username || getUsername(ref); + return ( + + ); + })} +
+ ) : null} + +
+ {type === "users" ? ( + <> + runUserAction("toggle-admin")}>{entity.is_admin ? "Revoke Admin" : "Grant Admin"} + runUserAction("toggle-ban")}>{entity.ban_until ? "Unban" : "Ban 7d"} + + ) : null} + Delete +
+ +
{JSON.stringify(entity, null, 2)}
+
+ ); +} + +function InspectorStack({ panels, getUsername, resolveUserByAnyRef, onOpenEntity, onClosePanel, onActionDone, addToast }) { + if (!panels.length) return null; + + return ( +
onClosePanel(0, true)}> +
event.stopPropagation()}> + {panels.map((panel, index) => ( + + ))} +
+
+ ); +} + +function TopSearch({ onOpenEntity, addToast, getUsername }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [results, setResults] = useState({ users: [], posts: [], projects: [], comments: [] }); @@ -476,20 +524,27 @@ function TopSearch({ onPick, addToast }) { }, [query, addToast]); const groups = [ - { label: "Users", key: "users", type: "users" }, - { label: "Bytes", key: "posts", type: "posts" }, - { label: "Streams", key: "projects", type: "projects" }, - { label: "Bits", key: "comments", type: "comments" }, + { key: "users", label: "Users", type: "users" }, + { key: "posts", label: "Bytes", type: "posts" }, + { key: "projects", label: "Streams", type: "projects" }, + { key: "comments", label: "Bits", type: "comments" }, ]; const hasResults = groups.some((group) => (results[group.key] || []).length); + const renderLabel = (item, type) => { + if (type === "users") return `@${item.username}`; + if (type === "posts") return `Byte #${item.id} • ${getUsername(item.user)}`; + if (type === "projects") return `${item.name || `Stream #${item.id}`} • ${getUsername(item.owner)}`; + return `Bit #${item.id} • ${getUsername(item.user)}`; + }; + return (
setQuery(event.target.value)} onFocus={() => setOpen(true)} onBlur={() => { @@ -502,21 +557,20 @@ function TopSearch({ onPick, addToast }) { {groups.map((group) => { const groupItems = results[group.key] || []; if (!groupItems.length) return null; - return (
{group.label}
{groupItems.slice(0, 5).map((item) => ( ))}
@@ -533,9 +587,10 @@ function App() { const [adminMe, setAdminMe] = useState(null); const [sidebarOpen, setSidebarOpen] = useState(false); const [toasts, setToasts] = useState([]); - const [selectedEntity, setSelectedEntity] = useState(null); - const [selectedEntityType, setSelectedEntityType] = useState("users"); - const [dataRefreshTick, setDataRefreshTick] = useState(0); + const [panels, setPanels] = useState([]); + const [refreshKey, setRefreshKey] = useState(0); + const [userLookup, setUserLookup] = useState({}); + const [usernameLookup, setUsernameLookup] = useState({}); const addToast = useCallback((message, type = "info") => { const id = Date.now() + Math.random(); @@ -545,14 +600,30 @@ function App() { }, 4200); }, []); + const hydrateUsers = useCallback(async () => { + try { + const users = normalizeListPayload(await api("/admin/users")); + const byId = {}; + const byName = {}; + users.forEach((user) => { + byId[String(user.id)] = user; + byName[String(user.username).toLowerCase()] = user; + }); + setUserLookup(byId); + setUsernameLookup(byName); + } catch (error) { + addToast(error.message, "error"); + } + }, [addToast]); + useEffect(() => { api("/admin/me").then(setAdminMe).catch(() => {}); + hydrateUsers(); const syncHash = () => { - const rawPage = window.location.hash.replace("#/", "") || "dashboard"; - const page = PAGE_ALIASES[rawPage] || rawPage; - const allowed = NAV_ITEMS.map((item) => item.key); - if (allowed.includes(page)) setActivePage(page); + const raw = window.location.hash.replace("#/", "") || "dashboard"; + const page = PAGE_ALIASES[raw] || raw; + if (NAV_ITEMS.some((item) => item.key === page)) setActivePage(page); else { setActivePage("dashboard"); window.location.hash = "#/dashboard"; @@ -561,32 +632,44 @@ function App() { window.addEventListener("hashchange", syncHash); syncHash(); - return () => window.removeEventListener("hashchange", syncHash); + }, [hydrateUsers]); + + const getUsername = useCallback((ref) => { + if (ref === null || ref === undefined) return "unknown"; + if (typeof ref === "string" && Number.isNaN(Number(ref))) return ref; + return userLookup[String(ref)]?.username || `user-${ref}`; + }, [userLookup]); + + const resolveUserByAnyRef = useCallback((ref) => { + if (ref === null || ref === undefined) return null; + if (typeof ref === "number" || !Number.isNaN(Number(ref))) { + return userLookup[String(ref)] || null; + } + return usernameLookup[String(ref).toLowerCase()] || null; + }, [userLookup, usernameLookup]); + + const openEntity = useCallback((entity, type) => { + const keyRoot = type === "users" ? (entity.username || entity.id) : (entity.id || JSON.stringify(entity)); + const key = `${type}:${keyRoot}`; + setPanels((current) => { + if (current.some((panel) => panel.key === key)) return current; + return [...current, { key, type, entity }]; + }); }, []); - const handleNavigate = (page) => { - setActivePage(page); - window.location.hash = `#/${page}`; - setSidebarOpen(false); - }; + const closePanel = useCallback((index, closeAll = false) => { + setPanels((current) => { + if (closeAll) return []; + return current.filter((_, currentIndex) => currentIndex !== index); + }); + }, []); - const handleSelectEntity = (entity, type) => { - setSelectedEntity(entity); - setSelectedEntityType(type); + const refreshAll = () => { + setRefreshKey((value) => value + 1); + hydrateUsers(); }; - const Page = activePage === "dashboard" ? ( - - ) : ( - - ); - const currentTitle = NAV_ITEMS.find((item) => item.key === activePage)?.label || "Dashboard"; return ( @@ -611,7 +694,11 @@ function App() { type="button" key={item.key} className={`nav-item ${activePage === item.key ? "active" : ""}`} - onClick={() => handleNavigate(item.key)} + onClick={() => { + setActivePage(item.key); + window.location.hash = `#/${item.key}`; + setSidebarOpen(false); + }} > {item.label} @@ -621,7 +708,7 @@ function App() {
- setDataRefreshTick((value) => value + 1)}>Refresh data + Refresh data { @@ -637,30 +724,39 @@ function App() {
- setSidebarOpen((value) => !value)}> - Menu - + setSidebarOpen((value) => !value)}>Menu DevBits {currentTitle}
-
- - setDataRefreshTick((value) => value + 1)}>Refresh + + Refresh
- {Page} + {activePage === "dashboard" ? ( + + ) : ( + + )}
setToasts((current) => current.filter((toast) => toast.id !== id))} /> - setSelectedEntity(null)} - onActionDone={() => setDataRefreshTick((value) => value + 1)} + @@ -668,4 +764,4 @@ function App() { } const root = ReactDOM.createRoot(document.getElementById("admin-app")); -root.render(); \ No newline at end of file +root.render(); From 0acea4fa2b8e2e0ce5c70598e24c4ac0131aee26 Mon Sep 17 00:00:00 2001 From: Eli Date: Mon, 16 Nov 2026 16:46:13 -0500 Subject: [PATCH 7/7] Remove AWS deploy workflow --- .github/workflows/aws.yml | 89 --------------------------------------- 1 file changed, 89 deletions(-) delete mode 100644 .github/workflows/aws.yml diff --git a/.github/workflows/aws.yml b/.github/workflows/aws.yml deleted file mode 100644 index 24c1397..0000000 --- a/.github/workflows/aws.yml +++ /dev/null @@ -1,89 +0,0 @@ -# This workflow will build and push a new container image to Amazon ECR, -# and then will deploy a new task definition to Amazon ECS. -# It is triggered manually via workflow_dispatch. -# -# To use this workflow, you will need to complete the following set-up steps: -# -# 1. Create an ECR repository to store your images. -# For example: `aws ecr create-repository --repository-name my-ecr-repo --region us-east-2`. -# Set the `AWS_REGION` and `ECR_REPOSITORY` variables in your GitHub repository/environment settings. -# -# 2. Create an ECS task definition, an ECS cluster, and an ECS service. -# For example, follow the Getting Started guide on the ECS console: -# https://us-east-2.console.aws.amazon.com/ecs/home?region=us-east-2#/firstRun -# Set the `ECS_SERVICE` and `ECS_CLUSTER` variables in your GitHub repository/environment settings. -# -# 3. Store your ECS task definition as a JSON file in your repository. -# The format should follow the output of `aws ecs register-task-definition --generate-cli-skeleton`. -# Set the `ECS_TASK_DEFINITION` and `CONTAINER_NAME` variables in your GitHub repository/environment settings. -# -# 4. Configure GitHub OIDC for AWS and create an IAM role that GitHub Actions can assume. -# Store the IAM role ARN in a GitHub Actions secret named `AWS_ROLE_ARN`. -# See https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services -# for setup instructions and recommended IAM policies. - -name: Deploy to Amazon ECS - -on: - workflow_dispatch: - -env: - AWS_REGION: ${{ vars.AWS_REGION }} - ECR_REPOSITORY: ${{ vars.ECR_REPOSITORY }} - ECS_SERVICE: ${{ vars.ECS_SERVICE }} - ECS_CLUSTER: ${{ vars.ECS_CLUSTER }} - ECS_TASK_DEFINITION: ${{ vars.ECS_TASK_DEFINITION }} - CONTAINER_NAME: ${{ vars.CONTAINER_NAME }} - -permissions: - contents: read - id-token: write - -jobs: - deploy: - name: Deploy - runs-on: ubuntu-latest - environment: production - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v1 - with: - role-to-assume: ${{ secrets.AWS_ROLE_ARN }} - aws-region: ${{ env.AWS_REGION }} - - - name: Login to Amazon ECR - id: login-ecr - uses: aws-actions/amazon-ecr-login@v1 - - - name: Build, tag, and push image to Amazon ECR - id: build-image - env: - ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} - IMAGE_TAG: ${{ github.sha }} - run: | - # Build a docker container and - # push it to ECR so that it can - # be deployed to ECS. - docker build -f backend/Dockerfile -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG backend - docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG - echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT - - - name: Fill in the new image ID in the Amazon ECS task definition - id: task-def - uses: aws-actions/amazon-ecs-render-task-definition@v1 - with: - task-definition: ${{ env.ECS_TASK_DEFINITION }} - container-name: ${{ env.CONTAINER_NAME }} - image: ${{ steps.build-image.outputs.image }} - - - name: Deploy Amazon ECS task definition - uses: aws-actions/amazon-ecs-deploy-task-definition@v1 - with: - task-definition: ${{ steps.task-def.outputs.task-definition }} - service: ${{ env.ECS_SERVICE }} - cluster: ${{ env.ECS_CLUSTER }} - wait-for-service-stability: true