mirror of
https://github.com/YuzuZensai/Minikura.git
synced 2026-03-30 15:25:37 +00:00
Compare commits
6 Commits
075ffb8256
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
d14f043e7c
|
|||
|
e8dbefde43
|
|||
|
134351b326
|
|||
|
34260259da
|
|||
|
98b685fe1b
|
|||
|
5a6d3da26d
|
78
.devcontainer/Dockerfile
Normal file
78
.devcontainer/Dockerfile
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
FROM ubuntu:24.04
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive
|
||||||
|
|
||||||
|
# Install base packages
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
openssh-server \
|
||||||
|
passwd \
|
||||||
|
sudo \
|
||||||
|
curl \
|
||||||
|
wget \
|
||||||
|
git \
|
||||||
|
jq \
|
||||||
|
unzip \
|
||||||
|
ca-certificates \
|
||||||
|
gnupg \
|
||||||
|
lsb-release \
|
||||||
|
iptables \
|
||||||
|
iproute2 \
|
||||||
|
postgresql-client \
|
||||||
|
apt-transport-https \
|
||||||
|
software-properties-common \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install Node.js 24
|
||||||
|
RUN curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \
|
||||||
|
&& apt-get install -y --no-install-recommends nodejs \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install Bun
|
||||||
|
RUN curl -fsSL https://bun.sh/install | bash \
|
||||||
|
&& mv /root/.bun/bin/bun /usr/local/bin/ \
|
||||||
|
&& ln -s /usr/local/bin/bun /usr/local/bin/bunx
|
||||||
|
|
||||||
|
# Install Docker
|
||||||
|
RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg \
|
||||||
|
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" > /etc/apt/sources.list.d/docker.list \
|
||||||
|
&& apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends docker-ce docker-ce-cli containerd.io docker-compose-plugin \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install kubectl
|
||||||
|
RUN curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/$(dpkg --print-architecture)/kubectl" \
|
||||||
|
&& install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl \
|
||||||
|
&& rm kubectl
|
||||||
|
|
||||||
|
# Install Helm
|
||||||
|
RUN curl -fsSL https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash
|
||||||
|
|
||||||
|
# Enable systemd
|
||||||
|
RUN find /lib/systemd/system/sysinit.target.wants -mindepth 1 -not -name "systemd-tmpfiles-setup.service" -delete; \
|
||||||
|
find /lib/systemd/system/multi-user.target.wants -mindepth 1 -not -name "systemd-user-sessions.service" -delete; \
|
||||||
|
rm -f /etc/systemd/system/*.wants/*; \
|
||||||
|
rm -f /lib/systemd/system/local-fs.target.wants/*; \
|
||||||
|
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
|
||||||
|
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
|
||||||
|
rm -f /lib/systemd/system/basic.target.wants/*; \
|
||||||
|
rm -f /lib/systemd/system/anaconda.target.wants/*;
|
||||||
|
|
||||||
|
# Create dev user with host UID/GID for seamless file permissions
|
||||||
|
ARG HOST_UID=1000
|
||||||
|
ARG HOST_GID=1000
|
||||||
|
RUN userdel -r $(getent passwd ${HOST_UID} | cut -d: -f1) 2>/dev/null || true && \
|
||||||
|
groupdel $(getent group ${HOST_GID} | cut -d: -f1) 2>/dev/null || true && \
|
||||||
|
groupadd -g ${HOST_GID} dev && \
|
||||||
|
useradd -m -s /bin/bash -u ${HOST_UID} -g ${HOST_GID} dev && \
|
||||||
|
echo "dev:dev" | chpasswd && \
|
||||||
|
echo 'dev ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/dev && \
|
||||||
|
chmod 440 /etc/sudoers.d/dev && \
|
||||||
|
usermod -aG docker dev
|
||||||
|
|
||||||
|
# Setup directories
|
||||||
|
RUN mkdir -p /home/dev/.kube /home/dev/.vscode-server && chown -R dev:dev /home/dev
|
||||||
|
|
||||||
|
WORKDIR /workspace
|
||||||
|
|
||||||
|
VOLUME [ "/sys/fs/cgroup" ]
|
||||||
|
CMD ["/usr/sbin/init"]
|
||||||
31
.devcontainer/devcontainer.json
Normal file
31
.devcontainer/devcontainer.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "Minikura Development",
|
||||||
|
"dockerComposeFile": "./docker-compose.yml",
|
||||||
|
"service": "devcontainer",
|
||||||
|
"workspaceFolder": "/workspace",
|
||||||
|
"remoteUser": "dev",
|
||||||
|
|
||||||
|
"postCreateCommand": "bash /workspace/.devcontainer/post-create.sh",
|
||||||
|
|
||||||
|
"forwardPorts": [3000, 3001, 5432, 6443, 25565, 25577],
|
||||||
|
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"extensions": [
|
||||||
|
"biomejs.biome",
|
||||||
|
"Prisma.prisma",
|
||||||
|
"ms-kubernetes-tools.vscode-kubernetes-tools",
|
||||||
|
"ms-azuretools.vscode-docker",
|
||||||
|
"bradlc.vscode-tailwindcss",
|
||||||
|
"redhat.vscode-yaml"
|
||||||
|
],
|
||||||
|
"settings": {
|
||||||
|
"editor.defaultFormatter": "biomejs.biome",
|
||||||
|
"editor.formatOnSave": true,
|
||||||
|
"[prisma]": {
|
||||||
|
"editor.defaultFormatter": "Prisma.prisma"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
59
.devcontainer/docker-compose.yml
Normal file
59
.devcontainer/docker-compose.yml
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
name: "minikura-devcontainer"
|
||||||
|
services:
|
||||||
|
devcontainer:
|
||||||
|
tty: true
|
||||||
|
privileged: true
|
||||||
|
cgroup: host
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
HOST_UID: ${HOST_UID:-1000}
|
||||||
|
HOST_GID: ${HOST_GID:-1000}
|
||||||
|
tmpfs:
|
||||||
|
- /var/lib/docker:mode=0777,dev,size=15g,suid,exec
|
||||||
|
- /var/lib/rancher:mode=0777,dev,size=15g,suid,exec
|
||||||
|
- /run
|
||||||
|
ports:
|
||||||
|
- "3000:3000" # backend API
|
||||||
|
- "3001:3001" # web frontend
|
||||||
|
- "6443:6443" # k3s API
|
||||||
|
- "25565:25565" # minecraft
|
||||||
|
- "25577:25577" # velocity
|
||||||
|
- "30000-32767:30000-32767" # NodePort range
|
||||||
|
volumes:
|
||||||
|
- "../:/workspace"
|
||||||
|
- "/sys/fs/cgroup:/sys/fs/cgroup:rw"
|
||||||
|
- vscode-server:/home/dev/.vscode-server
|
||||||
|
working_dir: "/workspace"
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
- KUBECONFIG=/home/dev/.kube/config
|
||||||
|
- DATABASE_URL=postgresql://postgres:postgres@db:5432/minikura?sslmode=disable
|
||||||
|
- WEB_URL=http://localhost:3001
|
||||||
|
- NEXT_PUBLIC_API_URL=http://localhost:3000
|
||||||
|
- KUBERNETES_NAMESPACE=minikura
|
||||||
|
- ENABLE_CRD_REFLECTION=true
|
||||||
|
|
||||||
|
db:
|
||||||
|
image: postgres:17
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: minikura
|
||||||
|
volumes:
|
||||||
|
- postgres-data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "5433:5432"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres-data:
|
||||||
|
vscode-server:
|
||||||
75
.devcontainer/post-create.sh
Executable file
75
.devcontainer/post-create.sh
Executable file
@@ -0,0 +1,75 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "=============================================="
|
||||||
|
echo " Minikura Development Environment Setup"
|
||||||
|
echo "=============================================="
|
||||||
|
|
||||||
|
# Start Docker
|
||||||
|
echo "==> Starting Docker..."
|
||||||
|
sudo service docker start
|
||||||
|
sleep 2
|
||||||
|
sudo chmod 666 /var/run/docker.sock
|
||||||
|
|
||||||
|
# Install and start k3s via install script (sets up systemd service)
|
||||||
|
echo "==> Installing k3s..."
|
||||||
|
curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--write-kubeconfig-mode 644 --disable traefik" sh -
|
||||||
|
|
||||||
|
# Wait for k3s to be ready
|
||||||
|
echo "==> Waiting for k3s..."
|
||||||
|
sleep 5
|
||||||
|
|
||||||
|
# Configure kubectl
|
||||||
|
echo "==> Configuring kubectl..."
|
||||||
|
mkdir -p /home/dev/.kube
|
||||||
|
until [ -f /etc/rancher/k3s/k3s.yaml ]; do sleep 1; done
|
||||||
|
sudo cp /etc/rancher/k3s/k3s.yaml /home/dev/.kube/config
|
||||||
|
sudo chown dev:dev /home/dev/.kube/config
|
||||||
|
chmod 600 /home/dev/.kube/config
|
||||||
|
|
||||||
|
# Allow k3s self-signed certs
|
||||||
|
kubectl config set-cluster default --insecure-skip-tls-verify=true
|
||||||
|
|
||||||
|
# Wait for k3s API server to be fully ready
|
||||||
|
echo "==> Waiting for k3s API server..."
|
||||||
|
for i in {1..60}; do
|
||||||
|
kubectl get nodes --request-timeout=2s >/dev/null 2>&1 && break
|
||||||
|
echo " Attempt $i/60..."
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
sleep 2 # Extra buffer for stability
|
||||||
|
|
||||||
|
# Verify k3s is actually working
|
||||||
|
echo "==> Verifying k3s..."
|
||||||
|
kubectl get nodes || { echo "[ERROR] k3s not responding properly"; exit 1; }
|
||||||
|
|
||||||
|
# Wait for node to be Ready
|
||||||
|
echo "==> Waiting for node to be Ready..."
|
||||||
|
for i in {1..30}; do
|
||||||
|
kubectl get nodes 2>/dev/null | grep -q " Ready" && break
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
|
||||||
|
# Create namespace
|
||||||
|
echo "==> Creating minikura namespace..."
|
||||||
|
kubectl create namespace minikura --dry-run=client -o yaml | kubectl apply -f - 2>/dev/null || true
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
echo "==> Installing dependencies..."
|
||||||
|
cd /workspace
|
||||||
|
sudo rm -rf node_modules apps/*/node_modules packages/*/node_modules 2>/dev/null || true
|
||||||
|
sudo chown -R dev:dev /workspace
|
||||||
|
bun install
|
||||||
|
|
||||||
|
# Setup database
|
||||||
|
echo "==> Setting up database..."
|
||||||
|
bun run db:generate
|
||||||
|
bun run db:push
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=============================================="
|
||||||
|
echo " Ready! Commands:"
|
||||||
|
echo " bun run dev - Start backend + web"
|
||||||
|
echo " bun run k8s:dev - Start K8s operator"
|
||||||
|
echo " kubectl get nodes"
|
||||||
|
echo "=============================================="
|
||||||
21
.env.example
21
.env.example
@@ -1,5 +1,18 @@
|
|||||||
DATABASE_URL=postgresql://postgres:password@localhost:5432/database?sslmode=disable
|
# Database Configuration
|
||||||
ENABLE_CRD_REFLECTION=true
|
# PostgreSQL connection string for the Minikura database
|
||||||
|
DATABASE_URL="postgresql://user:password@localhost:5432/minikura"
|
||||||
|
|
||||||
KUBERNETES_NAMESPACE=minikura
|
# Web Application
|
||||||
KUBERNETES_SKIP_TLS_VERIFY=true
|
# URL where the web frontend is running (used for CORS)
|
||||||
|
WEB_URL="http://localhost:3001"
|
||||||
|
|
||||||
|
# API URL that the web frontend should connect to
|
||||||
|
NEXT_PUBLIC_API_URL="http://localhost:3000"
|
||||||
|
|
||||||
|
# Kubernetes Configuration
|
||||||
|
KUBERNETES_NAMESPACE="minikura"
|
||||||
|
|
||||||
|
# Kubernetes Operator Configuration
|
||||||
|
# Enable CRD reflection to automatically sync database state to Kubernetes Custom Resources
|
||||||
|
# Set to "false" to disable automatic CRD creation from database entries
|
||||||
|
ENABLE_CRD_REFLECTION="true"
|
||||||
|
|||||||
@@ -4,22 +4,38 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": "./src/index.ts",
|
"exports": "./src/index.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun --watch src/index.ts",
|
"dev": "tsx watch src/index.ts",
|
||||||
"build": "bun build src/index.ts --target bun --outdir ./dist",
|
"dev:bun": "bun --watch src/index.ts",
|
||||||
"start": "NODE_ENV=production bun dist/index.js",
|
"build": "tsc",
|
||||||
"test": "bun test"
|
"start": "NODE_ENV=production node dist/index.js",
|
||||||
|
"test": "bun test",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"lint": "biome lint .",
|
||||||
|
"format": "biome format --write ."
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/bun": "^1.1.9"
|
"@types/bun": "^1.3.6",
|
||||||
|
"@types/node": "^25.0.9",
|
||||||
|
"tsx": "^4.19.2"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"typescript": "^5.0.0"
|
"typescript": "^5.0.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@elysiajs/swagger": "^1.1.1",
|
"@elysiajs/node": "^1.4.5",
|
||||||
|
"@kubernetes/client-node": "^1.4.0",
|
||||||
|
"@minikura/api": "workspace:*",
|
||||||
"@minikura/db": "workspace:*",
|
"@minikura/db": "workspace:*",
|
||||||
"argon2": "^0.41.1",
|
"@minikura/shared": "workspace:*",
|
||||||
"dotenv": "^16.4.5",
|
"@types/ws": "^8.18.1",
|
||||||
"elysia": "^1.1.13"
|
"better-auth": "^1.4.13",
|
||||||
|
"elysia": "^1.4.22",
|
||||||
|
"pino": "^10.3.1",
|
||||||
|
"pino-http": "^11.0.0",
|
||||||
|
"pino-pretty": "^13.1.3",
|
||||||
|
"undici": "^7.18.2",
|
||||||
|
"ws": "^8.19.0",
|
||||||
|
"yaml": "^2.8.2",
|
||||||
|
"zod": "^4.3.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
22
apps/backend/src/application/di-container.ts
Normal file
22
apps/backend/src/application/di-container.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { PrismaReverseProxyRepository } from "../infrastructure/repositories/prisma/reverse-proxy.repository.impl";
|
||||||
|
import { PrismaServerRepository } from "../infrastructure/repositories/prisma/server.repository.impl";
|
||||||
|
import { PrismaUserRepository } from "../infrastructure/repositories/prisma/user.repository.impl";
|
||||||
|
import { K8sService } from "../services/k8s";
|
||||||
|
import { WebSocketService } from "../services/websocket";
|
||||||
|
import { ReverseProxyService } from "./services/reverse-proxy.service";
|
||||||
|
import { ServerService } from "./services/server.service";
|
||||||
|
import { UserService } from "./services/user.service";
|
||||||
|
|
||||||
|
// Infrastructure layer
|
||||||
|
const userRepo = new PrismaUserRepository();
|
||||||
|
const serverRepo = new PrismaServerRepository();
|
||||||
|
const reverseProxyRepo = new PrismaReverseProxyRepository();
|
||||||
|
const webSocketService = new WebSocketService();
|
||||||
|
const k8sService = new K8sService();
|
||||||
|
|
||||||
|
// Application layer
|
||||||
|
export const userService = new UserService(userRepo);
|
||||||
|
export const serverService = new ServerService(serverRepo, k8sService);
|
||||||
|
export const reverseProxyService = new ReverseProxyService(reverseProxyRepo);
|
||||||
|
export const wsService = webSocketService;
|
||||||
|
export { k8sService };
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import type * as k8s from "@kubernetes/client-node";
|
||||||
|
import type { CustomResourceSummary } from "@minikura/api";
|
||||||
|
|
||||||
|
export interface IK8sService {
|
||||||
|
// Initialization
|
||||||
|
isInitialized(): boolean;
|
||||||
|
getConnectionInfo(): {
|
||||||
|
initialized: boolean;
|
||||||
|
currentContext?: string;
|
||||||
|
cluster?: string;
|
||||||
|
namespace: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pods
|
||||||
|
getPods(): Promise<any[]>;
|
||||||
|
getPodsByLabel(labelSelector: string): Promise<any[]>;
|
||||||
|
getPodInfo(podName: string): Promise<any>;
|
||||||
|
getPodLogs(
|
||||||
|
podName: string,
|
||||||
|
options?: {
|
||||||
|
container?: string;
|
||||||
|
tailLines?: number;
|
||||||
|
timestamps?: boolean;
|
||||||
|
sinceSeconds?: number;
|
||||||
|
}
|
||||||
|
): Promise<string>;
|
||||||
|
getPodMetrics(namespace?: string): Promise<any>;
|
||||||
|
|
||||||
|
// Workloads
|
||||||
|
getDeployments(): Promise<any[]>;
|
||||||
|
getStatefulSets(): Promise<any[]>;
|
||||||
|
|
||||||
|
// Network
|
||||||
|
getServices(): Promise<any[]>;
|
||||||
|
getIngresses(): Promise<any[]>;
|
||||||
|
getServiceInfo(serviceName: string): Promise<any>;
|
||||||
|
getServerConnectionInfo(serviceName: string): Promise<any>;
|
||||||
|
|
||||||
|
// Configuration
|
||||||
|
getConfigMaps(): Promise<any[]>;
|
||||||
|
|
||||||
|
// Custom Resources
|
||||||
|
getCustomResources(
|
||||||
|
group: string,
|
||||||
|
version: string,
|
||||||
|
plural: string
|
||||||
|
): Promise<CustomResourceSummary[]>;
|
||||||
|
getMinecraftServers(): Promise<CustomResourceSummary[]>;
|
||||||
|
getReverseProxyServers(): Promise<CustomResourceSummary[]>;
|
||||||
|
|
||||||
|
// Cluster
|
||||||
|
getNodes(): Promise<any[]>;
|
||||||
|
getNodeMetrics(): Promise<any>;
|
||||||
|
|
||||||
|
// Low-level access
|
||||||
|
getKubeConfig(): k8s.KubeConfig;
|
||||||
|
getCoreApi(): k8s.CoreV1Api;
|
||||||
|
getNamespace(): string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import type { EnvVariable, ReverseProxyWithEnvVars } from "@minikura/db";
|
||||||
|
import type {
|
||||||
|
ReverseProxyCreateInput,
|
||||||
|
ReverseProxyUpdateInput,
|
||||||
|
} from "../../domain/repositories/reverse-proxy.repository";
|
||||||
|
|
||||||
|
export interface IReverseProxyService {
|
||||||
|
getAllReverseProxies(omitSensitive?: boolean): Promise<ReverseProxyWithEnvVars[]>;
|
||||||
|
getReverseProxyById(id: string, omitSensitive?: boolean): Promise<ReverseProxyWithEnvVars>;
|
||||||
|
createReverseProxy(input: ReverseProxyCreateInput): Promise<ReverseProxyWithEnvVars>;
|
||||||
|
updateReverseProxy(id: string, input: ReverseProxyUpdateInput): Promise<ReverseProxyWithEnvVars>;
|
||||||
|
deleteReverseProxy(id: string): Promise<void>;
|
||||||
|
setEnvVariable(proxyId: string, key: string, value: string): Promise<void>;
|
||||||
|
getEnvVariables(proxyId: string): Promise<EnvVariable[]>;
|
||||||
|
deleteEnvVariable(proxyId: string, key: string): Promise<void>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import type { EnvVariable, ServerWithEnvVars } from "@minikura/db";
|
||||||
|
import type {
|
||||||
|
ServerCreateInput,
|
||||||
|
ServerUpdateInput,
|
||||||
|
} from "../../domain/repositories/server.repository";
|
||||||
|
|
||||||
|
export interface IServerService {
|
||||||
|
getAllServers(omitSensitive?: boolean): Promise<ServerWithEnvVars[]>;
|
||||||
|
getServerById(id: string, omitSensitive?: boolean): Promise<ServerWithEnvVars>;
|
||||||
|
createServer(input: ServerCreateInput): Promise<ServerWithEnvVars>;
|
||||||
|
updateServer(id: string, input: ServerUpdateInput): Promise<ServerWithEnvVars>;
|
||||||
|
deleteServer(id: string): Promise<void>;
|
||||||
|
setEnvVariable(serverId: string, key: string, value: string): Promise<void>;
|
||||||
|
getEnvVariables(serverId: string): Promise<EnvVariable[]>;
|
||||||
|
deleteEnvVariable(serverId: string, key: string): Promise<void>;
|
||||||
|
getConnectionInfo(serverId: string): Promise<any>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import type { UpdateSuspensionInput, UpdateUserInput, User } from "@minikura/db";
|
||||||
|
|
||||||
|
export interface IUserService {
|
||||||
|
getUserById(id: string): Promise<User>;
|
||||||
|
getUserByEmail(email: string): Promise<User | null>;
|
||||||
|
getAllUsers(): Promise<User[]>;
|
||||||
|
updateUser(id: string, input: UpdateUserInput): Promise<User>;
|
||||||
|
updateSuspension(id: string, input: UpdateSuspensionInput): Promise<User>;
|
||||||
|
suspendUser(id: string, suspendedUntil?: Date | null): Promise<User>;
|
||||||
|
unsuspendUser(id: string): Promise<User>;
|
||||||
|
deleteUser(requestingUserId: string, targetUserId: string): Promise<void>;
|
||||||
|
}
|
||||||
82
apps/backend/src/application/services/base-crud.service.ts
Normal file
82
apps/backend/src/application/services/base-crud.service.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import type { EnvVariable } from "@minikura/db";
|
||||||
|
import { ConflictError, NotFoundError } from "../../domain/errors/base.error";
|
||||||
|
import { eventBus } from "../../infrastructure/event-bus";
|
||||||
|
|
||||||
|
export abstract class BaseCrudService<
|
||||||
|
TEntity,
|
||||||
|
TCreateInput,
|
||||||
|
TUpdateInput,
|
||||||
|
TRepository extends {
|
||||||
|
findAll(omitSensitive?: boolean): Promise<TEntity[]>;
|
||||||
|
findById(id: string, omitSensitive?: boolean): Promise<TEntity | null>;
|
||||||
|
exists(id: string): Promise<boolean>;
|
||||||
|
create(input: TCreateInput): Promise<TEntity>;
|
||||||
|
update(id: string, input: TUpdateInput): Promise<TEntity>;
|
||||||
|
delete(id: string): Promise<void>;
|
||||||
|
setEnvVariable(entityId: string, key: string, value: string): Promise<void>;
|
||||||
|
getEnvVariables(entityId: string): Promise<EnvVariable[]>;
|
||||||
|
deleteEnvVariable(entityId: string, key: string): Promise<void>;
|
||||||
|
},
|
||||||
|
TEvents extends {
|
||||||
|
created: new (id: string, type: any, input: TCreateInput) => any;
|
||||||
|
updated: new (id: string, input: TUpdateInput) => any;
|
||||||
|
deleted: new (id: string) => any;
|
||||||
|
},
|
||||||
|
> {
|
||||||
|
constructor(
|
||||||
|
protected repository: TRepository,
|
||||||
|
protected events: TEvents,
|
||||||
|
protected entityName: string
|
||||||
|
) {}
|
||||||
|
|
||||||
|
protected abstract getEntityType(input: TCreateInput): any;
|
||||||
|
protected abstract getInputId(input: TCreateInput): string;
|
||||||
|
|
||||||
|
async getAll(omitSensitive = false): Promise<TEntity[]> {
|
||||||
|
return this.repository.findAll(omitSensitive);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getById(id: string, omitSensitive = false): Promise<TEntity> {
|
||||||
|
const entity = await this.repository.findById(id, omitSensitive);
|
||||||
|
if (!entity) {
|
||||||
|
throw new NotFoundError(this.entityName, id);
|
||||||
|
}
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(input: TCreateInput): Promise<TEntity> {
|
||||||
|
const id = this.getInputId(input);
|
||||||
|
const existing = await this.repository.exists(id);
|
||||||
|
if (existing) {
|
||||||
|
throw new ConflictError(this.entityName, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const entity = await this.repository.create(input);
|
||||||
|
const type = this.getEntityType(input);
|
||||||
|
await eventBus.publish(new this.events.created(id, type, input));
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, input: TUpdateInput): Promise<TEntity> {
|
||||||
|
const entity = await this.repository.update(id, input);
|
||||||
|
await eventBus.publish(new this.events.updated(id, input));
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(id: string): Promise<void> {
|
||||||
|
await this.repository.delete(id);
|
||||||
|
await eventBus.publish(new this.events.deleted(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async setEnvVariable(entityId: string, key: string, value: string): Promise<void> {
|
||||||
|
await this.repository.setEnvVariable(entityId, key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getEnvVariables(entityId: string): Promise<EnvVariable[]> {
|
||||||
|
return this.repository.getEnvVariables(entityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteEnvVariable(entityId: string, key: string): Promise<void> {
|
||||||
|
await this.repository.deleteEnvVariable(entityId, key);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import type { ReverseProxyWithEnvVars } from "@minikura/db";
|
||||||
|
import {
|
||||||
|
ReverseProxyCreatedEvent,
|
||||||
|
ReverseProxyDeletedEvent,
|
||||||
|
ReverseProxyUpdatedEvent,
|
||||||
|
} from "../../domain/events/reverse-proxy-lifecycle.events";
|
||||||
|
import type {
|
||||||
|
ReverseProxyCreateInput,
|
||||||
|
ReverseProxyRepository,
|
||||||
|
ReverseProxyUpdateInput,
|
||||||
|
} from "../../domain/repositories/reverse-proxy.repository";
|
||||||
|
import type { IReverseProxyService } from "../interfaces/reverse-proxy.service.interface";
|
||||||
|
import { BaseCrudService } from "./base-crud.service";
|
||||||
|
|
||||||
|
export class ReverseProxyService
|
||||||
|
extends BaseCrudService<
|
||||||
|
ReverseProxyWithEnvVars,
|
||||||
|
ReverseProxyCreateInput,
|
||||||
|
ReverseProxyUpdateInput,
|
||||||
|
ReverseProxyRepository,
|
||||||
|
{
|
||||||
|
created: typeof ReverseProxyCreatedEvent;
|
||||||
|
updated: typeof ReverseProxyUpdatedEvent;
|
||||||
|
deleted: typeof ReverseProxyDeletedEvent;
|
||||||
|
}
|
||||||
|
>
|
||||||
|
implements IReverseProxyService
|
||||||
|
{
|
||||||
|
constructor(reverseProxyRepo: ReverseProxyRepository) {
|
||||||
|
super(
|
||||||
|
reverseProxyRepo,
|
||||||
|
{
|
||||||
|
created: ReverseProxyCreatedEvent,
|
||||||
|
updated: ReverseProxyUpdatedEvent,
|
||||||
|
deleted: ReverseProxyDeletedEvent,
|
||||||
|
},
|
||||||
|
"ReverseProxyServer"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getEntityType(input: ReverseProxyCreateInput) {
|
||||||
|
return input.type || "VELOCITY";
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getInputId(input: ReverseProxyCreateInput): string {
|
||||||
|
return typeof input.id === "string" ? input.id : String(input.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllReverseProxies(omitSensitive = false) {
|
||||||
|
return this.getAll(omitSensitive);
|
||||||
|
}
|
||||||
|
|
||||||
|
getReverseProxyById(id: string, omitSensitive = false) {
|
||||||
|
return this.getById(id, omitSensitive);
|
||||||
|
}
|
||||||
|
|
||||||
|
createReverseProxy(input: ReverseProxyCreateInput) {
|
||||||
|
return this.create(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateReverseProxy(id: string, input: ReverseProxyUpdateInput) {
|
||||||
|
return this.update(id, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteReverseProxy(id: string) {
|
||||||
|
return this.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
78
apps/backend/src/application/services/server.service.ts
Normal file
78
apps/backend/src/application/services/server.service.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import type { ServerWithEnvVars } from "@minikura/db";
|
||||||
|
import {
|
||||||
|
ServerCreatedEvent,
|
||||||
|
ServerDeletedEvent,
|
||||||
|
ServerUpdatedEvent,
|
||||||
|
} from "../../domain/events/server-lifecycle.events";
|
||||||
|
import type {
|
||||||
|
ServerCreateInput,
|
||||||
|
ServerRepository,
|
||||||
|
ServerUpdateInput,
|
||||||
|
} from "../../domain/repositories/server.repository";
|
||||||
|
import type { K8sService } from "../../services/k8s";
|
||||||
|
import type { IServerService } from "../interfaces/server.service.interface";
|
||||||
|
import { BaseCrudService } from "./base-crud.service";
|
||||||
|
|
||||||
|
export class ServerService
|
||||||
|
extends BaseCrudService<
|
||||||
|
ServerWithEnvVars,
|
||||||
|
ServerCreateInput,
|
||||||
|
ServerUpdateInput,
|
||||||
|
ServerRepository,
|
||||||
|
{
|
||||||
|
created: typeof ServerCreatedEvent;
|
||||||
|
updated: typeof ServerUpdatedEvent;
|
||||||
|
deleted: typeof ServerDeletedEvent;
|
||||||
|
}
|
||||||
|
>
|
||||||
|
implements IServerService
|
||||||
|
{
|
||||||
|
constructor(
|
||||||
|
serverRepo: ServerRepository,
|
||||||
|
private k8sService: K8sService
|
||||||
|
) {
|
||||||
|
super(
|
||||||
|
serverRepo,
|
||||||
|
{
|
||||||
|
created: ServerCreatedEvent,
|
||||||
|
updated: ServerUpdatedEvent,
|
||||||
|
deleted: ServerDeletedEvent,
|
||||||
|
},
|
||||||
|
"Server"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getEntityType(input: ServerCreateInput) {
|
||||||
|
return input.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getInputId(input: ServerCreateInput): string {
|
||||||
|
return input.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllServers(omitSensitive = false) {
|
||||||
|
return this.getAll(omitSensitive);
|
||||||
|
}
|
||||||
|
|
||||||
|
getServerById(id: string, omitSensitive = false) {
|
||||||
|
return this.getById(id, omitSensitive);
|
||||||
|
}
|
||||||
|
|
||||||
|
createServer(input: ServerCreateInput) {
|
||||||
|
return this.create(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateServer(id: string, input: ServerUpdateInput) {
|
||||||
|
return this.update(id, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteServer(id: string) {
|
||||||
|
return this.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getConnectionInfo(serverId: string) {
|
||||||
|
await this.getServerById(serverId);
|
||||||
|
const serviceName = `minecraft-${serverId}`;
|
||||||
|
return this.k8sService.getServerConnectionInfo(serviceName);
|
||||||
|
}
|
||||||
|
}
|
||||||
65
apps/backend/src/application/services/user.service.ts
Normal file
65
apps/backend/src/application/services/user.service.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import type { UpdateSuspensionInput, UpdateUserInput, User } from "@minikura/db";
|
||||||
|
import { BusinessRuleError, NotFoundError } from "../../domain/errors/base.error";
|
||||||
|
import {
|
||||||
|
UserSuspendedEvent,
|
||||||
|
UserUnsuspendedEvent,
|
||||||
|
} from "../../domain/events/server-lifecycle.events";
|
||||||
|
import type { UserRepository } from "../../domain/repositories/user.repository";
|
||||||
|
import { eventBus } from "../../infrastructure/event-bus";
|
||||||
|
import type { IUserService } from "../interfaces/user.service.interface";
|
||||||
|
|
||||||
|
export class UserService implements IUserService {
|
||||||
|
constructor(private userRepo: UserRepository) {}
|
||||||
|
|
||||||
|
async getUserById(id: string): Promise<User> {
|
||||||
|
const user = await this.userRepo.findById(id);
|
||||||
|
if (!user) {
|
||||||
|
throw new NotFoundError("User", id);
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserByEmail(email: string): Promise<User | null> {
|
||||||
|
return this.userRepo.findByEmail(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllUsers(): Promise<User[]> {
|
||||||
|
return this.userRepo.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateUser(id: string, input: UpdateUserInput): Promise<User> {
|
||||||
|
return this.userRepo.update(id, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateSuspension(id: string, input: UpdateSuspensionInput): Promise<User> {
|
||||||
|
const user = await this.userRepo.updateSuspension(id, input);
|
||||||
|
if (input.isSuspended) {
|
||||||
|
const suspendedUntil = input.suspendedUntil instanceof Date ? input.suspendedUntil : null;
|
||||||
|
await eventBus.publish(new UserSuspendedEvent(id, suspendedUntil));
|
||||||
|
} else {
|
||||||
|
await eventBus.publish(new UserUnsuspendedEvent(id));
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async suspendUser(id: string, suspendedUntil?: Date | null): Promise<User> {
|
||||||
|
return this.updateSuspension(id, {
|
||||||
|
isSuspended: true,
|
||||||
|
suspendedUntil: suspendedUntil ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async unsuspendUser(id: string): Promise<User> {
|
||||||
|
return this.updateSuspension(id, {
|
||||||
|
isSuspended: false,
|
||||||
|
suspendedUntil: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteUser(requestingUserId: string, targetUserId: string): Promise<void> {
|
||||||
|
if (requestingUserId === targetUserId) {
|
||||||
|
throw new BusinessRuleError("Cannot delete yourself");
|
||||||
|
}
|
||||||
|
await this.userRepo.delete(targetUserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
36
apps/backend/src/config/constants.ts
Normal file
36
apps/backend/src/config/constants.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
export const API_KEY_PREFIXES = {
|
||||||
|
SERVER: "minikura_server_api_key_",
|
||||||
|
REVERSE_PROXY: "minikura_reverse_proxy_server_api_key_",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const DEFAULT_PORTS = {
|
||||||
|
MINECRAFT: 25565,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const DEFAULT_MEMORY = {
|
||||||
|
SERVER: 2048, // MB
|
||||||
|
REVERSE_PROXY: 512, // MB
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const DEFAULT_MEMORY_REQUEST = {
|
||||||
|
SERVER: 1024, // MB
|
||||||
|
REVERSE_PROXY: 512, // MB
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const DEFAULT_CPU = {
|
||||||
|
SERVER: {
|
||||||
|
REQUEST: "500m",
|
||||||
|
LIMIT: "2",
|
||||||
|
},
|
||||||
|
REVERSE_PROXY: {
|
||||||
|
REQUEST: "250m",
|
||||||
|
LIMIT: "500m",
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const VALIDATION = {
|
||||||
|
ID_PATTERN: /^[a-zA-Z0-9-_]+$/,
|
||||||
|
ID_ERROR_MESSAGE: "ID must be alphanumeric with - or _",
|
||||||
|
PORT_MIN: 1,
|
||||||
|
PORT_MAX: 65535,
|
||||||
|
} as const;
|
||||||
31
apps/backend/src/domain/entities/enums.ts
Normal file
31
apps/backend/src/domain/entities/enums.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import {
|
||||||
|
MinecraftServerJarType,
|
||||||
|
GameMode as PrismaGameMode,
|
||||||
|
ServerDifficulty as PrismaServerDifficulty,
|
||||||
|
ServerType as PrismaServerType,
|
||||||
|
ServiceType as PrismaServiceType,
|
||||||
|
ReverseProxyServerType,
|
||||||
|
} from "@minikura/db";
|
||||||
|
|
||||||
|
export enum UserRole {
|
||||||
|
ADMIN = "admin",
|
||||||
|
USER = "user",
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MinecraftJarType = MinecraftServerJarType;
|
||||||
|
export type MinecraftJarType = (typeof MinecraftJarType)[keyof typeof MinecraftJarType];
|
||||||
|
|
||||||
|
export const ReverseProxyType = ReverseProxyServerType;
|
||||||
|
export type ReverseProxyType = (typeof ReverseProxyType)[keyof typeof ReverseProxyType];
|
||||||
|
|
||||||
|
export const ServerType = PrismaServerType;
|
||||||
|
export type ServerType = (typeof ServerType)[keyof typeof ServerType];
|
||||||
|
|
||||||
|
export const ServiceType = PrismaServiceType;
|
||||||
|
export type ServiceType = (typeof ServiceType)[keyof typeof ServiceType];
|
||||||
|
|
||||||
|
export const ServerDifficulty = PrismaServerDifficulty;
|
||||||
|
export type ServerDifficulty = (typeof ServerDifficulty)[keyof typeof ServerDifficulty];
|
||||||
|
|
||||||
|
export const GameMode = PrismaGameMode;
|
||||||
|
export type GameMode = (typeof GameMode)[keyof typeof GameMode];
|
||||||
65
apps/backend/src/domain/errors/base.error.ts
Normal file
65
apps/backend/src/domain/errors/base.error.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
export abstract class DomainError extends Error {
|
||||||
|
abstract readonly code: string;
|
||||||
|
abstract readonly statusCode: number;
|
||||||
|
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = this.constructor.name;
|
||||||
|
Error.captureStackTrace(this, this.constructor);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJSON() {
|
||||||
|
return {
|
||||||
|
name: this.name,
|
||||||
|
code: this.code,
|
||||||
|
message: this.message,
|
||||||
|
statusCode: this.statusCode,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NotFoundError extends DomainError {
|
||||||
|
readonly code = "NOT_FOUND";
|
||||||
|
readonly statusCode = 404;
|
||||||
|
|
||||||
|
constructor(resource: string, identifier?: string) {
|
||||||
|
super(identifier ? `${resource} not found: ${identifier}` : `${resource} not found`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ConflictError extends DomainError {
|
||||||
|
readonly code = "CONFLICT";
|
||||||
|
readonly statusCode = 409;
|
||||||
|
|
||||||
|
constructor(resource: string, identifier?: string) {
|
||||||
|
super(identifier ? `${resource} already exists: ${identifier}` : `${resource} already exists`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UnauthorizedError extends DomainError {
|
||||||
|
readonly code = "UNAUTHORIZED";
|
||||||
|
readonly statusCode = 401;
|
||||||
|
|
||||||
|
constructor(message = "Unauthorized access") {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ForbiddenError extends DomainError {
|
||||||
|
readonly code = "FORBIDDEN";
|
||||||
|
readonly statusCode = 403;
|
||||||
|
|
||||||
|
constructor(message = "Forbidden access") {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ValidationError extends DomainError {
|
||||||
|
readonly code = "VALIDATION_ERROR";
|
||||||
|
readonly statusCode = 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BusinessRuleError extends DomainError {
|
||||||
|
readonly code = "BUSINESS_RULE_VIOLATION";
|
||||||
|
readonly statusCode = 422;
|
||||||
|
}
|
||||||
9
apps/backend/src/domain/events/domain-event.ts
Normal file
9
apps/backend/src/domain/events/domain-event.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export abstract class DomainEvent {
|
||||||
|
readonly occurredAt: Date;
|
||||||
|
readonly eventId: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.occurredAt = new Date();
|
||||||
|
this.eventId = crypto.randomUUID();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { ReverseProxyType } from "../entities/enums";
|
||||||
|
import type {
|
||||||
|
ReverseProxyCreateInput,
|
||||||
|
ReverseProxyUpdateInput,
|
||||||
|
} from "../repositories/reverse-proxy.repository";
|
||||||
|
import { DomainEvent } from "./domain-event";
|
||||||
|
|
||||||
|
export class ReverseProxyCreatedEvent extends DomainEvent {
|
||||||
|
constructor(
|
||||||
|
public readonly proxyId: string,
|
||||||
|
public readonly proxyType: ReverseProxyType,
|
||||||
|
public readonly config: ReverseProxyCreateInput
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReverseProxyUpdatedEvent extends DomainEvent {
|
||||||
|
constructor(
|
||||||
|
public readonly proxyId: string,
|
||||||
|
public readonly changes: ReverseProxyUpdateInput
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReverseProxyDeletedEvent extends DomainEvent {
|
||||||
|
constructor(public readonly proxyId: string) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
43
apps/backend/src/domain/events/server-lifecycle.events.ts
Normal file
43
apps/backend/src/domain/events/server-lifecycle.events.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import type { ServerType } from "../entities/enums";
|
||||||
|
import type { ServerCreateInput, ServerUpdateInput } from "../repositories/server.repository";
|
||||||
|
import { DomainEvent } from "./domain-event";
|
||||||
|
|
||||||
|
export class ServerCreatedEvent extends DomainEvent {
|
||||||
|
constructor(
|
||||||
|
public readonly serverId: string,
|
||||||
|
public readonly serverType: ServerType,
|
||||||
|
public readonly config: ServerCreateInput
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerUpdatedEvent extends DomainEvent {
|
||||||
|
constructor(
|
||||||
|
public readonly serverId: string,
|
||||||
|
public readonly changes: ServerUpdateInput
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerDeletedEvent extends DomainEvent {
|
||||||
|
constructor(public readonly serverId: string) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UserSuspendedEvent extends DomainEvent {
|
||||||
|
constructor(
|
||||||
|
public readonly userId: string,
|
||||||
|
public readonly suspendedUntil: Date | null
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UserUnsuspendedEvent extends DomainEvent {
|
||||||
|
constructor(public readonly userId: string) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type { EnvVariable, ReverseProxyWithEnvVars } from "@minikura/db";
|
||||||
|
import type { z } from "zod";
|
||||||
|
import type {
|
||||||
|
createReverseProxySchema,
|
||||||
|
updateReverseProxySchema,
|
||||||
|
} from "../../schemas/server.schema";
|
||||||
|
|
||||||
|
export type ReverseProxyCreateInput = z.infer<typeof createReverseProxySchema>;
|
||||||
|
export type ReverseProxyUpdateInput = z.infer<typeof updateReverseProxySchema>;
|
||||||
|
|
||||||
|
export interface ReverseProxyRepository {
|
||||||
|
findById(id: string, omitSensitive?: boolean): Promise<ReverseProxyWithEnvVars | null>;
|
||||||
|
findAll(omitSensitive?: boolean): Promise<ReverseProxyWithEnvVars[]>;
|
||||||
|
exists(id: string): Promise<boolean>;
|
||||||
|
create(input: ReverseProxyCreateInput): Promise<ReverseProxyWithEnvVars>;
|
||||||
|
update(id: string, input: ReverseProxyUpdateInput): Promise<ReverseProxyWithEnvVars>;
|
||||||
|
delete(id: string): Promise<void>;
|
||||||
|
setEnvVariable(proxyId: string, key: string, value: string): Promise<void>;
|
||||||
|
getEnvVariables(proxyId: string): Promise<EnvVariable[]>;
|
||||||
|
deleteEnvVariable(proxyId: string, key: string): Promise<void>;
|
||||||
|
replaceEnvVariables(proxyId: string, envVars: EnvVariable[]): Promise<void>;
|
||||||
|
}
|
||||||
19
apps/backend/src/domain/repositories/server.repository.ts
Normal file
19
apps/backend/src/domain/repositories/server.repository.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import type { EnvVariable, ServerWithEnvVars } from "@minikura/db";
|
||||||
|
import type { z } from "zod";
|
||||||
|
import type { createServerSchema, updateServerSchema } from "../../schemas/server.schema";
|
||||||
|
|
||||||
|
export type ServerCreateInput = z.infer<typeof createServerSchema>;
|
||||||
|
export type ServerUpdateInput = z.infer<typeof updateServerSchema>;
|
||||||
|
|
||||||
|
export interface ServerRepository {
|
||||||
|
findById(id: string, omitSensitive?: boolean): Promise<ServerWithEnvVars | null>;
|
||||||
|
findAll(omitSensitive?: boolean): Promise<ServerWithEnvVars[]>;
|
||||||
|
exists(id: string): Promise<boolean>;
|
||||||
|
create(input: ServerCreateInput): Promise<ServerWithEnvVars>;
|
||||||
|
update(id: string, input: ServerUpdateInput): Promise<ServerWithEnvVars>;
|
||||||
|
delete(id: string): Promise<void>;
|
||||||
|
setEnvVariable(serverId: string, key: string, value: string): Promise<void>;
|
||||||
|
getEnvVariables(serverId: string): Promise<EnvVariable[]>;
|
||||||
|
deleteEnvVariable(serverId: string, key: string): Promise<void>;
|
||||||
|
replaceEnvVariables(serverId: string, envVars: EnvVariable[]): Promise<void>;
|
||||||
|
}
|
||||||
11
apps/backend/src/domain/repositories/user.repository.ts
Normal file
11
apps/backend/src/domain/repositories/user.repository.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import type { UpdateSuspensionInput, UpdateUserInput, User } from "@minikura/db";
|
||||||
|
|
||||||
|
export interface UserRepository {
|
||||||
|
findById(id: string): Promise<User | null>;
|
||||||
|
findByEmail(email: string): Promise<User | null>;
|
||||||
|
findAll(): Promise<User[]>;
|
||||||
|
update(id: string, input: UpdateUserInput): Promise<User>;
|
||||||
|
updateSuspension(id: string, input: UpdateSuspensionInput): Promise<User>;
|
||||||
|
delete(id: string): Promise<void>;
|
||||||
|
count(): Promise<number>;
|
||||||
|
}
|
||||||
33
apps/backend/src/domain/value-objects/api-key.vo.ts
Normal file
33
apps/backend/src/domain/value-objects/api-key.vo.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
export class ApiKey {
|
||||||
|
private static readonly SERVER_PREFIX = "minikura_srv_";
|
||||||
|
private static readonly REVERSE_PROXY_PREFIX = "minikura_proxy_";
|
||||||
|
private static readonly TOKEN_BYTES = 32;
|
||||||
|
|
||||||
|
private constructor(private readonly value: string) {}
|
||||||
|
|
||||||
|
static generate(type: "server" | "reverse-proxy"): ApiKey {
|
||||||
|
const prefix = type === "server" ? ApiKey.SERVER_PREFIX : ApiKey.REVERSE_PROXY_PREFIX;
|
||||||
|
const token = Buffer.from(crypto.randomUUID())
|
||||||
|
.toString("base64")
|
||||||
|
.replace(/[^a-zA-Z0-9]/g, "")
|
||||||
|
.substring(0, ApiKey.TOKEN_BYTES);
|
||||||
|
return new ApiKey(`${prefix}${token}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
static validate(value: string): boolean {
|
||||||
|
const patterns = [
|
||||||
|
new RegExp(`^${ApiKey.SERVER_PREFIX}[a-zA-Z0-9]{32}$`),
|
||||||
|
new RegExp(`^${ApiKey.REVERSE_PROXY_PREFIX}[a-zA-Z0-9]{32}$`),
|
||||||
|
];
|
||||||
|
return patterns.some((pattern) => pattern.test(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): "server" | "reverse-proxy" {
|
||||||
|
if (this.value.startsWith(ApiKey.SERVER_PREFIX)) return "server";
|
||||||
|
return "reverse-proxy";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
export class K8sConnectionInfo {
|
||||||
|
constructor(
|
||||||
|
public readonly host: string,
|
||||||
|
public readonly port: number,
|
||||||
|
public readonly namespace: string
|
||||||
|
) {}
|
||||||
|
|
||||||
|
toUrl(): string {
|
||||||
|
return `${this.host}:${this.port}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
toConnectionString(): string {
|
||||||
|
return `Host: ${this.host}, Port: ${this.port}, Namespace: ${this.namespace}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
39
apps/backend/src/domain/value-objects/server-config.vo.ts
Normal file
39
apps/backend/src/domain/value-objects/server-config.vo.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
export class ServerConfig {
|
||||||
|
constructor(
|
||||||
|
public readonly memory: number,
|
||||||
|
public readonly memoryRequest: number,
|
||||||
|
public readonly cpuRequest: string,
|
||||||
|
public readonly cpuLimit: string,
|
||||||
|
public readonly jvmOpts: string | null
|
||||||
|
) {}
|
||||||
|
|
||||||
|
static fromDefaults(): ServerConfig {
|
||||||
|
return new ServerConfig(2048, 1024, "250m", "500m", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromInput(input: {
|
||||||
|
memory?: number;
|
||||||
|
memoryRequest?: number;
|
||||||
|
cpuRequest?: string;
|
||||||
|
cpuLimit?: string;
|
||||||
|
jvmOpts?: string;
|
||||||
|
}): ServerConfig {
|
||||||
|
return new ServerConfig(
|
||||||
|
input.memory ?? 2048,
|
||||||
|
input.memoryRequest ?? 1024,
|
||||||
|
input.cpuRequest ?? "250m",
|
||||||
|
input.cpuLimit ?? "500m",
|
||||||
|
input.jvmOpts ?? null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getJvmArgs(): string {
|
||||||
|
const args: string[] = [`-Xmx${this.memory}M`];
|
||||||
|
|
||||||
|
if (this.jvmOpts) {
|
||||||
|
args.push(this.jvmOpts);
|
||||||
|
}
|
||||||
|
|
||||||
|
return args.join(" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,650 +1,43 @@
|
|||||||
import { dotenvLoad } from "dotenv-mono";
|
import { dotenvLoad } from "dotenv-mono";
|
||||||
const dotenv = dotenvLoad();
|
|
||||||
|
|
||||||
import { Elysia, error, t } from "elysia";
|
dotenvLoad();
|
||||||
import { swagger } from "@elysiajs/swagger";
|
|
||||||
import { prisma, ServerType } from "@minikura/db";
|
|
||||||
|
|
||||||
import { ServerService } from "./services/server";
|
import { Elysia } from "elysia";
|
||||||
import { UserService } from "./services/user";
|
import { node } from "@elysiajs/node";
|
||||||
import argon2 from "argon2";
|
import { logger } from "./infrastructure/logger";
|
||||||
import { SessionService } from "./services/session";
|
import { auth } from "./middleware/auth";
|
||||||
|
import { authPlugin } from "./middleware/auth-plugin";
|
||||||
|
import { errorHandler } from "./middleware/error-handler";
|
||||||
|
import { bootstrapRoutes } from "./routes/bootstrap";
|
||||||
|
import { k8sRoutes } from "./routes/k8s";
|
||||||
|
import { reverseProxyRoutes } from "./routes/reverse-proxy";
|
||||||
|
import { serverRoutes } from "./routes/servers";
|
||||||
|
import { terminalRoutes } from "./routes/terminal";
|
||||||
|
import { userRoutes } from "./routes/users";
|
||||||
|
|
||||||
enum ReturnError {
|
// Register event handlers
|
||||||
INVALID_USERNAME_OR_PASSWORD = "INVALID_USERNAME_OR_PASSWORD",
|
import "./infrastructure/event-handlers";
|
||||||
MISSING_TOKEN = "MISSING_TOKEN",
|
|
||||||
REVOKED_TOKEN = "REVOKED_TOKEN",
|
|
||||||
EXPIRED_TOKEN = "EXPIRED_TOKEN",
|
|
||||||
INVALID_TOKEN = "INVALID_TOKEN",
|
|
||||||
SERVER_NAME_IN_USE = "SERVER_NAME_IN_USE",
|
|
||||||
SERVER_NOT_FOUND = "SERVER_NOT_FOUND",
|
|
||||||
}
|
|
||||||
|
|
||||||
const bootstrap = async () => {
|
const app = new Elysia({ adapter: node() })
|
||||||
const users = await prisma.user.findMany();
|
.use(errorHandler)
|
||||||
if (users.length !== 0) {
|
.onRequest(({ set }) => {
|
||||||
return;
|
const origin = process.env.WEB_URL || "http://localhost:3001";
|
||||||
}
|
set.headers["Access-Control-Allow-Origin"] = origin;
|
||||||
|
set.headers["Access-Control-Allow-Credentials"] = "true";
|
||||||
await prisma.user.create({
|
set.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS";
|
||||||
data: {
|
set.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, Cookie";
|
||||||
username: "admin",
|
|
||||||
password: await argon2.hash("admin"),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log("Default user created");
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const connectedClients = new Set<any>();
|
|
||||||
const broadcastServerChange = (action: string, serverType: string, serverId: string) => {
|
|
||||||
const message = {
|
|
||||||
type: "SERVER_CHANGE",
|
|
||||||
action,
|
|
||||||
serverType,
|
|
||||||
serverId,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
|
|
||||||
connectedClients.forEach(client => {
|
|
||||||
try {
|
|
||||||
client.send(JSON.stringify(message));
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error sending WebSocket message:", error);
|
|
||||||
connectedClients.delete(client);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
console.log(`Notified Velocity proxy: ${action} ${serverType} ${serverId}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const app = new Elysia()
|
|
||||||
.use(swagger({
|
|
||||||
path: '/swagger',
|
|
||||||
documentation: {
|
|
||||||
info: {
|
|
||||||
title: 'Minikura API Documentation',
|
|
||||||
version: '1.0.0'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.ws("/ws", {
|
|
||||||
open(ws) {
|
|
||||||
const apiKey = ws.data.query.apiKey;
|
|
||||||
if (!apiKey) {
|
|
||||||
console.log("apiKey required");
|
|
||||||
ws.close();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
connectedClients.add(ws);
|
|
||||||
console.log("Velocity proxy connected via WebSocket");
|
|
||||||
},
|
|
||||||
close(ws) {
|
|
||||||
connectedClients.delete(ws);
|
|
||||||
console.log("Velocity proxy disconnected from WebSocket");
|
|
||||||
},
|
|
||||||
message(ws, message) {
|
|
||||||
console.log("Received message from Velocity proxy:", message);
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
.group('/api', app => app
|
.options("/*", () => new Response(null, { status: 204 }))
|
||||||
.derive(async ({ headers, cookie: { session_token }, path }) => {
|
.all("/auth/*", ({ request }) => auth.handler(request))
|
||||||
// Skip token validation for login route
|
.use(bootstrapRoutes)
|
||||||
if (path === '/api/login') {
|
.use(authPlugin)
|
||||||
return {
|
.group("/api", (app) =>
|
||||||
server: null,
|
app.use(userRoutes).use(serverRoutes).use(reverseProxyRoutes).use(k8sRoutes).use(terminalRoutes)
|
||||||
session: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const auth = session_token.value;
|
|
||||||
const token = headers.authorization?.split(" ")[1];
|
|
||||||
|
|
||||||
if (!auth && !token)
|
|
||||||
return error("Unauthorized", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.MISSING_TOKEN,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (auth) {
|
|
||||||
const session = await SessionService.validate(auth);
|
|
||||||
if (session.status === SessionService.SESSION_STATUS.REVOKED) {
|
|
||||||
return error("Unauthorized", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.REVOKED_TOKEN,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (session.status === SessionService.SESSION_STATUS.EXPIRED) {
|
|
||||||
return error("Unauthorized", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.EXPIRED_TOKEN,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
session.status === SessionService.SESSION_STATUS.INVALID ||
|
|
||||||
session.status !== SessionService.SESSION_STATUS.VALID ||
|
|
||||||
!session.session
|
|
||||||
) {
|
|
||||||
return error("Unauthorized", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.INVALID_TOKEN,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
server: null,
|
|
||||||
session: session.session,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token) {
|
|
||||||
const session = await SessionService.validateApiKey(token);
|
|
||||||
if (session.status === SessionService.SESSION_STATUS.INVALID) {
|
|
||||||
return error("Unauthorized", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.INVALID_TOKEN,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
session.status === SessionService.SESSION_STATUS.VALID &&
|
|
||||||
session.server
|
|
||||||
) {
|
|
||||||
return {
|
|
||||||
session: null,
|
|
||||||
server: session.server,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Should never reach here
|
|
||||||
return error("Unauthorized", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.INVALID_TOKEN,
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.post(
|
|
||||||
"/login",
|
|
||||||
async ({ body, cookie: { session_token } }) => {
|
|
||||||
const user = await UserService.getUserByUsername(body.username);
|
|
||||||
const valid = await argon2.verify(user?.password || "fake", body.password);
|
|
||||||
|
|
||||||
if (!user || !valid) {
|
|
||||||
return error("Unauthorized", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.INVALID_USERNAME_OR_PASSWORD,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = await SessionService.create(user.id);
|
|
||||||
|
|
||||||
session_token.httpOnly = true;
|
|
||||||
session_token.value = session.token;
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{
|
|
||||||
body: t.Object({
|
|
||||||
username: t.String({ minLength: 1 }),
|
|
||||||
password: t.String({ minLength: 1 }),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
.post("/logout", async ({ session, cookie: { session_token } }) => {
|
.get("/health", () => ({ status: "ok" }));
|
||||||
if (!session) return { success: true };
|
|
||||||
|
|
||||||
await SessionService.revoke(session.token);
|
|
||||||
|
|
||||||
session_token.remove();
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.get("/servers", async ({ session }) => {
|
|
||||||
// Broadcast to all connected WebSocket clients
|
|
||||||
const message = {
|
|
||||||
type: "test",
|
|
||||||
endpoint: "/servers",
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
|
|
||||||
connectedClients.forEach(client => {
|
|
||||||
try {
|
|
||||||
client.send(JSON.stringify(message));
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error sending WebSocket message:", error);
|
|
||||||
connectedClients.delete(client);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`/servers API called, notified ${connectedClients.size} WebSocket clients`);
|
|
||||||
|
|
||||||
return await ServerService.getAllServers(!session);
|
|
||||||
})
|
|
||||||
.get("/servers/:id", async ({ session, params: { id } }) => {
|
|
||||||
return await ServerService.getServerById(id, !session);
|
|
||||||
})
|
|
||||||
.post(
|
|
||||||
"/servers",
|
|
||||||
async ({ body, error }) => {
|
|
||||||
// Must be a-z, A-Z, 0-9, and -_ only
|
|
||||||
if (!/^[a-zA-Z0-9-_]+$/.test(body.id)) {
|
|
||||||
return error("Bad Request", "ID must be a-z, A-Z, 0-9, and -_ only");
|
|
||||||
}
|
|
||||||
|
|
||||||
const _server = await ServerService.getServerById(body.id);
|
|
||||||
if (_server) {
|
|
||||||
return error("Conflict", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NAME_IN_USE,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const server = await ServerService.createServer({
|
|
||||||
id: body.id,
|
|
||||||
description: body.description,
|
|
||||||
listen_port: body.listen_port,
|
|
||||||
type: body.type,
|
|
||||||
env_variables: body.env_variables,
|
|
||||||
memory: body.memory,
|
|
||||||
});
|
|
||||||
|
|
||||||
broadcastServerChange("CREATE", "SERVER", server.id,);
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
server,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{
|
|
||||||
body: t.Object({
|
|
||||||
id: t.String({ minLength: 1 }),
|
|
||||||
description: t.Nullable(t.String({ minLength: 1 })),
|
|
||||||
listen_port: t.Integer({ minimum: 1, maximum: 65535 }),
|
|
||||||
type: t.Enum(ServerType),
|
|
||||||
env_variables: t.Optional(t.Array(t.Object({
|
|
||||||
key: t.String({ minLength: 1 }),
|
|
||||||
value: t.String(),
|
|
||||||
}))),
|
|
||||||
memory: t.Optional(t.String({ minLength: 1 })),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.patch(
|
|
||||||
"/servers/:id",
|
|
||||||
async ({ session, params: { id }, body }) => {
|
|
||||||
const server = await ServerService.getServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create update data with only fields that exist in the model
|
|
||||||
const data: any = {};
|
|
||||||
|
|
||||||
if (body.description !== undefined) data.description = body.description;
|
|
||||||
if (body.listen_port !== undefined) data.listen_port = body.listen_port;
|
|
||||||
if (body.memory !== undefined) data.memory = body.memory;
|
|
||||||
// Don't allow service_type to be updated through API
|
|
||||||
|
|
||||||
await prisma.server.update({
|
|
||||||
where: { id },
|
|
||||||
data,
|
|
||||||
});
|
|
||||||
|
|
||||||
const newServer = await ServerService.getServerById(id, !session);
|
|
||||||
|
|
||||||
broadcastServerChange("UPDATE", "SERVER", server.id);
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
server: newServer,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{
|
|
||||||
body: t.Object({
|
|
||||||
description: t.Optional(t.Nullable(t.String({ minLength: 1 }))),
|
|
||||||
listen_port: t.Optional(t.Integer({ minimum: 1, maximum: 65535 })),
|
|
||||||
memory: t.Optional(t.String({ minLength: 1 })),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.delete("/servers/:id", async ({ params: { id } }) => {
|
|
||||||
const server = await ServerService.getServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await prisma.server.delete({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
|
|
||||||
broadcastServerChange("DELETE", "SERVER", server.id);
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.get("/reverse_proxy_servers", async ({ session }) => {
|
|
||||||
return await ServerService.getAllReverseProxyServers(!session);
|
|
||||||
})
|
|
||||||
.post(
|
|
||||||
"/reverse_proxy_servers",
|
|
||||||
async ({ body, error }) => {
|
|
||||||
// Must be a-z, A-Z, 0-9, and -_ only
|
|
||||||
if (!/^[a-zA-Z0-9-_]+$/.test(body.id)) {
|
|
||||||
return error("Bad Request", "ID must be a-z, A-Z, 0-9, and -_ only");
|
|
||||||
}
|
|
||||||
|
|
||||||
const _server = await ServerService.getReverseProxyServerById(body.id);
|
|
||||||
if (_server) {
|
|
||||||
return error("Conflict", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NAME_IN_USE,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const server = await ServerService.createReverseProxyServer({
|
|
||||||
id: body.id,
|
|
||||||
description: body.description,
|
|
||||||
external_address: body.external_address,
|
|
||||||
external_port: body.external_port,
|
|
||||||
listen_port: body.listen_port,
|
|
||||||
type: body.type,
|
|
||||||
env_variables: body.env_variables,
|
|
||||||
memory: body.memory,
|
|
||||||
});
|
|
||||||
|
|
||||||
broadcastServerChange("CREATE", "REVERSE_PROXY_SERVER", server.id);
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
server,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{
|
|
||||||
body: t.Object({
|
|
||||||
id: t.String({ minLength: 1 }),
|
|
||||||
description: t.Nullable(t.String({ minLength: 1 })),
|
|
||||||
external_address: t.String({ minLength: 1 }),
|
|
||||||
external_port: t.Integer({ minimum: 1, maximum: 65535 }),
|
|
||||||
listen_port: t.Optional(t.Integer({ minimum: 1, maximum: 65535 })),
|
|
||||||
type: t.Optional(t.Enum({ VELOCITY: "VELOCITY", BUNGEECORD: "BUNGEECORD" })),
|
|
||||||
env_variables: t.Optional(t.Array(t.Object({
|
|
||||||
key: t.String({ minLength: 1 }),
|
|
||||||
value: t.String(),
|
|
||||||
}))),
|
|
||||||
memory: t.Optional(t.String({ minLength: 1 })),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.patch(
|
|
||||||
"/reverse_proxy_servers/:id",
|
|
||||||
async ({ session, params: { id }, body }) => {
|
|
||||||
const server = await prisma.reverseProxyServer.findUnique({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create update data with only fields that exist in the model
|
|
||||||
const data: any = {};
|
|
||||||
|
|
||||||
if (body.description !== undefined) data.description = body.description;
|
|
||||||
if (body.external_address !== undefined) data.external_address = body.external_address;
|
|
||||||
if (body.external_port !== undefined) data.external_port = body.external_port;
|
|
||||||
if (body.listen_port !== undefined) data.listen_port = body.listen_port;
|
|
||||||
if (body.type !== undefined) data.type = body.type;
|
|
||||||
if (body.memory !== undefined) data.memory = body.memory;
|
|
||||||
// Don't allow service_type to be updated through API
|
|
||||||
|
|
||||||
await prisma.reverseProxyServer.update({
|
|
||||||
where: { id },
|
|
||||||
data,
|
|
||||||
});
|
|
||||||
|
|
||||||
const newServer = await ServerService.getReverseProxyServerById(
|
|
||||||
id,
|
|
||||||
!session
|
|
||||||
);
|
|
||||||
|
|
||||||
broadcastServerChange("UPDATE", "REVERSE_PROXY_SERVER", server.id);
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
server: newServer,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{
|
|
||||||
body: t.Object({
|
|
||||||
description: t.Optional(t.Nullable(t.String({ minLength: 1 }))),
|
|
||||||
external_address: t.Optional(t.String({ minLength: 1 })),
|
|
||||||
external_port: t.Optional(t.Integer({ minimum: 1, maximum: 65535 })),
|
|
||||||
listen_port: t.Optional(t.Integer({ minimum: 1, maximum: 65535 })),
|
|
||||||
type: t.Optional(t.Enum({ VELOCITY: "VELOCITY", BUNGEECORD: "BUNGEECORD" })),
|
|
||||||
memory: t.Optional(t.String({ minLength: 1 })),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.delete("/reverse_proxy_servers/:id", async ({ params: { id } }) => {
|
|
||||||
const server = await prisma.reverseProxyServer.findUnique({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await prisma.reverseProxyServer.delete({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
|
|
||||||
broadcastServerChange("DELETE", "REVERSE_PROXY_SERVER", server.id);
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.get("/servers/:id/env", async ({ params: { id } }) => {
|
|
||||||
const server = await ServerService.getServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
env_variables: server.env_variables,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.post(
|
|
||||||
"/servers/:id/env",
|
|
||||||
async ({ params: { id }, body }) => {
|
|
||||||
const server = await ServerService.getServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const envVar = await prisma.customEnvironmentVariable.upsert({
|
|
||||||
where: {
|
|
||||||
key_server_id: {
|
|
||||||
key: body.key,
|
|
||||||
server_id: id,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
update: {
|
|
||||||
value: body.value,
|
|
||||||
},
|
|
||||||
create: {
|
|
||||||
key: body.key,
|
|
||||||
value: body.value,
|
|
||||||
server_id: id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
env_var: envVar,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{
|
|
||||||
body: t.Object({
|
|
||||||
key: t.String({ minLength: 1 }),
|
|
||||||
value: t.String(),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.delete("/servers/:id/env/:key", async ({ params: { id, key } }) => {
|
|
||||||
const server = await ServerService.getServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await prisma.customEnvironmentVariable.delete({
|
|
||||||
where: {
|
|
||||||
key_server_id: {
|
|
||||||
key,
|
|
||||||
server_id: id,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: "Environment variable not found",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.get("/reverse_proxy_servers/:id/env", async ({ params: { id } }) => {
|
|
||||||
const server = await ServerService.getReverseProxyServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
env_variables: server.env_variables,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.post(
|
|
||||||
"/reverse_proxy_servers/:id/env",
|
|
||||||
async ({ params: { id }, body }) => {
|
|
||||||
const server = await ServerService.getReverseProxyServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const envVar = await prisma.customEnvironmentVariable.upsert({
|
|
||||||
where: {
|
|
||||||
key_reverse_proxy_id: {
|
|
||||||
key: body.key,
|
|
||||||
reverse_proxy_id: id,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
update: {
|
|
||||||
value: body.value,
|
|
||||||
},
|
|
||||||
create: {
|
|
||||||
key: body.key,
|
|
||||||
value: body.value,
|
|
||||||
reverse_proxy_id: id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
env_var: envVar,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
{
|
|
||||||
body: t.Object({
|
|
||||||
key: t.String({ minLength: 1 }),
|
|
||||||
value: t.String(),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.delete("/reverse_proxy_servers/:id/env/:key", async ({ params: { id, key } }) => {
|
|
||||||
const server = await ServerService.getReverseProxyServerById(id);
|
|
||||||
if (!server) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: ReturnError.SERVER_NOT_FOUND,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await prisma.customEnvironmentVariable.delete({
|
|
||||||
where: {
|
|
||||||
key_reverse_proxy_id: {
|
|
||||||
key,
|
|
||||||
reverse_proxy_id: id,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
return error("Not Found", {
|
|
||||||
success: false,
|
|
||||||
message: "Environment variable not found",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.listen(3000, async () => {
|
|
||||||
console.log("Server is running on port 3000");
|
|
||||||
bootstrap();
|
|
||||||
});
|
|
||||||
|
|
||||||
export type App = typeof app;
|
export type App = typeof app;
|
||||||
|
|
||||||
|
app.listen(3000, () => {
|
||||||
|
logger.info({ port: 3000, url: "http://localhost:3000" }, "Backend API server started");
|
||||||
|
});
|
||||||
|
|||||||
26
apps/backend/src/infrastructure/api-key-generator.ts
Normal file
26
apps/backend/src/infrastructure/api-key-generator.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
export interface ApiKeyGenerator {
|
||||||
|
generateServerApiKey(): string;
|
||||||
|
generateReverseProxyApiKey(): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ApiKeyGeneratorImpl implements ApiKeyGenerator {
|
||||||
|
private readonly SERVER_PREFIX = "minikura_srv_";
|
||||||
|
private readonly REVERSE_PROXY_PREFIX = "minikura_proxy_";
|
||||||
|
private readonly TOKEN_LENGTH = 32;
|
||||||
|
|
||||||
|
generateServerApiKey(): string {
|
||||||
|
const token = Buffer.from(crypto.randomUUID())
|
||||||
|
.toString("base64")
|
||||||
|
.replace(/[^a-zA-Z0-9]/g, "")
|
||||||
|
.substring(0, this.TOKEN_LENGTH);
|
||||||
|
return `${this.SERVER_PREFIX}${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
generateReverseProxyApiKey(): string {
|
||||||
|
const token = Buffer.from(crypto.randomUUID())
|
||||||
|
.toString("base64")
|
||||||
|
.replace(/[^a-zA-Z0-9]/g, "")
|
||||||
|
.substring(0, this.TOKEN_LENGTH);
|
||||||
|
return `${this.REVERSE_PROXY_PREFIX}${token}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
46
apps/backend/src/infrastructure/event-bus.ts
Normal file
46
apps/backend/src/infrastructure/event-bus.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import type { DomainEvent } from "../domain/events/domain-event";
|
||||||
|
import { logger } from "./logger";
|
||||||
|
|
||||||
|
type EventHandler<T extends DomainEvent = DomainEvent> = (event: T) => void | Promise<void>;
|
||||||
|
|
||||||
|
export class EventBus {
|
||||||
|
private handlers = new Map<string, Set<EventHandler>>();
|
||||||
|
private eventHistory: DomainEvent[] = [];
|
||||||
|
|
||||||
|
subscribe<T extends DomainEvent>(
|
||||||
|
eventClass: { new (...args: any[]): T },
|
||||||
|
handler: EventHandler<T>
|
||||||
|
): () => void {
|
||||||
|
const eventName = eventClass.name;
|
||||||
|
if (!this.handlers.has(eventName)) {
|
||||||
|
this.handlers.set(eventName, new Set());
|
||||||
|
}
|
||||||
|
this.handlers.get(eventName)?.add(handler as EventHandler);
|
||||||
|
return () => {
|
||||||
|
this.handlers.get(eventName)?.delete(handler as EventHandler);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async publish<T extends DomainEvent>(event: T): Promise<void> {
|
||||||
|
this.eventHistory.push(event);
|
||||||
|
const eventName = event.constructor.name;
|
||||||
|
const handlers = this.handlers.get(eventName) || [];
|
||||||
|
for (const handler of handlers) {
|
||||||
|
try {
|
||||||
|
await handler(event);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error, eventName }, "Error executing event handler");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getHistory(): DomainEvent[] {
|
||||||
|
return [...this.eventHistory];
|
||||||
|
}
|
||||||
|
|
||||||
|
clearHistory(): void {
|
||||||
|
this.eventHistory = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const eventBus = new EventBus();
|
||||||
6
apps/backend/src/infrastructure/event-handlers/index.ts
Normal file
6
apps/backend/src/infrastructure/event-handlers/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import "./server-event.handler";
|
||||||
|
import "./user-event.handler";
|
||||||
|
|
||||||
|
import { logger } from "../logger";
|
||||||
|
|
||||||
|
logger.debug("All domain event handlers registered");
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { wsService } from "../../application/di-container";
|
||||||
|
import {
|
||||||
|
ServerCreatedEvent,
|
||||||
|
ServerDeletedEvent,
|
||||||
|
ServerUpdatedEvent,
|
||||||
|
} from "../../domain/events/server-lifecycle.events";
|
||||||
|
import { eventBus } from "../event-bus";
|
||||||
|
import { logger } from "../logger";
|
||||||
|
|
||||||
|
eventBus.subscribe(ServerCreatedEvent, async (event) => {
|
||||||
|
logger.info({ serverId: event.serverId, serverType: event.serverType }, "Server created event");
|
||||||
|
wsService.broadcast("create", event.serverType, event.serverId);
|
||||||
|
});
|
||||||
|
|
||||||
|
eventBus.subscribe(ServerUpdatedEvent, async (event) => {
|
||||||
|
logger.info({ serverId: event.serverId }, "Server updated event");
|
||||||
|
wsService.broadcast("update", "server", event.serverId);
|
||||||
|
});
|
||||||
|
|
||||||
|
eventBus.subscribe(ServerDeletedEvent, async (event) => {
|
||||||
|
logger.info({ serverId: event.serverId }, "Server deleted event");
|
||||||
|
wsService.broadcast("delete", "server", event.serverId);
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import {
|
||||||
|
UserSuspendedEvent,
|
||||||
|
UserUnsuspendedEvent,
|
||||||
|
} from "../../domain/events/server-lifecycle.events";
|
||||||
|
import { eventBus } from "../event-bus";
|
||||||
|
import { logger } from "../logger";
|
||||||
|
|
||||||
|
eventBus.subscribe(UserSuspendedEvent, async (event) => {
|
||||||
|
if (event.suspendedUntil) {
|
||||||
|
logger.warn(
|
||||||
|
{ userId: event.userId, suspendedUntil: event.suspendedUntil.toISOString() },
|
||||||
|
"User suspended with expiry"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
logger.warn({ userId: event.userId }, "User suspended indefinitely");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
eventBus.subscribe(UserUnsuspendedEvent, async (event) => {
|
||||||
|
logger.info({ userId: event.userId }, "User unsuspended");
|
||||||
|
});
|
||||||
5
apps/backend/src/infrastructure/logger.ts
Normal file
5
apps/backend/src/infrastructure/logger.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { createLogger } from "@minikura/shared";
|
||||||
|
|
||||||
|
export { createLogger };
|
||||||
|
|
||||||
|
export const logger = createLogger("backend-api");
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import { type EnvVariable, prisma, type ReverseProxyWithEnvVars } from "@minikura/db";
|
||||||
|
import { ConflictError, NotFoundError } from "../../../domain/errors/base.error";
|
||||||
|
import type {
|
||||||
|
ReverseProxyCreateInput,
|
||||||
|
ReverseProxyRepository,
|
||||||
|
ReverseProxyUpdateInput,
|
||||||
|
} from "../../../domain/repositories/reverse-proxy.repository";
|
||||||
|
import { ApiKeyGeneratorImpl } from "../../api-key-generator";
|
||||||
|
|
||||||
|
export class PrismaReverseProxyRepository implements ReverseProxyRepository {
|
||||||
|
private apiKeyGenerator = new ApiKeyGeneratorImpl();
|
||||||
|
|
||||||
|
async findById(id: string, omitSensitive = false): Promise<ReverseProxyWithEnvVars | null> {
|
||||||
|
const proxy = await prisma.reverseProxyServer.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!proxy) return null;
|
||||||
|
|
||||||
|
if (omitSensitive) {
|
||||||
|
const { api_key, ...rest } = proxy;
|
||||||
|
return { ...rest, api_key: "" } as ReverseProxyWithEnvVars;
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(omitSensitive = false): Promise<ReverseProxyWithEnvVars[]> {
|
||||||
|
const proxies = await prisma.reverseProxyServer.findMany({
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (omitSensitive) {
|
||||||
|
return proxies.map((proxy) => {
|
||||||
|
const { api_key, ...rest } = proxy;
|
||||||
|
return { ...rest, api_key: "" } as ReverseProxyWithEnvVars;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies;
|
||||||
|
}
|
||||||
|
|
||||||
|
async exists(id: string): Promise<boolean> {
|
||||||
|
const proxy = await prisma.reverseProxyServer.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
return proxy !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(input: ReverseProxyCreateInput): Promise<ReverseProxyWithEnvVars> {
|
||||||
|
const existing = await this.exists(input.id);
|
||||||
|
if (existing) {
|
||||||
|
throw new ConflictError("ReverseProxyServer", input.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = this.apiKeyGenerator.generateReverseProxyApiKey();
|
||||||
|
|
||||||
|
const proxy = await prisma.reverseProxyServer.create({
|
||||||
|
data: {
|
||||||
|
id: input.id,
|
||||||
|
type: input.type ?? "VELOCITY",
|
||||||
|
description: input.description ?? null,
|
||||||
|
external_address: input.external_address,
|
||||||
|
external_port: input.external_port,
|
||||||
|
listen_port: input.listen_port ?? 25577,
|
||||||
|
service_type: input.service_type ?? "LOAD_BALANCER",
|
||||||
|
node_port: input.node_port ?? null,
|
||||||
|
memory: input.memory ?? 512,
|
||||||
|
cpu_request: input.cpu_request ?? "100m",
|
||||||
|
cpu_limit: input.cpu_limit ?? "200m",
|
||||||
|
api_key: token,
|
||||||
|
env_variables: input.env_variables
|
||||||
|
? {
|
||||||
|
create: input.env_variables.map((ev) => ({
|
||||||
|
key: ev.key,
|
||||||
|
value: ev.value,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, input: ReverseProxyUpdateInput): Promise<ReverseProxyWithEnvVars> {
|
||||||
|
const proxy = await prisma.reverseProxyServer.findUnique({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!proxy) {
|
||||||
|
throw new NotFoundError("ReverseProxyServer", id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update proxy fields
|
||||||
|
const updated = await prisma.reverseProxyServer.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
description: input.description,
|
||||||
|
external_address: input.external_address,
|
||||||
|
external_port: input.external_port,
|
||||||
|
listen_port: input.listen_port,
|
||||||
|
type: input.type,
|
||||||
|
service_type: input.service_type,
|
||||||
|
node_port: input.node_port,
|
||||||
|
memory: input.memory,
|
||||||
|
cpu_request: input.cpu_request,
|
||||||
|
cpu_limit: input.cpu_limit,
|
||||||
|
},
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(id: string): Promise<void> {
|
||||||
|
await prisma.reverseProxyServer.delete({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async setEnvVariable(proxyId: string, key: string, value: string): Promise<void> {
|
||||||
|
await prisma.customEnvironmentVariable.upsert({
|
||||||
|
where: {
|
||||||
|
key_reverse_proxy_id: {
|
||||||
|
key,
|
||||||
|
reverse_proxy_id: proxyId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
value,
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
reverse_proxy_id: proxyId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getEnvVariables(proxyId: string): Promise<EnvVariable[]> {
|
||||||
|
const proxy = await prisma.reverseProxyServer.findUnique({
|
||||||
|
where: { id: proxyId },
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!proxy) {
|
||||||
|
throw new NotFoundError("ReverseProxyServer", proxyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxy.env_variables.map((ev) => ({
|
||||||
|
key: ev.key,
|
||||||
|
value: ev.value,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteEnvVariable(proxyId: string, key: string): Promise<void> {
|
||||||
|
await prisma.customEnvironmentVariable.deleteMany({
|
||||||
|
where: {
|
||||||
|
key,
|
||||||
|
reverse_proxy_id: proxyId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async replaceEnvVariables(proxyId: string, envVars: EnvVariable[]): Promise<void> {
|
||||||
|
await prisma.customEnvironmentVariable.deleteMany({
|
||||||
|
where: { reverse_proxy_id: proxyId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (envVars.length > 0) {
|
||||||
|
await prisma.customEnvironmentVariable.createMany({
|
||||||
|
data: envVars.map((envVar) => ({
|
||||||
|
key: envVar.key,
|
||||||
|
value: envVar.value,
|
||||||
|
reverse_proxy_id: proxyId,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
import { type EnvVariable, prisma, type ServerWithEnvVars } from "@minikura/db";
|
||||||
|
import { ConflictError, NotFoundError } from "../../../domain/errors/base.error";
|
||||||
|
import type {
|
||||||
|
ServerCreateInput,
|
||||||
|
ServerRepository,
|
||||||
|
ServerUpdateInput,
|
||||||
|
} from "../../../domain/repositories/server.repository";
|
||||||
|
import { ApiKeyGeneratorImpl } from "../../api-key-generator";
|
||||||
|
|
||||||
|
export class PrismaServerRepository implements ServerRepository {
|
||||||
|
private apiKeyGenerator = new ApiKeyGeneratorImpl();
|
||||||
|
|
||||||
|
async findById(id: string, omitSensitive = false): Promise<ServerWithEnvVars | null> {
|
||||||
|
const server = await prisma.server.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!server) return null;
|
||||||
|
|
||||||
|
if (omitSensitive) {
|
||||||
|
const { api_key, ...rest } = server;
|
||||||
|
return { ...rest, api_key: "" } as ServerWithEnvVars;
|
||||||
|
}
|
||||||
|
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(omitSensitive = false): Promise<ServerWithEnvVars[]> {
|
||||||
|
const servers = await prisma.server.findMany({
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (omitSensitive) {
|
||||||
|
return servers.map((server) => {
|
||||||
|
const { api_key, ...rest } = server;
|
||||||
|
return { ...rest, api_key: "" } as ServerWithEnvVars;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return servers;
|
||||||
|
}
|
||||||
|
|
||||||
|
async exists(id: string): Promise<boolean> {
|
||||||
|
const server = await prisma.server.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
return server !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(input: ServerCreateInput): Promise<ServerWithEnvVars> {
|
||||||
|
const existing = await this.exists(input.id);
|
||||||
|
if (existing) {
|
||||||
|
throw new ConflictError("Server", input.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = this.apiKeyGenerator.generateServerApiKey();
|
||||||
|
|
||||||
|
const server = await prisma.server.create({
|
||||||
|
data: {
|
||||||
|
id: input.id,
|
||||||
|
type: input.type,
|
||||||
|
description: input.description ?? null,
|
||||||
|
listen_port: input.listen_port,
|
||||||
|
service_type: input.service_type ?? "CLUSTER_IP",
|
||||||
|
node_port: input.node_port ?? null,
|
||||||
|
memory: input.memory ?? 2048,
|
||||||
|
memory_request: input.memory_request ?? 1024,
|
||||||
|
cpu_request: input.cpu_request ?? "250m",
|
||||||
|
cpu_limit: input.cpu_limit ?? "500m",
|
||||||
|
jar_type: input.jar_type ?? "PAPER",
|
||||||
|
minecraft_version: input.minecraft_version ?? "LATEST",
|
||||||
|
jvm_opts: input.jvm_opts ?? null,
|
||||||
|
use_aikar_flags: input.use_aikar_flags ?? true,
|
||||||
|
use_meowice_flags: input.use_meowice_flags ?? false,
|
||||||
|
difficulty: input.difficulty ?? "EASY",
|
||||||
|
game_mode: input.game_mode ?? "SURVIVAL",
|
||||||
|
max_players: input.max_players ?? 20,
|
||||||
|
pvp: input.pvp ?? true,
|
||||||
|
online_mode: input.online_mode ?? true,
|
||||||
|
motd: input.motd ?? null,
|
||||||
|
level_seed: input.level_seed ?? null,
|
||||||
|
level_type: input.level_type ?? null,
|
||||||
|
api_key: token,
|
||||||
|
env_variables: input.env_variables
|
||||||
|
? {
|
||||||
|
create: input.env_variables.map((ev) => ({
|
||||||
|
key: ev.key,
|
||||||
|
value: ev.value,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, input: ServerUpdateInput): Promise<ServerWithEnvVars> {
|
||||||
|
const server = await prisma.server.findUnique({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!server) {
|
||||||
|
throw new NotFoundError("Server", id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle env variables separately
|
||||||
|
if (input.env_variables !== undefined) {
|
||||||
|
await this.replaceEnvVariables(id, input.env_variables);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update server fields
|
||||||
|
const updated = await prisma.server.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
description: input.description,
|
||||||
|
listen_port: input.listen_port,
|
||||||
|
service_type: input.service_type,
|
||||||
|
node_port: input.node_port,
|
||||||
|
memory: input.memory,
|
||||||
|
memory_request: input.memory_request,
|
||||||
|
cpu_request: input.cpu_request,
|
||||||
|
cpu_limit: input.cpu_limit,
|
||||||
|
jar_type: input.jar_type,
|
||||||
|
minecraft_version: input.minecraft_version,
|
||||||
|
jvm_opts: input.jvm_opts,
|
||||||
|
use_aikar_flags: input.use_aikar_flags,
|
||||||
|
use_meowice_flags: input.use_meowice_flags,
|
||||||
|
difficulty: input.difficulty,
|
||||||
|
game_mode: input.game_mode,
|
||||||
|
max_players: input.max_players,
|
||||||
|
pvp: input.pvp,
|
||||||
|
online_mode: input.online_mode,
|
||||||
|
motd: input.motd,
|
||||||
|
level_seed: input.level_seed,
|
||||||
|
level_type: input.level_type,
|
||||||
|
},
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(id: string): Promise<void> {
|
||||||
|
await prisma.server.delete({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async setEnvVariable(serverId: string, key: string, value: string): Promise<void> {
|
||||||
|
await prisma.customEnvironmentVariable.upsert({
|
||||||
|
where: {
|
||||||
|
key_server_id: {
|
||||||
|
key,
|
||||||
|
server_id: serverId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
value,
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
server_id: serverId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getEnvVariables(serverId: string): Promise<EnvVariable[]> {
|
||||||
|
const server = await prisma.server.findUnique({
|
||||||
|
where: { id: serverId },
|
||||||
|
include: { env_variables: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!server) {
|
||||||
|
throw new NotFoundError("Server", serverId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return server.env_variables.map((ev) => ({
|
||||||
|
key: ev.key,
|
||||||
|
value: ev.value,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteEnvVariable(serverId: string, key: string): Promise<void> {
|
||||||
|
await prisma.customEnvironmentVariable.deleteMany({
|
||||||
|
where: {
|
||||||
|
key,
|
||||||
|
server_id: serverId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async replaceEnvVariables(serverId: string, envVars: EnvVariable[]): Promise<void> {
|
||||||
|
await prisma.customEnvironmentVariable.deleteMany({
|
||||||
|
where: { server_id: serverId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (envVars.length > 0) {
|
||||||
|
await prisma.customEnvironmentVariable.createMany({
|
||||||
|
data: envVars.map((envVar) => ({
|
||||||
|
key: envVar.key,
|
||||||
|
value: envVar.value,
|
||||||
|
server_id: serverId,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { prisma, type UpdateSuspensionInput, type UpdateUserInput, type User } from "@minikura/db";
|
||||||
|
import type { UserRepository } from "../../../domain/repositories/user.repository";
|
||||||
|
|
||||||
|
export class PrismaUserRepository implements UserRepository {
|
||||||
|
async findById(id: string): Promise<User | null> {
|
||||||
|
return await prisma.user.findUnique({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByEmail(email: string): Promise<User | null> {
|
||||||
|
return await prisma.user.findUnique({
|
||||||
|
where: { email },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(): Promise<User[]> {
|
||||||
|
return await prisma.user.findMany({
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, input: UpdateUserInput): Promise<User> {
|
||||||
|
return await prisma.user.update({
|
||||||
|
where: { id },
|
||||||
|
data: input,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateSuspension(id: string, input: UpdateSuspensionInput): Promise<User> {
|
||||||
|
return await prisma.user.update({
|
||||||
|
where: { id },
|
||||||
|
data: input,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(id: string): Promise<void> {
|
||||||
|
await prisma.user.delete({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async count(): Promise<number> {
|
||||||
|
return await prisma.user.count();
|
||||||
|
}
|
||||||
|
}
|
||||||
57
apps/backend/src/middleware/auth-guards.ts
Normal file
57
apps/backend/src/middleware/auth-guards.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import type { User } from "@minikura/db";
|
||||||
|
import type { Elysia } from "elysia";
|
||||||
|
import { ForbiddenError, UnauthorizedError } from "../domain/errors/base.error";
|
||||||
|
|
||||||
|
export const requireAuth = (app: Elysia) => {
|
||||||
|
return app.derive((ctx: any) => {
|
||||||
|
const { user, isSuspended } = ctx as {
|
||||||
|
user: User | null;
|
||||||
|
isSuspended: boolean;
|
||||||
|
};
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedError();
|
||||||
|
}
|
||||||
|
if (isSuspended) {
|
||||||
|
throw new ForbiddenError("Account is suspended");
|
||||||
|
}
|
||||||
|
return { user };
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const requireAdmin = (app: Elysia) => {
|
||||||
|
return app.derive((ctx: any) => {
|
||||||
|
const { user, isSuspended } = ctx as {
|
||||||
|
user: User | null;
|
||||||
|
isSuspended: boolean;
|
||||||
|
};
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedError();
|
||||||
|
}
|
||||||
|
if (isSuspended) {
|
||||||
|
throw new ForbiddenError("Account is suspended");
|
||||||
|
}
|
||||||
|
if (user.role !== "admin") {
|
||||||
|
throw new ForbiddenError("Admin access required");
|
||||||
|
}
|
||||||
|
return { user };
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const requireRole = (role: string) => (app: Elysia) => {
|
||||||
|
return app.derive((ctx: any) => {
|
||||||
|
const { user, isSuspended } = ctx as {
|
||||||
|
user: User | null;
|
||||||
|
isSuspended: boolean;
|
||||||
|
};
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedError();
|
||||||
|
}
|
||||||
|
if (isSuspended) {
|
||||||
|
throw new ForbiddenError("Account is suspended");
|
||||||
|
}
|
||||||
|
if (user.role !== role) {
|
||||||
|
throw new ForbiddenError(`${role} access required`);
|
||||||
|
}
|
||||||
|
return { user };
|
||||||
|
});
|
||||||
|
};
|
||||||
44
apps/backend/src/middleware/auth-plugin.ts
Normal file
44
apps/backend/src/middleware/auth-plugin.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { isUserSuspended } from "@minikura/db";
|
||||||
|
import { Elysia } from "elysia";
|
||||||
|
import { auth } from "./auth";
|
||||||
|
|
||||||
|
async function getSessionFromHeaders(headers: Headers | Record<string, string>) {
|
||||||
|
const headersObj =
|
||||||
|
headers instanceof Headers ? headers : new Headers(headers as Record<string, string>);
|
||||||
|
|
||||||
|
return auth.api.getSession({
|
||||||
|
headers: headersObj,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authPlugin = new Elysia({ name: "auth" })
|
||||||
|
.mount(auth.handler)
|
||||||
|
.derive({ as: "scoped" }, async ({ request }) => {
|
||||||
|
const session = await getSessionFromHeaders(request.headers);
|
||||||
|
|
||||||
|
if (
|
||||||
|
session?.user &&
|
||||||
|
isUserSuspended(
|
||||||
|
session.user as unknown as Pick<
|
||||||
|
{ isSuspended: boolean; suspendedUntil: Date | null },
|
||||||
|
"isSuspended" | "suspendedUntil"
|
||||||
|
>
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
user: null,
|
||||||
|
session: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
isSuspended: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
user: session?.user || null,
|
||||||
|
session: session?.session || null,
|
||||||
|
isAuthenticated: Boolean(session?.user),
|
||||||
|
isSuspended: false,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
export type AuthPlugin = typeof authPlugin;
|
||||||
20
apps/backend/src/middleware/auth.ts
Normal file
20
apps/backend/src/middleware/auth.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { prisma } from "@minikura/db";
|
||||||
|
import { betterAuth } from "better-auth";
|
||||||
|
import { prismaAdapter } from "better-auth/adapters/prisma";
|
||||||
|
import { admin, openAPI } from "better-auth/plugins";
|
||||||
|
|
||||||
|
export const auth = betterAuth({
|
||||||
|
database: prismaAdapter(prisma, {
|
||||||
|
provider: "postgresql",
|
||||||
|
usePlural: false,
|
||||||
|
}),
|
||||||
|
emailAndPassword: { enabled: true },
|
||||||
|
plugins: [admin(), openAPI()],
|
||||||
|
trustedOrigins: [process.env.WEB_URL || "http://localhost:3001"],
|
||||||
|
session: {
|
||||||
|
cookieCache: { enabled: true, maxAge: 60 * 5 },
|
||||||
|
},
|
||||||
|
basePath: "/auth",
|
||||||
|
});
|
||||||
|
|
||||||
|
export type Auth = typeof auth;
|
||||||
36
apps/backend/src/middleware/error-handler.ts
Normal file
36
apps/backend/src/middleware/error-handler.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import type { Elysia } from "elysia";
|
||||||
|
import { DomainError } from "../domain/errors/base.error";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
|
||||||
|
export const errorHandler = (app: Elysia) => {
|
||||||
|
return app.onError(({ error, set }) => {
|
||||||
|
if (error instanceof DomainError) {
|
||||||
|
logger.warn({ code: error.code, message: error.message }, "Domain error occurred");
|
||||||
|
set.status = error.statusCode;
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: error.code,
|
||||||
|
message: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof Error && (error.name === "ValidationError" || error.name === "ZodError")) {
|
||||||
|
logger.warn({ err: error, message: error.message }, "Validation error");
|
||||||
|
set.status = 400;
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "VALIDATION_ERROR",
|
||||||
|
message: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.error({ err: error }, "Unhandled error in API request");
|
||||||
|
|
||||||
|
set.status = 500;
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: "INTERNAL_SERVER_ERROR",
|
||||||
|
message: "An unexpected error occurred",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
25
apps/backend/src/middleware/zod-validator.ts
Normal file
25
apps/backend/src/middleware/zod-validator.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import type { z } from "zod";
|
||||||
|
|
||||||
|
type ErrorHandler = (code: number, value: unknown) => never;
|
||||||
|
|
||||||
|
export function validateBody<T extends z.ZodType>(
|
||||||
|
schema: T,
|
||||||
|
body: unknown,
|
||||||
|
error: ErrorHandler
|
||||||
|
): z.infer<T> {
|
||||||
|
const result = schema.safeParse(body);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
const firstError = result.error.issues[0];
|
||||||
|
const message = `${firstError.path.join(".")}: ${firstError.message}`;
|
||||||
|
throw error(400, { message });
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function zodValidate<T extends z.ZodType>(schema: T) {
|
||||||
|
return (context: { body: unknown; error: ErrorHandler }) => {
|
||||||
|
return validateBody(schema, context.body, context.error);
|
||||||
|
};
|
||||||
|
}
|
||||||
52
apps/backend/src/routes/bootstrap.ts
Normal file
52
apps/backend/src/routes/bootstrap.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { prisma } from "@minikura/db";
|
||||||
|
import { getErrorMessage } from "@minikura/shared/errors";
|
||||||
|
import { Elysia } from "elysia";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
import { auth } from "../middleware/auth";
|
||||||
|
import { bootstrapSchema } from "../schemas/bootstrap.schema";
|
||||||
|
|
||||||
|
export const bootstrapRoutes = new Elysia({ prefix: "/bootstrap" })
|
||||||
|
.get("/status", async () => {
|
||||||
|
const userCount = await prisma.user.count();
|
||||||
|
return { needsSetup: userCount === 0 };
|
||||||
|
})
|
||||||
|
.post("/setup", async ({ body, set }) => {
|
||||||
|
const userCount = await prisma.user.count();
|
||||||
|
if (userCount > 0) {
|
||||||
|
set.status = 400;
|
||||||
|
return { message: "Setup already completed" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const validated = bootstrapSchema.safeParse(body);
|
||||||
|
if (!validated.success) {
|
||||||
|
const firstError = validated.error.issues[0];
|
||||||
|
set.status = 400;
|
||||||
|
return {
|
||||||
|
message: `${firstError.path.join(".")}: ${firstError.message}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const data = validated.data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await auth.api.createUser({
|
||||||
|
body: {
|
||||||
|
email: data.email,
|
||||||
|
password: data.password,
|
||||||
|
name: data.name,
|
||||||
|
role: "admin",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.user) {
|
||||||
|
logger.error({ result }, "No user in bootstrap response");
|
||||||
|
set.status = 500;
|
||||||
|
return { message: "Failed to create user" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (err: unknown) {
|
||||||
|
logger.error({ err }, "Bootstrap setup failed");
|
||||||
|
set.status = 500;
|
||||||
|
return { message: getErrorMessage(err) };
|
||||||
|
}
|
||||||
|
});
|
||||||
80
apps/backend/src/routes/k8s.ts
Normal file
80
apps/backend/src/routes/k8s.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import { labelKeys } from "@minikura/api";
|
||||||
|
import { Elysia } from "elysia";
|
||||||
|
import { k8sService } from "../application/di-container";
|
||||||
|
import { requireAuth } from "../middleware/auth-guards";
|
||||||
|
import { authPlugin } from "../middleware/auth-plugin";
|
||||||
|
|
||||||
|
export const k8sRoutes = new Elysia({ prefix: "/k8s" })
|
||||||
|
.use(authPlugin)
|
||||||
|
.use(requireAuth)
|
||||||
|
.get("/status", async () => {
|
||||||
|
return k8sService.getConnectionInfo();
|
||||||
|
})
|
||||||
|
.get("/pods", async () => {
|
||||||
|
return await k8sService.getPods();
|
||||||
|
})
|
||||||
|
.get("/deployments", async () => {
|
||||||
|
return await k8sService.getDeployments();
|
||||||
|
})
|
||||||
|
.get("/statefulsets", async () => {
|
||||||
|
return await k8sService.getStatefulSets();
|
||||||
|
})
|
||||||
|
.get("/services", async () => {
|
||||||
|
return await k8sService.getServices();
|
||||||
|
})
|
||||||
|
.get("/configmaps", async () => {
|
||||||
|
return await k8sService.getConfigMaps();
|
||||||
|
})
|
||||||
|
.get("/ingresses", async () => {
|
||||||
|
return await k8sService.getIngresses();
|
||||||
|
})
|
||||||
|
.get("/minecraft-servers", async () => {
|
||||||
|
return await k8sService.getMinecraftServers();
|
||||||
|
})
|
||||||
|
.get("/reverse-proxy-servers", async () => {
|
||||||
|
return await k8sService.getReverseProxyServers();
|
||||||
|
})
|
||||||
|
.get("/pods/:podName", async ({ params }) => {
|
||||||
|
return await k8sService.getPodInfo(params.podName);
|
||||||
|
})
|
||||||
|
.get("/pods/:podName/logs", async ({ params, query, set }) => {
|
||||||
|
const options = {
|
||||||
|
container: query.container as string | undefined,
|
||||||
|
tailLines: query.tailLines ? parseInt(query.tailLines as string, 10) : 1000,
|
||||||
|
timestamps: query.timestamps === "true",
|
||||||
|
sinceSeconds: query.sinceSeconds ? parseInt(query.sinceSeconds as string, 10) : undefined,
|
||||||
|
};
|
||||||
|
const logs = await k8sService.getPodLogs(params.podName, options);
|
||||||
|
|
||||||
|
// Return as plain text
|
||||||
|
const headers = (set.headers ?? {}) as Record<string, string>;
|
||||||
|
headers["content-type"] = "text/plain";
|
||||||
|
set.headers = headers;
|
||||||
|
return logs;
|
||||||
|
})
|
||||||
|
.get("/servers/:serverId/pods", async ({ params }) => {
|
||||||
|
const labelSelector = `${labelKeys.serverId}=${params.serverId}`;
|
||||||
|
return await k8sService.getPodsByLabel(labelSelector);
|
||||||
|
})
|
||||||
|
.get("/reverse-proxy/:serverId/pods", async ({ params }) => {
|
||||||
|
const labelSelector = `${labelKeys.proxyId}=${params.serverId}`;
|
||||||
|
return await k8sService.getPodsByLabel(labelSelector);
|
||||||
|
})
|
||||||
|
.get("/services/:serviceName", async ({ params }) => {
|
||||||
|
return await k8sService.getServiceInfo(params.serviceName);
|
||||||
|
})
|
||||||
|
.get("/services/:serviceName/connection-info", async ({ params }) => {
|
||||||
|
return await k8sService.getServerConnectionInfo(params.serviceName);
|
||||||
|
})
|
||||||
|
.get("/nodes", async () => {
|
||||||
|
return await k8sService.getNodes();
|
||||||
|
})
|
||||||
|
.group("/metrics", (app) =>
|
||||||
|
app
|
||||||
|
.get("/pods", async () => {
|
||||||
|
return await k8sService.getPodMetrics();
|
||||||
|
})
|
||||||
|
.get("/nodes", async () => {
|
||||||
|
return await k8sService.getNodeMetrics();
|
||||||
|
})
|
||||||
|
);
|
||||||
53
apps/backend/src/routes/reverse-proxy.ts
Normal file
53
apps/backend/src/routes/reverse-proxy.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import { Elysia } from "elysia";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { reverseProxyService } from "../application/di-container";
|
||||||
|
import { requireAuth } from "../middleware/auth-guards";
|
||||||
|
import { createReverseProxySchema, updateReverseProxySchema } from "../schemas/server.schema";
|
||||||
|
|
||||||
|
const envVariableSchema = z.object({
|
||||||
|
key: z.string(),
|
||||||
|
value: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const reverseProxyRoutes = new Elysia({ prefix: "/reverse-proxy" })
|
||||||
|
.use(requireAuth)
|
||||||
|
.get("/", async () => {
|
||||||
|
return await reverseProxyService.getAllReverseProxies(false);
|
||||||
|
})
|
||||||
|
|
||||||
|
.get("/:id", async ({ params }) => {
|
||||||
|
return await reverseProxyService.getReverseProxyById(params.id, false);
|
||||||
|
})
|
||||||
|
|
||||||
|
.post("/", async ({ body }) => {
|
||||||
|
const payload = createReverseProxySchema.parse(body);
|
||||||
|
const proxy = await reverseProxyService.createReverseProxy(payload);
|
||||||
|
return proxy;
|
||||||
|
})
|
||||||
|
|
||||||
|
.patch("/:id", async ({ params, body }) => {
|
||||||
|
const payload = updateReverseProxySchema.parse(body);
|
||||||
|
const proxy = await reverseProxyService.updateReverseProxy(params.id, payload);
|
||||||
|
return proxy;
|
||||||
|
})
|
||||||
|
|
||||||
|
.delete("/:id", async ({ params }) => {
|
||||||
|
await reverseProxyService.deleteReverseProxy(params.id);
|
||||||
|
return { success: true };
|
||||||
|
})
|
||||||
|
|
||||||
|
.get("/:id/env", async ({ params }) => {
|
||||||
|
const envVariables = await reverseProxyService.getEnvVariables(params.id);
|
||||||
|
return { env_variables: envVariables };
|
||||||
|
})
|
||||||
|
|
||||||
|
.post("/:id/env", async ({ params, body }) => {
|
||||||
|
const payload = envVariableSchema.parse(body);
|
||||||
|
await reverseProxyService.setEnvVariable(params.id, payload.key, payload.value);
|
||||||
|
return { success: true };
|
||||||
|
})
|
||||||
|
|
||||||
|
.delete("/:id/env/:key", async ({ params }) => {
|
||||||
|
await reverseProxyService.deleteEnvVariable(params.id, params.key);
|
||||||
|
return { success: true };
|
||||||
|
});
|
||||||
71
apps/backend/src/routes/servers.ts
Normal file
71
apps/backend/src/routes/servers.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import { Elysia } from "elysia";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { serverService, wsService } from "../application/di-container";
|
||||||
|
import { requireAuth } from "../middleware/auth-guards";
|
||||||
|
import { createServerSchema, updateServerSchema } from "../schemas/server.schema";
|
||||||
|
import type { WebSocketClient } from "../services/websocket";
|
||||||
|
|
||||||
|
const envVariableSchema = z.object({
|
||||||
|
key: z.string(),
|
||||||
|
value: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const serverRoutes = new Elysia({ prefix: "/servers" })
|
||||||
|
.ws("/ws", {
|
||||||
|
open(ws: WebSocketClient & { data?: { query?: Record<string, string> }; close: () => void }) {
|
||||||
|
if (!ws.data?.query?.apiKey) {
|
||||||
|
ws.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
wsService.addClient(ws);
|
||||||
|
},
|
||||||
|
close(ws: WebSocketClient) {
|
||||||
|
wsService.removeClient(ws);
|
||||||
|
},
|
||||||
|
message() {},
|
||||||
|
})
|
||||||
|
.use(requireAuth)
|
||||||
|
.get("/", async () => {
|
||||||
|
return await serverService.getAllServers(false);
|
||||||
|
})
|
||||||
|
|
||||||
|
.get("/:id", async ({ params }) => {
|
||||||
|
return await serverService.getServerById(params.id, false);
|
||||||
|
})
|
||||||
|
|
||||||
|
.get("/:id/connection-info", async ({ params }) => {
|
||||||
|
return await serverService.getConnectionInfo(params.id);
|
||||||
|
})
|
||||||
|
|
||||||
|
.post("/", async ({ body }) => {
|
||||||
|
const payload = createServerSchema.parse(body);
|
||||||
|
const server = await serverService.createServer(payload);
|
||||||
|
return server;
|
||||||
|
})
|
||||||
|
|
||||||
|
.patch("/:id", async ({ params, body }) => {
|
||||||
|
const payload = updateServerSchema.parse(body);
|
||||||
|
const server = await serverService.updateServer(params.id, payload);
|
||||||
|
return server;
|
||||||
|
})
|
||||||
|
|
||||||
|
.delete("/:id", async ({ params }) => {
|
||||||
|
await serverService.deleteServer(params.id);
|
||||||
|
return { success: true };
|
||||||
|
})
|
||||||
|
|
||||||
|
.get("/:id/env", async ({ params }) => {
|
||||||
|
const envVariables = await serverService.getEnvVariables(params.id);
|
||||||
|
return { env_variables: envVariables };
|
||||||
|
})
|
||||||
|
|
||||||
|
.post("/:id/env", async ({ params, body }) => {
|
||||||
|
const payload = envVariableSchema.parse(body);
|
||||||
|
await serverService.setEnvVariable(params.id, payload.key, payload.value);
|
||||||
|
return { success: true };
|
||||||
|
})
|
||||||
|
|
||||||
|
.delete("/:id/env/:key", async ({ params }) => {
|
||||||
|
await serverService.deleteEnvVariable(params.id, params.key);
|
||||||
|
return { success: true };
|
||||||
|
});
|
||||||
355
apps/backend/src/routes/terminal.ts
Normal file
355
apps/backend/src/routes/terminal.ts
Normal file
@@ -0,0 +1,355 @@
|
|||||||
|
import { getErrorMessage } from "@minikura/shared/errors";
|
||||||
|
import { Elysia } from "elysia";
|
||||||
|
import { k8sService } from "../application/di-container";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
|
||||||
|
type TerminalWsData = {
|
||||||
|
query?: Record<string, string>;
|
||||||
|
k8sWs?: WebSocket;
|
||||||
|
};
|
||||||
|
|
||||||
|
type TerminalWs = {
|
||||||
|
data: TerminalWsData;
|
||||||
|
send: (message: string) => void;
|
||||||
|
close: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type TerminalMessage =
|
||||||
|
| { type: "input"; data: string }
|
||||||
|
| { type: "resize"; cols: number; rows: number };
|
||||||
|
|
||||||
|
type BunTlsOptions = {
|
||||||
|
rejectUnauthorized: boolean;
|
||||||
|
cert?: string;
|
||||||
|
key?: string;
|
||||||
|
ca?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||||
|
open: async (ws: TerminalWs) => {
|
||||||
|
const podName = ws.data.query?.podName;
|
||||||
|
const container = ws.data.query?.container;
|
||||||
|
const shell = ws.data.query?.shell || "/bin/sh";
|
||||||
|
const mode = ws.data.query?.mode || "shell";
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
`Opening terminal for pod: ${podName}, container: ${container}, shell: ${shell}, mode: ${mode}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!podName) {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "error",
|
||||||
|
data: "Pod name is required",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
ws.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!k8sService.isInitialized()) {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "error",
|
||||||
|
data: "Kubernetes client not initialized",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
ws.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const kc = k8sService.getKubeConfig();
|
||||||
|
const namespace = k8sService.getNamespace();
|
||||||
|
const cluster = kc.getCurrentCluster();
|
||||||
|
const user = kc.getCurrentUser();
|
||||||
|
|
||||||
|
if (!cluster) {
|
||||||
|
throw new Error("No current cluster configured");
|
||||||
|
}
|
||||||
|
|
||||||
|
const server = cluster.server;
|
||||||
|
const isAttach = mode === "attach";
|
||||||
|
const apiPath = isAttach
|
||||||
|
? `/api/v1/namespaces/${namespace}/pods/${podName}/attach`
|
||||||
|
: `/api/v1/namespaces/${namespace}/pods/${podName}/exec`;
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
stdout: "true",
|
||||||
|
stderr: "true",
|
||||||
|
stdin: "true",
|
||||||
|
tty: "true",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isAttach) {
|
||||||
|
params.append("command", shell);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container) {
|
||||||
|
params.append("container", container);
|
||||||
|
}
|
||||||
|
|
||||||
|
const wsUrl = `${server}${apiPath}?${params.toString()}`
|
||||||
|
.replace("https://", "wss://")
|
||||||
|
.replace("http://", "ws://");
|
||||||
|
|
||||||
|
logger.debug(`Connecting to Kubernetes: ${wsUrl}`);
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
Connection: "Upgrade",
|
||||||
|
Upgrade: "websocket",
|
||||||
|
"Sec-WebSocket-Version": "13",
|
||||||
|
"Sec-WebSocket-Key": Buffer.from(Math.random().toString())
|
||||||
|
.toString("base64")
|
||||||
|
.substring(0, 24),
|
||||||
|
"Sec-WebSocket-Protocol": "v4.channel.k8s.io",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (user?.token) {
|
||||||
|
headers.Authorization = `Bearer ${user.token}`;
|
||||||
|
} else if (user?.username && user?.password) {
|
||||||
|
const auth = Buffer.from(`${user.username}:${user.password}`).toString("base64");
|
||||||
|
headers.Authorization = `Basic ${auth}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tlsOptions: BunTlsOptions = {
|
||||||
|
rejectUnauthorized: cluster.skipTLSVerify !== true,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (user?.certData) {
|
||||||
|
tlsOptions.cert = Buffer.from(user.certData, "base64").toString();
|
||||||
|
}
|
||||||
|
if (user?.keyData) {
|
||||||
|
tlsOptions.key = Buffer.from(user.keyData, "base64").toString();
|
||||||
|
}
|
||||||
|
if (cluster.caData) {
|
||||||
|
tlsOptions.ca = Buffer.from(cluster.caData, "base64").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
const wsOptions = { headers, tls: tlsOptions };
|
||||||
|
const k8sWs = new WebSocket(wsUrl, wsOptions as unknown as string | string[]);
|
||||||
|
ws.data.k8sWs = k8sWs;
|
||||||
|
|
||||||
|
k8sWs.onopen = async () => {
|
||||||
|
logger.debug(`Connected to Kubernetes ${isAttach ? "attach" : "exec"}`);
|
||||||
|
|
||||||
|
if (isAttach) {
|
||||||
|
try {
|
||||||
|
const coreApi = k8sService.getCoreApi();
|
||||||
|
const logs = await coreApi.readNamespacedPodLog({
|
||||||
|
name: podName,
|
||||||
|
namespace: namespace,
|
||||||
|
container: container,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (logs) {
|
||||||
|
const lines = logs.split("\n");
|
||||||
|
for (const line of lines) {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "output",
|
||||||
|
data: `${line}\r\n`,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "ready",
|
||||||
|
data: "Attached to container (showing logs since start)",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} catch (logError) {
|
||||||
|
logger.error("Failed to fetch historical logs:", logError);
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "ready",
|
||||||
|
data: "Attached to container",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "ready",
|
||||||
|
data: "Shell ready",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
k8sWs.onmessage = (event: MessageEvent) => {
|
||||||
|
try {
|
||||||
|
const data = event.data;
|
||||||
|
|
||||||
|
let buffer: Uint8Array;
|
||||||
|
|
||||||
|
if (data instanceof Uint8Array) {
|
||||||
|
buffer = data;
|
||||||
|
} else if (data instanceof ArrayBuffer) {
|
||||||
|
buffer = new Uint8Array(data);
|
||||||
|
} else if (Buffer.isBuffer(data)) {
|
||||||
|
buffer = new Uint8Array(data);
|
||||||
|
} else if (data instanceof Blob) {
|
||||||
|
data.arrayBuffer().then((ab) => {
|
||||||
|
const uint8 = new Uint8Array(ab);
|
||||||
|
processBuffer(uint8);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
} else if (typeof data === "string") {
|
||||||
|
ws.send(JSON.stringify({ type: "output", data }));
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
logger.debug(
|
||||||
|
"Unknown data type:",
|
||||||
|
typeof data,
|
||||||
|
"constructor:",
|
||||||
|
data?.constructor?.name
|
||||||
|
);
|
||||||
|
buffer = new Uint8Array(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
processBuffer(buffer);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("Error processing Kubernetes message:", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function processBuffer(buffer: Uint8Array): void {
|
||||||
|
if (buffer.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const channel = buffer[0];
|
||||||
|
const message = new TextDecoder().decode(buffer.slice(1));
|
||||||
|
|
||||||
|
if (channel === 1 || channel === 2) {
|
||||||
|
ws.send(JSON.stringify({ type: "output", data: message }));
|
||||||
|
} else if (channel === 3) {
|
||||||
|
logger.error("Kubernetes error channel:", message);
|
||||||
|
ws.send(JSON.stringify({ type: "error", data: message }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
k8sWs.onerror = (error: Event) => {
|
||||||
|
logger.error("Kubernetes WebSocket error:", error);
|
||||||
|
const message = getErrorMessage(error);
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "error",
|
||||||
|
data: `Connection error: ${message}`,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
k8sWs.onclose = (event: CloseEvent) => {
|
||||||
|
logger.debug(`Kubernetes WebSocket closed: ${event.code} ${event.reason}`);
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "close",
|
||||||
|
data: event.reason || "Connection closed",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
ws.close();
|
||||||
|
};
|
||||||
|
} catch (error: unknown) {
|
||||||
|
logger.error("Error setting up terminal:", error);
|
||||||
|
if (error instanceof Error) {
|
||||||
|
logger.error("Error stack:", error.stack);
|
||||||
|
}
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "error",
|
||||||
|
data: `Failed to connect: ${getErrorMessage(error)}`,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
ws.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
message: async (ws: TerminalWs, message: unknown) => {
|
||||||
|
try {
|
||||||
|
const data = parseTerminalMessage(message);
|
||||||
|
if (!data) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const k8sWs = ws.data.k8sWs;
|
||||||
|
|
||||||
|
if (!k8sWs || k8sWs.readyState !== WebSocket.OPEN) {
|
||||||
|
logger.error("Kubernetes WebSocket not ready, state:", k8sWs?.readyState);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.type === "input") {
|
||||||
|
logger.debug("Sending input to k8s:", data.data);
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const textData = encoder.encode(data.data);
|
||||||
|
const buffer = new Uint8Array(1 + textData.length);
|
||||||
|
buffer[0] = 0;
|
||||||
|
buffer.set(textData, 1);
|
||||||
|
k8sWs.send(buffer.buffer);
|
||||||
|
} else if (data.type === "resize") {
|
||||||
|
const resizeMsg = JSON.stringify({
|
||||||
|
Width: data.cols,
|
||||||
|
Height: data.rows,
|
||||||
|
});
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const textData = encoder.encode(resizeMsg);
|
||||||
|
const buffer = new Uint8Array(1 + textData.length);
|
||||||
|
buffer[0] = 4;
|
||||||
|
buffer.set(textData, 1);
|
||||||
|
k8sWs.send(buffer.buffer);
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
logger.error("Error handling terminal message:", error);
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "error",
|
||||||
|
data: `Error: ${getErrorMessage(error)}`,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
close: (ws: TerminalWs) => {
|
||||||
|
logger.debug("Client WebSocket closed");
|
||||||
|
const k8sWs = ws.data.k8sWs;
|
||||||
|
if (k8sWs && k8sWs.readyState === WebSocket.OPEN) {
|
||||||
|
k8sWs.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function parseTerminalMessage(message: unknown): TerminalMessage | null {
|
||||||
|
if (typeof message === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(message) as unknown;
|
||||||
|
return isTerminalMessage(parsed) ? parsed : null;
|
||||||
|
} catch {
|
||||||
|
logger.error("Failed to parse message as JSON:", message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTerminalMessage(value: unknown): value is TerminalMessage {
|
||||||
|
if (!value || typeof value !== "object") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!("type" in value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const type = (value as { type?: unknown }).type;
|
||||||
|
if (type === "input") {
|
||||||
|
return typeof (value as { data?: unknown }).data === "string";
|
||||||
|
}
|
||||||
|
if (type === "resize") {
|
||||||
|
const cols = (value as { cols?: unknown }).cols;
|
||||||
|
const rows = (value as { rows?: unknown }).rows;
|
||||||
|
return typeof cols === "number" && typeof rows === "number";
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
30
apps/backend/src/routes/users.ts
Normal file
30
apps/backend/src/routes/users.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import type { UpdateUserInput } from "@minikura/db";
|
||||||
|
import { Elysia } from "elysia";
|
||||||
|
import { userService } from "../application/di-container";
|
||||||
|
import { requireAdmin, requireAuth } from "../middleware/auth-guards";
|
||||||
|
|
||||||
|
export const userRoutes = new Elysia({ prefix: "/users" })
|
||||||
|
.use(requireAdmin)
|
||||||
|
.get("/", async () => {
|
||||||
|
const users = await userService.getAllUsers();
|
||||||
|
return users;
|
||||||
|
})
|
||||||
|
|
||||||
|
.use(requireAuth)
|
||||||
|
.get("/:id", async ({ params }) => {
|
||||||
|
const foundUser = await userService.getUserById(params.id);
|
||||||
|
return foundUser;
|
||||||
|
})
|
||||||
|
|
||||||
|
.use(requireAdmin)
|
||||||
|
.patch("/:id", async ({ params, body }) => {
|
||||||
|
const input = body as UpdateUserInput;
|
||||||
|
const updatedUser = await userService.updateUser(params.id, input);
|
||||||
|
return updatedUser;
|
||||||
|
})
|
||||||
|
|
||||||
|
.use(requireAuth)
|
||||||
|
.delete("/:id", async ({ params, user }) => {
|
||||||
|
await userService.deleteUser(user.id, params.id);
|
||||||
|
return { success: true };
|
||||||
|
});
|
||||||
9
apps/backend/src/schemas/bootstrap.schema.ts
Normal file
9
apps/backend/src/schemas/bootstrap.schema.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const bootstrapSchema = z.object({
|
||||||
|
name: z.string().min(1, "Name is required"),
|
||||||
|
email: z.string().email("Valid email is required"),
|
||||||
|
password: z.string().min(8, "Password must be at least 8 characters"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type BootstrapInput = z.infer<typeof bootstrapSchema>;
|
||||||
148
apps/backend/src/schemas/server.schema.ts
Normal file
148
apps/backend/src/schemas/server.schema.ts
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
import {
|
||||||
|
MinecraftServerJarType,
|
||||||
|
ReverseProxyServerType,
|
||||||
|
ServerType,
|
||||||
|
ServiceType,
|
||||||
|
} from "@minikura/db";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { GameMode, ServerDifficulty } from "../domain/entities/enums";
|
||||||
|
|
||||||
|
export const serverIdSchema = z.object({
|
||||||
|
id: z
|
||||||
|
.string()
|
||||||
|
.min(1, "Server ID is required")
|
||||||
|
.regex(/^[a-zA-Z0-9-_]+$/, "ID must be alphanumeric with - or _"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const createServerSchema = z.object({
|
||||||
|
id: z
|
||||||
|
.string()
|
||||||
|
.min(1, "Server ID is required")
|
||||||
|
.regex(/^[a-zA-Z0-9-_]+$/, "ID must be alphanumeric with - or _"),
|
||||||
|
description: z.string().nullable().optional(),
|
||||||
|
listen_port: z.number().int().min(1).max(65535),
|
||||||
|
type: z.nativeEnum(ServerType),
|
||||||
|
service_type: z.nativeEnum(ServiceType).optional(),
|
||||||
|
node_port: z.union([z.number().int().min(30000).max(32767), z.null()]).optional(),
|
||||||
|
env_variables: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
key: z.string().min(1),
|
||||||
|
value: z.string(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
memory: z.number().int().min(256).optional(),
|
||||||
|
memory_request: z.number().int().min(256).optional(),
|
||||||
|
cpu_request: z.string().optional(),
|
||||||
|
cpu_limit: z.string().optional(),
|
||||||
|
|
||||||
|
jar_type: z.nativeEnum(MinecraftServerJarType).optional(),
|
||||||
|
minecraft_version: z.string().optional(),
|
||||||
|
|
||||||
|
jvm_opts: z.string().optional(),
|
||||||
|
use_aikar_flags: z.boolean().optional(),
|
||||||
|
use_meowice_flags: z.boolean().optional(),
|
||||||
|
|
||||||
|
difficulty: z.nativeEnum(ServerDifficulty).optional(),
|
||||||
|
game_mode: z.nativeEnum(GameMode).optional(),
|
||||||
|
max_players: z.number().int().min(1).max(1000).optional(),
|
||||||
|
pvp: z.boolean().optional(),
|
||||||
|
online_mode: z.boolean().optional(),
|
||||||
|
motd: z.string().optional(),
|
||||||
|
level_seed: z.string().optional(),
|
||||||
|
level_type: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateServerSchema = z.object({
|
||||||
|
description: z.string().nullable().optional(),
|
||||||
|
listen_port: z.number().int().min(1).max(65535).optional(),
|
||||||
|
service_type: z.nativeEnum(ServiceType).optional(),
|
||||||
|
node_port: z
|
||||||
|
.union([
|
||||||
|
z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(30000, "Node port must be at least 30000")
|
||||||
|
.max(32767, "Node port must be at most 32767"),
|
||||||
|
z.null(),
|
||||||
|
])
|
||||||
|
.optional(),
|
||||||
|
env_variables: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
key: z.string().min(1),
|
||||||
|
value: z.string(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
memory: z.number().int().min(256).optional(),
|
||||||
|
memory_request: z.number().int().min(256).optional(),
|
||||||
|
cpu_request: z.string().optional(),
|
||||||
|
cpu_limit: z.string().optional(),
|
||||||
|
|
||||||
|
jar_type: z.nativeEnum(MinecraftServerJarType).optional(),
|
||||||
|
minecraft_version: z.string().optional(),
|
||||||
|
|
||||||
|
jvm_opts: z.string().optional(),
|
||||||
|
use_aikar_flags: z.boolean().optional(),
|
||||||
|
use_meowice_flags: z.boolean().optional(),
|
||||||
|
|
||||||
|
difficulty: z.nativeEnum(ServerDifficulty).optional(),
|
||||||
|
game_mode: z.nativeEnum(GameMode).optional(),
|
||||||
|
max_players: z.number().int().min(1).max(1000).optional(),
|
||||||
|
pvp: z.boolean().optional(),
|
||||||
|
online_mode: z.boolean().optional(),
|
||||||
|
motd: z.string().optional(),
|
||||||
|
level_seed: z.string().optional(),
|
||||||
|
level_type: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const createReverseProxySchema = z.object({
|
||||||
|
id: z
|
||||||
|
.string()
|
||||||
|
.min(1, "Server ID is required")
|
||||||
|
.regex(/^[a-zA-Z0-9-_]+$/, "ID must be alphanumeric with - or _"),
|
||||||
|
description: z.string().nullable().optional(),
|
||||||
|
external_address: z.string().min(1, "External address is required"),
|
||||||
|
external_port: z.number().int().min(1).max(65535),
|
||||||
|
listen_port: z.number().int().min(1).max(65535).optional(),
|
||||||
|
type: z.nativeEnum(ReverseProxyServerType).optional(),
|
||||||
|
service_type: z.nativeEnum(ServiceType).optional(),
|
||||||
|
node_port: z.union([z.number().int().min(30000).max(32767), z.null()]).optional(),
|
||||||
|
env_variables: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
key: z.string().min(1),
|
||||||
|
value: z.string(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
memory: z.number().int().min(256).optional(),
|
||||||
|
cpu_request: z.string().optional(),
|
||||||
|
cpu_limit: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateReverseProxySchema = z.object({
|
||||||
|
description: z.string().nullable().optional(),
|
||||||
|
external_address: z.string().optional(),
|
||||||
|
external_port: z.number().int().min(1).max(65535).optional(),
|
||||||
|
listen_port: z.number().int().min(1).max(65535).optional(),
|
||||||
|
type: z.nativeEnum(ReverseProxyServerType).optional(),
|
||||||
|
service_type: z.nativeEnum(ServiceType).optional(),
|
||||||
|
node_port: z.union([z.number().int().min(30000).max(32767), z.null()]).optional(),
|
||||||
|
memory: z.number().int().min(256).optional(),
|
||||||
|
cpu_request: z.string().optional(),
|
||||||
|
cpu_limit: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const envVariableSchema = z.object({
|
||||||
|
key: z.string().min(1, "Key is required"),
|
||||||
|
value: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreateServerInput = z.infer<typeof createServerSchema>;
|
||||||
|
export type UpdateServerInput = z.infer<typeof updateServerSchema>;
|
||||||
|
export type CreateReverseProxyInput = z.infer<typeof createReverseProxySchema>;
|
||||||
|
export type UpdateReverseProxyInput = z.infer<typeof updateReverseProxySchema>;
|
||||||
|
export type EnvVariableInput = z.infer<typeof envVariableSchema>;
|
||||||
19
apps/backend/src/schemas/user.schema.ts
Normal file
19
apps/backend/src/schemas/user.schema.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const updateUserSchema = z.object({
|
||||||
|
name: z.string().min(1).optional(),
|
||||||
|
role: z.enum(["admin", "user"]).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateSuspensionSchema = z.object({
|
||||||
|
isSuspended: z.boolean(),
|
||||||
|
suspendedUntil: z.string().nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const suspendUserSchema = z.object({
|
||||||
|
suspendedUntil: z.string().nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type UpdateUserInput = z.infer<typeof updateUserSchema>;
|
||||||
|
export type UpdateSuspensionInput = z.infer<typeof updateSuspensionSchema>;
|
||||||
|
export type SuspendUserInput = z.infer<typeof suspendUserSchema>;
|
||||||
273
apps/backend/src/services/k8s.ts
Normal file
273
apps/backend/src/services/k8s.ts
Normal file
@@ -0,0 +1,273 @@
|
|||||||
|
import * as k8s from "@kubernetes/client-node";
|
||||||
|
import type { CustomResourceSummary } from "@minikura/api";
|
||||||
|
import { API_GROUP } from "@minikura/api";
|
||||||
|
import { buildKubeConfig } from "@minikura/shared/kube-auth";
|
||||||
|
import type { IK8sService } from "../application/interfaces/k8s.service.interface";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
import { ClusterOperations } from "./kubernetes/operations/cluster.operations";
|
||||||
|
import { CustomResourceOperations } from "./kubernetes/operations/custom-resource.operations";
|
||||||
|
import { NetworkOperations } from "./kubernetes/operations/network.operations";
|
||||||
|
import { PodOperations } from "./kubernetes/operations/pod.operations";
|
||||||
|
import { WorkloadOperations } from "./kubernetes/operations/workload.operations";
|
||||||
|
import { K8sResources } from "./kubernetes/resources";
|
||||||
|
|
||||||
|
const CUSTOM_RESOURCE_VERSION = "v1alpha1";
|
||||||
|
|
||||||
|
export class K8sService implements IK8sService {
|
||||||
|
private kc!: k8s.KubeConfig;
|
||||||
|
private coreApi!: k8s.CoreV1Api;
|
||||||
|
private appsApi!: k8s.AppsV1Api;
|
||||||
|
private customObjectsApi!: k8s.CustomObjectsApi;
|
||||||
|
private networkingApi!: k8s.NetworkingV1Api;
|
||||||
|
private namespace: string;
|
||||||
|
private initialized: boolean = false;
|
||||||
|
private resources!: K8sResources;
|
||||||
|
|
||||||
|
private podOps!: PodOperations;
|
||||||
|
private clusterOps!: ClusterOperations;
|
||||||
|
private customResourceOps!: CustomResourceOperations;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.namespace = process.env.KUBERNETES_NAMESPACE || "minikura";
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.kc = buildKubeConfig();
|
||||||
|
this.initializeClients();
|
||||||
|
this.initializeOperations();
|
||||||
|
this.resources = new K8sResources(
|
||||||
|
this.coreApi,
|
||||||
|
this.appsApi,
|
||||||
|
this.networkingApi,
|
||||||
|
this.namespace
|
||||||
|
);
|
||||||
|
this.initialized = true;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error }, "Failed to initialize Kubernetes client");
|
||||||
|
this.initialized = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private initializeClients(): void {
|
||||||
|
this.coreApi = this.kc.makeApiClient(k8s.CoreV1Api);
|
||||||
|
this.appsApi = this.kc.makeApiClient(k8s.AppsV1Api);
|
||||||
|
this.customObjectsApi = this.kc.makeApiClient(k8s.CustomObjectsApi);
|
||||||
|
this.networkingApi = this.kc.makeApiClient(k8s.NetworkingV1Api);
|
||||||
|
}
|
||||||
|
|
||||||
|
private initializeOperations(): void {
|
||||||
|
this.podOps = new PodOperations(this.coreApi, this.namespace);
|
||||||
|
this.workloadOps = new WorkloadOperations(this.appsApi, this.namespace);
|
||||||
|
this.networkOps = new NetworkOperations(this.coreApi, this.networkingApi, this.namespace);
|
||||||
|
this.clusterOps = new ClusterOperations(this.coreApi, this.customObjectsApi, this.namespace);
|
||||||
|
this.customResourceOps = new CustomResourceOperations(this.customObjectsApi, this.namespace);
|
||||||
|
}
|
||||||
|
|
||||||
|
isInitialized(): boolean {
|
||||||
|
return this.initialized;
|
||||||
|
}
|
||||||
|
|
||||||
|
getConnectionInfo(): {
|
||||||
|
initialized: boolean;
|
||||||
|
currentContext?: string;
|
||||||
|
cluster?: string;
|
||||||
|
namespace: string;
|
||||||
|
} {
|
||||||
|
if (!this.initialized) {
|
||||||
|
return { initialized: false, namespace: this.namespace };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const currentContext = this.kc.getCurrentContext();
|
||||||
|
const cluster = this.kc.getCurrentCluster()?.name;
|
||||||
|
return {
|
||||||
|
initialized: true,
|
||||||
|
currentContext,
|
||||||
|
cluster,
|
||||||
|
namespace: this.namespace,
|
||||||
|
};
|
||||||
|
} catch (_error) {
|
||||||
|
return { initialized: false, namespace: this.namespace };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPods() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listPods();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getDeployments() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listDeployments();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStatefulSets() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listStatefulSets();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServices() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listServices();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getConfigMaps() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listConfigMaps();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getIngresses() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listIngresses();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureInitialized(): void {
|
||||||
|
if (!this.initialized) {
|
||||||
|
throw new Error("Kubernetes client not initialized");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCustomResources(
|
||||||
|
group: string,
|
||||||
|
version: string,
|
||||||
|
plural: string
|
||||||
|
): Promise<CustomResourceSummary[]> {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.customResourceOps.listCustomResources(group, version, plural);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMinecraftServers() {
|
||||||
|
return this.getCustomResources(API_GROUP, CUSTOM_RESOURCE_VERSION, "minecraftservers");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getReverseProxyServers() {
|
||||||
|
return this.getCustomResources(API_GROUP, CUSTOM_RESOURCE_VERSION, "reverseproxyservers");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodLogs(
|
||||||
|
podName: string,
|
||||||
|
options?: {
|
||||||
|
container?: string;
|
||||||
|
tailLines?: number;
|
||||||
|
timestamps?: boolean;
|
||||||
|
sinceSeconds?: number;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.podOps.getPodLogs(podName, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodsByLabel(labelSelector: string) {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listPodsByLabel(labelSelector);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodInfo(podName: string) {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.getPodInfo(podName);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServiceInfo(serviceName: string) {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.getServiceInfo(serviceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getNodes() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.resources.listNodes();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServerConnectionInfo(serviceName: string) {
|
||||||
|
this.ensureInitialized();
|
||||||
|
const service = await this.getServiceInfo(serviceName);
|
||||||
|
const nodes = await this.getNodes();
|
||||||
|
|
||||||
|
if (service.type === "ClusterIP") {
|
||||||
|
return {
|
||||||
|
type: "ClusterIP",
|
||||||
|
ip: service.clusterIP,
|
||||||
|
port: service.ports[0]?.port || null,
|
||||||
|
connectionString:
|
||||||
|
service.clusterIP && service.ports[0]?.port
|
||||||
|
? `${service.clusterIP}:${service.ports[0].port}`
|
||||||
|
: null,
|
||||||
|
note: "Only accessible within the cluster",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (service.type === "NodePort") {
|
||||||
|
const nodeIP = nodes[0]?.externalIP || nodes[0]?.internalIP;
|
||||||
|
const nodePort = service.ports[0]?.nodePort;
|
||||||
|
return {
|
||||||
|
type: "NodePort",
|
||||||
|
nodeIP,
|
||||||
|
nodePort,
|
||||||
|
port: service.ports[0]?.port || null,
|
||||||
|
connectionString: nodeIP && nodePort ? `${nodeIP}:${nodePort}` : null,
|
||||||
|
note:
|
||||||
|
nodeIP && !nodes[0]?.externalIP
|
||||||
|
? "Using internal IP (may not be accessible from outside the cluster network)"
|
||||||
|
: "Accessible from any node in the cluster",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (service.type === "LoadBalancer") {
|
||||||
|
const externalIP = service.loadBalancerIP || service.loadBalancerHostname;
|
||||||
|
return {
|
||||||
|
type: "LoadBalancer",
|
||||||
|
externalIP,
|
||||||
|
port: service.ports[0]?.port || null,
|
||||||
|
connectionString:
|
||||||
|
externalIP && service.ports[0]?.port ? `${externalIP}:${service.ports[0].port}` : null,
|
||||||
|
note: !externalIP ? "LoadBalancer IP pending" : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: service.type,
|
||||||
|
note: "Unknown service type",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
getKubeConfig(): k8s.KubeConfig {
|
||||||
|
return this.kc;
|
||||||
|
}
|
||||||
|
|
||||||
|
getCoreApi(): k8s.CoreV1Api {
|
||||||
|
return this.coreApi;
|
||||||
|
}
|
||||||
|
|
||||||
|
getNamespace(): string {
|
||||||
|
return this.namespace;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodMetrics(namespace?: string) {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.executeOperationSafe(
|
||||||
|
() => this.podOps.getPodMetrics(this.customObjectsApi, namespace),
|
||||||
|
{ items: [] },
|
||||||
|
"Error fetching pod metrics"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getNodeMetrics() {
|
||||||
|
this.ensureInitialized();
|
||||||
|
return this.executeOperationSafe(
|
||||||
|
() => this.clusterOps.getNodeMetrics(),
|
||||||
|
{ items: [] },
|
||||||
|
"Error fetching node metrics"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async executeOperationSafe<T>(
|
||||||
|
operation: () => Promise<T>,
|
||||||
|
defaultValue: T,
|
||||||
|
errorContext: string
|
||||||
|
): Promise<T> {
|
||||||
|
try {
|
||||||
|
return await operation();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
logger.error({ err: error, context: errorContext }, "K8s operation failed");
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { getErrorMessage } from "@minikura/shared/errors";
|
||||||
|
import { logger } from "../../../infrastructure/logger";
|
||||||
|
|
||||||
|
export abstract class BaseK8sOperations {
|
||||||
|
protected namespace: string;
|
||||||
|
|
||||||
|
constructor(namespace: string) {
|
||||||
|
this.namespace = namespace;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async executeOperation<T>(
|
||||||
|
operation: () => Promise<T>,
|
||||||
|
errorContext: string
|
||||||
|
): Promise<T> {
|
||||||
|
try {
|
||||||
|
return await operation();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const errorMessage = getErrorMessage(error);
|
||||||
|
logger.error({ err: error, context: errorContext }, "K8s operation failed");
|
||||||
|
throw new Error(`${errorContext}: ${errorMessage}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async executeOperationSafe<T>(
|
||||||
|
operation: () => Promise<T>,
|
||||||
|
defaultValue: T,
|
||||||
|
errorContext: string
|
||||||
|
): Promise<T> {
|
||||||
|
try {
|
||||||
|
return await operation();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
logger.error({ err: error, context: errorContext }, "K8s operation failed (safe mode)");
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getNamespace(): string {
|
||||||
|
return this.namespace;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import type * as k8s from "@kubernetes/client-node";
|
||||||
|
import { BaseK8sOperations } from "./base.operations";
|
||||||
|
|
||||||
|
export class ClusterOperations extends BaseK8sOperations {
|
||||||
|
constructor(
|
||||||
|
private coreApi: k8s.CoreV1Api,
|
||||||
|
private customObjectsApi: k8s.CustomObjectsApi,
|
||||||
|
namespace: string
|
||||||
|
) {
|
||||||
|
super(namespace);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listNodes() {
|
||||||
|
return this.executeOperation(
|
||||||
|
() => this.coreApi.listNode().then((r) => r.items),
|
||||||
|
"Failed to fetch nodes"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getNodeMetrics() {
|
||||||
|
return this.executeOperation(
|
||||||
|
() =>
|
||||||
|
this.customObjectsApi.listClusterCustomObject({
|
||||||
|
group: "metrics.k8s.io",
|
||||||
|
version: "v1beta1",
|
||||||
|
plural: "nodes",
|
||||||
|
}),
|
||||||
|
"Failed to fetch node metrics"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listConfigMaps(namespace?: string) {
|
||||||
|
const ns = namespace || this.namespace;
|
||||||
|
return this.executeOperation(
|
||||||
|
() => this.coreApi.listNamespacedConfigMap({ namespace: ns }).then((r) => r.items),
|
||||||
|
"Failed to fetch configmaps"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type * as k8s from "@kubernetes/client-node";
|
||||||
|
import type { CustomResourceSummary } from "@minikura/api";
|
||||||
|
import { getAge } from "@minikura/shared/errors";
|
||||||
|
import { BaseK8sOperations } from "./base.operations";
|
||||||
|
|
||||||
|
interface CustomResourceItem {
|
||||||
|
kind?: string;
|
||||||
|
metadata?: {
|
||||||
|
name?: string;
|
||||||
|
namespace?: string;
|
||||||
|
creationTimestamp?: string;
|
||||||
|
labels?: Record<string, string>;
|
||||||
|
};
|
||||||
|
spec?: Record<string, unknown>;
|
||||||
|
status?: { phase?: string; [key: string]: unknown };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CustomResourceList {
|
||||||
|
items?: CustomResourceItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CustomResourceOperations extends BaseK8sOperations {
|
||||||
|
constructor(
|
||||||
|
private customObjectsApi: k8s.CustomObjectsApi,
|
||||||
|
namespace: string
|
||||||
|
) {
|
||||||
|
super(namespace);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listCustomResources(
|
||||||
|
group: string,
|
||||||
|
version: string,
|
||||||
|
plural: string
|
||||||
|
): Promise<CustomResourceSummary[]> {
|
||||||
|
return this.executeOperation(async () => {
|
||||||
|
const response = await this.customObjectsApi.listNamespacedCustomObject({
|
||||||
|
group,
|
||||||
|
version,
|
||||||
|
namespace: this.namespace,
|
||||||
|
plural,
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = (response as unknown as CustomResourceList).items || [];
|
||||||
|
|
||||||
|
return items.map((item) => ({
|
||||||
|
name: item.metadata?.name ?? "",
|
||||||
|
namespace: item.metadata?.namespace ?? this.namespace,
|
||||||
|
age: getAge(item.metadata?.creationTimestamp),
|
||||||
|
labels: item.metadata?.labels,
|
||||||
|
spec: item.spec ?? {},
|
||||||
|
status: item.status ?? {},
|
||||||
|
}));
|
||||||
|
}, `Failed to fetch custom resources (${plural})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
6
apps/backend/src/services/kubernetes/operations/index.ts
Normal file
6
apps/backend/src/services/kubernetes/operations/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export { BaseK8sOperations } from "./base.operations";
|
||||||
|
export { ClusterOperations } from "./cluster.operations";
|
||||||
|
export { CustomResourceOperations } from "./custom-resource.operations";
|
||||||
|
export { NetworkOperations } from "./network.operations";
|
||||||
|
export { PodOperations } from "./pod.operations";
|
||||||
|
export { WorkloadOperations } from "./workload.operations";
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import type * as k8s from "@kubernetes/client-node";
|
||||||
|
import { BaseK8sOperations } from "./base.operations";
|
||||||
|
|
||||||
|
export class NetworkOperations extends BaseK8sOperations {
|
||||||
|
constructor(
|
||||||
|
private coreApi: k8s.CoreV1Api,
|
||||||
|
private networkingApi: k8s.NetworkingV1Api,
|
||||||
|
namespace: string
|
||||||
|
) {
|
||||||
|
super(namespace);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listServices() {
|
||||||
|
return this.executeOperation(
|
||||||
|
() => this.coreApi.listNamespacedService({ namespace: this.namespace }).then((r) => r.items),
|
||||||
|
"Failed to fetch services"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listIngresses() {
|
||||||
|
return this.executeOperation(
|
||||||
|
() =>
|
||||||
|
this.networkingApi
|
||||||
|
.listNamespacedIngress({ namespace: this.namespace })
|
||||||
|
.then((r) => r.items),
|
||||||
|
"Failed to fetch ingresses"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServiceInfo(serviceName: string) {
|
||||||
|
return this.executeOperation(
|
||||||
|
() => this.coreApi.readNamespacedService({ name: serviceName, namespace: this.namespace }),
|
||||||
|
`Failed to fetch service info for ${serviceName}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServerConnectionInfo(serviceName: string) {
|
||||||
|
return this.executeOperation(async () => {
|
||||||
|
const service = await this.coreApi.readNamespacedService({
|
||||||
|
name: serviceName,
|
||||||
|
namespace: this.namespace,
|
||||||
|
});
|
||||||
|
|
||||||
|
const serviceType = service.spec?.type || "ClusterIP";
|
||||||
|
const ports = service.spec?.ports || [];
|
||||||
|
|
||||||
|
let host: string;
|
||||||
|
let externalHost: string | undefined;
|
||||||
|
|
||||||
|
switch (serviceType) {
|
||||||
|
case "LoadBalancer": {
|
||||||
|
const ingress = service.status?.loadBalancer?.ingress?.[0];
|
||||||
|
host =
|
||||||
|
ingress?.hostname ||
|
||||||
|
ingress?.ip ||
|
||||||
|
`${serviceName}.${this.namespace}.svc.cluster.local`;
|
||||||
|
externalHost = ingress?.hostname || ingress?.ip;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "NodePort":
|
||||||
|
host = `${serviceName}.${this.namespace}.svc.cluster.local`;
|
||||||
|
externalHost = "<node-ip>";
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
host = `${serviceName}.${this.namespace}.svc.cluster.local`;
|
||||||
|
externalHost = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const portMappings = ports.map((port) => ({
|
||||||
|
name: port.name,
|
||||||
|
port: port.port,
|
||||||
|
targetPort: port.targetPort,
|
||||||
|
nodePort: port.nodePort,
|
||||||
|
protocol: port.protocol || "TCP",
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
serviceName,
|
||||||
|
namespace: this.namespace,
|
||||||
|
serviceType,
|
||||||
|
internalHost: host,
|
||||||
|
externalHost,
|
||||||
|
ports: portMappings,
|
||||||
|
};
|
||||||
|
}, `Failed to fetch connection info for service ${serviceName}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import type * as k8s from "@kubernetes/client-node";
|
||||||
|
import { BaseK8sOperations } from "./base.operations";
|
||||||
|
|
||||||
|
export class PodOperations extends BaseK8sOperations {
|
||||||
|
constructor(
|
||||||
|
private coreApi: k8s.CoreV1Api,
|
||||||
|
namespace: string
|
||||||
|
) {
|
||||||
|
super(namespace);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listPods() {
|
||||||
|
return this.executeOperation(
|
||||||
|
() => this.coreApi.listNamespacedPod({ namespace: this.namespace }).then((r) => r.items),
|
||||||
|
"Failed to fetch pods"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listPodsByLabel(labelSelector: string) {
|
||||||
|
return this.executeOperation(
|
||||||
|
() =>
|
||||||
|
this.coreApi
|
||||||
|
.listNamespacedPod({ namespace: this.namespace, labelSelector })
|
||||||
|
.then((r) => r.items),
|
||||||
|
"Failed to fetch pods by label"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodInfo(podName: string) {
|
||||||
|
return this.executeOperation(
|
||||||
|
() => this.coreApi.readNamespacedPod({ name: podName, namespace: this.namespace }),
|
||||||
|
`Failed to fetch pod info for ${podName}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodLogs(
|
||||||
|
podName: string,
|
||||||
|
options?: {
|
||||||
|
container?: string;
|
||||||
|
tailLines?: number;
|
||||||
|
timestamps?: boolean;
|
||||||
|
sinceSeconds?: number;
|
||||||
|
}
|
||||||
|
): Promise<string> {
|
||||||
|
return this.executeOperation(
|
||||||
|
() =>
|
||||||
|
this.coreApi.readNamespacedPodLog({
|
||||||
|
name: podName,
|
||||||
|
namespace: this.namespace,
|
||||||
|
container: options?.container,
|
||||||
|
tailLines: options?.tailLines,
|
||||||
|
timestamps: options?.timestamps,
|
||||||
|
sinceSeconds: options?.sinceSeconds,
|
||||||
|
}),
|
||||||
|
`Failed to fetch logs for pod ${podName}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodMetrics(customObjectsApi: k8s.CustomObjectsApi, namespace?: string) {
|
||||||
|
const ns = namespace || this.namespace;
|
||||||
|
return this.executeOperation(
|
||||||
|
() =>
|
||||||
|
customObjectsApi.listNamespacedCustomObject({
|
||||||
|
group: "metrics.k8s.io",
|
||||||
|
version: "v1beta1",
|
||||||
|
namespace: ns,
|
||||||
|
plural: "pods",
|
||||||
|
}),
|
||||||
|
"Failed to fetch pod metrics"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type * as k8s from "@kubernetes/client-node";
|
||||||
|
import { BaseK8sOperations } from "./base.operations";
|
||||||
|
|
||||||
|
export class WorkloadOperations extends BaseK8sOperations {
|
||||||
|
constructor(
|
||||||
|
private appsApi: k8s.AppsV1Api,
|
||||||
|
namespace: string
|
||||||
|
) {
|
||||||
|
super(namespace);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listDeployments() {
|
||||||
|
return this.executeOperation(
|
||||||
|
() =>
|
||||||
|
this.appsApi.listNamespacedDeployment({ namespace: this.namespace }).then((r) => r.items),
|
||||||
|
"Failed to fetch deployments"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listStatefulSets() {
|
||||||
|
return this.executeOperation(
|
||||||
|
() =>
|
||||||
|
this.appsApi.listNamespacedStatefulSet({ namespace: this.namespace }).then((r) => r.items),
|
||||||
|
"Failed to fetch statefulsets"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
257
apps/backend/src/services/kubernetes/resources.ts
Normal file
257
apps/backend/src/services/kubernetes/resources.ts
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
import type * as k8s from "@kubernetes/client-node";
|
||||||
|
import type {
|
||||||
|
DeploymentInfo,
|
||||||
|
K8sConfigMapSummary,
|
||||||
|
K8sIngressSummary,
|
||||||
|
K8sNodeSummary,
|
||||||
|
K8sServiceInfo,
|
||||||
|
K8sServicePort,
|
||||||
|
K8sServiceSummary,
|
||||||
|
PodDetails,
|
||||||
|
PodInfo,
|
||||||
|
StatefulSetInfo,
|
||||||
|
} from "@minikura/api";
|
||||||
|
import { getAge } from "@minikura/shared/errors";
|
||||||
|
|
||||||
|
export class K8sResources {
|
||||||
|
constructor(
|
||||||
|
private readonly coreApi: k8s.CoreV1Api,
|
||||||
|
private readonly appsApi: k8s.AppsV1Api,
|
||||||
|
private readonly networkingApi: k8s.NetworkingV1Api,
|
||||||
|
private readonly namespace: string
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async listPods(): Promise<PodInfo[]> {
|
||||||
|
const response = await this.coreApi.listNamespacedPod({ namespace: this.namespace });
|
||||||
|
return response.items.map((pod) => mapPodInfo(pod));
|
||||||
|
}
|
||||||
|
|
||||||
|
async listPodsByLabel(labelSelector: string): Promise<PodInfo[]> {
|
||||||
|
const response = await this.coreApi.listNamespacedPod({
|
||||||
|
namespace: this.namespace,
|
||||||
|
labelSelector,
|
||||||
|
});
|
||||||
|
return response.items.map((pod) => ({
|
||||||
|
...mapPodInfo(pod),
|
||||||
|
containers: pod.spec?.containers?.map((container) => container.name ?? "") || [],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPodInfo(podName: string): Promise<PodDetails> {
|
||||||
|
const response = await this.coreApi.readNamespacedPod({
|
||||||
|
name: podName,
|
||||||
|
namespace: this.namespace,
|
||||||
|
});
|
||||||
|
const pod = response;
|
||||||
|
return {
|
||||||
|
...mapPodInfo(pod),
|
||||||
|
containers: pod.spec?.containers?.map((container) => container.name ?? "") || [],
|
||||||
|
ip: pod.status?.podIP,
|
||||||
|
conditions:
|
||||||
|
pod.status?.conditions?.map((condition) => ({
|
||||||
|
type: condition.type,
|
||||||
|
status: condition.status,
|
||||||
|
lastTransitionTime: condition.lastTransitionTime
|
||||||
|
? condition.lastTransitionTime.toISOString()
|
||||||
|
: undefined,
|
||||||
|
})) || [],
|
||||||
|
containerStatuses:
|
||||||
|
pod.status?.containerStatuses?.map((status) => ({
|
||||||
|
name: status.name,
|
||||||
|
ready: status.ready,
|
||||||
|
restartCount: status.restartCount,
|
||||||
|
state: status.state
|
||||||
|
? {
|
||||||
|
waiting: status.state.waiting
|
||||||
|
? {
|
||||||
|
reason: status.state.waiting.reason,
|
||||||
|
message: status.state.waiting.message,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
running: status.state.running
|
||||||
|
? {
|
||||||
|
startedAt: status.state.running.startedAt,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
terminated: status.state.terminated
|
||||||
|
? {
|
||||||
|
reason: status.state.terminated.reason,
|
||||||
|
exitCode: status.state.terminated.exitCode,
|
||||||
|
finishedAt: status.state.terminated.finishedAt,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
})) || [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async listDeployments(): Promise<DeploymentInfo[]> {
|
||||||
|
const response = await this.appsApi.listNamespacedDeployment({ namespace: this.namespace });
|
||||||
|
return response.items.map((deployment) => ({
|
||||||
|
name: deployment.metadata?.name ?? "",
|
||||||
|
namespace: deployment.metadata?.namespace,
|
||||||
|
ready: `${deployment.status?.readyReplicas ?? 0}/${deployment.status?.replicas ?? 0}`,
|
||||||
|
desired: deployment.status?.replicas ?? 0,
|
||||||
|
current: deployment.status?.replicas ?? 0,
|
||||||
|
updated: deployment.status?.updatedReplicas ?? 0,
|
||||||
|
upToDate: deployment.status?.updatedReplicas ?? 0,
|
||||||
|
available: deployment.status?.availableReplicas ?? 0,
|
||||||
|
age: getAge(deployment.metadata?.creationTimestamp),
|
||||||
|
labels: deployment.metadata?.labels,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async listStatefulSets(): Promise<StatefulSetInfo[]> {
|
||||||
|
const response = await this.appsApi.listNamespacedStatefulSet({ namespace: this.namespace });
|
||||||
|
return response.items.map((statefulSet) => ({
|
||||||
|
name: statefulSet.metadata?.name ?? "",
|
||||||
|
namespace: statefulSet.metadata?.namespace,
|
||||||
|
ready: `${statefulSet.status?.readyReplicas ?? 0}/${statefulSet.spec?.replicas ?? 0}`,
|
||||||
|
desired: statefulSet.spec?.replicas ?? 0,
|
||||||
|
current: statefulSet.status?.currentReplicas ?? 0,
|
||||||
|
updated: statefulSet.status?.updatedReplicas ?? 0,
|
||||||
|
age: getAge(statefulSet.metadata?.creationTimestamp),
|
||||||
|
labels: statefulSet.metadata?.labels,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async listServices(): Promise<K8sServiceSummary[]> {
|
||||||
|
const response = await this.coreApi.listNamespacedService({ namespace: this.namespace });
|
||||||
|
return response.items.map((service) => {
|
||||||
|
const ports = service.spec?.ports ?? [];
|
||||||
|
const portSummary = ports
|
||||||
|
.map((port) => `${port.port}${port.nodePort ? `:${port.nodePort}` : ""}/${port.protocol}`)
|
||||||
|
.join(", ");
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: service.metadata?.name ?? "",
|
||||||
|
namespace: service.metadata?.namespace,
|
||||||
|
type: service.spec?.type,
|
||||||
|
clusterIP: service.spec?.clusterIP ?? null,
|
||||||
|
externalIP:
|
||||||
|
service.status?.loadBalancer?.ingress?.[0]?.ip ||
|
||||||
|
service.spec?.externalIPs?.join(", ") ||
|
||||||
|
"<none>",
|
||||||
|
ports: portSummary,
|
||||||
|
age: getAge(service.metadata?.creationTimestamp),
|
||||||
|
labels: service.metadata?.labels,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async listConfigMaps(): Promise<K8sConfigMapSummary[]> {
|
||||||
|
const response = await this.coreApi.listNamespacedConfigMap({ namespace: this.namespace });
|
||||||
|
return response.items.map((configMap) => ({
|
||||||
|
name: configMap.metadata?.name ?? "",
|
||||||
|
namespace: configMap.metadata?.namespace,
|
||||||
|
data: Object.keys(configMap.data ?? {}).length,
|
||||||
|
age: getAge(configMap.metadata?.creationTimestamp),
|
||||||
|
labels: configMap.metadata?.labels,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async listIngresses(): Promise<K8sIngressSummary[]> {
|
||||||
|
const response = await this.networkingApi.listNamespacedIngress({ namespace: this.namespace });
|
||||||
|
return response.items.map((ingress) => {
|
||||||
|
const hosts =
|
||||||
|
ingress.spec?.rules
|
||||||
|
?.map((rule) => rule.host)
|
||||||
|
.filter((host): host is string => Boolean(host))
|
||||||
|
.join(", ") || "<none>";
|
||||||
|
const addresses =
|
||||||
|
ingress.status?.loadBalancer?.ingress
|
||||||
|
?.map((item) => item.ip || item.hostname)
|
||||||
|
.filter((entry): entry is string => Boolean(entry))
|
||||||
|
.join(", ") || "<pending>";
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: ingress.metadata?.name ?? "",
|
||||||
|
namespace: ingress.metadata?.namespace,
|
||||||
|
className: ingress.spec?.ingressClassName ?? null,
|
||||||
|
hosts,
|
||||||
|
address: addresses,
|
||||||
|
age: getAge(ingress.metadata?.creationTimestamp),
|
||||||
|
labels: ingress.metadata?.labels,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServiceInfo(serviceName: string): Promise<K8sServiceInfo> {
|
||||||
|
const response = await this.coreApi.readNamespacedService({
|
||||||
|
name: serviceName,
|
||||||
|
namespace: this.namespace,
|
||||||
|
});
|
||||||
|
const service = response;
|
||||||
|
const ports: K8sServicePort[] =
|
||||||
|
service.spec?.ports?.map((port) => ({
|
||||||
|
name: port.name ?? null,
|
||||||
|
protocol: port.protocol ?? null,
|
||||||
|
port: port.port,
|
||||||
|
targetPort: port.targetPort,
|
||||||
|
nodePort: port.nodePort ?? null,
|
||||||
|
})) || [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: service.metadata?.name,
|
||||||
|
namespace: service.metadata?.namespace,
|
||||||
|
type: service.spec?.type,
|
||||||
|
clusterIP: service.spec?.clusterIP ?? null,
|
||||||
|
externalIPs: service.spec?.externalIPs || [],
|
||||||
|
loadBalancerIP: service.status?.loadBalancer?.ingress?.[0]?.ip || null,
|
||||||
|
loadBalancerHostname: service.status?.loadBalancer?.ingress?.[0]?.hostname || null,
|
||||||
|
ports,
|
||||||
|
selector: service.spec?.selector,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async listNodes(): Promise<K8sNodeSummary[]> {
|
||||||
|
const response = await this.coreApi.listNode();
|
||||||
|
return response.items.map((node) => {
|
||||||
|
const labels = node.metadata?.labels ?? {};
|
||||||
|
const roles = Object.keys(labels)
|
||||||
|
.filter((label) => label.startsWith("node-role.kubernetes.io/"))
|
||||||
|
.map((label) => label.replace("node-role.kubernetes.io/", ""))
|
||||||
|
.join(",");
|
||||||
|
const addresses = node.status?.addresses ?? [];
|
||||||
|
const internalIP = addresses.find((address) => address.type === "InternalIP")?.address;
|
||||||
|
const externalIP = addresses.find((address) => address.type === "ExternalIP")?.address;
|
||||||
|
const hostname = addresses.find((address) => address.type === "Hostname")?.address;
|
||||||
|
const readyCondition = node.status?.conditions?.find(
|
||||||
|
(condition) => condition.type === "Ready"
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: node.metadata?.name,
|
||||||
|
status: readyCondition?.status === "True" ? "Ready" : "NotReady",
|
||||||
|
roles: roles || "<none>",
|
||||||
|
age: getAge(node.metadata?.creationTimestamp),
|
||||||
|
version: node.status?.nodeInfo?.kubeletVersion,
|
||||||
|
internalIP,
|
||||||
|
externalIP,
|
||||||
|
hostname,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapPodInfo(pod: k8s.V1Pod): PodInfo {
|
||||||
|
const containerStatuses = pod.status?.containerStatuses ?? [];
|
||||||
|
const readyCount = containerStatuses.filter((status) => status.ready).length;
|
||||||
|
const totalCount = containerStatuses.length;
|
||||||
|
const restarts = containerStatuses.reduce(
|
||||||
|
(accumulator, status) => accumulator + (status.restartCount ?? 0),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: pod.metadata?.name ?? "",
|
||||||
|
namespace: pod.metadata?.namespace,
|
||||||
|
status: pod.status?.phase ?? "Unknown",
|
||||||
|
ready: `${readyCount}/${totalCount}`,
|
||||||
|
restarts,
|
||||||
|
age: getAge(pod.metadata?.creationTimestamp),
|
||||||
|
labels: pod.metadata?.labels,
|
||||||
|
nodeName: pod.spec?.nodeName,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,276 +0,0 @@
|
|||||||
import { prisma } from "@minikura/db";
|
|
||||||
import type { ServerType } from "@minikura/db";
|
|
||||||
import crypto from "node:crypto";
|
|
||||||
|
|
||||||
export namespace ServerService {
|
|
||||||
export async function getAllServers(omitSensitive = false) {
|
|
||||||
if (omitSensitive) {
|
|
||||||
return await prisma.server.findMany({
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
type: true,
|
|
||||||
description: true,
|
|
||||||
listen_port: true,
|
|
||||||
memory: true,
|
|
||||||
created_at: true,
|
|
||||||
updated_at: true,
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
return await prisma.server.findMany({
|
|
||||||
include: {
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAllReverseProxyServers(omitSensitive = false) {
|
|
||||||
if (omitSensitive) {
|
|
||||||
return await prisma.reverseProxyServer.findMany({
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
type: true,
|
|
||||||
description: true,
|
|
||||||
external_address: true,
|
|
||||||
external_port: true,
|
|
||||||
listen_port: true,
|
|
||||||
memory: true,
|
|
||||||
created_at: true,
|
|
||||||
updated_at: true,
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
return await prisma.reverseProxyServer.findMany({
|
|
||||||
include: {
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getServerById(id: string, omitSensitive = false) {
|
|
||||||
if (omitSensitive) {
|
|
||||||
return await prisma.server.findUnique({
|
|
||||||
where: { id },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
type: true,
|
|
||||||
description: true,
|
|
||||||
listen_port: true,
|
|
||||||
memory: true,
|
|
||||||
created_at: true,
|
|
||||||
updated_at: true,
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
return await prisma.server.findUnique({
|
|
||||||
where: { id },
|
|
||||||
include: {
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getReverseProxyServerById(
|
|
||||||
id: string,
|
|
||||||
omitSensitive = false
|
|
||||||
) {
|
|
||||||
if (omitSensitive) {
|
|
||||||
return await prisma.reverseProxyServer.findUnique({
|
|
||||||
where: { id },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
type: true,
|
|
||||||
description: true,
|
|
||||||
external_address: true,
|
|
||||||
external_port: true,
|
|
||||||
listen_port: true,
|
|
||||||
memory: true,
|
|
||||||
created_at: true,
|
|
||||||
updated_at: true,
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
return await prisma.reverseProxyServer.findUnique({
|
|
||||||
where: { id },
|
|
||||||
include: {
|
|
||||||
env_variables: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createReverseProxyServer({
|
|
||||||
id,
|
|
||||||
description,
|
|
||||||
external_address,
|
|
||||||
external_port,
|
|
||||||
listen_port,
|
|
||||||
type,
|
|
||||||
env_variables,
|
|
||||||
memory,
|
|
||||||
}: {
|
|
||||||
id: string;
|
|
||||||
description: string | null;
|
|
||||||
external_address: string;
|
|
||||||
external_port: number;
|
|
||||||
listen_port?: number;
|
|
||||||
type?: "VELOCITY" | "BUNGEECORD";
|
|
||||||
env_variables?: { key: string; value: string }[];
|
|
||||||
memory?: string;
|
|
||||||
}) {
|
|
||||||
let token = crypto.randomBytes(64).toString("hex");
|
|
||||||
token = token
|
|
||||||
.split("")
|
|
||||||
.map((char) => (Math.random() > 0.5 ? char.toUpperCase() : char))
|
|
||||||
.join("");
|
|
||||||
token = `minikura_reverse_proxy_server_api_key_${token}`;
|
|
||||||
|
|
||||||
return await prisma.reverseProxyServer.create({
|
|
||||||
data: {
|
|
||||||
id,
|
|
||||||
description,
|
|
||||||
external_address,
|
|
||||||
external_port,
|
|
||||||
listen_port: listen_port || 25565,
|
|
||||||
type: type || "VELOCITY",
|
|
||||||
api_key: token,
|
|
||||||
memory: memory || "512M",
|
|
||||||
env_variables: env_variables ? {
|
|
||||||
create: env_variables.map(ev => ({
|
|
||||||
key: ev.key,
|
|
||||||
value: ev.value
|
|
||||||
}))
|
|
||||||
} : undefined,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
env_variables: true,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createServer({
|
|
||||||
id,
|
|
||||||
description,
|
|
||||||
type,
|
|
||||||
listen_port,
|
|
||||||
env_variables,
|
|
||||||
memory,
|
|
||||||
}: {
|
|
||||||
id: string;
|
|
||||||
description: string | null;
|
|
||||||
type: ServerType;
|
|
||||||
listen_port: number;
|
|
||||||
env_variables?: { key: string; value: string }[];
|
|
||||||
memory?: string;
|
|
||||||
}) {
|
|
||||||
let token = crypto.randomBytes(64).toString("hex");
|
|
||||||
token = token
|
|
||||||
.split("")
|
|
||||||
.map((char) => (Math.random() > 0.5 ? char.toUpperCase() : char))
|
|
||||||
.join("");
|
|
||||||
token = `minikura_server_api_key_${token}`;
|
|
||||||
|
|
||||||
return await prisma.server.create({
|
|
||||||
data: {
|
|
||||||
id,
|
|
||||||
description,
|
|
||||||
type,
|
|
||||||
listen_port,
|
|
||||||
api_key: token,
|
|
||||||
memory: memory || "1G",
|
|
||||||
env_variables: env_variables ? {
|
|
||||||
create: env_variables.map(ev => ({
|
|
||||||
key: ev.key,
|
|
||||||
value: ev.value
|
|
||||||
}))
|
|
||||||
} : undefined,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
env_variables: true,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setServerEnvironmentVariable(
|
|
||||||
serverId: string,
|
|
||||||
key: string,
|
|
||||||
value: string
|
|
||||||
) {
|
|
||||||
// Upsert pattern - create if doesn't exist, update if it does
|
|
||||||
return await prisma.customEnvironmentVariable.upsert({
|
|
||||||
where: {
|
|
||||||
key_server_id: {
|
|
||||||
key,
|
|
||||||
server_id: serverId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
update: {
|
|
||||||
value,
|
|
||||||
},
|
|
||||||
create: {
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
server_id: serverId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setReverseProxyEnvironmentVariable(
|
|
||||||
proxyId: string,
|
|
||||||
key: string,
|
|
||||||
value: string
|
|
||||||
) {
|
|
||||||
// Upsert pattern - create if doesn't exist, update if it does
|
|
||||||
return await prisma.customEnvironmentVariable.upsert({
|
|
||||||
where: {
|
|
||||||
key_reverse_proxy_id: {
|
|
||||||
key,
|
|
||||||
reverse_proxy_id: proxyId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
update: {
|
|
||||||
value,
|
|
||||||
},
|
|
||||||
create: {
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
reverse_proxy_id: proxyId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deleteServerEnvironmentVariable(
|
|
||||||
serverId: string,
|
|
||||||
key: string
|
|
||||||
) {
|
|
||||||
return await prisma.customEnvironmentVariable.delete({
|
|
||||||
where: {
|
|
||||||
key_server_id: {
|
|
||||||
key,
|
|
||||||
server_id: serverId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deleteReverseProxyEnvironmentVariable(
|
|
||||||
proxyId: string,
|
|
||||||
key: string
|
|
||||||
) {
|
|
||||||
return await prisma.customEnvironmentVariable.delete({
|
|
||||||
where: {
|
|
||||||
key_reverse_proxy_id: {
|
|
||||||
key,
|
|
||||||
reverse_proxy_id: proxyId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
import { prisma } from "@minikura/db";
|
|
||||||
import crypto from "node:crypto";
|
|
||||||
|
|
||||||
export namespace SessionService {
|
|
||||||
export enum SESSION_STATUS {
|
|
||||||
VALID = "VALID",
|
|
||||||
INVALID = "INVALID",
|
|
||||||
REVOKED = "REVOKED",
|
|
||||||
EXPIRED = "EXPIRED",
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function validate(token: string) {
|
|
||||||
const session = await prisma.session.findUnique({
|
|
||||||
where: {
|
|
||||||
token,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!session) {
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.INVALID,
|
|
||||||
session: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (session.revoked) {
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.REVOKED,
|
|
||||||
session,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (session.expires_at < new Date()) {
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.EXPIRED,
|
|
||||||
session,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.VALID,
|
|
||||||
session,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function validateApiKey(apiKey: string) {
|
|
||||||
// If starts with "minikura_reverse_proxy_server_api_key_"
|
|
||||||
if (apiKey.startsWith("minikura_reverse_proxy_server_api_key_")) {
|
|
||||||
const reverseProxyServer = await prisma.reverseProxyServer.findUnique({
|
|
||||||
where: {
|
|
||||||
api_key: apiKey,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!reverseProxyServer) {
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.INVALID,
|
|
||||||
session: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.VALID,
|
|
||||||
server: reverseProxyServer,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (apiKey.startsWith("minikura_server_api_key_")) {
|
|
||||||
const server = await prisma.server.findUnique({
|
|
||||||
where: {
|
|
||||||
api_key: apiKey,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!server) {
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.INVALID,
|
|
||||||
session: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.VALID,
|
|
||||||
server: server,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: SESSION_STATUS.INVALID,
|
|
||||||
session: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function create(userId: string) {
|
|
||||||
let token = crypto.randomBytes(64).toString("hex");
|
|
||||||
token = token
|
|
||||||
.split("")
|
|
||||||
.map((char) => (Math.random() > 0.5 ? char.toUpperCase() : char))
|
|
||||||
.join("");
|
|
||||||
token = `minikura_user_session_${token}`;
|
|
||||||
|
|
||||||
return await prisma.session.create({
|
|
||||||
data: {
|
|
||||||
token,
|
|
||||||
user: {
|
|
||||||
connect: {
|
|
||||||
id: userId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
// Expires in 48 hours
|
|
||||||
expires_at: new Date(Date.now() + 48 * 60 * 60 * 1000),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function revoke(token: string) {
|
|
||||||
return await prisma.session.update({
|
|
||||||
where: {
|
|
||||||
token,
|
|
||||||
},
|
|
||||||
data: {
|
|
||||||
revoked: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { prisma } from "@minikura/db";
|
|
||||||
|
|
||||||
export namespace UserService {
|
|
||||||
export async function getUserByUsername(username: string) {
|
|
||||||
return await prisma.user.findUnique({
|
|
||||||
where: { username },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
55
apps/backend/src/services/websocket.ts
Normal file
55
apps/backend/src/services/websocket.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
|
||||||
|
export type WebSocketClient = {
|
||||||
|
send: (message: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface IWebSocketService {
|
||||||
|
addClient(client: WebSocketClient): void;
|
||||||
|
removeClient(client: WebSocketClient): void;
|
||||||
|
broadcast(action: string, serverType: string, serverId: string): void;
|
||||||
|
getClientCount(): number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WebSocketService implements IWebSocketService {
|
||||||
|
private clients = new Set<WebSocketClient>();
|
||||||
|
|
||||||
|
addClient(client: WebSocketClient): void {
|
||||||
|
this.clients.add(client);
|
||||||
|
logger.debug({ totalClients: this.clients.size }, "WebSocket client connected");
|
||||||
|
}
|
||||||
|
|
||||||
|
removeClient(client: WebSocketClient): void {
|
||||||
|
this.clients.delete(client);
|
||||||
|
logger.debug({ totalClients: this.clients.size }, "WebSocket client disconnected");
|
||||||
|
}
|
||||||
|
|
||||||
|
broadcast(action: string, serverType: string, serverId: string): void {
|
||||||
|
const message = JSON.stringify({
|
||||||
|
type: "SERVER_CHANGE",
|
||||||
|
action,
|
||||||
|
serverType,
|
||||||
|
serverId,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send to all connected clients, removing any that fail
|
||||||
|
let failedClients = 0;
|
||||||
|
this.clients.forEach((client) => {
|
||||||
|
try {
|
||||||
|
client.send(message);
|
||||||
|
} catch {
|
||||||
|
failedClients++;
|
||||||
|
this.clients.delete(client);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (failedClients > 0) {
|
||||||
|
logger.warn({ failedClients }, "Removed failed WebSocket clients");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getClientCount(): number {
|
||||||
|
return this.clients.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
144
apps/web/app/bootstrap/page.tsx
Normal file
144
apps/web/app/bootstrap/page.tsx
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { api } from "@/lib/api-client";
|
||||||
|
|
||||||
|
export default function BootstrapPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [checkingStatus, setCheckingStatus] = useState(true);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const checkStatus = async () => {
|
||||||
|
try {
|
||||||
|
const { data } = await api.bootstrap.status.get();
|
||||||
|
|
||||||
|
if (data && !data.needsSetup) {
|
||||||
|
router.replace("/login");
|
||||||
|
}
|
||||||
|
} catch (_err) {
|
||||||
|
} finally {
|
||||||
|
setCheckingStatus(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
checkStatus();
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const email = formData.get("email") as string;
|
||||||
|
const password = formData.get("password") as string;
|
||||||
|
const confirmPassword = formData.get("confirmPassword") as string;
|
||||||
|
const name = formData.get("name") as string;
|
||||||
|
|
||||||
|
if (password !== confirmPassword) {
|
||||||
|
setError("Passwords do not match");
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data, error: apiError } = await api.bootstrap.setup.post({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (apiError) {
|
||||||
|
const errorMessage =
|
||||||
|
"value" in apiError &&
|
||||||
|
typeof apiError.value === "object" &&
|
||||||
|
apiError.value &&
|
||||||
|
"message" in apiError.value
|
||||||
|
? String(apiError.value.message)
|
||||||
|
: "Failed to create admin user";
|
||||||
|
setError(errorMessage);
|
||||||
|
} else if (data?.success) {
|
||||||
|
router.push("/login");
|
||||||
|
} else {
|
||||||
|
setError("Failed to create admin user");
|
||||||
|
}
|
||||||
|
} catch (_err) {
|
||||||
|
setError("Failed to connect to server");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (checkingStatus) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 p-4">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader className="space-y-1">
|
||||||
|
<CardTitle className="text-2xl font-bold text-center">Welcome to Minikura</CardTitle>
|
||||||
|
<CardDescription className="text-center">
|
||||||
|
Create your admin account to get started
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Full Name</Label>
|
||||||
|
<Input id="name" name="name" placeholder="John Doe" required autoFocus />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="admin@example.com"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">Password</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
placeholder="••••••••"
|
||||||
|
minLength={8}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="confirmPassword">Confirm Password</Label>
|
||||||
|
<Input
|
||||||
|
id="confirmPassword"
|
||||||
|
name="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
placeholder="••••••••"
|
||||||
|
minLength={8}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && <div className="text-sm text-red-600 text-center">{error}</div>}
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "Creating..." : "Create Admin Account"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
533
apps/web/app/dashboard/k8s/page.tsx
Normal file
533
apps/web/app/dashboard/k8s/page.tsx
Normal file
@@ -0,0 +1,533 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type {
|
||||||
|
CustomResourceSummary,
|
||||||
|
DeploymentInfo,
|
||||||
|
K8sConfigMapSummary,
|
||||||
|
K8sServiceSummary,
|
||||||
|
K8sStatus,
|
||||||
|
PodInfo,
|
||||||
|
StatefulSetInfo,
|
||||||
|
} from "@minikura/api";
|
||||||
|
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/components/ui/table";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import { api } from "@/lib/api-client";
|
||||||
|
|
||||||
|
export default function K8sResourcesPage() {
|
||||||
|
const [status, setStatus] = useState<K8sStatus | null>(null);
|
||||||
|
const [pods, setPods] = useState<PodInfo[]>([]);
|
||||||
|
const [deployments, setDeployments] = useState<DeploymentInfo[]>([]);
|
||||||
|
const [statefulSets, setStatefulSets] = useState<StatefulSetInfo[]>([]);
|
||||||
|
const [services, setServices] = useState<K8sServiceSummary[]>([]);
|
||||||
|
const [configMaps, setConfigMaps] = useState<K8sConfigMapSummary[]>([]);
|
||||||
|
const [minecraftServers, setMinecraftServers] = useState<CustomResourceSummary[]>([]);
|
||||||
|
const [reverseProxyServers, setReverseProxyServers] = useState<CustomResourceSummary[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const fetchData = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const [
|
||||||
|
statusRes,
|
||||||
|
podsRes,
|
||||||
|
deploymentsRes,
|
||||||
|
statefulSetsRes,
|
||||||
|
servicesRes,
|
||||||
|
configMapsRes,
|
||||||
|
minecraftServersRes,
|
||||||
|
reverseProxyServersRes,
|
||||||
|
] = await Promise.allSettled([
|
||||||
|
api.api.k8s.status.get(),
|
||||||
|
api.api.k8s.pods.get(),
|
||||||
|
api.api.k8s.deployments.get(),
|
||||||
|
api.api.k8s.statefulsets.get(),
|
||||||
|
api.api.k8s.services.get(),
|
||||||
|
api.api.k8s.configmaps.get(),
|
||||||
|
api.api.k8s["minecraft-servers"].get(),
|
||||||
|
api.api.k8s["reverse-proxy-servers"].get(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (statusRes.status === "fulfilled" && statusRes.value.data) {
|
||||||
|
setStatus(statusRes.value.data as K8sStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (podsRes.status === "fulfilled" && podsRes.value.data) {
|
||||||
|
setPods(podsRes.value.data as PodInfo[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deploymentsRes.status === "fulfilled" && deploymentsRes.value.data) {
|
||||||
|
setDeployments(deploymentsRes.value.data as DeploymentInfo[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statefulSetsRes.status === "fulfilled" && statefulSetsRes.value.data) {
|
||||||
|
setStatefulSets(statefulSetsRes.value.data as StatefulSetInfo[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (servicesRes.status === "fulfilled" && servicesRes.value.data) {
|
||||||
|
setServices(servicesRes.value.data as K8sServiceSummary[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (configMapsRes.status === "fulfilled" && configMapsRes.value.data) {
|
||||||
|
setConfigMaps(configMapsRes.value.data as K8sConfigMapSummary[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (minecraftServersRes.status === "fulfilled" && minecraftServersRes.value.data) {
|
||||||
|
setMinecraftServers(minecraftServersRes.value.data as CustomResourceSummary[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reverseProxyServersRes.status === "fulfilled" && reverseProxyServersRes.value.data) {
|
||||||
|
setReverseProxyServers(reverseProxyServersRes.value.data as CustomResourceSummary[]);
|
||||||
|
}
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const errorMessage =
|
||||||
|
err instanceof Error ? err.message : "Failed to fetch Kubernetes resources";
|
||||||
|
setError(errorMessage);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// biome-ignore lint/correctness/useExhaustiveDependencies: fetchData intentionally omitted to avoid infinite loop
|
||||||
|
useEffect(() => {
|
||||||
|
fetchData();
|
||||||
|
const interval = setInterval(fetchData, 30000);
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const getStatusBadge = (phase: string) => {
|
||||||
|
const variants: Record<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
icon: React.ComponentType<{ className?: string }>;
|
||||||
|
variant: "default" | "destructive" | "secondary";
|
||||||
|
}
|
||||||
|
> = {
|
||||||
|
Running: { icon: CheckCircle2, variant: "default" },
|
||||||
|
Succeeded: { icon: CheckCircle2, variant: "default" },
|
||||||
|
Failed: { icon: XCircle, variant: "destructive" },
|
||||||
|
Pending: { icon: AlertCircle, variant: "secondary" },
|
||||||
|
Unknown: { icon: AlertCircle, variant: "secondary" },
|
||||||
|
};
|
||||||
|
|
||||||
|
const status = variants[phase] || variants.Unknown;
|
||||||
|
const Icon = status.icon;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Badge variant={status.variant}>
|
||||||
|
<Icon className="mr-1 h-3 w-3" />
|
||||||
|
{phase}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading && !status) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Kubernetes Resources</h1>
|
||||||
|
<p className="text-muted-foreground">View and monitor your Kubernetes resources</p>
|
||||||
|
</div>
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<Skeleton className="h-6 w-48" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Skeleton className="h-40 w-full" />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Kubernetes Resources</h1>
|
||||||
|
<p className="text-muted-foreground">View and monitor your Kubernetes resources</p>
|
||||||
|
</div>
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-destructive flex items-center gap-2">
|
||||||
|
<XCircle className="h-5 w-5" />
|
||||||
|
Error
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<p className="text-sm text-muted-foreground">{error}</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!status?.initialized) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Kubernetes Resources</h1>
|
||||||
|
<p className="text-muted-foreground">View and monitor your Kubernetes resources</p>
|
||||||
|
</div>
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<AlertCircle className="h-5 w-5 text-yellow-500" />
|
||||||
|
Kubernetes Not Connected
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
The Kubernetes client is not initialized. Please ensure the operator is running with
|
||||||
|
proper Kubernetes configuration.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Set{" "}
|
||||||
|
<code className="bg-muted px-1 py-0.5 rounded">KUBERNETES_SKIP_TLS_VERIFY=true</code>{" "}
|
||||||
|
if using self-signed certificates.
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Kubernetes Resources</h1>
|
||||||
|
<p className="text-muted-foreground">View and monitor your Kubernetes resources</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<CheckCircle2 className="h-5 w-5 text-green-500" />
|
||||||
|
<span className="text-sm font-medium">Connected to Kubernetes</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Tabs defaultValue="pods" className="space-y-4">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="pods">Pods ({pods.length})</TabsTrigger>
|
||||||
|
<TabsTrigger value="deployments">Deployments ({deployments.length})</TabsTrigger>
|
||||||
|
<TabsTrigger value="statefulsets">StatefulSets ({statefulSets.length})</TabsTrigger>
|
||||||
|
<TabsTrigger value="services">Services ({services.length})</TabsTrigger>
|
||||||
|
<TabsTrigger value="configmaps">ConfigMaps ({configMaps.length})</TabsTrigger>
|
||||||
|
<TabsTrigger value="minecraft">Minecraft Servers ({minecraftServers.length})</TabsTrigger>
|
||||||
|
<TabsTrigger value="reverseproxy">
|
||||||
|
Reverse Proxies ({reverseProxyServers.length})
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
|
||||||
|
<TabsContent value="pods" className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Pods</CardTitle>
|
||||||
|
<CardDescription>Running pods in the minikura namespace</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{pods.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No pods found</p>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Ready</TableHead>
|
||||||
|
<TableHead>Restarts</TableHead>
|
||||||
|
<TableHead>Node</TableHead>
|
||||||
|
<TableHead>Age</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{pods.map((pod) => (
|
||||||
|
<TableRow key={pod.name}>
|
||||||
|
<TableCell className="font-medium">{pod.name}</TableCell>
|
||||||
|
<TableCell>{getStatusBadge(pod.status)}</TableCell>
|
||||||
|
<TableCell>{pod.ready}</TableCell>
|
||||||
|
<TableCell>{pod.restarts}</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{pod.nodeName || "-"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">{pod.age}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="deployments" className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Deployments</CardTitle>
|
||||||
|
<CardDescription>Deployments in the minikura namespace</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{deployments.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No deployments found</p>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Ready</TableHead>
|
||||||
|
<TableHead>Up-to-date</TableHead>
|
||||||
|
<TableHead>Available</TableHead>
|
||||||
|
<TableHead>Age</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{deployments.map((deployment) => (
|
||||||
|
<TableRow key={deployment.name}>
|
||||||
|
<TableCell className="font-medium">{deployment.name}</TableCell>
|
||||||
|
<TableCell>{deployment.ready}</TableCell>
|
||||||
|
<TableCell>{deployment.upToDate ?? deployment.updated}</TableCell>
|
||||||
|
<TableCell>{deployment.available ?? 0}</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{deployment.age}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="statefulsets" className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>StatefulSets</CardTitle>
|
||||||
|
<CardDescription>StatefulSets in the minikura namespace</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{statefulSets.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No statefulsets found</p>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Ready</TableHead>
|
||||||
|
<TableHead>Desired</TableHead>
|
||||||
|
<TableHead>Current</TableHead>
|
||||||
|
<TableHead>Age</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{statefulSets.map((statefulSet) => (
|
||||||
|
<TableRow key={statefulSet.name}>
|
||||||
|
<TableCell className="font-medium">{statefulSet.name}</TableCell>
|
||||||
|
<TableCell>{statefulSet.ready}</TableCell>
|
||||||
|
<TableCell>{statefulSet.desired}</TableCell>
|
||||||
|
<TableCell>{statefulSet.current}</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{statefulSet.age}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="services" className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Services</CardTitle>
|
||||||
|
<CardDescription>Services in the minikura namespace</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{services.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No services found</p>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Type</TableHead>
|
||||||
|
<TableHead>Cluster IP</TableHead>
|
||||||
|
<TableHead>External IP</TableHead>
|
||||||
|
<TableHead>Ports</TableHead>
|
||||||
|
<TableHead>Age</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{services.map((service) => (
|
||||||
|
<TableRow key={service.name}>
|
||||||
|
<TableCell className="font-medium">{service.name}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant="outline">{service.type}</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{service.clusterIP}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{service.externalIP}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{service.ports}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{service.age}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="configmaps" className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>ConfigMaps</CardTitle>
|
||||||
|
<CardDescription>ConfigMaps in the minikura namespace</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{configMaps.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No configmaps found</p>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Data Keys</TableHead>
|
||||||
|
<TableHead>Age</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{configMaps.map((cm) => (
|
||||||
|
<TableRow key={cm.name}>
|
||||||
|
<TableCell className="font-medium">{cm.name}</TableCell>
|
||||||
|
<TableCell>{cm.data}</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">{cm.age}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="minecraft" className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Minecraft Servers</CardTitle>
|
||||||
|
<CardDescription>Custom Minecraft server resources</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{minecraftServers.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No Minecraft servers found</p>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Age</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{minecraftServers.map((server) => (
|
||||||
|
<TableRow key={server.name}>
|
||||||
|
<TableCell className="font-medium">{server.name}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{server.status?.phase ? (
|
||||||
|
getStatusBadge(server.status.phase)
|
||||||
|
) : (
|
||||||
|
<Badge variant="secondary">Unknown</Badge>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{server.age}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="reverseproxy" className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Reverse Proxy Servers</CardTitle>
|
||||||
|
<CardDescription>Custom reverse proxy server resources</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{reverseProxyServers.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No reverse proxy servers found</p>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Age</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{reverseProxyServers.map((server) => (
|
||||||
|
<TableRow key={server.name}>
|
||||||
|
<TableCell className="font-medium">{server.name}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{server.status?.phase ? (
|
||||||
|
getStatusBadge(server.status.phase)
|
||||||
|
) : (
|
||||||
|
<Badge variant="secondary">Unknown</Badge>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-muted-foreground">
|
||||||
|
{server.age}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
5
apps/web/app/dashboard/layout.tsx
Normal file
5
apps/web/app/dashboard/layout.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { DashboardLayout } from "@/components/dashboard-layout";
|
||||||
|
|
||||||
|
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||||
|
return <DashboardLayout>{children}</DashboardLayout>;
|
||||||
|
}
|
||||||
5
apps/web/app/dashboard/page.tsx
Normal file
5
apps/web/app/dashboard/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
export default function DashboardPage() {
|
||||||
|
redirect("/dashboard/users");
|
||||||
|
}
|
||||||
192
apps/web/app/dashboard/servers/create/page.tsx
Normal file
192
apps/web/app/dashboard/servers/create/page.tsx
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { CreateServerRequest } from "@minikura/api";
|
||||||
|
import { ArrowLeft } from "lucide-react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { ServerForm, type ServerFormData } from "@/components/server-form";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { api } from "@/lib/api-client";
|
||||||
|
|
||||||
|
const toDifficultyUppercase = (value: string): "PEACEFUL" | "EASY" | "NORMAL" | "HARD" => {
|
||||||
|
return value.toUpperCase() as "PEACEFUL" | "EASY" | "NORMAL" | "HARD";
|
||||||
|
};
|
||||||
|
|
||||||
|
const toModeUppercase = (value: string): "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR" => {
|
||||||
|
return value.toUpperCase() as "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR";
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function CreateServerPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const handleSubmit = async (data: ServerFormData) => {
|
||||||
|
const filteredEnvVars = data.envVars.filter((ev) => ev.key && ev.value);
|
||||||
|
|
||||||
|
const envVariables: Record<string, string> = {};
|
||||||
|
|
||||||
|
if (data.allowFlight) envVariables.ALLOW_FLIGHT = String(data.allowFlight);
|
||||||
|
if (data.enableCommandBlock)
|
||||||
|
envVariables.ENABLE_COMMAND_BLOCK = String(data.enableCommandBlock);
|
||||||
|
if (data.spawnProtection) envVariables.SPAWN_PROTECTION = data.spawnProtection;
|
||||||
|
if (data.viewDistance) envVariables.VIEW_DISTANCE = data.viewDistance;
|
||||||
|
if (data.simulationDistance) envVariables.SIMULATION_DISTANCE = data.simulationDistance;
|
||||||
|
|
||||||
|
if (data.levelName) envVariables.LEVEL = data.levelName;
|
||||||
|
if (data.levelSeed) envVariables.SEED = data.levelSeed;
|
||||||
|
if (data.levelType) envVariables.LEVEL_TYPE = data.levelType;
|
||||||
|
if (data.generatorSettings) envVariables.GENERATOR_SETTINGS = data.generatorSettings;
|
||||||
|
if (data.hardcore) envVariables.HARDCORE = String(data.hardcore);
|
||||||
|
if (data.spawnAnimals !== undefined) envVariables.SPAWN_ANIMALS = String(data.spawnAnimals);
|
||||||
|
if (data.spawnMonsters !== undefined) envVariables.SPAWN_MONSTERS = String(data.spawnMonsters);
|
||||||
|
if (data.spawnNpcs !== undefined) envVariables.SPAWN_NPCS = String(data.spawnNpcs);
|
||||||
|
|
||||||
|
if (data.enableWhitelist) envVariables.ENABLE_WHITELIST = String(data.enableWhitelist);
|
||||||
|
if (data.whitelist) envVariables.WHITELIST = data.whitelist;
|
||||||
|
if (data.whitelistFile) envVariables.WHITELIST_FILE = data.whitelistFile;
|
||||||
|
if (data.ops) envVariables.OPS = data.ops;
|
||||||
|
if (data.opsFile) envVariables.OPS_FILE = data.opsFile;
|
||||||
|
|
||||||
|
if (data.jvmXxOpts) envVariables.JVM_XX_OPTS = data.jvmXxOpts;
|
||||||
|
if (data.jvmDdOpts) envVariables.JVM_DD_OPTS = data.jvmDdOpts;
|
||||||
|
if (data.enableJmx) envVariables.ENABLE_JMX = String(data.enableJmx);
|
||||||
|
|
||||||
|
if (data.resourcePack) envVariables.RESOURCE_PACK = data.resourcePack;
|
||||||
|
if (data.resourcePackSha1) envVariables.RESOURCE_PACK_SHA1 = data.resourcePackSha1;
|
||||||
|
if (data.resourcePackEnforce)
|
||||||
|
envVariables.RESOURCE_PACK_ENFORCE = String(data.resourcePackEnforce);
|
||||||
|
|
||||||
|
if (data.enableRcon !== undefined) envVariables.ENABLE_RCON = String(data.enableRcon);
|
||||||
|
if (data.rconPassword) envVariables.RCON_PASSWORD = data.rconPassword;
|
||||||
|
if (data.rconPort) envVariables.RCON_PORT = data.rconPort;
|
||||||
|
if (data.rconCmdsStartup) envVariables.RCON_CMDS_STARTUP = data.rconCmdsStartup;
|
||||||
|
if (data.rconCmdsOnConnect) envVariables.RCON_CMDS_ON_CONNECT = data.rconCmdsOnConnect;
|
||||||
|
if (data.rconCmdsFirstConnect) envVariables.RCON_CMDS_FIRST_CONNECT = data.rconCmdsFirstConnect;
|
||||||
|
if (data.rconCmdsOnDisconnect) envVariables.RCON_CMDS_ON_DISCONNECT = data.rconCmdsOnDisconnect;
|
||||||
|
if (data.rconCmdsLastDisconnect)
|
||||||
|
envVariables.RCON_CMDS_LAST_DISCONNECT = data.rconCmdsLastDisconnect;
|
||||||
|
|
||||||
|
if (data.enableQuery !== undefined) envVariables.ENABLE_QUERY = String(data.enableQuery);
|
||||||
|
if (data.queryPort) envVariables.QUERY_PORT = data.queryPort;
|
||||||
|
|
||||||
|
if (data.enableAutopause) envVariables.ENABLE_AUTOPAUSE = String(data.enableAutopause);
|
||||||
|
if (data.autopauseTimeoutEst) envVariables.AUTOPAUSE_TIMEOUT_EST = data.autopauseTimeoutEst;
|
||||||
|
if (data.autopauseTimeoutInit) envVariables.AUTOPAUSE_TIMEOUT_INIT = data.autopauseTimeoutInit;
|
||||||
|
if (data.autopauseTimeoutKn) envVariables.AUTOPAUSE_TIMEOUT_KN = data.autopauseTimeoutKn;
|
||||||
|
if (data.autopausePeriod) envVariables.AUTOPAUSE_PERIOD = data.autopausePeriod;
|
||||||
|
if (data.autopauseKnockInterface)
|
||||||
|
envVariables.AUTOPAUSE_KNOCK_INTERFACE = data.autopauseKnockInterface;
|
||||||
|
|
||||||
|
if (data.enableAutostop) envVariables.ENABLE_AUTOSTOP = String(data.enableAutostop);
|
||||||
|
if (data.autostopTimeoutEst) envVariables.AUTOSTOP_TIMEOUT_EST = data.autostopTimeoutEst;
|
||||||
|
if (data.autostopTimeoutInit) envVariables.AUTOSTOP_TIMEOUT_INIT = data.autostopTimeoutInit;
|
||||||
|
if (data.autostopPeriod) envVariables.AUTOSTOP_PERIOD = data.autostopPeriod;
|
||||||
|
|
||||||
|
if (data.plugins) envVariables.PLUGINS = data.plugins;
|
||||||
|
if (data.removeOldPlugins) envVariables.REMOVE_OLD_PLUGINS = String(data.removeOldPlugins);
|
||||||
|
if (data.spigetResources) envVariables.SPIGET_RESOURCES = data.spigetResources;
|
||||||
|
|
||||||
|
if (data.paperBuild) envVariables.PAPER_BUILD = data.paperBuild;
|
||||||
|
|
||||||
|
if (data.type === "CUSTOM" && data.customJarUrl) {
|
||||||
|
envVariables.CUSTOM_SERVER = data.customJarUrl;
|
||||||
|
envVariables.VERSION = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.timezone) envVariables.TZ = data.timezone;
|
||||||
|
if (data.uid) envVariables.UID = data.uid;
|
||||||
|
if (data.gid) envVariables.GID = data.gid;
|
||||||
|
if (data.stopDuration) envVariables.STOP_DURATION = data.stopDuration;
|
||||||
|
if (data.serverIcon) envVariables.ICON = data.serverIcon;
|
||||||
|
|
||||||
|
envVariables.EULA = String(data.eula);
|
||||||
|
|
||||||
|
envVariables.TYPE = data.type;
|
||||||
|
if (data.type !== "CUSTOM" && data.version) {
|
||||||
|
envVariables.VERSION = data.version;
|
||||||
|
}
|
||||||
|
if (data.type === "CUSTOM" && !data.customJarUrl) {
|
||||||
|
throw new Error("Custom jar URL is required for custom servers");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const envVar of filteredEnvVars) {
|
||||||
|
envVariables[envVar.key] = envVar.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: CreateServerRequest = {
|
||||||
|
id: data.id.trim(),
|
||||||
|
description: data.description.trim() || null,
|
||||||
|
listen_port: Number(data.listenPort),
|
||||||
|
type: "STATEFUL",
|
||||||
|
service_type: data.serviceType,
|
||||||
|
node_port: data.serviceType === "NODE_PORT" && data.nodePort ? Number(data.nodePort) : null,
|
||||||
|
env_variables: Object.entries(envVariables).map(([key, value]) => ({ key, value })),
|
||||||
|
memory: data.memoryLimit ? Number(data.memoryLimit) : undefined,
|
||||||
|
memory_request: data.memoryRequest ? Number(data.memoryRequest) : undefined,
|
||||||
|
cpu_request: data.cpuRequest || undefined,
|
||||||
|
cpu_limit: data.cpuLimit || undefined,
|
||||||
|
jar_type: data.type === "CUSTOM" ? "VANILLA" : data.type,
|
||||||
|
minecraft_version: data.type === "CUSTOM" ? undefined : data.version || "LATEST",
|
||||||
|
jvm_opts: data.jvmOpts || undefined,
|
||||||
|
use_aikar_flags: data.useAikarFlags || undefined,
|
||||||
|
use_meowice_flags: data.useMeowiceFlags || undefined,
|
||||||
|
difficulty: toDifficultyUppercase(data.difficulty),
|
||||||
|
game_mode: toModeUppercase(data.mode),
|
||||||
|
max_players: data.maxPlayers ? Number(data.maxPlayers) : undefined,
|
||||||
|
pvp: data.pvp,
|
||||||
|
online_mode: data.onlineMode,
|
||||||
|
motd: data.motd,
|
||||||
|
level_seed: data.levelSeed,
|
||||||
|
level_type: data.levelType,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await api.api.servers.post(payload);
|
||||||
|
|
||||||
|
if (response.error) {
|
||||||
|
const errorMsg =
|
||||||
|
typeof response.error === "object" &&
|
||||||
|
response.error &&
|
||||||
|
"value" in response.error &&
|
||||||
|
typeof response.error.value === "object" &&
|
||||||
|
response.error.value &&
|
||||||
|
"message" in response.error.value
|
||||||
|
? String(response.error.value.message)
|
||||||
|
: "Failed to create server";
|
||||||
|
throw new Error(errorMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
router.push("/dashboard/servers");
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => router.push("/dashboard/servers")}>
|
||||||
|
<ArrowLeft className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Create Minecraft Server</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">
|
||||||
|
Configure your new Minecraft server with comprehensive settings
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Server Configuration</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Complete configuration for itzg/minecraft-server Docker image with all environment
|
||||||
|
variables
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ServerForm
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
onCancel={() => router.push("/dashboard/servers")}
|
||||||
|
submitLabel="Create Server"
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
460
apps/web/app/dashboard/servers/edit/[id]/page.tsx
Normal file
460
apps/web/app/dashboard/servers/edit/[id]/page.tsx
Normal file
@@ -0,0 +1,460 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { NormalServer, UpdateServerRequest } from "@minikura/api";
|
||||||
|
import { ArrowLeft } from "lucide-react";
|
||||||
|
import { useParams, useRouter } from "next/navigation";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { ServerForm, type ServerFormData, type ServerType } from "@/components/server-form";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { api } from "@/lib/api-client";
|
||||||
|
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||||
|
|
||||||
|
export default function EditServerPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const params = useParams();
|
||||||
|
const serverId = params.id as string;
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [serverData, setServerData] = useState<NormalServer | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchServer = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
const normalResponse = await api.api.servers.get();
|
||||||
|
if (normalResponse.data) {
|
||||||
|
const servers = normalResponse.data as unknown as NormalServer[];
|
||||||
|
const server = servers.find((s) => s.id === serverId);
|
||||||
|
if (server) {
|
||||||
|
setServerData(server);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const proxyResponse = await getReverseProxyApi().get();
|
||||||
|
if (proxyResponse.data) {
|
||||||
|
const proxies = proxyResponse.data as unknown as NormalServer[];
|
||||||
|
const proxy = proxies.find((p) => p.id === serverId);
|
||||||
|
if (proxy) {
|
||||||
|
setServerData(proxy);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setError("Server not found");
|
||||||
|
setLoading(false);
|
||||||
|
} catch (_err) {
|
||||||
|
setError("Failed to load server data");
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (serverId) {
|
||||||
|
fetchServer();
|
||||||
|
}
|
||||||
|
}, [serverId]);
|
||||||
|
|
||||||
|
const toServiceType = (value?: string | null): ServerFormData["serviceType"] => {
|
||||||
|
if (value === "NODE_PORT" || value === "LOAD_BALANCER") {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return "CLUSTER_IP";
|
||||||
|
};
|
||||||
|
|
||||||
|
const toDifficulty = (value?: string | null): ServerFormData["difficulty"] => {
|
||||||
|
if (value === "peaceful" || value === "easy" || value === "normal" || value === "hard") {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return "easy";
|
||||||
|
};
|
||||||
|
|
||||||
|
const toMode = (value?: string | null): ServerFormData["mode"] => {
|
||||||
|
if (value === "creative" || value === "adventure" || value === "spectator") {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return "survival";
|
||||||
|
};
|
||||||
|
|
||||||
|
const toDifficultyUppercase = (value: string): "PEACEFUL" | "EASY" | "NORMAL" | "HARD" => {
|
||||||
|
return value.toUpperCase() as "PEACEFUL" | "EASY" | "NORMAL" | "HARD";
|
||||||
|
};
|
||||||
|
|
||||||
|
const toModeUppercase = (value: string): "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR" => {
|
||||||
|
return value.toUpperCase() as "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR";
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseEnvVariables = (envVars?: Array<{ key: string; value: string }>) => {
|
||||||
|
if (!envVars) return {};
|
||||||
|
|
||||||
|
const parsed: Record<string, string> = {};
|
||||||
|
for (const { key, value } of envVars) {
|
||||||
|
parsed[key] = value;
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async (data: ServerFormData) => {
|
||||||
|
if (!serverData) return;
|
||||||
|
|
||||||
|
const filteredEnvVars = data.envVars.filter((ev) => ev.key && ev.value);
|
||||||
|
|
||||||
|
const envVariables: Record<string, string> = {};
|
||||||
|
if (data.allowFlight) envVariables.ALLOW_FLIGHT = String(data.allowFlight);
|
||||||
|
if (data.enableCommandBlock)
|
||||||
|
envVariables.ENABLE_COMMAND_BLOCK = String(data.enableCommandBlock);
|
||||||
|
if (data.spawnProtection) envVariables.SPAWN_PROTECTION = data.spawnProtection;
|
||||||
|
if (data.viewDistance) envVariables.VIEW_DISTANCE = data.viewDistance;
|
||||||
|
if (data.simulationDistance) envVariables.SIMULATION_DISTANCE = data.simulationDistance;
|
||||||
|
|
||||||
|
if (data.levelSeed) envVariables.SEED = data.levelSeed;
|
||||||
|
if (data.levelType) envVariables.LEVEL_TYPE = data.levelType;
|
||||||
|
if (data.generatorSettings) envVariables.GENERATOR_SETTINGS = data.generatorSettings;
|
||||||
|
if (data.hardcore) envVariables.HARDCORE = String(data.hardcore);
|
||||||
|
if (data.spawnAnimals !== undefined) envVariables.SPAWN_ANIMALS = String(data.spawnAnimals);
|
||||||
|
if (data.spawnMonsters !== undefined) envVariables.SPAWN_MONSTERS = String(data.spawnMonsters);
|
||||||
|
if (data.spawnNpcs !== undefined) envVariables.SPAWN_NPCS = String(data.spawnNpcs);
|
||||||
|
|
||||||
|
if (data.enableWhitelist) envVariables.ENABLE_WHITELIST = String(data.enableWhitelist);
|
||||||
|
if (data.whitelist) envVariables.WHITELIST = data.whitelist;
|
||||||
|
if (data.whitelistFile) envVariables.WHITELIST_FILE = data.whitelistFile;
|
||||||
|
if (data.ops) envVariables.OPS = data.ops;
|
||||||
|
if (data.opsFile) envVariables.OPS_FILE = data.opsFile;
|
||||||
|
|
||||||
|
if (data.jvmXxOpts) envVariables.JVM_XX_OPTS = data.jvmXxOpts;
|
||||||
|
if (data.jvmDdOpts) envVariables.JVM_DD_OPTS = data.jvmDdOpts;
|
||||||
|
if (data.enableJmx) envVariables.ENABLE_JMX = String(data.enableJmx);
|
||||||
|
|
||||||
|
if (data.resourcePack) envVariables.RESOURCE_PACK = data.resourcePack;
|
||||||
|
if (data.resourcePackSha1) envVariables.RESOURCE_PACK_SHA1 = data.resourcePackSha1;
|
||||||
|
if (data.resourcePackEnforce)
|
||||||
|
envVariables.RESOURCE_PACK_ENFORCE = String(data.resourcePackEnforce);
|
||||||
|
|
||||||
|
if (data.enableRcon !== undefined) envVariables.ENABLE_RCON = String(data.enableRcon);
|
||||||
|
if (data.rconPassword) envVariables.RCON_PASSWORD = data.rconPassword;
|
||||||
|
if (data.rconPort) envVariables.RCON_PORT = data.rconPort;
|
||||||
|
if (data.rconCmdsStartup) envVariables.RCON_CMDS_STARTUP = data.rconCmdsStartup;
|
||||||
|
if (data.rconCmdsOnConnect) envVariables.RCON_CMDS_ON_CONNECT = data.rconCmdsOnConnect;
|
||||||
|
if (data.rconCmdsFirstConnect) envVariables.RCON_CMDS_FIRST_CONNECT = data.rconCmdsFirstConnect;
|
||||||
|
if (data.rconCmdsOnDisconnect) envVariables.RCON_CMDS_ON_DISCONNECT = data.rconCmdsOnDisconnect;
|
||||||
|
if (data.rconCmdsLastDisconnect)
|
||||||
|
envVariables.RCON_CMDS_LAST_DISCONNECT = data.rconCmdsLastDisconnect;
|
||||||
|
|
||||||
|
if (data.enableQuery !== undefined) envVariables.ENABLE_QUERY = String(data.enableQuery);
|
||||||
|
if (data.queryPort) envVariables.QUERY_PORT = data.queryPort;
|
||||||
|
|
||||||
|
if (data.enableAutopause) envVariables.ENABLE_AUTOPAUSE = String(data.enableAutopause);
|
||||||
|
if (data.autopauseTimeoutEst) envVariables.AUTOPAUSE_TIMEOUT_EST = data.autopauseTimeoutEst;
|
||||||
|
if (data.autopauseTimeoutInit) envVariables.AUTOPAUSE_TIMEOUT_INIT = data.autopauseTimeoutInit;
|
||||||
|
if (data.autopauseTimeoutKn) envVariables.AUTOPAUSE_TIMEOUT_KN = data.autopauseTimeoutKn;
|
||||||
|
if (data.autopausePeriod) envVariables.AUTOPAUSE_PERIOD = data.autopausePeriod;
|
||||||
|
if (data.autopauseKnockInterface)
|
||||||
|
envVariables.AUTOPAUSE_KNOCK_INTERFACE = data.autopauseKnockInterface;
|
||||||
|
|
||||||
|
if (data.enableAutostop) envVariables.ENABLE_AUTOSTOP = String(data.enableAutostop);
|
||||||
|
if (data.autostopTimeoutEst) envVariables.AUTOSTOP_TIMEOUT_EST = data.autostopTimeoutEst;
|
||||||
|
if (data.autostopTimeoutInit) envVariables.AUTOSTOP_TIMEOUT_INIT = data.autostopTimeoutInit;
|
||||||
|
if (data.autostopPeriod) envVariables.AUTOSTOP_PERIOD = data.autostopPeriod;
|
||||||
|
|
||||||
|
if (data.plugins) envVariables.PLUGINS = data.plugins;
|
||||||
|
if (data.removeOldPlugins) envVariables.REMOVE_OLD_PLUGINS = String(data.removeOldPlugins);
|
||||||
|
if (data.spigetResources) envVariables.SPIGET_RESOURCES = data.spigetResources;
|
||||||
|
|
||||||
|
if (data.paperBuild) envVariables.PAPER_BUILD = data.paperBuild;
|
||||||
|
|
||||||
|
if (data.type === "CUSTOM" && data.customJarUrl) {
|
||||||
|
envVariables.CUSTOM_SERVER = data.customJarUrl;
|
||||||
|
envVariables.VERSION = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.timezone) envVariables.TZ = data.timezone;
|
||||||
|
if (data.uid) envVariables.UID = data.uid;
|
||||||
|
if (data.gid) envVariables.GID = data.gid;
|
||||||
|
if (data.stopDuration) envVariables.STOP_DURATION = data.stopDuration;
|
||||||
|
if (data.serverIcon) envVariables.ICON = data.serverIcon;
|
||||||
|
|
||||||
|
envVariables.EULA = String(data.eula);
|
||||||
|
envVariables.TYPE = data.type;
|
||||||
|
if (data.type !== "CUSTOM" && data.version) {
|
||||||
|
envVariables.VERSION = data.version;
|
||||||
|
}
|
||||||
|
if (data.type === "CUSTOM" && !data.customJarUrl) {
|
||||||
|
throw new Error("Custom jar URL is required for custom servers");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const envVar of filteredEnvVars) {
|
||||||
|
envVariables[envVar.key] = envVar.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: UpdateServerRequest = {
|
||||||
|
description: data.description.trim() || null,
|
||||||
|
listen_port: Number(data.listenPort),
|
||||||
|
service_type: data.serviceType,
|
||||||
|
node_port: data.serviceType === "NODE_PORT" && data.nodePort ? Number(data.nodePort) : null,
|
||||||
|
env_variables: Object.entries(envVariables).map(([key, value]) => ({ key, value })),
|
||||||
|
memory: data.memoryLimit ? Number(data.memoryLimit) : undefined,
|
||||||
|
memory_request: data.memoryRequest ? Number(data.memoryRequest) : undefined,
|
||||||
|
cpu_request: data.cpuRequest || undefined,
|
||||||
|
cpu_limit: data.cpuLimit || undefined,
|
||||||
|
jar_type: data.type === "CUSTOM" ? "VANILLA" : data.type,
|
||||||
|
minecraft_version: data.type === "CUSTOM" ? undefined : data.version || "LATEST",
|
||||||
|
jvm_opts: data.jvmOpts || undefined,
|
||||||
|
use_aikar_flags: data.useAikarFlags || undefined,
|
||||||
|
use_meowice_flags: data.useMeowiceFlags || undefined,
|
||||||
|
difficulty: toDifficultyUppercase(data.difficulty),
|
||||||
|
game_mode: toModeUppercase(data.mode),
|
||||||
|
max_players: data.maxPlayers ? Number(data.maxPlayers) : undefined,
|
||||||
|
pvp: data.pvp,
|
||||||
|
online_mode: data.onlineMode,
|
||||||
|
motd: data.motd,
|
||||||
|
level_seed: data.levelSeed,
|
||||||
|
level_type: data.levelType,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await api.api.servers({ id: serverId }).patch(payload);
|
||||||
|
|
||||||
|
if (response.error) {
|
||||||
|
const errorMsg =
|
||||||
|
typeof response.error === "object" &&
|
||||||
|
response.error &&
|
||||||
|
"value" in response.error &&
|
||||||
|
typeof response.error.value === "object" &&
|
||||||
|
response.error.value &&
|
||||||
|
"message" in response.error.value
|
||||||
|
? String(response.error.value.message)
|
||||||
|
: "Failed to update server";
|
||||||
|
throw new Error(errorMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
router.push("/dashboard/servers");
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center min-h-screen">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
|
||||||
|
<p className="text-muted-foreground">Loading server data...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !serverData) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center min-h-screen">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="bg-destructive/10 text-destructive px-6 py-4 rounded-lg">
|
||||||
|
{error || "Server not found"}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
className="mt-4"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => router.push("/dashboard/servers")}
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||||
|
Back to Servers
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const envVars = parseEnvVariables(serverData.env_variables);
|
||||||
|
|
||||||
|
const dockerManagedKeys = new Set([
|
||||||
|
"EULA",
|
||||||
|
"TYPE",
|
||||||
|
"VERSION",
|
||||||
|
"CUSTOM_SERVER",
|
||||||
|
"MOTD",
|
||||||
|
"DIFFICULTY",
|
||||||
|
"MODE",
|
||||||
|
"MAX_PLAYERS",
|
||||||
|
"PVP",
|
||||||
|
"ONLINE_MODE",
|
||||||
|
"ALLOW_FLIGHT",
|
||||||
|
"ENABLE_COMMAND_BLOCK",
|
||||||
|
"SPAWN_PROTECTION",
|
||||||
|
"VIEW_DISTANCE",
|
||||||
|
"SIMULATION_DISTANCE",
|
||||||
|
"LEVEL",
|
||||||
|
"SEED",
|
||||||
|
"LEVEL_TYPE",
|
||||||
|
"GENERATOR_SETTINGS",
|
||||||
|
"HARDCORE",
|
||||||
|
"SPAWN_ANIMALS",
|
||||||
|
"SPAWN_MONSTERS",
|
||||||
|
"SPAWN_NPCS",
|
||||||
|
"ENABLE_WHITELIST",
|
||||||
|
"WHITELIST",
|
||||||
|
"WHITELIST_FILE",
|
||||||
|
"OPS",
|
||||||
|
"OPS_FILE",
|
||||||
|
"USE_AIKAR_FLAGS",
|
||||||
|
"USE_MEOWICE_FLAGS",
|
||||||
|
"JVM_OPTS",
|
||||||
|
"JVM_XX_OPTS",
|
||||||
|
"JVM_DD_OPTS",
|
||||||
|
"ENABLE_JMX",
|
||||||
|
"RESOURCE_PACK",
|
||||||
|
"RESOURCE_PACK_SHA1",
|
||||||
|
"RESOURCE_PACK_ENFORCE",
|
||||||
|
"ENABLE_RCON",
|
||||||
|
"RCON_PASSWORD",
|
||||||
|
"RCON_PORT",
|
||||||
|
"RCON_CMDS_STARTUP",
|
||||||
|
"RCON_CMDS_ON_CONNECT",
|
||||||
|
"RCON_CMDS_FIRST_CONNECT",
|
||||||
|
"RCON_CMDS_ON_DISCONNECT",
|
||||||
|
"RCON_CMDS_LAST_DISCONNECT",
|
||||||
|
"ENABLE_QUERY",
|
||||||
|
"QUERY_PORT",
|
||||||
|
"ENABLE_AUTOPAUSE",
|
||||||
|
"AUTOPAUSE_TIMEOUT_EST",
|
||||||
|
"AUTOPAUSE_TIMEOUT_INIT",
|
||||||
|
"AUTOPAUSE_TIMEOUT_KN",
|
||||||
|
"AUTOPAUSE_PERIOD",
|
||||||
|
"AUTOPAUSE_KNOCK_INTERFACE",
|
||||||
|
"ENABLE_AUTOSTOP",
|
||||||
|
"AUTOSTOP_TIMEOUT_EST",
|
||||||
|
"AUTOSTOP_TIMEOUT_INIT",
|
||||||
|
"AUTOSTOP_PERIOD",
|
||||||
|
"PLUGINS",
|
||||||
|
"REMOVE_OLD_PLUGINS",
|
||||||
|
"SPIGET_RESOURCES",
|
||||||
|
"PAPER_BUILD",
|
||||||
|
"TZ",
|
||||||
|
"UID",
|
||||||
|
"GID",
|
||||||
|
"STOP_DURATION",
|
||||||
|
"ICON",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const customEnvVars = Object.entries(envVars)
|
||||||
|
.filter(([key]) => !dockerManagedKeys.has(key))
|
||||||
|
.map(([key, value]) => ({ id: crypto.randomUUID(), key, value }));
|
||||||
|
|
||||||
|
const initialData: Partial<ServerFormData> = {
|
||||||
|
id: serverData.id,
|
||||||
|
description: serverData.description || "",
|
||||||
|
memoryLimit: String(serverData.memory || 2048),
|
||||||
|
memoryRequest: String(serverData.memory_request ?? 1024),
|
||||||
|
cpuRequest: serverData.cpu_request || "500m",
|
||||||
|
cpuLimit: serverData.cpu_limit || "2",
|
||||||
|
type: (envVars.TYPE || serverData.jar_type || "PAPER") as ServerType,
|
||||||
|
version: envVars.VERSION || serverData.minecraft_version || "",
|
||||||
|
customJarUrl: envVars.CUSTOM_SERVER || undefined,
|
||||||
|
eula: envVars.EULA === "true",
|
||||||
|
listenPort: String(serverData.listen_port || 25565),
|
||||||
|
serviceType: toServiceType(serverData.service_type),
|
||||||
|
nodePort: serverData.node_port ? String(serverData.node_port) : undefined,
|
||||||
|
|
||||||
|
motd: envVars.MOTD || serverData.motd || undefined,
|
||||||
|
difficulty: toDifficulty(envVars.DIFFICULTY || serverData.difficulty),
|
||||||
|
mode: toMode(envVars.MODE || serverData.game_mode),
|
||||||
|
maxPlayers: envVars.MAX_PLAYERS || String(serverData.max_players || 20),
|
||||||
|
pvp: envVars.PVP ? envVars.PVP === "true" : (serverData.pvp ?? true),
|
||||||
|
onlineMode: envVars.ONLINE_MODE
|
||||||
|
? envVars.ONLINE_MODE === "true"
|
||||||
|
: (serverData.online_mode ?? true),
|
||||||
|
allowFlight: envVars.ALLOW_FLIGHT === "true",
|
||||||
|
enableCommandBlock: envVars.ENABLE_COMMAND_BLOCK === "true",
|
||||||
|
spawnProtection: envVars.SPAWN_PROTECTION || "16",
|
||||||
|
viewDistance: envVars.VIEW_DISTANCE || "10",
|
||||||
|
simulationDistance: envVars.SIMULATION_DISTANCE || "10",
|
||||||
|
|
||||||
|
levelName: envVars.LEVEL || "world",
|
||||||
|
levelSeed: envVars.SEED || serverData.level_seed || undefined,
|
||||||
|
levelType: envVars.LEVEL_TYPE || serverData.level_type || undefined,
|
||||||
|
generatorSettings: envVars.GENERATOR_SETTINGS || undefined,
|
||||||
|
hardcore: envVars.HARDCORE === "true",
|
||||||
|
spawnAnimals: envVars.SPAWN_ANIMALS !== "false",
|
||||||
|
spawnMonsters: envVars.SPAWN_MONSTERS !== "false",
|
||||||
|
spawnNpcs: envVars.SPAWN_NPCS !== "false",
|
||||||
|
|
||||||
|
enableWhitelist: envVars.ENABLE_WHITELIST === "true",
|
||||||
|
whitelist: envVars.WHITELIST || undefined,
|
||||||
|
whitelistFile: envVars.WHITELIST_FILE || undefined,
|
||||||
|
ops: envVars.OPS || undefined,
|
||||||
|
opsFile: envVars.OPS_FILE || undefined,
|
||||||
|
|
||||||
|
useAikarFlags: envVars.USE_AIKAR_FLAGS === "true" || serverData.use_aikar_flags || false,
|
||||||
|
useMeowiceFlags: envVars.USE_MEOWICE_FLAGS === "true" || serverData.use_meowice_flags || false,
|
||||||
|
jvmOpts: envVars.JVM_OPTS || serverData.jvm_opts || undefined,
|
||||||
|
jvmXxOpts: envVars.JVM_XX_OPTS || undefined,
|
||||||
|
jvmDdOpts: envVars.JVM_DD_OPTS || undefined,
|
||||||
|
enableJmx: envVars.ENABLE_JMX === "true",
|
||||||
|
|
||||||
|
resourcePack: envVars.RESOURCE_PACK || undefined,
|
||||||
|
resourcePackSha1: envVars.RESOURCE_PACK_SHA1 || undefined,
|
||||||
|
resourcePackEnforce: envVars.RESOURCE_PACK_ENFORCE === "true",
|
||||||
|
|
||||||
|
enableRcon: envVars.ENABLE_RCON !== "false",
|
||||||
|
rconPassword: envVars.RCON_PASSWORD || undefined,
|
||||||
|
rconPort: envVars.RCON_PORT || "25575",
|
||||||
|
rconCmdsStartup: envVars.RCON_CMDS_STARTUP || undefined,
|
||||||
|
rconCmdsOnConnect: envVars.RCON_CMDS_ON_CONNECT || undefined,
|
||||||
|
rconCmdsFirstConnect: envVars.RCON_CMDS_FIRST_CONNECT || undefined,
|
||||||
|
rconCmdsOnDisconnect: envVars.RCON_CMDS_ON_DISCONNECT || undefined,
|
||||||
|
rconCmdsLastDisconnect: envVars.RCON_CMDS_LAST_DISCONNECT || undefined,
|
||||||
|
|
||||||
|
enableQuery: envVars.ENABLE_QUERY === "true",
|
||||||
|
queryPort: envVars.QUERY_PORT || "25565",
|
||||||
|
|
||||||
|
enableAutopause: envVars.ENABLE_AUTOPAUSE === "true",
|
||||||
|
autopauseTimeoutEst: envVars.AUTOPAUSE_TIMEOUT_EST || "3600",
|
||||||
|
autopauseTimeoutInit: envVars.AUTOPAUSE_TIMEOUT_INIT || "600",
|
||||||
|
autopauseTimeoutKn: envVars.AUTOPAUSE_TIMEOUT_KN || "120",
|
||||||
|
autopausePeriod: envVars.AUTOPAUSE_PERIOD || "10",
|
||||||
|
autopauseKnockInterface: envVars.AUTOPAUSE_KNOCK_INTERFACE || "eth0",
|
||||||
|
|
||||||
|
enableAutostop: envVars.ENABLE_AUTOSTOP === "true",
|
||||||
|
autostopTimeoutEst: envVars.AUTOSTOP_TIMEOUT_EST || "3600",
|
||||||
|
autostopTimeoutInit: envVars.AUTOSTOP_TIMEOUT_INIT || "1800",
|
||||||
|
autostopPeriod: envVars.AUTOSTOP_PERIOD || "10",
|
||||||
|
|
||||||
|
plugins: envVars.PLUGINS || undefined,
|
||||||
|
removeOldPlugins: envVars.REMOVE_OLD_PLUGINS === "true",
|
||||||
|
spigetResources: envVars.SPIGET_RESOURCES || undefined,
|
||||||
|
|
||||||
|
paperBuild: envVars.PAPER_BUILD || undefined,
|
||||||
|
|
||||||
|
serverIcon: envVars.ICON || undefined,
|
||||||
|
|
||||||
|
envVars: customEnvVars,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => router.push("/dashboard/servers")}>
|
||||||
|
<ArrowLeft className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Edit Server: {serverData.id}</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">Update your Minecraft server configuration</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Server Configuration</CardTitle>
|
||||||
|
<CardDescription>Modify settings for your Minecraft server</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ServerForm
|
||||||
|
initialData={initialData}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
onCancel={() => router.push("/dashboard/servers")}
|
||||||
|
submitLabel="Save Changes"
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
451
apps/web/app/dashboard/servers/page.tsx
Normal file
451
apps/web/app/dashboard/servers/page.tsx
Normal file
@@ -0,0 +1,451 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { ConnectionInfo, NormalServer, PodInfo, ReverseProxyServer } from "@minikura/api";
|
||||||
|
import {
|
||||||
|
AlertCircle,
|
||||||
|
Check,
|
||||||
|
CheckCircle2,
|
||||||
|
Copy,
|
||||||
|
FileText,
|
||||||
|
Globe,
|
||||||
|
Pencil,
|
||||||
|
Plus,
|
||||||
|
Server,
|
||||||
|
Trash2,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/components/ui/table";
|
||||||
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
|
import { api } from "@/lib/api-client";
|
||||||
|
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||||
|
|
||||||
|
function ServerStatusCell({ serverId, type }: { serverId: string; type: "normal" | "proxy" }) {
|
||||||
|
const [pods, setPods] = useState<PodInfo[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchPods = async () => {
|
||||||
|
try {
|
||||||
|
const endpoint =
|
||||||
|
type === "normal"
|
||||||
|
? api.api.k8s.servers({ serverId }).pods.get
|
||||||
|
: api.api.k8s["reverse-proxy"]({ serverId }).pods.get;
|
||||||
|
const res = await endpoint();
|
||||||
|
if (res.data) {
|
||||||
|
setPods(res.data as PodInfo[]);
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchPods();
|
||||||
|
}, [serverId, type]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<div className="h-3 w-3 animate-pulse bg-muted rounded-full" />
|
||||||
|
Loading...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pods.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<AlertCircle className="h-3 w-3" />
|
||||||
|
No pods
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const allRunning = pods.every((pod) => pod.status === "Running");
|
||||||
|
const readyCount = pods.filter((pod) => pod.ready === "1/1").length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{allRunning ? (
|
||||||
|
<CheckCircle2 className="h-3 w-3 text-green-500" />
|
||||||
|
) : (
|
||||||
|
<AlertCircle className="h-3 w-3 text-yellow-500" />
|
||||||
|
)}
|
||||||
|
<span className="text-xs">
|
||||||
|
{readyCount}/{pods.length} Ready
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConnectionInfoCell({ serverId, type }: { serverId: string; type: "normal" | "proxy" }) {
|
||||||
|
const [connectionInfo, setConnectionInfo] = useState<ConnectionInfo | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchConnectionInfo = async () => {
|
||||||
|
try {
|
||||||
|
const reverseProxyApi = getReverseProxyApi();
|
||||||
|
const endpoint =
|
||||||
|
type === "normal"
|
||||||
|
? api.api.servers({ id: serverId })["connection-info"]
|
||||||
|
: reverseProxyApi({ id: serverId })["connection-info"];
|
||||||
|
const res = await endpoint.get();
|
||||||
|
if (res.data) {
|
||||||
|
setConnectionInfo(res.data as ConnectionInfo);
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchConnectionInfo();
|
||||||
|
}, [serverId, type]);
|
||||||
|
|
||||||
|
const handleCopy = async () => {
|
||||||
|
if (connectionInfo?.connectionString) {
|
||||||
|
await navigator.clipboard.writeText(connectionInfo.connectionString);
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <span className="text-muted-foreground text-xs">Loading...</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!connectionInfo) {
|
||||||
|
return <span className="text-muted-foreground text-xs">N/A</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TooltipProvider>
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<Badge variant="secondary" className="w-fit text-xs">
|
||||||
|
{connectionInfo.type}
|
||||||
|
</Badge>
|
||||||
|
{connectionInfo.connectionString && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<code className="text-xs bg-muted px-1.5 py-0.5 rounded font-mono">
|
||||||
|
{connectionInfo.connectionString}
|
||||||
|
</code>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon" className="h-5 w-5" onClick={handleCopy}>
|
||||||
|
{copied ? (
|
||||||
|
<Check className="h-3 w-3 text-green-500" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-3 w-3" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
<p>{copied ? "Copied!" : "Copy to clipboard"}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{connectionInfo.note && (
|
||||||
|
<p className="text-xs text-muted-foreground">{connectionInfo.note}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TooltipProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ServersPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [normalServers, setNormalServers] = useState<NormalServer[]>([]);
|
||||||
|
const [reverseProxies, setReverseProxies] = useState<ReverseProxyServer[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<{
|
||||||
|
id: string;
|
||||||
|
type: "normal" | "proxy";
|
||||||
|
} | null>(null);
|
||||||
|
|
||||||
|
const fetchServers = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const reverseProxyApi = getReverseProxyApi();
|
||||||
|
const [normalRes, proxyRes] = await Promise.all([
|
||||||
|
api.api.servers.get(),
|
||||||
|
reverseProxyApi.get(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (normalRes.data) {
|
||||||
|
setNormalServers(normalRes.data as unknown as NormalServer[]);
|
||||||
|
}
|
||||||
|
if (proxyRes.data) {
|
||||||
|
setReverseProxies(proxyRes.data as unknown as ReverseProxyServer[]);
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchServers();
|
||||||
|
}, [fetchServers]);
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (!deleteTarget) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const reverseProxyApi = getReverseProxyApi();
|
||||||
|
if (deleteTarget.type === "normal") {
|
||||||
|
await api.api.servers({ id: deleteTarget.id }).delete();
|
||||||
|
} else {
|
||||||
|
await reverseProxyApi({ id: deleteTarget.id }).delete();
|
||||||
|
}
|
||||||
|
await fetchServers();
|
||||||
|
setDeleteTarget(null);
|
||||||
|
} catch (_error) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Server Management</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">Manage your Minecraft servers</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-center h-64">
|
||||||
|
<p className="text-muted-foreground">Loading...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Server Management</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">
|
||||||
|
Manage your Minecraft servers and reverse proxies
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => router.push("/dashboard/servers/create")}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Create Server
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Server className="h-5 w-5" />
|
||||||
|
<CardTitle>Minecraft Servers</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>Manage your normal Minecraft server instances</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{normalServers.length === 0 ? (
|
||||||
|
<div className="flex items-center justify-center h-32 border-2 border-dashed rounded-lg">
|
||||||
|
<p className="text-muted-foreground">No servers created yet</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>ID</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Storage</TableHead>
|
||||||
|
<TableHead>Software</TableHead>
|
||||||
|
<TableHead>Version</TableHead>
|
||||||
|
<TableHead>Memory (MB)</TableHead>
|
||||||
|
<TableHead>Network</TableHead>
|
||||||
|
<TableHead>Description</TableHead>
|
||||||
|
<TableHead className="text-right">Actions</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{normalServers.map((server) => (
|
||||||
|
<TableRow key={server.id}>
|
||||||
|
<TableCell className="font-medium">{server.id}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<ServerStatusCell serverId={server.id} type="normal" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant="outline">{server.type}</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant="secondary">{server.jar_type || "VANILLA"}</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">
|
||||||
|
{server.minecraft_version || "LATEST"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{server.memory || 1024}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<ConnectionInfoCell serverId={server.id} type="normal" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">
|
||||||
|
{server.description || "-"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => router.push(`/dashboard/servers/${server.id}/logs`)}
|
||||||
|
title="View Logs"
|
||||||
|
>
|
||||||
|
<FileText className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => router.push(`/dashboard/servers/edit/${server.id}`)}
|
||||||
|
title="Edit Server"
|
||||||
|
>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setDeleteTarget({ id: server.id, type: "normal" })}
|
||||||
|
title="Delete"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Globe className="h-5 w-5" />
|
||||||
|
<CardTitle>Reverse Proxy Servers</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>Manage your Velocity and BungeeCord proxy servers</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{reverseProxies.length === 0 ? (
|
||||||
|
<div className="flex items-center justify-center h-32 border-2 border-dashed rounded-lg">
|
||||||
|
<p className="text-muted-foreground">No reverse proxies created yet</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>ID</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Type</TableHead>
|
||||||
|
<TableHead>External</TableHead>
|
||||||
|
<TableHead>Listen Port</TableHead>
|
||||||
|
<TableHead>Memory (MB)</TableHead>
|
||||||
|
<TableHead>Network</TableHead>
|
||||||
|
<TableHead>Description</TableHead>
|
||||||
|
<TableHead className="text-right">Actions</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{reverseProxies.map((proxy) => (
|
||||||
|
<TableRow key={proxy.id}>
|
||||||
|
<TableCell className="font-medium">{proxy.id}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<ServerStatusCell serverId={proxy.id} type="proxy" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant="outline">{proxy.type}</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{proxy.external_address}:{proxy.external_port}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{proxy.listen_port}</TableCell>
|
||||||
|
<TableCell>{proxy.memory}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<ConnectionInfoCell serverId={proxy.id} type="proxy" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-muted-foreground">
|
||||||
|
{proxy.description || "-"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => router.push(`/dashboard/servers/${proxy.id}/logs`)}
|
||||||
|
title="View Logs"
|
||||||
|
>
|
||||||
|
<FileText className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => router.push(`/dashboard/servers/edit/${proxy.id}`)}
|
||||||
|
title="Edit Server"
|
||||||
|
>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setDeleteTarget({ id: proxy.id, type: "proxy" })}
|
||||||
|
title="Delete"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Delete Server</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Are you sure you want to delete this{" "}
|
||||||
|
{deleteTarget?.type === "normal" ? "server" : "reverse proxy"}? This action cannot be
|
||||||
|
undone.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setDeleteTarget(null)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={handleDelete}>
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
89
apps/web/app/dashboard/topology/page.tsx
Normal file
89
apps/web/app/dashboard/topology/page.tsx
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Network, RefreshCw } from "lucide-react";
|
||||||
|
import { TopologyCanvas } from "@/components/topology/topology-canvas";
|
||||||
|
import { useTopologyData } from "@/hooks/use-topology-data";
|
||||||
|
|
||||||
|
export default function TopologyPage() {
|
||||||
|
const { graph, loading, error } = useTopologyData();
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">
|
||||||
|
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-center h-[calc(100vh-250px)]">
|
||||||
|
<div className="flex flex-col items-center gap-2">
|
||||||
|
<RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
<p className="text-muted-foreground">Loading topology...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">
|
||||||
|
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-center h-[calc(100vh-250px)] border-2 border-dashed rounded-lg">
|
||||||
|
<div className="flex flex-col items-center gap-2 p-6 text-center">
|
||||||
|
<p className="text-destructive font-semibold">Error loading topology</p>
|
||||||
|
<p className="text-muted-foreground text-sm">{error}</p>
|
||||||
|
<p className="text-muted-foreground text-xs mt-2">Auto-retrying...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!graph || graph.nodes.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">
|
||||||
|
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-center h-[calc(100vh-250px)] border-2 border-dashed rounded-lg">
|
||||||
|
<div className="flex flex-col items-center gap-2 p-6 text-center">
|
||||||
|
<p className="text-muted-foreground">No servers or infrastructure found</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Create a server to see it appear in the topology
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="p-2 bg-primary/10 rounded-lg">
|
||||||
|
<Network className="h-6 w-6 text-primary" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">
|
||||||
|
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TopologyCanvas graph={graph} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
336
apps/web/app/dashboard/users/page.tsx
Normal file
336
apps/web/app/dashboard/users/page.tsx
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Ban, CheckCircle, Edit, Trash2 } from "lucide-react";
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/components/ui/table";
|
||||||
|
import { api } from "@/lib/api-client";
|
||||||
|
import { getUserApi } from "@/lib/api-helpers";
|
||||||
|
import { useSession } from "@/lib/auth-client";
|
||||||
|
|
||||||
|
type User = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
role: string;
|
||||||
|
createdAt: string;
|
||||||
|
emailVerified: boolean;
|
||||||
|
isSuspended: boolean;
|
||||||
|
suspendedUntil: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function UsersPage() {
|
||||||
|
const { data: session } = useSession();
|
||||||
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||||
|
const [suspendingUser, setSuspendingUser] = useState<User | null>(null);
|
||||||
|
const [deleteUser, setDeleteUser] = useState<User | null>(null);
|
||||||
|
|
||||||
|
const fetchUsers = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const { data } = await api.api.users.get();
|
||||||
|
if (data && typeof data === "object" && "users" in data) {
|
||||||
|
setUsers(data.users as User[]);
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchUsers();
|
||||||
|
}, [fetchUsers]);
|
||||||
|
|
||||||
|
const handleEdit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!editingUser) return;
|
||||||
|
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const name = formData.get("name") as string;
|
||||||
|
const role = formData.get("role") as string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error } = await api.api.users({ id: editingUser.id }).patch({
|
||||||
|
name,
|
||||||
|
role: role as "admin" | "user",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!error) {
|
||||||
|
await fetchUsers();
|
||||||
|
setEditingUser(null);
|
||||||
|
}
|
||||||
|
} catch (_error) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSuspend = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!suspendingUser) return;
|
||||||
|
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const suspendedUntil = formData.get("suspendedUntil") as string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error } = await getUserApi(suspendingUser.id).suspension.patch({
|
||||||
|
isSuspended: true,
|
||||||
|
suspendedUntil: suspendedUntil || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!error) {
|
||||||
|
await fetchUsers();
|
||||||
|
setSuspendingUser(null);
|
||||||
|
}
|
||||||
|
} catch (_error) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUnsuspend = async (userId: string) => {
|
||||||
|
try {
|
||||||
|
const { error } = await getUserApi(userId).suspension.patch({
|
||||||
|
isSuspended: false,
|
||||||
|
suspendedUntil: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!error) {
|
||||||
|
await fetchUsers();
|
||||||
|
}
|
||||||
|
} catch (_error) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (!deleteUser) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error } = await api.api.users({ id: deleteUser.id }).delete();
|
||||||
|
|
||||||
|
if (!error) {
|
||||||
|
await fetchUsers();
|
||||||
|
setDeleteUser(null);
|
||||||
|
}
|
||||||
|
} catch (_error) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isUserSuspended = (user: User): boolean => {
|
||||||
|
if (!user.isSuspended) return false;
|
||||||
|
if (user.suspendedUntil && new Date(user.suspendedUntil) <= new Date()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-64">
|
||||||
|
<div className="text-muted-foreground">Loading...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold">User Management</h1>
|
||||||
|
<p className="text-muted-foreground mt-1">Manage user accounts and permissions</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Users</CardTitle>
|
||||||
|
<CardDescription>All registered users in the system</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>Email</TableHead>
|
||||||
|
<TableHead>Role</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead>Created</TableHead>
|
||||||
|
<TableHead className="text-right">Actions</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{users.map((user) => (
|
||||||
|
<TableRow key={user.id}>
|
||||||
|
<TableCell className="font-medium">{user.name}</TableCell>
|
||||||
|
<TableCell>{user.email}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={user.role === "admin" ? "default" : "secondary"}>
|
||||||
|
{user.role}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{isUserSuspended(user) ? (
|
||||||
|
<Badge variant="destructive">
|
||||||
|
Suspended
|
||||||
|
{user.suspendedUntil &&
|
||||||
|
` until ${new Date(user.suspendedUntil).toLocaleDateString()}`}
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant={user.emailVerified ? "default" : "outline"}>
|
||||||
|
{user.emailVerified ? "Active" : "Unverified"}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{new Date(user.createdAt).toLocaleDateString()}</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<Button variant="ghost" size="icon" onClick={() => setEditingUser(user)}>
|
||||||
|
<Edit className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
{isUserSuspended(user) ? (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleUnsuspend(user.id)}
|
||||||
|
>
|
||||||
|
<CheckCircle className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setSuspendingUser(user)}
|
||||||
|
>
|
||||||
|
<Ban className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
disabled={user.id === session?.user?.id}
|
||||||
|
onClick={() => setDeleteUser(user)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Dialog open={!!editingUser} onOpenChange={() => setEditingUser(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Edit User</DialogTitle>
|
||||||
|
<DialogDescription>Update user information and role</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<form onSubmit={handleEdit}>
|
||||||
|
<div className="space-y-4 py-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Name</Label>
|
||||||
|
<Input id="name" name="name" defaultValue={editingUser?.name} required />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="role">Role</Label>
|
||||||
|
<Select name="role" defaultValue={editingUser?.role}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="user">User</SelectItem>
|
||||||
|
<SelectItem value="admin">Admin</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="button" variant="outline" onClick={() => setEditingUser(null)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit">Save Changes</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog open={!!suspendingUser} onOpenChange={() => setSuspendingUser(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Suspend User</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Suspend {suspendingUser?.name} from accessing the system
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<form onSubmit={handleSuspend}>
|
||||||
|
<div className="space-y-4 py-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="suspendedUntil">Suspend Until (Optional)</Label>
|
||||||
|
<Input
|
||||||
|
id="suspendedUntil"
|
||||||
|
name="suspendedUntil"
|
||||||
|
type="datetime-local"
|
||||||
|
placeholder="Leave empty for indefinite suspension"
|
||||||
|
/>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Leave empty for indefinite suspension
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="button" variant="outline" onClick={() => setSuspendingUser(null)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" variant="destructive">
|
||||||
|
Suspend User
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog open={!!deleteUser} onOpenChange={() => setDeleteUser(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Delete User</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Are you sure you want to delete {deleteUser?.name}? This action cannot be undone.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setDeleteUser(null)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={handleDelete}>
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
150
apps/web/app/globals.css
Normal file
150
apps/web/app/globals.css
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
@import "tw-animate-css";
|
||||||
|
|
||||||
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
--radius-sm: calc(var(--radius) - 4px);
|
||||||
|
--radius-md: calc(var(--radius) - 2px);
|
||||||
|
--radius-lg: var(--radius);
|
||||||
|
--radius-xl: calc(var(--radius) + 4px);
|
||||||
|
--radius-2xl: calc(var(--radius) + 8px);
|
||||||
|
--radius-3xl: calc(var(--radius) + 12px);
|
||||||
|
--radius-4xl: calc(var(--radius) + 16px);
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--radius: 0.625rem;
|
||||||
|
--background: oklch(1 0 0);
|
||||||
|
--foreground: oklch(0.145 0 0);
|
||||||
|
--card: oklch(1 0 0);
|
||||||
|
--card-foreground: oklch(0.145 0 0);
|
||||||
|
--popover: oklch(1 0 0);
|
||||||
|
--popover-foreground: oklch(0.145 0 0);
|
||||||
|
--primary: oklch(0.205 0 0);
|
||||||
|
--primary-foreground: oklch(0.985 0 0);
|
||||||
|
--secondary: oklch(0.97 0 0);
|
||||||
|
--secondary-foreground: oklch(0.205 0 0);
|
||||||
|
--muted: oklch(0.97 0 0);
|
||||||
|
--muted-foreground: oklch(0.556 0 0);
|
||||||
|
--accent: oklch(0.97 0 0);
|
||||||
|
--accent-foreground: oklch(0.205 0 0);
|
||||||
|
--destructive: oklch(0.577 0.245 27.325);
|
||||||
|
--border: oklch(0.922 0 0);
|
||||||
|
--input: oklch(0.922 0 0);
|
||||||
|
--ring: oklch(0.708 0 0);
|
||||||
|
--chart-1: oklch(0.646 0.222 41.116);
|
||||||
|
--chart-2: oklch(0.6 0.118 184.704);
|
||||||
|
--chart-3: oklch(0.398 0.07 227.392);
|
||||||
|
--chart-4: oklch(0.828 0.189 84.429);
|
||||||
|
--chart-5: oklch(0.769 0.188 70.08);
|
||||||
|
--sidebar: oklch(0.985 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.145 0 0);
|
||||||
|
--sidebar-primary: oklch(0.205 0 0);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.97 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||||
|
--sidebar-border: oklch(0.922 0 0);
|
||||||
|
--sidebar-ring: oklch(0.708 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: oklch(0.145 0 0);
|
||||||
|
--foreground: oklch(0.985 0 0);
|
||||||
|
--card: oklch(0.205 0 0);
|
||||||
|
--card-foreground: oklch(0.985 0 0);
|
||||||
|
--popover: oklch(0.205 0 0);
|
||||||
|
--popover-foreground: oklch(0.985 0 0);
|
||||||
|
--primary: oklch(0.922 0 0);
|
||||||
|
--primary-foreground: oklch(0.205 0 0);
|
||||||
|
--secondary: oklch(0.269 0 0);
|
||||||
|
--secondary-foreground: oklch(0.985 0 0);
|
||||||
|
--muted: oklch(0.269 0 0);
|
||||||
|
--muted-foreground: oklch(0.708 0 0);
|
||||||
|
--accent: oklch(0.269 0 0);
|
||||||
|
--accent-foreground: oklch(0.985 0 0);
|
||||||
|
--destructive: oklch(0.704 0.191 22.216);
|
||||||
|
--border: oklch(1 0 0 / 10%);
|
||||||
|
--input: oklch(1 0 0 / 15%);
|
||||||
|
--ring: oklch(0.556 0 0);
|
||||||
|
--chart-1: oklch(0.488 0.243 264.376);
|
||||||
|
--chart-2: oklch(0.696 0.17 162.48);
|
||||||
|
--chart-3: oklch(0.769 0.188 70.08);
|
||||||
|
--chart-4: oklch(0.627 0.265 303.9);
|
||||||
|
--chart-5: oklch(0.645 0.246 16.439);
|
||||||
|
--sidebar: oklch(0.205 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.269 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-border: oklch(1 0 0 / 10%);
|
||||||
|
--sidebar-ring: oklch(0.556 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border outline-ring/50;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
@apply bg-background text-foreground;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes accordion-down {
|
||||||
|
from {
|
||||||
|
height: 0;
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
height: var(--radix-accordion-content-height);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes accordion-up {
|
||||||
|
from {
|
||||||
|
height: var(--radix-accordion-content-height);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
height: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer utilities {
|
||||||
|
.animate-accordion-down {
|
||||||
|
animation: accordion-down 0.2s ease-out;
|
||||||
|
}
|
||||||
|
.animate-accordion-up {
|
||||||
|
animation: accordion-up 0.2s ease-out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
export default function RootLayout({
|
import type { Metadata } from "next";
|
||||||
children,
|
import "./globals.css";
|
||||||
}: {
|
|
||||||
children: React.ReactNode;
|
export const metadata: Metadata = {
|
||||||
}) {
|
title: "Minikura - Minecraft Server Manager",
|
||||||
|
description: "Manage your Minecraft servers with ease",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<body>{children}</body>
|
<body className="antialiased">{children}</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
106
apps/web/app/login/page.tsx
Normal file
106
apps/web/app/login/page.tsx
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { signIn, useSession } from "@/lib/auth-client";
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const { data: session, isPending } = useSession();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isPending && session?.user) {
|
||||||
|
router.replace("/dashboard");
|
||||||
|
}
|
||||||
|
}, [session, isPending, router]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
|
||||||
|
const formData = new FormData(e.currentTarget);
|
||||||
|
const email = formData.get("email") as string;
|
||||||
|
const password = formData.get("password") as string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await signIn.email({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
setError(result.error.message || "Invalid email or password");
|
||||||
|
} else {
|
||||||
|
router.push("/dashboard");
|
||||||
|
}
|
||||||
|
} catch (_err) {
|
||||||
|
setError("Failed to connect to server");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isPending) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session?.user) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 p-4">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader className="space-y-1">
|
||||||
|
<CardTitle className="text-2xl font-bold text-center">Minikura</CardTitle>
|
||||||
|
<CardDescription className="text-center">Sign in to your account</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="admin@example.com"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">Password</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
placeholder="••••••••"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && <div className="text-sm text-red-600 text-center">{error}</div>}
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "Signing in..." : "Sign In"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
import { api } from "@minikura/api";
|
import { treaty } from "@elysiajs/eden";
|
||||||
|
import type { App } from "@minikura/backend";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
async function fetchData() {
|
export const dynamic = "force-dynamic";
|
||||||
const response = await api.index.get();
|
|
||||||
return response;
|
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
|
||||||
}
|
const api = treaty<App>(apiUrl);
|
||||||
|
|
||||||
export default async function Page() {
|
export default async function HomePage() {
|
||||||
const data = await fetchData();
|
const { data } = await api.bootstrap.status.get();
|
||||||
|
|
||||||
return (
|
if (data?.needsSetup) {
|
||||||
<div>
|
redirect("/bootstrap");
|
||||||
<h1>Hello React</h1>
|
} else {
|
||||||
<pre>{JSON.stringify(data, null, 2)}</pre>
|
redirect("/login");
|
||||||
</div>
|
}
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
22
apps/web/components.json
Normal file
22
apps/web/components.json
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "new-york",
|
||||||
|
"rsc": true,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "",
|
||||||
|
"css": "app/globals.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
158
apps/web/components/dashboard-layout.tsx
Normal file
158
apps/web/components/dashboard-layout.tsx
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { GitGraph, Loader2, LogOut, Network, Server, Settings, Users } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import {
|
||||||
|
Sidebar,
|
||||||
|
SidebarContent,
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupContent,
|
||||||
|
SidebarGroupLabel,
|
||||||
|
SidebarHeader,
|
||||||
|
SidebarInset,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
SidebarProvider,
|
||||||
|
SidebarTrigger,
|
||||||
|
} from "@/components/ui/sidebar";
|
||||||
|
import { signOut, useSession } from "@/lib/auth-client";
|
||||||
|
|
||||||
|
const menuItems = [
|
||||||
|
{ href: "/dashboard/users", icon: Users, label: "Users" },
|
||||||
|
{ href: "/dashboard/servers", icon: Server, label: "Servers" },
|
||||||
|
{ href: "/dashboard/topology", icon: GitGraph, label: "Network" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const k8sMenuItems = [{ href: "/dashboard/k8s", icon: Network, label: "Resources" }];
|
||||||
|
|
||||||
|
export function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
const router = useRouter();
|
||||||
|
const { data: session, isPending } = useSession();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isPending && !session?.user) {
|
||||||
|
router.replace("/login");
|
||||||
|
}
|
||||||
|
}, [session, isPending, router]);
|
||||||
|
|
||||||
|
if (isPending) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSignOut = async () => {
|
||||||
|
await signOut();
|
||||||
|
window.location.href = "/login";
|
||||||
|
};
|
||||||
|
|
||||||
|
const userInitials =
|
||||||
|
session?.user?.name
|
||||||
|
?.split(" ")
|
||||||
|
.map((n) => n[0])
|
||||||
|
.join("")
|
||||||
|
.toUpperCase() || "U";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SidebarProvider>
|
||||||
|
<Sidebar>
|
||||||
|
<SidebarHeader className="border-b px-6 py-4">
|
||||||
|
<h2 className="text-lg font-semibold">Minikura</h2>
|
||||||
|
</SidebarHeader>
|
||||||
|
<SidebarContent>
|
||||||
|
<SidebarGroup>
|
||||||
|
<SidebarGroupContent>
|
||||||
|
<SidebarMenu>
|
||||||
|
{menuItems.map((item) => (
|
||||||
|
<SidebarMenuItem key={item.href}>
|
||||||
|
<SidebarMenuButton asChild isActive={pathname === item.href}>
|
||||||
|
<Link href={item.href}>
|
||||||
|
<item.icon className="h-4 w-4" />
|
||||||
|
<span>{item.label}</span>
|
||||||
|
</Link>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
))}
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroupContent>
|
||||||
|
</SidebarGroup>
|
||||||
|
<SidebarGroup>
|
||||||
|
<SidebarGroupLabel>Kubernetes</SidebarGroupLabel>
|
||||||
|
<SidebarGroupContent>
|
||||||
|
<SidebarMenu>
|
||||||
|
{k8sMenuItems.map((item) => (
|
||||||
|
<SidebarMenuItem key={item.href}>
|
||||||
|
<SidebarMenuButton asChild isActive={pathname === item.href}>
|
||||||
|
<Link href={item.href}>
|
||||||
|
<item.icon className="h-4 w-4" />
|
||||||
|
<span>{item.label}</span>
|
||||||
|
</Link>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
))}
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroupContent>
|
||||||
|
</SidebarGroup>
|
||||||
|
</SidebarContent>
|
||||||
|
<div className="border-t p-4">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" className="w-full justify-start gap-2 px-2">
|
||||||
|
<Avatar className="h-8 w-8">
|
||||||
|
<AvatarFallback>{userInitials}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex flex-col items-start text-sm">
|
||||||
|
<span className="font-medium">{session?.user?.name}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{session?.user?.email}</span>
|
||||||
|
</div>
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-56">
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href="/dashboard/settings">
|
||||||
|
<Settings className="mr-2 h-4 w-4" />
|
||||||
|
Settings
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem onClick={handleSignOut}>
|
||||||
|
<LogOut className="mr-2 h-4 w-4" />
|
||||||
|
Sign Out
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
<SidebarInset>
|
||||||
|
<header className="flex h-16 items-center gap-4 border-b bg-background px-6">
|
||||||
|
<SidebarTrigger />
|
||||||
|
<div className="flex-1" />
|
||||||
|
</header>
|
||||||
|
<main className="flex-1 p-6 min-w-0 overflow-auto">{children}</main>
|
||||||
|
</SidebarInset>
|
||||||
|
</SidebarProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
1428
apps/web/components/server-form.tsx
Normal file
1428
apps/web/components/server-form.tsx
Normal file
File diff suppressed because it is too large
Load Diff
301
apps/web/components/terminal.tsx
Normal file
301
apps/web/components/terminal.tsx
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ClipboardAddon } from "@xterm/addon-clipboard";
|
||||||
|
import { FitAddon } from "@xterm/addon-fit";
|
||||||
|
import { ImageAddon } from "@xterm/addon-image";
|
||||||
|
import { LigaturesAddon } from "@xterm/addon-ligatures";
|
||||||
|
import { SearchAddon } from "@xterm/addon-search";
|
||||||
|
import { Unicode11Addon } from "@xterm/addon-unicode11";
|
||||||
|
import { WebLinksAddon } from "@xterm/addon-web-links";
|
||||||
|
import { WebglAddon } from "@xterm/addon-webgl";
|
||||||
|
import { Terminal as XTerm } from "@xterm/xterm";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import "@xterm/xterm/css/xterm.css";
|
||||||
|
|
||||||
|
type TerminalProps = {
|
||||||
|
podName: string;
|
||||||
|
container: string;
|
||||||
|
shell?: string;
|
||||||
|
mode?: "shell" | "attach";
|
||||||
|
onClose?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function Terminal({
|
||||||
|
podName,
|
||||||
|
container,
|
||||||
|
shell = "/bin/sh",
|
||||||
|
mode = "shell",
|
||||||
|
onClose,
|
||||||
|
}: TerminalProps) {
|
||||||
|
const terminalRef = useRef<HTMLDivElement>(null);
|
||||||
|
const xtermRef = useRef<XTerm | null>(null);
|
||||||
|
const wsRef = useRef<WebSocket | null>(null);
|
||||||
|
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||||
|
const searchAddonRef = useRef<SearchAddon | null>(null);
|
||||||
|
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [connected, setConnected] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [showSearch, setShowSearch] = useState(false);
|
||||||
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (showSearch && searchInputRef.current) {
|
||||||
|
searchInputRef.current.focus();
|
||||||
|
}
|
||||||
|
}, [showSearch]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!terminalRef.current) return;
|
||||||
|
|
||||||
|
const term = new XTerm({
|
||||||
|
cursorBlink: true,
|
||||||
|
fontSize: 14,
|
||||||
|
fontFamily: 'JetBrains Mono, Fira Code, Menlo, Monaco, "Courier New", monospace',
|
||||||
|
fontWeight: "normal",
|
||||||
|
fontWeightBold: "bold",
|
||||||
|
letterSpacing: 0,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
theme: {
|
||||||
|
background: "#0a0a0a",
|
||||||
|
foreground: "#e0e0e0",
|
||||||
|
cursor: "#00ff00",
|
||||||
|
cursorAccent: "#000000",
|
||||||
|
selectionBackground: "#3a3d41",
|
||||||
|
selectionForeground: "#ffffff",
|
||||||
|
black: "#000000",
|
||||||
|
red: "#ff5555",
|
||||||
|
green: "#50fa7b",
|
||||||
|
yellow: "#f1fa8c",
|
||||||
|
blue: "#bd93f9",
|
||||||
|
magenta: "#ff79c6",
|
||||||
|
cyan: "#8be9fd",
|
||||||
|
white: "#bfbfbf",
|
||||||
|
brightBlack: "#4d4d4d",
|
||||||
|
brightRed: "#ff6e67",
|
||||||
|
brightGreen: "#5af78e",
|
||||||
|
brightYellow: "#f4f99d",
|
||||||
|
brightBlue: "#caa9fa",
|
||||||
|
brightMagenta: "#ff92d0",
|
||||||
|
brightCyan: "#9aedfe",
|
||||||
|
brightWhite: "#e6e6e6",
|
||||||
|
},
|
||||||
|
rows: 30,
|
||||||
|
cols: 100,
|
||||||
|
allowProposedApi: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const fitAddon = new FitAddon();
|
||||||
|
const webLinksAddon = new WebLinksAddon();
|
||||||
|
const searchAddon = new SearchAddon();
|
||||||
|
const clipboardAddon = new ClipboardAddon();
|
||||||
|
const unicode11Addon = new Unicode11Addon();
|
||||||
|
const imageAddon = new ImageAddon();
|
||||||
|
|
||||||
|
term.loadAddon(fitAddon);
|
||||||
|
term.loadAddon(webLinksAddon);
|
||||||
|
term.loadAddon(searchAddon);
|
||||||
|
term.loadAddon(clipboardAddon);
|
||||||
|
term.loadAddon(unicode11Addon);
|
||||||
|
term.loadAddon(imageAddon);
|
||||||
|
|
||||||
|
term.unicode.activeVersion = "11";
|
||||||
|
|
||||||
|
term.open(terminalRef.current);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const ligaturesAddon = new LigaturesAddon();
|
||||||
|
term.loadAddon(ligaturesAddon);
|
||||||
|
} catch (_e) {}
|
||||||
|
|
||||||
|
fitAddon.fit();
|
||||||
|
|
||||||
|
xtermRef.current = term;
|
||||||
|
fitAddonRef.current = fitAddon;
|
||||||
|
searchAddonRef.current = searchAddon;
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
try {
|
||||||
|
const webglAddon = new WebglAddon();
|
||||||
|
term.loadAddon(webglAddon);
|
||||||
|
} catch (_e) {}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
term.attachCustomKeyEventHandler((event) => {
|
||||||
|
if ((event.ctrlKey || event.metaKey) && event.key === "f") {
|
||||||
|
event.preventDefault();
|
||||||
|
setShowSearch((prev) => !prev);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||||
|
const wsUrl = `${protocol}//${window.location.hostname}:3000/api/terminal/exec?podName=${encodeURIComponent(podName)}&container=${encodeURIComponent(container)}&shell=${encodeURIComponent(shell)}&mode=${mode}`;
|
||||||
|
const ws = new WebSocket(wsUrl);
|
||||||
|
wsRef.current = ws;
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
setConnected(true);
|
||||||
|
term.writeln(
|
||||||
|
`\r\n\x1b[1;32mConnecting to ${mode === "attach" ? "container" : "shell"}...\x1b[0m\r\n`
|
||||||
|
);
|
||||||
|
|
||||||
|
const { cols, rows } = term;
|
||||||
|
ws.send(JSON.stringify({ type: "resize", cols, rows }));
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
try {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
|
||||||
|
if (message.type === "output") {
|
||||||
|
term.write(message.data);
|
||||||
|
} else if (message.type === "ready") {
|
||||||
|
term.writeln(`\x1b[1;32m${message.data}\x1b[0m\r\n`);
|
||||||
|
} else if (message.type === "error") {
|
||||||
|
term.writeln(`\r\n\x1b[1;31mError: ${message.data}\x1b[0m\r\n`);
|
||||||
|
setError(message.data);
|
||||||
|
} else if (message.type === "close") {
|
||||||
|
term.writeln(`\r\n\x1b[1;33m${message.data}\x1b[0m\r\n`);
|
||||||
|
setConnected(false);
|
||||||
|
}
|
||||||
|
} catch (_err) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onerror = (_err) => {
|
||||||
|
term.writeln("\r\n\x1b[1;31mWebSocket error\x1b[0m\r\n");
|
||||||
|
setError("Connection error");
|
||||||
|
setConnected(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
term.writeln("\r\n\x1b[1;33mConnection closed\x1b[0m\r\n");
|
||||||
|
setConnected(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
term.onData((data) => {
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({ type: "input", data }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
term.onResize(({ cols, rows }) => {
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({ type: "resize", cols, rows }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleResize = () => {
|
||||||
|
fitAddon.fit();
|
||||||
|
};
|
||||||
|
window.addEventListener("resize", handleResize);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("resize", handleResize);
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.close();
|
||||||
|
}
|
||||||
|
term.dispose();
|
||||||
|
};
|
||||||
|
}, [podName, container, shell, mode]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative w-full h-full">
|
||||||
|
<div className="absolute top-2 right-2 flex items-center gap-2 z-10">
|
||||||
|
{connected && (
|
||||||
|
<div className="flex items-center gap-2 bg-green-500/20 text-green-500 text-xs px-2 py-1 rounded">
|
||||||
|
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||||
|
Connected
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-500/20 text-red-500 text-xs px-2 py-1 rounded">{error}</div>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowSearch(!showSearch)}
|
||||||
|
className="bg-muted hover:bg-muted/80 text-foreground text-xs px-2 py-1 rounded"
|
||||||
|
title="Search (Ctrl+F)"
|
||||||
|
>
|
||||||
|
🔍 Search
|
||||||
|
</button>
|
||||||
|
{onClose && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="bg-muted hover:bg-muted/80 text-foreground text-xs px-2 py-1 rounded"
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showSearch && (
|
||||||
|
<div className="absolute top-12 right-2 bg-background border border-border rounded-lg p-3 shadow-lg z-20 min-w-[300px]">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
ref={searchInputRef}
|
||||||
|
type="text"
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
searchAddonRef.current?.findNext(searchTerm, {
|
||||||
|
caseSensitive: false,
|
||||||
|
wholeWord: false,
|
||||||
|
regex: false,
|
||||||
|
});
|
||||||
|
} else if (e.key === "Escape") {
|
||||||
|
setShowSearch(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="Search..."
|
||||||
|
className="flex-1 px-2 py-1 text-sm bg-muted border border-border rounded focus:outline-none focus:ring-2 focus:ring-primary"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
searchAddonRef.current?.findNext(searchTerm, {
|
||||||
|
caseSensitive: false,
|
||||||
|
wholeWord: false,
|
||||||
|
regex: false,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
className="px-2 py-1 text-xs bg-primary text-primary-foreground rounded hover:bg-primary/90"
|
||||||
|
title="Find Next"
|
||||||
|
>
|
||||||
|
↓
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
searchAddonRef.current?.findPrevious(searchTerm, {
|
||||||
|
caseSensitive: false,
|
||||||
|
wholeWord: false,
|
||||||
|
regex: false,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
className="px-2 py-1 text-xs bg-primary text-primary-foreground rounded hover:bg-primary/90"
|
||||||
|
title="Find Previous"
|
||||||
|
>
|
||||||
|
↑
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowSearch(false)}
|
||||||
|
className="px-2 py-1 text-xs bg-muted hover:bg-muted/80 rounded"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground mt-2">
|
||||||
|
Press Enter to find next, Esc to close
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div ref={terminalRef} className="w-full h-full" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
341
apps/web/components/topology/controls/node-details-panel.tsx
Normal file
341
apps/web/components/topology/controls/node-details-panel.tsx
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Box } from "lucide-react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import {
|
||||||
|
Sheet,
|
||||||
|
SheetContent,
|
||||||
|
SheetHeader,
|
||||||
|
SheetTitle,
|
||||||
|
} from "@/components/ui/sheet";
|
||||||
|
import type {
|
||||||
|
K8sNodeMetadata,
|
||||||
|
ProxyMetadata,
|
||||||
|
ServerMetadata,
|
||||||
|
TopologyNodeData,
|
||||||
|
} from "@/lib/topology-types";
|
||||||
|
|
||||||
|
interface NodeDetailsPanelProps {
|
||||||
|
node: TopologyNodeData | null;
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function NodeDetailsPanel({
|
||||||
|
node,
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
}: NodeDetailsPanelProps) {
|
||||||
|
if (!node) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet open={open} onOpenChange={onClose}>
|
||||||
|
<SheetContent className="w-full sm:w-[600px] lg:w-[700px] overflow-y-auto p-6">
|
||||||
|
<SheetHeader className="mb-6">
|
||||||
|
<SheetTitle>{node.label}</SheetTitle>
|
||||||
|
</SheetHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4 pr-2">
|
||||||
|
{/* Type and Status */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant="outline">
|
||||||
|
{node.type === "server"
|
||||||
|
? "Minecraft Server"
|
||||||
|
: node.type === "proxy"
|
||||||
|
? "Reverse Proxy"
|
||||||
|
: "Kubernetes Node"}
|
||||||
|
</Badge>
|
||||||
|
<Badge
|
||||||
|
variant={
|
||||||
|
node.status === "healthy"
|
||||||
|
? "default"
|
||||||
|
: node.status === "degraded"
|
||||||
|
? "secondary"
|
||||||
|
: "destructive"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{node.status}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
{node.type === "server" && (
|
||||||
|
<ServerDetails metadata={node.metadata as ServerMetadata} />
|
||||||
|
)}
|
||||||
|
{node.type === "proxy" && (
|
||||||
|
<ProxyDetails metadata={node.metadata as ProxyMetadata} />
|
||||||
|
)}
|
||||||
|
{node.type === "k8s-node" && (
|
||||||
|
<K8sNodeDetails metadata={node.metadata as K8sNodeMetadata} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ServerDetails({ metadata }: { metadata: ServerMetadata }) {
|
||||||
|
const { server, podCount, readyPods, pods, k8sNodes, connectedProxies } =
|
||||||
|
metadata;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<DetailSection title="Server Configuration">
|
||||||
|
<DetailItem label="ID" value={server.id} />
|
||||||
|
{server.description && (
|
||||||
|
<DetailItem label="Description" value={server.description} />
|
||||||
|
)}
|
||||||
|
<DetailItem label="Type" value={server.type} />
|
||||||
|
<DetailItem label="Jar Type" value={server.jar_type} />
|
||||||
|
<DetailItem
|
||||||
|
label="Minecraft Version"
|
||||||
|
value={server.minecraft_version}
|
||||||
|
/>
|
||||||
|
<DetailItem label="Port" value={server.listen_port.toString()} />
|
||||||
|
</DetailSection>
|
||||||
|
|
||||||
|
<DetailSection title="Kubernetes Info">
|
||||||
|
<DetailItem label="Pods" value={`${readyPods}/${podCount} Ready`} />
|
||||||
|
{k8sNodes.length > 0 && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center gap-2 text-sm mb-2">
|
||||||
|
<Box className="h-4 w-4 text-muted-foreground" />
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
Running on {k8sNodes.length} K8s node(s):
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{k8sNodes.map((nodeName) => (
|
||||||
|
<div
|
||||||
|
key={nodeName}
|
||||||
|
className="text-sm p-2 bg-blue-50 border border-blue-200 rounded ml-6"
|
||||||
|
>
|
||||||
|
<span className="font-mono text-xs break-all">{nodeName}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{pods.map((pod) => (
|
||||||
|
<div key={pod.name} className="text-sm mt-2 p-2 bg-muted rounded">
|
||||||
|
<div className="font-medium font-mono text-xs break-all">
|
||||||
|
{pod.name}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground space-y-0.5 mt-1">
|
||||||
|
<div>
|
||||||
|
Status: {pod.status} • {pod.ready}
|
||||||
|
</div>
|
||||||
|
<div>Restarts: {pod.restarts}</div>
|
||||||
|
{pod.nodeName && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Box className="h-3 w-3 shrink-0" />
|
||||||
|
<span className="break-all">Node: {pod.nodeName}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</DetailSection>
|
||||||
|
|
||||||
|
{connectedProxies.length > 0 && (
|
||||||
|
<DetailSection title="Proxy Connections">
|
||||||
|
<DetailItem
|
||||||
|
label="Behind Proxies"
|
||||||
|
value={connectedProxies.length.toString()}
|
||||||
|
/>
|
||||||
|
<div className="mt-2 space-y-1">
|
||||||
|
{connectedProxies.map((proxyId) => (
|
||||||
|
<div
|
||||||
|
key={proxyId}
|
||||||
|
className="text-sm p-2 bg-blue-50 border border-blue-200 rounded font-mono break-all"
|
||||||
|
>
|
||||||
|
{proxyId}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</DetailSection>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DetailSection title="Resources">
|
||||||
|
<DetailItem
|
||||||
|
label="Memory"
|
||||||
|
value={`${server.memory_request}MB / ${server.memory}MB`}
|
||||||
|
/>
|
||||||
|
<DetailItem
|
||||||
|
label="CPU Request"
|
||||||
|
value={server.cpu_request || "Not set"}
|
||||||
|
/>
|
||||||
|
<DetailItem label="CPU Limit" value={server.cpu_limit || "Not set"} />
|
||||||
|
</DetailSection>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProxyDetails({ metadata }: { metadata: ProxyMetadata }) {
|
||||||
|
const { proxy, podCount, readyPods, pods, k8sNodes, connectedServers } =
|
||||||
|
metadata;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<DetailSection title="Proxy Configuration">
|
||||||
|
<DetailItem label="ID" value={proxy.id} />
|
||||||
|
{proxy.description && (
|
||||||
|
<DetailItem label="Description" value={proxy.description} />
|
||||||
|
)}
|
||||||
|
<DetailItem label="Type" value={proxy.type} />
|
||||||
|
<DetailItem
|
||||||
|
label="External Address"
|
||||||
|
value={`${proxy.external_address}:${proxy.external_port}`}
|
||||||
|
/>
|
||||||
|
<DetailItem label="Listen Port" value={proxy.listen_port.toString()} />
|
||||||
|
</DetailSection>
|
||||||
|
|
||||||
|
<DetailSection title="Kubernetes Info">
|
||||||
|
<DetailItem label="Pods" value={`${readyPods}/${podCount} Ready`} />
|
||||||
|
{k8sNodes.length > 0 && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center gap-2 text-sm mb-2">
|
||||||
|
<Box className="h-4 w-4 text-muted-foreground" />
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
Running on {k8sNodes.length} K8s node(s):
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{k8sNodes.map((nodeName) => (
|
||||||
|
<div
|
||||||
|
key={nodeName}
|
||||||
|
className="text-sm p-2 bg-blue-50 border border-blue-200 rounded ml-6"
|
||||||
|
>
|
||||||
|
<span className="font-mono text-xs break-all">{nodeName}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{pods.map((pod) => (
|
||||||
|
<div key={pod.name} className="text-sm mt-2 p-2 bg-muted rounded">
|
||||||
|
<div className="font-medium font-mono text-xs break-all">
|
||||||
|
{pod.name}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground space-y-0.5 mt-1">
|
||||||
|
<div>
|
||||||
|
Status: {pod.status} • {pod.ready}
|
||||||
|
</div>
|
||||||
|
<div>Restarts: {pod.restarts}</div>
|
||||||
|
{pod.nodeName && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Box className="h-3 w-3 shrink-0" />
|
||||||
|
<span className="break-all">Node: {pod.nodeName}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</DetailSection>
|
||||||
|
|
||||||
|
<DetailSection title="Connected Servers">
|
||||||
|
<DetailItem label="Total" value={connectedServers.length.toString()} />
|
||||||
|
{connectedServers.length > 0 && (
|
||||||
|
<div className="mt-2 space-y-1">
|
||||||
|
{connectedServers.map((serverId) => (
|
||||||
|
<div
|
||||||
|
key={serverId}
|
||||||
|
className="text-sm p-2 bg-green-50 border border-green-200 rounded font-mono break-all"
|
||||||
|
>
|
||||||
|
{serverId}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DetailSection>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function K8sNodeDetails({ metadata }: { metadata: K8sNodeMetadata }) {
|
||||||
|
const { node, podCount, serverPods, proxyPods } = metadata;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<DetailSection title="Node Information">
|
||||||
|
<DetailItem label="Name" value={node.name || "Unknown"} />
|
||||||
|
<DetailItem label="Status" value={node.status} />
|
||||||
|
{node.version && <DetailItem label="Version" value={node.version} />}
|
||||||
|
{node.internalIP && (
|
||||||
|
<DetailItem label="Internal IP" value={node.internalIP} />
|
||||||
|
)}
|
||||||
|
{node.externalIP && (
|
||||||
|
<DetailItem label="External IP" value={node.externalIP} />
|
||||||
|
)}
|
||||||
|
</DetailSection>
|
||||||
|
|
||||||
|
<DetailSection title="Node Details">
|
||||||
|
<DetailItem label="Roles" value={node.roles} />
|
||||||
|
<DetailItem label="Age" value={node.age} />
|
||||||
|
{node.hostname && <DetailItem label="Hostname" value={node.hostname} />}
|
||||||
|
</DetailSection>
|
||||||
|
|
||||||
|
<DetailSection title="Running Pods">
|
||||||
|
<DetailItem label="Total Pods" value={podCount.toString()} />
|
||||||
|
<DetailItem label="Server Pods" value={serverPods.length.toString()} />
|
||||||
|
<DetailItem label="Proxy Pods" value={proxyPods.length.toString()} />
|
||||||
|
|
||||||
|
{serverPods.length > 0 && (
|
||||||
|
<div className="mt-3">
|
||||||
|
<p className="text-sm font-medium mb-2">Server Pods:</p>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{serverPods.map((podName) => (
|
||||||
|
<div
|
||||||
|
key={podName}
|
||||||
|
className="text-xs p-2 bg-green-50 border border-green-200 rounded font-mono break-all"
|
||||||
|
>
|
||||||
|
{podName}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{proxyPods.length > 0 && (
|
||||||
|
<div className="mt-3">
|
||||||
|
<p className="text-sm font-medium mb-2">Proxy Pods:</p>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{proxyPods.map((podName) => (
|
||||||
|
<div
|
||||||
|
key={podName}
|
||||||
|
className="text-xs p-2 bg-blue-50 border border-blue-200 rounded font-mono break-all"
|
||||||
|
>
|
||||||
|
{podName}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DetailSection>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DetailSection({
|
||||||
|
title,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="font-semibold text-sm">{title}</h3>
|
||||||
|
<div className="space-y-2">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DetailItem({ label, value }: { label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<div className="flex justify-between items-start text-sm gap-4">
|
||||||
|
<span className="text-muted-foreground shrink-0">{label}:</span>
|
||||||
|
<span className="font-medium text-right break-words">{value}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
159
apps/web/components/topology/controls/topology-toolbar.tsx
Normal file
159
apps/web/components/topology/controls/topology-toolbar.tsx
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Box, Filter, Globe, Search, Server } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import type { TopologyFilters } from "@/lib/topology-types";
|
||||||
|
|
||||||
|
interface TopologyToolbarProps {
|
||||||
|
filters: TopologyFilters;
|
||||||
|
onFiltersChange: (filters: TopologyFilters) => void;
|
||||||
|
metadata: {
|
||||||
|
totalServers: number;
|
||||||
|
totalProxies: number;
|
||||||
|
totalK8sNodes: number;
|
||||||
|
totalConnections: number;
|
||||||
|
healthySystems: number;
|
||||||
|
degradedSystems: number;
|
||||||
|
unhealthySystems: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TopologyToolbar({ filters, onFiltersChange, metadata }: TopologyToolbarProps) {
|
||||||
|
const [searchQuery, setSearchQuery] = useState(filters.searchQuery);
|
||||||
|
|
||||||
|
const handleSearchChange = (value: string) => {
|
||||||
|
setSearchQuery(value);
|
||||||
|
onFiltersChange({ ...filters, searchQuery: value });
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleFilter = (key: keyof TopologyFilters) => {
|
||||||
|
onFiltersChange({ ...filters, [key]: !filters[key] });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-3 p-4 bg-white/90 backdrop-blur-sm rounded-lg border shadow-lg min-w-[350px]">
|
||||||
|
{/* Stats */}
|
||||||
|
<div className="grid grid-cols-3 gap-2">
|
||||||
|
<div className="flex flex-col items-center p-2 bg-muted/50 rounded">
|
||||||
|
<div className="flex items-center gap-1 text-muted-foreground mb-1">
|
||||||
|
<Server className="h-3 w-3" />
|
||||||
|
<span className="text-xs">Servers</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-lg font-bold">{metadata.totalServers}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-center p-2 bg-muted/50 rounded">
|
||||||
|
<div className="flex items-center gap-1 text-muted-foreground mb-1">
|
||||||
|
<Globe className="h-3 w-3" />
|
||||||
|
<span className="text-xs">Proxies</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-lg font-bold">{metadata.totalProxies}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-center p-2 bg-muted/50 rounded">
|
||||||
|
<div className="flex items-center gap-1 text-muted-foreground mb-1">
|
||||||
|
<Box className="h-3 w-3" />
|
||||||
|
<span className="text-xs">Nodes</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-lg font-bold">{metadata.totalK8sNodes}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Health Status */}
|
||||||
|
<div className="flex gap-2 justify-between text-xs">
|
||||||
|
<Badge variant="outline" className="flex items-center gap-1">
|
||||||
|
<div className="w-2 h-2 rounded-full bg-green-500" />
|
||||||
|
{metadata.healthySystems} Healthy
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="outline" className="flex items-center gap-1">
|
||||||
|
<div className="w-2 h-2 rounded-full bg-yellow-500" />
|
||||||
|
{metadata.degradedSystems} Degraded
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="outline" className="flex items-center gap-1">
|
||||||
|
<div className="w-2 h-2 rounded-full bg-red-500" />
|
||||||
|
{metadata.unhealthySystems} Down
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Search */}
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="Search..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => handleSearchChange(e.target.value)}
|
||||||
|
className="pl-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filters */}
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button variant="outline" size="sm" className="w-full">
|
||||||
|
<Filter className="h-4 w-4 mr-2" />
|
||||||
|
Filters
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-80" align="start">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h4 className="font-semibold mb-3">Show/Hide</h4>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label htmlFor="show-servers" className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<Server className="h-4 w-4" />
|
||||||
|
<span>Servers</span>
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id="show-servers"
|
||||||
|
checked={filters.showServers}
|
||||||
|
onCheckedChange={() => toggleFilter("showServers")}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label htmlFor="show-proxies" className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<Globe className="h-4 w-4" />
|
||||||
|
<span>Reverse Proxies</span>
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id="show-proxies"
|
||||||
|
checked={filters.showProxies}
|
||||||
|
onCheckedChange={() => toggleFilter("showProxies")}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label
|
||||||
|
htmlFor="show-k8s-nodes"
|
||||||
|
className="flex items-center gap-2 cursor-pointer"
|
||||||
|
>
|
||||||
|
<Box className="h-4 w-4" />
|
||||||
|
<span>K8s Nodes</span>
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id="show-k8s-nodes"
|
||||||
|
checked={filters.showK8sNodes}
|
||||||
|
onCheckedChange={() => toggleFilter("showK8sNodes")}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label htmlFor="show-connections" className="cursor-pointer">
|
||||||
|
Connection Lines
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id="show-connections"
|
||||||
|
checked={filters.showConnections}
|
||||||
|
onCheckedChange={() => toggleFilter("showConnections")}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
83
apps/web/components/topology/layouts/hierarchical-layout.ts
Normal file
83
apps/web/components/topology/layouts/hierarchical-layout.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import type { TopologyEdge, TopologyNode } from "@/lib/topology-types";
|
||||||
|
|
||||||
|
const LAYOUT_CONFIG = {
|
||||||
|
TIER_SPACING: 300, // Vertical spacing between proxy and server tiers
|
||||||
|
NODE_SPACING: 250, // Horizontal spacing between nodes
|
||||||
|
START_X: 150, // Left padding
|
||||||
|
START_Y: 100, // Top padding
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function applyHierarchicalLayout(
|
||||||
|
nodes: TopologyNode[],
|
||||||
|
edges: TopologyEdge[]
|
||||||
|
): { nodes: TopologyNode[]; edges: TopologyEdge[] } {
|
||||||
|
const proxyNodes = nodes.filter((n) => n.data.type === "proxy");
|
||||||
|
const serverNodes = nodes.filter((n) => n.data.type === "server");
|
||||||
|
|
||||||
|
const layoutedNodes: TopologyNode[] = [];
|
||||||
|
|
||||||
|
const maxNodesInTier = Math.max(proxyNodes.length, serverNodes.length);
|
||||||
|
const tierWidth = maxNodesInTier * LAYOUT_CONFIG.NODE_SPACING;
|
||||||
|
|
||||||
|
const proxyOffsetX = (tierWidth - proxyNodes.length * LAYOUT_CONFIG.NODE_SPACING) / 2;
|
||||||
|
proxyNodes.forEach((node, index) => {
|
||||||
|
const x = LAYOUT_CONFIG.START_X + proxyOffsetX + index * LAYOUT_CONFIG.NODE_SPACING;
|
||||||
|
const y = LAYOUT_CONFIG.START_Y;
|
||||||
|
|
||||||
|
layoutedNodes.push({
|
||||||
|
...node,
|
||||||
|
position: { x, y },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const serverOffsetX = (tierWidth - serverNodes.length * LAYOUT_CONFIG.NODE_SPACING) / 2;
|
||||||
|
serverNodes.forEach((node, index) => {
|
||||||
|
const x = LAYOUT_CONFIG.START_X + serverOffsetX + index * LAYOUT_CONFIG.NODE_SPACING;
|
||||||
|
const y = LAYOUT_CONFIG.START_Y + LAYOUT_CONFIG.TIER_SPACING;
|
||||||
|
|
||||||
|
layoutedNodes.push({
|
||||||
|
...node,
|
||||||
|
position: { x, y },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
nodes: layoutedNodes,
|
||||||
|
edges,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyGridLayout(
|
||||||
|
nodes: TopologyNode[],
|
||||||
|
edges: TopologyEdge[]
|
||||||
|
): { nodes: TopologyNode[]; edges: TopologyEdge[] } {
|
||||||
|
const columns = Math.ceil(Math.sqrt(nodes.length));
|
||||||
|
|
||||||
|
const layoutedNodes = nodes.map((node, index) => ({
|
||||||
|
...node,
|
||||||
|
position: {
|
||||||
|
x: LAYOUT_CONFIG.START_X + (index % columns) * LAYOUT_CONFIG.NODE_SPACING,
|
||||||
|
y: LAYOUT_CONFIG.START_Y + Math.floor(index / columns) * LAYOUT_CONFIG.TIER_SPACING,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
nodes: layoutedNodes,
|
||||||
|
edges,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function layoutTopologyGraph(
|
||||||
|
nodes: TopologyNode[],
|
||||||
|
edges: TopologyEdge[]
|
||||||
|
): { nodes: TopologyNode[]; edges: TopologyEdge[] } {
|
||||||
|
if (nodes.length === 0) {
|
||||||
|
return { nodes: [], edges: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nodes.length < 20) {
|
||||||
|
return applyHierarchicalLayout(nodes, edges);
|
||||||
|
}
|
||||||
|
|
||||||
|
return applyGridLayout(nodes, edges);
|
||||||
|
}
|
||||||
142
apps/web/components/topology/nodes/k8s-node.tsx
Normal file
142
apps/web/components/topology/nodes/k8s-node.tsx
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
import type { NodeProps } from "@xyflow/react";
|
||||||
|
import { Handle, Position } from "@xyflow/react";
|
||||||
|
import { Box, Cpu, HardDrive, Network, Server as ServerIcon } from "lucide-react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
import type { K8sNodeMetadata, TopologyNodeData } from "@/lib/topology-types";
|
||||||
|
|
||||||
|
export function K8sNodeComponent({ data, selected }: NodeProps) {
|
||||||
|
const nodeData = data as TopologyNodeData;
|
||||||
|
const metadata = nodeData.metadata as K8sNodeMetadata;
|
||||||
|
const { node, podCount, serverPods, proxyPods, health, metrics } = metadata;
|
||||||
|
|
||||||
|
const getStatusBadge = () => {
|
||||||
|
switch (health) {
|
||||||
|
case "healthy":
|
||||||
|
return <Badge className="bg-green-500 hover:bg-green-600 text-xs">Healthy</Badge>;
|
||||||
|
case "degraded":
|
||||||
|
return <Badge className="bg-yellow-500 hover:bg-yellow-600 text-xs">Degraded</Badge>;
|
||||||
|
case "unhealthy":
|
||||||
|
return <Badge className="bg-red-500 hover:bg-red-600 text-xs">Unhealthy</Badge>;
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<Badge variant="secondary" className="text-xs">
|
||||||
|
Unknown
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"rounded-lg border bg-card p-3 shadow-md hover:shadow-lg transition-all w-[300px]",
|
||||||
|
selected && "ring-2 ring-primary ring-offset-2 shadow-xl"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Handle type="target" position={Position.Top} className="w-3 h-3 !bg-gray-400" />
|
||||||
|
|
||||||
|
<div className="space-y-2.5">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||||
|
<div className="rounded-md bg-blue-500/10 p-1.5">
|
||||||
|
<Box className="h-4 w-4 text-blue-600" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="font-bold text-sm truncate">{node.name || "Unknown"}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">Kubernetes Node</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{getStatusBadge()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{node.status}
|
||||||
|
</Badge>
|
||||||
|
{node.version && (
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{node.version}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{node.roles}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-xs bg-muted/50 rounded px-2 py-1.5">
|
||||||
|
<span className="text-muted-foreground">Total Pods</span>
|
||||||
|
<span className="font-semibold text-blue-600">{podCount}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1 text-[11px]">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<ServerIcon className="h-3 w-3" /> Server Pods
|
||||||
|
</span>
|
||||||
|
<span className="font-medium">{serverPods.length}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<Network className="h-3 w-3" /> Proxy Pods
|
||||||
|
</span>
|
||||||
|
<span className="font-medium">{proxyPods.length}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{metrics && (metrics.cpuUsage || metrics.memoryUsage) && (
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
{metrics.cpuUsage && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<Cpu className="h-3 w-3" /> CPU
|
||||||
|
</span>
|
||||||
|
<span className="font-semibold text-xs text-blue-600">{metrics.cpuUsage}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{metrics.memoryUsage && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<HardDrive className="h-3 w-3" /> Memory
|
||||||
|
</span>
|
||||||
|
<span className="font-semibold text-xs text-blue-600">{metrics.memoryUsage}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Age</span>
|
||||||
|
<span className="font-medium">{node.age}</span>
|
||||||
|
</div>
|
||||||
|
{node.hostname && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Hostname</span>
|
||||||
|
<span className="font-medium font-mono text-[10px] truncate">{node.hostname}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(node.internalIP || node.externalIP) && (
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
{node.internalIP && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Internal IP</span>
|
||||||
|
<span className="font-mono text-[10px] font-medium">{node.internalIP}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{node.externalIP && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">External IP</span>
|
||||||
|
<span className="font-mono text-[10px] font-medium">{node.externalIP}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Handle type="source" position={Position.Bottom} className="w-3 h-3 !bg-gray-400" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
9
apps/web/components/topology/nodes/node-types.ts
Normal file
9
apps/web/components/topology/nodes/node-types.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { K8sNodeComponent } from "./k8s-node";
|
||||||
|
import { ProxyNode } from "./proxy-node";
|
||||||
|
import { ServerNode } from "./server-node";
|
||||||
|
|
||||||
|
export const nodeTypes = {
|
||||||
|
server: ServerNode,
|
||||||
|
proxy: ProxyNode,
|
||||||
|
"k8s-node": K8sNodeComponent,
|
||||||
|
};
|
||||||
206
apps/web/components/topology/nodes/proxy-node.tsx
Normal file
206
apps/web/components/topology/nodes/proxy-node.tsx
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
import type { NodeProps } from "@xyflow/react";
|
||||||
|
import { Handle, Position } from "@xyflow/react";
|
||||||
|
import { Box, Check, Copy, Cpu, Globe, HardDrive, Network } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
import type { ProxyMetadata, TopologyNodeData } from "@/lib/topology-types";
|
||||||
|
|
||||||
|
export function ProxyNode({ data, selected }: NodeProps) {
|
||||||
|
const nodeData = data as TopologyNodeData | TopologyNodeData;
|
||||||
|
const metadata = nodeData.metadata as ProxyMetadata | ProxyMetadata;
|
||||||
|
const { proxy, readyPods, podCount, health, connectedServers } = metadata;
|
||||||
|
|
||||||
|
const k8sNodes = "k8sNodes" in metadata ? metadata.k8sNodes : [];
|
||||||
|
const connectionInfo = "connectionInfo" in metadata ? metadata.connectionInfo : null;
|
||||||
|
const metrics = "metrics" in metadata ? metadata.metrics : undefined;
|
||||||
|
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
const handleCopy = async (e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (connectionInfo?.connectionString) {
|
||||||
|
await navigator.clipboard.writeText(connectionInfo.connectionString);
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadge = () => {
|
||||||
|
switch (health) {
|
||||||
|
case "healthy":
|
||||||
|
return <Badge className="bg-green-500 hover:bg-green-600 text-xs">Healthy</Badge>;
|
||||||
|
case "degraded":
|
||||||
|
return <Badge className="bg-yellow-500 hover:bg-yellow-600 text-xs">Degraded</Badge>;
|
||||||
|
case "unhealthy":
|
||||||
|
return <Badge className="bg-red-500 hover:bg-red-600 text-xs">Unhealthy</Badge>;
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<Badge variant="secondary" className="text-xs">
|
||||||
|
Unknown
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"rounded-lg border bg-card p-3 shadow-md hover:shadow-lg transition-all w-[300px]",
|
||||||
|
selected && "ring-2 ring-primary ring-offset-2 shadow-xl"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Handle type="target" position={Position.Top} className="w-3 h-3 !bg-gray-400" />
|
||||||
|
|
||||||
|
<div className="space-y-2.5">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||||
|
<div className="rounded-md bg-blue-500/10 p-1.5">
|
||||||
|
<Globe className="h-4 w-4 text-blue-500" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="font-bold text-sm truncate">{proxy.id}</p>
|
||||||
|
{proxy.description && (
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{proxy.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{getStatusBadge()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{proxy.type}
|
||||||
|
</Badge>
|
||||||
|
{connectionInfo && (
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{connectionInfo.type}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-xs bg-muted/50 rounded px-2 py-1.5">
|
||||||
|
<span className="text-muted-foreground">Pods</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"font-semibold",
|
||||||
|
readyPods === podCount ? "text-green-600" : "text-yellow-600"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{readyPods}/{podCount}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{proxy.node_port && (
|
||||||
|
<div className="space-y-1 text-[11px]">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<Network className="h-3 w-3" /> NodePort
|
||||||
|
</span>
|
||||||
|
<span className="font-medium">{proxy.node_port}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{connectionInfo?.connectionString && (
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Address</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<code className="text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono flex-1 truncate">
|
||||||
|
{connectionInfo.connectionString}
|
||||||
|
</code>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-5 w-5 shrink-0"
|
||||||
|
onClick={handleCopy}
|
||||||
|
title={copied ? "Copied!" : "Copy address"}
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<Check className="h-3 w-3 text-green-500" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-3 w-3" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{connectionInfo.note && (
|
||||||
|
<p className="text-[10px] text-muted-foreground italic">{connectionInfo.note}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<HardDrive className="h-3 w-3" /> Memory
|
||||||
|
</span>
|
||||||
|
<span className="font-medium text-xs">
|
||||||
|
{metrics?.memoryUsage && (
|
||||||
|
<span className="text-blue-600">{metrics.memoryUsage} / </span>
|
||||||
|
)}
|
||||||
|
<span className="text-muted-foreground">{proxy.memory}MB</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<Cpu className="h-3 w-3" /> CPU
|
||||||
|
</span>
|
||||||
|
<span className="font-medium text-xs">
|
||||||
|
{metrics?.cpuUsage && <span className="text-blue-600">{metrics.cpuUsage} / </span>}
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{proxy.cpu_request || "N/A"}/{proxy.cpu_limit || "N/A"}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{"pods" in metadata && metadata.pods && metadata.pods.length > 0 && (
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Restarts</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"font-medium",
|
||||||
|
metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0) > 0
|
||||||
|
? "text-yellow-600"
|
||||||
|
: "text-green-600"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{metadata.pods[0]?.age && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Age</span>
|
||||||
|
<span className="font-medium">{metadata.pods[0].age}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{metadata.pods[0]?.ip && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Pod IP</span>
|
||||||
|
<span className="font-medium font-mono text-[10px]">{metadata.pods[0].ip}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Routing To</span>
|
||||||
|
<span className="font-semibold text-blue-600">{connectedServers.length} servers</span>
|
||||||
|
</div>
|
||||||
|
{k8sNodes.length > 0 && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<Box className="h-3 w-3" /> K8s Node
|
||||||
|
</span>
|
||||||
|
<span className="font-medium">{k8sNodes[0]}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Handle type="source" position={Position.Bottom} className="w-3 h-3 !bg-gray-400" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
210
apps/web/components/topology/nodes/server-node.tsx
Normal file
210
apps/web/components/topology/nodes/server-node.tsx
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
import type { NodeProps } from "@xyflow/react";
|
||||||
|
import { Handle, Position } from "@xyflow/react";
|
||||||
|
import { Box, Check, Copy, Cpu, HardDrive, Server } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
import type { ServerMetadata, TopologyNodeData } from "@/lib/topology-types";
|
||||||
|
|
||||||
|
export function ServerNode({ data, selected }: NodeProps) {
|
||||||
|
const nodeData = data as TopologyNodeData | TopologyNodeData;
|
||||||
|
const metadata = nodeData.metadata as ServerMetadata | ServerMetadata;
|
||||||
|
const { server, readyPods, podCount, health } = metadata;
|
||||||
|
|
||||||
|
const k8sNodes = "k8sNodes" in metadata ? metadata.k8sNodes : [];
|
||||||
|
const connectedProxies = "connectedProxies" in metadata ? metadata.connectedProxies : [];
|
||||||
|
const connectionInfo = "connectionInfo" in metadata ? metadata.connectionInfo : null;
|
||||||
|
const metrics = "metrics" in metadata ? metadata.metrics : undefined;
|
||||||
|
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
const handleCopy = async (e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (connectionInfo?.connectionString) {
|
||||||
|
await navigator.clipboard.writeText(connectionInfo.connectionString);
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadge = () => {
|
||||||
|
switch (health) {
|
||||||
|
case "healthy":
|
||||||
|
return <Badge className="bg-green-500 hover:bg-green-600 text-xs">Healthy</Badge>;
|
||||||
|
case "degraded":
|
||||||
|
return <Badge className="bg-yellow-500 hover:bg-yellow-600 text-xs">Degraded</Badge>;
|
||||||
|
case "unhealthy":
|
||||||
|
return <Badge className="bg-red-500 hover:bg-red-600 text-xs">Unhealthy</Badge>;
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<Badge variant="secondary" className="text-xs">
|
||||||
|
Unknown
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"rounded-lg border bg-card p-3 shadow-md hover:shadow-lg transition-all w-[300px]",
|
||||||
|
selected && "ring-2 ring-primary ring-offset-2 shadow-xl"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Handle type="target" position={Position.Top} className="w-3 h-3 !bg-gray-400" />
|
||||||
|
|
||||||
|
<div className="space-y-2.5">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||||
|
<div className="rounded-md bg-primary/10 p-1.5">
|
||||||
|
<Server className="h-4 w-4 text-primary" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="font-bold text-sm truncate">{server.id}</p>
|
||||||
|
{server.description && (
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{server.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{getStatusBadge()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{server.jar_type}
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
MC {server.minecraft_version}
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{server.type}
|
||||||
|
</Badge>
|
||||||
|
{connectionInfo && (
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">
|
||||||
|
{connectionInfo.type}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-xs bg-muted/50 rounded px-2 py-1.5">
|
||||||
|
<span className="text-muted-foreground">Pods</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"font-semibold",
|
||||||
|
readyPods === podCount ? "text-green-600" : "text-yellow-600"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{readyPods}/{podCount}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1 text-[11px]">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<HardDrive className="h-3 w-3" /> Memory
|
||||||
|
</span>
|
||||||
|
<span className="font-medium text-xs">
|
||||||
|
{metrics?.memoryUsage && (
|
||||||
|
<span className="text-blue-600">{metrics.memoryUsage} / </span>
|
||||||
|
)}
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{server.memory_request}/{server.memory}MB
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<Cpu className="h-3 w-3" /> CPU
|
||||||
|
</span>
|
||||||
|
<span className="font-medium text-xs">
|
||||||
|
{metrics?.cpuUsage && <span className="text-blue-600">{metrics.cpuUsage} / </span>}
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{server.cpu_request || "N/A"}/{server.cpu_limit || "N/A"}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{connectionInfo?.connectionString && (
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<code className="text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono flex-1 truncate">
|
||||||
|
{connectionInfo.connectionString}
|
||||||
|
</code>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-5 w-5 shrink-0"
|
||||||
|
onClick={handleCopy}
|
||||||
|
title={copied ? "Copied!" : "Copy address"}
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<Check className="h-3 w-3 text-green-500" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-3 w-3" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{connectionInfo.note && (
|
||||||
|
<p className="text-[10px] text-muted-foreground italic">{connectionInfo.note}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{"pods" in metadata && metadata.pods && metadata.pods.length > 0 && (
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Restarts</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"font-medium",
|
||||||
|
metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0) > 0
|
||||||
|
? "text-yellow-600"
|
||||||
|
: "text-green-600"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{metadata.pods[0]?.age && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Age</span>
|
||||||
|
<span className="font-medium">{metadata.pods[0].age}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{metadata.pods[0]?.ip && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Pod IP</span>
|
||||||
|
<span className="font-medium font-mono text-[10px]">{metadata.pods[0].ip}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{(k8sNodes.length > 0 || connectedProxies.length > 0) && (
|
||||||
|
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||||
|
{connectedProxies.length > 0 && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Exposed By</span>
|
||||||
|
<span className="font-semibold text-blue-600">
|
||||||
|
{connectedProxies.length} proxies
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{k8sNodes.length > 0 && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground flex items-center gap-1">
|
||||||
|
<Box className="h-3 w-3" /> K8s Node
|
||||||
|
</span>
|
||||||
|
<span className="font-medium">{k8sNodes[0]}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Handle type="source" position={Position.Bottom} className="w-3 h-3 !bg-gray-400" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
128
apps/web/components/topology/topology-canvas.tsx
Normal file
128
apps/web/components/topology/topology-canvas.tsx
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Background, BackgroundVariant, Controls, MiniMap, Panel, ReactFlow } from "@xyflow/react";
|
||||||
|
import { useCallback, useMemo, useState } from "react";
|
||||||
|
import "@xyflow/react/dist/style.css";
|
||||||
|
import { useGraphLayout } from "@/hooks/use-graph-layout";
|
||||||
|
import type { TopologyFilters, TopologyGraph, TopologyNodeData } from "@/lib/topology-types";
|
||||||
|
import { filterEdges, filterNodes } from "@/lib/topology-utils";
|
||||||
|
import { NodeDetailsPanel } from "./controls/node-details-panel";
|
||||||
|
import { TopologyToolbar } from "./controls/topology-toolbar";
|
||||||
|
import { nodeTypes } from "./nodes/node-types";
|
||||||
|
|
||||||
|
interface TopologyCanvasProps {
|
||||||
|
graph: TopologyGraph;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TopologyCanvas({ graph }: TopologyCanvasProps) {
|
||||||
|
const [selectedNode, setSelectedNode] = useState<TopologyNodeData | null>(null);
|
||||||
|
const [filters, setFilters] = useState<TopologyFilters>({
|
||||||
|
showServers: true,
|
||||||
|
showProxies: true,
|
||||||
|
showK8sNodes: true,
|
||||||
|
showConnections: true,
|
||||||
|
searchQuery: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const filteredNodes = useMemo(() => {
|
||||||
|
return filterNodes(graph.nodes, filters);
|
||||||
|
}, [graph.nodes, filters]);
|
||||||
|
|
||||||
|
const filteredEdges = useMemo(() => {
|
||||||
|
if (!filters.showConnections) return [];
|
||||||
|
const visibleNodeIds = new Set(filteredNodes.map((node) => node.id));
|
||||||
|
return filterEdges(graph.edges, visibleNodeIds);
|
||||||
|
}, [graph.edges, filteredNodes, filters.showConnections]);
|
||||||
|
|
||||||
|
const { nodes, edges } = useGraphLayout({
|
||||||
|
nodes: filteredNodes,
|
||||||
|
edges: filteredEdges,
|
||||||
|
});
|
||||||
|
|
||||||
|
const onNodeClick = useCallback((_event: React.MouseEvent, node: any) => {
|
||||||
|
setSelectedNode(node.data as TopologyNodeData);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const onPaneClick = useCallback(() => {
|
||||||
|
setSelectedNode(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleCloseDetails = useCallback(() => {
|
||||||
|
setSelectedNode(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-[calc(100vh-250px)] w-full rounded-lg border bg-background shadow-xl">
|
||||||
|
<ReactFlow
|
||||||
|
nodes={nodes}
|
||||||
|
edges={edges}
|
||||||
|
nodeTypes={nodeTypes}
|
||||||
|
onNodeClick={onNodeClick}
|
||||||
|
onPaneClick={onPaneClick}
|
||||||
|
fitView
|
||||||
|
fitViewOptions={{
|
||||||
|
padding: 0.2,
|
||||||
|
includeHiddenNodes: false,
|
||||||
|
minZoom: 0.1,
|
||||||
|
maxZoom: 1.5,
|
||||||
|
}}
|
||||||
|
minZoom={0.1}
|
||||||
|
maxZoom={1.5}
|
||||||
|
defaultEdgeOptions={{
|
||||||
|
animated: false,
|
||||||
|
type: "smoothstep",
|
||||||
|
style: {
|
||||||
|
stroke: "#9ca3af",
|
||||||
|
strokeWidth: 2,
|
||||||
|
strokeDasharray: "5 5",
|
||||||
|
},
|
||||||
|
markerEnd: {
|
||||||
|
type: "arrowclosed",
|
||||||
|
color: "#9ca3af",
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
proOptions={{ hideAttribution: true }}
|
||||||
|
>
|
||||||
|
<Background variant={BackgroundVariant.Dots} color="#cbd5e1" gap={24} size={1} />
|
||||||
|
<Controls
|
||||||
|
showZoom
|
||||||
|
showFitView
|
||||||
|
showInteractive
|
||||||
|
className="bg-white/80 backdrop-blur-sm border shadow-lg"
|
||||||
|
/>
|
||||||
|
<MiniMap
|
||||||
|
nodeColor={(node: any) => {
|
||||||
|
const data = node.data as TopologyNodeData;
|
||||||
|
const colors = {
|
||||||
|
healthy: "#22c55e",
|
||||||
|
degraded: "#eab308",
|
||||||
|
unhealthy: "#ef4444",
|
||||||
|
unknown: "#94a3b8",
|
||||||
|
};
|
||||||
|
return colors[data.status] || "#94a3b8";
|
||||||
|
}}
|
||||||
|
maskColor="rgba(0, 0, 0, 0.05)"
|
||||||
|
className="bg-white/80 backdrop-blur-sm border shadow-lg"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Panel position="top-left">
|
||||||
|
<div className="m-2">
|
||||||
|
<TopologyToolbar
|
||||||
|
filters={filters}
|
||||||
|
onFiltersChange={setFilters}
|
||||||
|
metadata={graph.metadata}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
</ReactFlow>
|
||||||
|
|
||||||
|
<NodeDetailsPanel
|
||||||
|
node={selectedNode}
|
||||||
|
open={selectedNode !== null}
|
||||||
|
onClose={handleCloseDetails}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
54
apps/web/components/ui/accordion.tsx
Normal file
54
apps/web/components/ui/accordion.tsx
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||||
|
import { ChevronDown } from "lucide-react";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
const Accordion = AccordionPrimitive.Root;
|
||||||
|
|
||||||
|
const AccordionItem = React.forwardRef<
|
||||||
|
React.ElementRef<typeof AccordionPrimitive.Item>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<AccordionPrimitive.Item ref={ref} className={cn("border-b", className)} {...props} />
|
||||||
|
));
|
||||||
|
AccordionItem.displayName = "AccordionItem";
|
||||||
|
|
||||||
|
const AccordionTrigger = React.forwardRef<
|
||||||
|
React.ElementRef<typeof AccordionPrimitive.Trigger>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<AccordionPrimitive.Header className="flex">
|
||||||
|
<AccordionPrimitive.Trigger
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
|
||||||
|
</AccordionPrimitive.Trigger>
|
||||||
|
</AccordionPrimitive.Header>
|
||||||
|
));
|
||||||
|
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
|
||||||
|
|
||||||
|
const AccordionContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof AccordionPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<AccordionPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className={cn("pb-4 pt-0", className)}>{children}</div>
|
||||||
|
</AccordionPrimitive.Content>
|
||||||
|
));
|
||||||
|
|
||||||
|
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
|
||||||
|
|
||||||
|
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
|
||||||
41
apps/web/components/ui/avatar.tsx
Normal file
41
apps/web/components/ui/avatar.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Root
|
||||||
|
data-slot="avatar"
|
||||||
|
className={cn("relative flex size-8 shrink-0 overflow-hidden rounded-full", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Image
|
||||||
|
data-slot="avatar-image"
|
||||||
|
className={cn("aspect-square size-full", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarFallback({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Fallback
|
||||||
|
data-slot="avatar-fallback"
|
||||||
|
className={cn("bg-muted flex size-full items-center justify-center rounded-full", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Avatar, AvatarImage, AvatarFallback };
|
||||||
39
apps/web/components/ui/badge.tsx
Normal file
39
apps/web/components/ui/badge.tsx
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
|
secondary:
|
||||||
|
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
|
destructive:
|
||||||
|
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
function Badge({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot : "span";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants };
|
||||||
60
apps/web/components/ui/button.tsx
Normal file
60
apps/web/components/ui/button.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||||
|
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
|
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||||
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
|
icon: "size-9",
|
||||||
|
"icon-sm": "size-8",
|
||||||
|
"icon-lg": "size-10",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
function Button({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"button"> &
|
||||||
|
VariantProps<typeof buttonVariants> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="button"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Button, buttonVariants };
|
||||||
75
apps/web/components/ui/card.tsx
Normal file
75
apps/web/components/ui/card.tsx
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card"
|
||||||
|
className={cn(
|
||||||
|
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-header"
|
||||||
|
className={cn(
|
||||||
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-title"
|
||||||
|
className={cn("leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-action"
|
||||||
|
className={cn("col-start-2 row-span-2 row-start-1 self-start justify-self-end", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return <div data-slot="card-content" className={cn("px-6", className)} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-footer"
|
||||||
|
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
|
||||||
28
apps/web/components/ui/checkbox.tsx
Normal file
28
apps/web/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||||
|
import { Check } from "lucide-react";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
const Checkbox = React.forwardRef<
|
||||||
|
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<CheckboxPrimitive.Root
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
|
||||||
|
<Check className="h-4 w-4" />
|
||||||
|
</CheckboxPrimitive.Indicator>
|
||||||
|
</CheckboxPrimitive.Root>
|
||||||
|
));
|
||||||
|
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
|
||||||
|
|
||||||
|
export { Checkbox };
|
||||||
129
apps/web/components/ui/dialog.tsx
Normal file
129
apps/web/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||||
|
import { XIcon } from "lucide-react";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||||
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||||
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||||
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||||
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Overlay
|
||||||
|
data-slot="dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||||
|
showCloseButton?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DialogPortal data-slot="dialog-portal">
|
||||||
|
<DialogOverlay />
|
||||||
|
<DialogPrimitive.Content
|
||||||
|
data-slot="dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close
|
||||||
|
data-slot="dialog-close"
|
||||||
|
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||||
|
>
|
||||||
|
<XIcon />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</DialogPrimitive.Content>
|
||||||
|
</DialogPortal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-footer"
|
||||||
|
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Title
|
||||||
|
data-slot="dialog-title"
|
||||||
|
className={cn("text-lg leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Description
|
||||||
|
data-slot="dialog-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogOverlay,
|
||||||
|
DialogPortal,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
};
|
||||||
228
apps/web/components/ui/dropdown-menu.tsx
Normal file
228
apps/web/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||||
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||||
|
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||||
|
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuContent({
|
||||||
|
className,
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Portal>
|
||||||
|
<DropdownMenuPrimitive.Content
|
||||||
|
data-slot="dropdown-menu-content"
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</DropdownMenuPrimitive.Portal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||||
|
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean;
|
||||||
|
variant?: "default" | "destructive";
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Item
|
||||||
|
data-slot="dropdown-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.CheckboxItem
|
||||||
|
data-slot="dropdown-menu-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.CheckboxItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||||
|
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.RadioItem
|
||||||
|
data-slot="dropdown-menu-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.RadioItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Label
|
||||||
|
data-slot="dropdown-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Separator
|
||||||
|
data-slot="dropdown-menu-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="dropdown-menu-shortcut"
|
||||||
|
className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||||
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
|
data-slot="dropdown-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto size-4" />
|
||||||
|
</DropdownMenuPrimitive.SubTrigger>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubContent
|
||||||
|
data-slot="dropdown-menu-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuShortcut,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
};
|
||||||
151
apps/web/components/ui/form.tsx
Normal file
151
apps/web/components/ui/form.tsx
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type * as LabelPrimitive from "@radix-ui/react-label";
|
||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import * as React from "react";
|
||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
type ControllerProps,
|
||||||
|
type FieldPath,
|
||||||
|
type FieldValues,
|
||||||
|
FormProvider,
|
||||||
|
useFormContext,
|
||||||
|
useFormState,
|
||||||
|
} from "react-hook-form";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
const Form = FormProvider;
|
||||||
|
|
||||||
|
type FormFieldContextValue<
|
||||||
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||||
|
> = {
|
||||||
|
name: TName;
|
||||||
|
};
|
||||||
|
|
||||||
|
const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue);
|
||||||
|
|
||||||
|
const FormField = <
|
||||||
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||||
|
>({
|
||||||
|
...props
|
||||||
|
}: ControllerProps<TFieldValues, TName>) => {
|
||||||
|
return (
|
||||||
|
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||||
|
<Controller {...props} />
|
||||||
|
</FormFieldContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const useFormField = () => {
|
||||||
|
const fieldContext = React.useContext(FormFieldContext);
|
||||||
|
const itemContext = React.useContext(FormItemContext);
|
||||||
|
const { getFieldState } = useFormContext();
|
||||||
|
const formState = useFormState({ name: fieldContext.name });
|
||||||
|
const fieldState = getFieldState(fieldContext.name, formState);
|
||||||
|
|
||||||
|
if (!fieldContext) {
|
||||||
|
throw new Error("useFormField should be used within <FormField>");
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = itemContext;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: fieldContext.name,
|
||||||
|
formItemId: `${id}-form-item`,
|
||||||
|
formDescriptionId: `${id}-form-item-description`,
|
||||||
|
formMessageId: `${id}-form-item-message`,
|
||||||
|
...fieldState,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
type FormItemContextValue = {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);
|
||||||
|
|
||||||
|
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
const id = React.useId();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormItemContext.Provider value={{ id }}>
|
||||||
|
<div data-slot="form-item" className={cn("grid gap-2", className)} {...props} />
|
||||||
|
</FormItemContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormLabel({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
|
const { error, formItemId } = useFormField();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Label
|
||||||
|
data-slot="form-label"
|
||||||
|
data-error={!!error}
|
||||||
|
className={cn("data-[error=true]:text-destructive", className)}
|
||||||
|
htmlFor={formItemId}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||||
|
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Slot
|
||||||
|
data-slot="form-control"
|
||||||
|
id={formItemId}
|
||||||
|
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
|
||||||
|
aria-invalid={!!error}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
const { formDescriptionId } = useFormField();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="form-description"
|
||||||
|
id={formDescriptionId}
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
const { error, formMessageId } = useFormField();
|
||||||
|
const body = error ? String(error?.message ?? "") : props.children;
|
||||||
|
|
||||||
|
if (!body) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="form-message"
|
||||||
|
id={formMessageId}
|
||||||
|
className={cn("text-destructive text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{body}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
useFormField,
|
||||||
|
Form,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormControl,
|
||||||
|
FormDescription,
|
||||||
|
FormMessage,
|
||||||
|
FormField,
|
||||||
|
};
|
||||||
21
apps/web/components/ui/input.tsx
Normal file
21
apps/web/components/ui/input.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
data-slot="input"
|
||||||
|
className={cn(
|
||||||
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||||
|
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Input };
|
||||||
21
apps/web/components/ui/label.tsx
Normal file
21
apps/web/components/ui/label.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/cn";
|
||||||
|
|
||||||
|
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<LabelPrimitive.Root
|
||||||
|
data-slot="label"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Label };
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user