mirror of
https://github.com/YuzuZensai/Minikura.git
synced 2026-03-30 13:25:40 +00:00
Compare commits
3 Commits
98b685fe1b
...
e8dbefde43
| Author | SHA1 | Date | |
|---|---|---|---|
|
e8dbefde43
|
|||
|
134351b326
|
|||
|
34260259da
|
@@ -70,7 +70,7 @@ RUN userdel -r $(getent passwd ${HOST_UID} | cut -d: -f1) 2>/dev/null || true &&
|
||||
usermod -aG docker dev
|
||||
|
||||
# Setup directories
|
||||
RUN mkdir -p /home/dev/.kube && chown -R dev:dev /home/dev
|
||||
RUN mkdir -p /home/dev/.kube /home/dev/.vscode-server && chown -R dev:dev /home/dev
|
||||
|
||||
WORKDIR /workspace
|
||||
|
||||
|
||||
@@ -20,9 +20,11 @@ services:
|
||||
- "6443:6443" # k3s API
|
||||
- "25565:25565" # minecraft
|
||||
- "25577:25577" # velocity
|
||||
- "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:
|
||||
@@ -53,3 +55,4 @@ services:
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
vscode-server:
|
||||
|
||||
@@ -36,6 +36,9 @@ done
|
||||
# Create namespace
|
||||
kubectl create namespace minikura --dry-run=client -o yaml | kubectl apply -f - 2>/dev/null || true
|
||||
|
||||
# Uncomment the line below if you need service account token in .env
|
||||
# bash /workspace/.devcontainer/setup-k8s-token.sh
|
||||
|
||||
# Install dependencies
|
||||
echo "==> Installing dependencies..."
|
||||
cd /workspace
|
||||
|
||||
103
.devcontainer/setup-k8s-token.sh
Executable file
103
.devcontainer/setup-k8s-token.sh
Executable file
@@ -0,0 +1,103 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
NAMESPACE="minikura"
|
||||
SERVICE_ACCOUNT="minikura-backend"
|
||||
SECRET_NAME="minikura-backend-token"
|
||||
|
||||
echo "==> Setting up Kubernetes service account..."
|
||||
|
||||
# Create service account if it doesn't exist
|
||||
kubectl create serviceaccount $SERVICE_ACCOUNT -n $NAMESPACE --dry-run=client -o yaml | kubectl apply -f - 2>/dev/null || true
|
||||
|
||||
# Create RBAC role
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: minikura-backend-role
|
||||
namespace: $NAMESPACE
|
||||
rules:
|
||||
- apiGroups: [""]
|
||||
resources: ["services", "pods", "pods/log"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["apps"]
|
||||
resources: ["deployments", "statefulsets"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["networking.k8s.io"]
|
||||
resources: ["ingresses"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: [""]
|
||||
resources: ["nodes"]
|
||||
verbs: ["get", "list"]
|
||||
EOF
|
||||
|
||||
# Create role binding
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: minikura-backend-rolebinding
|
||||
namespace: $NAMESPACE
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: $SERVICE_ACCOUNT
|
||||
namespace: $NAMESPACE
|
||||
roleRef:
|
||||
kind: Role
|
||||
name: minikura-backend-role
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
EOF
|
||||
|
||||
# Create secret for service account token
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: $SECRET_NAME
|
||||
namespace: $NAMESPACE
|
||||
annotations:
|
||||
kubernetes.io/service-account.name: $SERVICE_ACCOUNT
|
||||
type: kubernetes.io/service-account-token
|
||||
EOF
|
||||
|
||||
echo "==> Waiting for token to be generated..."
|
||||
sleep 3
|
||||
|
||||
# Get the token
|
||||
TOKEN=$(kubectl get secret $SECRET_NAME -n $NAMESPACE -o jsonpath='{.data.token}' 2>/dev/null | base64 -d)
|
||||
|
||||
if [ -z "$TOKEN" ]; then
|
||||
echo "[ERROR] Failed to retrieve service account token"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=============================================="
|
||||
echo "[OK] Service Account Token Retrieved"
|
||||
echo "=============================================="
|
||||
echo "Service Account: $SERVICE_ACCOUNT"
|
||||
echo "Namespace: $NAMESPACE"
|
||||
echo "Token: ${TOKEN:0:50}...${TOKEN: -20}"
|
||||
echo ""
|
||||
|
||||
# Update .env file with the new token
|
||||
ENV_FILE="/workspace/.env"
|
||||
|
||||
if [ -f "$ENV_FILE" ]; then
|
||||
# Check if token line exists
|
||||
if grep -q "^KUBERNETES_SERVICE_ACCOUNT_TOKEN=" "$ENV_FILE"; then
|
||||
# Update existing token
|
||||
sed -i "s|^KUBERNETES_SERVICE_ACCOUNT_TOKEN=.*|KUBERNETES_SERVICE_ACCOUNT_TOKEN=\"$TOKEN\"|" "$ENV_FILE"
|
||||
echo "[OK] Updated KUBERNETES_SERVICE_ACCOUNT_TOKEN in .env"
|
||||
else
|
||||
# Add token to end of file
|
||||
echo "KUBERNETES_SERVICE_ACCOUNT_TOKEN=\"$TOKEN\"" >> "$ENV_FILE"
|
||||
echo "[OK] Added KUBERNETES_SERVICE_ACCOUNT_TOKEN to .env"
|
||||
fi
|
||||
else
|
||||
echo "[WARNING] .env file not found at $ENV_FILE"
|
||||
fi
|
||||
|
||||
echo "=============================================="
|
||||
echo ""
|
||||
33
.env.example
33
.env.example
@@ -1,5 +1,30 @@
|
||||
DATABASE_URL=postgresql://postgres:password@localhost:5432/database?sslmode=disable
|
||||
ENABLE_CRD_REFLECTION=true
|
||||
# Database Configuration
|
||||
# PostgreSQL connection string for the Minikura database
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/minikura"
|
||||
|
||||
KUBERNETES_NAMESPACE=minikura
|
||||
KUBERNETES_SKIP_TLS_VERIFY=true
|
||||
# Web Application
|
||||
# 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
|
||||
# The Kubernetes namespace where resources will be created
|
||||
KUBERNETES_NAMESPACE="minikura"
|
||||
|
||||
# Skip TLS certificate verification for Kubernetes API
|
||||
KUBERNETES_SKIP_TLS_VERIFY="true"
|
||||
|
||||
# Node.js TLS rejection control (needed when KUBERNETES_SKIP_TLS_VERIFY is true)
|
||||
NODE_TLS_REJECT_UNAUTHORIZED="0"
|
||||
|
||||
# Optional: Service account token for Kubernetes authentication
|
||||
# By default, uses ~/.kube/config (local development or in-cluster config)
|
||||
# Only set this for production deployments outside the cluster
|
||||
# KUBERNETES_SERVICE_ACCOUNT_TOKEN="your-token-here"
|
||||
|
||||
# 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"
|
||||
|
||||
@@ -1,25 +1,39 @@
|
||||
{
|
||||
"name": "@minikura/backend",
|
||||
"module": "src/index.ts",
|
||||
"type": "module",
|
||||
"exports": "./src/index.ts",
|
||||
"scripts": {
|
||||
"dev": "bun --watch src/index.ts",
|
||||
"build": "bun build src/index.ts --target bun --outdir ./dist",
|
||||
"start": "NODE_ENV=production bun dist/index.js",
|
||||
"test": "bun test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.1.9"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@elysiajs/swagger": "^1.1.1",
|
||||
"@minikura/db": "workspace:*",
|
||||
"argon2": "^0.41.1",
|
||||
"dotenv": "^16.4.5",
|
||||
"elysia": "^1.1.13"
|
||||
}
|
||||
"name": "@minikura/backend",
|
||||
"module": "src/index.ts",
|
||||
"type": "module",
|
||||
"exports": "./src/index.ts",
|
||||
"scripts": {
|
||||
"dev": "bun --watch src/index.ts",
|
||||
"build": "bun build src/index.ts --target bun --outdir ./dist",
|
||||
"start": "NODE_ENV=production bun dist/index.js",
|
||||
"test": "bun test",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "biome lint .",
|
||||
"format": "biome format --write ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^3.0.0",
|
||||
"@types/bun": "^1.3.6"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@elysiajs/cors": "1.1.1",
|
||||
"@elysiajs/swagger": "1.1.3",
|
||||
"@kubernetes/client-node": "^1.4.0",
|
||||
"@minikura/db": "workspace:*",
|
||||
"@sinclair/typebox": "^0.34.47",
|
||||
"@types/ws": "^8.18.1",
|
||||
"argon2": "^0.44.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-auth": "^1.4.13",
|
||||
"dotenv": "^17.2.3",
|
||||
"elysia": "^1.4.22",
|
||||
"undici": "^7.18.2",
|
||||
"ws": "^8.19.0",
|
||||
"yaml": "^2.8.2",
|
||||
"zod": "^4.3.5"
|
||||
}
|
||||
}
|
||||
|
||||
20
apps/backend/src/application/di-container.ts
Normal file
20
apps/backend/src/application/di-container.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
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();
|
||||
|
||||
// Application layer
|
||||
export const userService = new UserService(userRepo);
|
||||
export const serverService = new ServerService(serverRepo, K8sService.getInstance());
|
||||
export const reverseProxyService = new ReverseProxyService(reverseProxyRepo);
|
||||
export const wsService = webSocketService;
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { EnvVariable, ReverseProxyWithEnvVars } from "@minikura/db";
|
||||
import { ConflictError, NotFoundError } from "../../domain/errors/base.error";
|
||||
import {
|
||||
ReverseProxyCreatedEvent,
|
||||
ReverseProxyDeletedEvent,
|
||||
ReverseProxyUpdatedEvent,
|
||||
} from "../../domain/events/reverse-proxy-lifecycle.events";
|
||||
import type {
|
||||
ReverseProxyCreateInput,
|
||||
ReverseProxyRepository,
|
||||
ReverseProxyUpdateInput,
|
||||
} from "../../domain/repositories/reverse-proxy.repository";
|
||||
import { eventBus } from "../../infrastructure/event-bus";
|
||||
|
||||
export class ReverseProxyService {
|
||||
constructor(private reverseProxyRepo: ReverseProxyRepository) {}
|
||||
|
||||
async getAllReverseProxies(
|
||||
omitSensitive = false,
|
||||
): Promise<ReverseProxyWithEnvVars[]> {
|
||||
return this.reverseProxyRepo.findAll(omitSensitive);
|
||||
}
|
||||
|
||||
async getReverseProxyById(
|
||||
id: string,
|
||||
omitSensitive = false,
|
||||
): Promise<ReverseProxyWithEnvVars> {
|
||||
const proxy = await this.reverseProxyRepo.findById(id, omitSensitive);
|
||||
if (!proxy) {
|
||||
throw new NotFoundError("ReverseProxyServer", id);
|
||||
}
|
||||
return proxy;
|
||||
}
|
||||
|
||||
async createReverseProxy(
|
||||
input: ReverseProxyCreateInput,
|
||||
): Promise<ReverseProxyWithEnvVars> {
|
||||
const id = typeof input.id === "string" ? input.id : String(input.id);
|
||||
const existing = await this.reverseProxyRepo.exists(id);
|
||||
if (existing) {
|
||||
throw new ConflictError("ReverseProxyServer", id);
|
||||
}
|
||||
|
||||
const proxy = await this.reverseProxyRepo.create(input);
|
||||
await eventBus.publish(
|
||||
new ReverseProxyCreatedEvent(proxy.id, proxy.type, input),
|
||||
);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
async updateReverseProxy(
|
||||
id: string,
|
||||
input: ReverseProxyUpdateInput,
|
||||
): Promise<ReverseProxyWithEnvVars> {
|
||||
const proxy = await this.reverseProxyRepo.update(id, input);
|
||||
await eventBus.publish(new ReverseProxyUpdatedEvent(id, input));
|
||||
return proxy;
|
||||
}
|
||||
|
||||
async deleteReverseProxy(id: string): Promise<void> {
|
||||
await this.reverseProxyRepo.delete(id);
|
||||
await eventBus.publish(new ReverseProxyDeletedEvent(id));
|
||||
}
|
||||
|
||||
async setEnvVariable(
|
||||
proxyId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<void> {
|
||||
await this.reverseProxyRepo.setEnvVariable(proxyId, key, value);
|
||||
}
|
||||
|
||||
async getEnvVariables(proxyId: string): Promise<EnvVariable[]> {
|
||||
return this.reverseProxyRepo.getEnvVariables(proxyId);
|
||||
}
|
||||
|
||||
async deleteEnvVariable(proxyId: string, key: string): Promise<void> {
|
||||
await this.reverseProxyRepo.deleteEnvVariable(proxyId, key);
|
||||
}
|
||||
}
|
||||
85
apps/backend/src/application/services/server.service.ts
Normal file
85
apps/backend/src/application/services/server.service.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import type { EnvVariable, ServerWithEnvVars } from "@minikura/db";
|
||||
import { ConflictError, NotFoundError } from "../../domain/errors/base.error";
|
||||
import {
|
||||
ServerCreatedEvent,
|
||||
ServerDeletedEvent,
|
||||
ServerUpdatedEvent,
|
||||
} from "../../domain/events/server-lifecycle.events";
|
||||
import type {
|
||||
ServerCreateInput,
|
||||
ServerRepository,
|
||||
ServerUpdateInput,
|
||||
} from "../../domain/repositories/server.repository";
|
||||
import { eventBus } from "../../infrastructure/event-bus";
|
||||
import type { K8sService } from "../../services/k8s";
|
||||
|
||||
export class ServerService {
|
||||
constructor(
|
||||
private serverRepo: ServerRepository,
|
||||
private k8sService: K8sService,
|
||||
) {}
|
||||
|
||||
async getAllServers(omitSensitive = false): Promise<ServerWithEnvVars[]> {
|
||||
return this.serverRepo.findAll(omitSensitive);
|
||||
}
|
||||
|
||||
async getServerById(
|
||||
id: string,
|
||||
omitSensitive = false,
|
||||
): Promise<ServerWithEnvVars> {
|
||||
const server = await this.serverRepo.findById(id, omitSensitive);
|
||||
if (!server) {
|
||||
throw new NotFoundError("Server", id);
|
||||
}
|
||||
return server;
|
||||
}
|
||||
|
||||
async createServer(input: ServerCreateInput): Promise<ServerWithEnvVars> {
|
||||
const existing = await this.serverRepo.exists(input.id);
|
||||
if (existing) {
|
||||
throw new ConflictError("Server", input.id);
|
||||
}
|
||||
|
||||
const server = await this.serverRepo.create(input);
|
||||
await eventBus.publish(
|
||||
new ServerCreatedEvent(server.id, server.type, input),
|
||||
);
|
||||
return server;
|
||||
}
|
||||
|
||||
async updateServer(
|
||||
id: string,
|
||||
input: ServerUpdateInput,
|
||||
): Promise<ServerWithEnvVars> {
|
||||
const server = await this.serverRepo.update(id, input);
|
||||
await eventBus.publish(new ServerUpdatedEvent(id, input));
|
||||
return server;
|
||||
}
|
||||
|
||||
async deleteServer(id: string): Promise<void> {
|
||||
await this.serverRepo.delete(id);
|
||||
await eventBus.publish(new ServerDeletedEvent(id));
|
||||
}
|
||||
|
||||
async setEnvVariable(
|
||||
serverId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<void> {
|
||||
await this.serverRepo.setEnvVariable(serverId, key, value);
|
||||
}
|
||||
|
||||
async getEnvVariables(serverId: string): Promise<EnvVariable[]> {
|
||||
return this.serverRepo.getEnvVariables(serverId);
|
||||
}
|
||||
|
||||
async deleteEnvVariable(serverId: string, key: string): Promise<void> {
|
||||
await this.serverRepo.deleteEnvVariable(serverId, key);
|
||||
}
|
||||
|
||||
async getConnectionInfo(serverId: string) {
|
||||
await this.getServerById(serverId);
|
||||
const serviceName = `minecraft-${serverId}`;
|
||||
return this.k8sService.getServerConnectionInfo(serviceName);
|
||||
}
|
||||
}
|
||||
64
apps/backend/src/application/services/user.service.ts
Normal file
64
apps/backend/src/application/services/user.service.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
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";
|
||||
|
||||
export class UserService {
|
||||
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];
|
||||
75
apps/backend/src/domain/errors/base.error.ts
Normal file
75
apps/backend/src/domain/errors/base.error.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
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;
|
||||
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export class BusinessRuleError extends DomainError {
|
||||
readonly code = "BUSINESS_RULE_VIOLATION";
|
||||
readonly statusCode = 422;
|
||||
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
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,28 @@
|
||||
import { DomainEvent } from "./domain-event";
|
||||
import type { ReverseProxyType } from "../entities/enums";
|
||||
import type { ReverseProxyCreateInput, ReverseProxyUpdateInput } from "../repositories/reverse-proxy.repository";
|
||||
|
||||
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, Server, 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,41 @@
|
||||
import { dotenvLoad } from "dotenv-mono";
|
||||
const dotenv = dotenvLoad();
|
||||
|
||||
import { Elysia, error, t } from "elysia";
|
||||
import { swagger } from "@elysiajs/swagger";
|
||||
import { prisma, ServerType } from "@minikura/db";
|
||||
dotenvLoad();
|
||||
|
||||
import { ServerService } from "./services/server";
|
||||
import { UserService } from "./services/user";
|
||||
import argon2 from "argon2";
|
||||
import { SessionService } from "./services/session";
|
||||
import { Elysia } from "elysia";
|
||||
import { auth } from "./lib/auth";
|
||||
import { authPlugin } from "./lib/auth-plugin";
|
||||
import { errorHandler } from "./lib/error-handler";
|
||||
import { bootstrapRoutes } from "./routes/bootstrap";
|
||||
import { k8sRoutes } from "./routes/k8s";
|
||||
import { reverseProxyRoutes } from "./routes/reverse-proxy.routes";
|
||||
import { serverRoutes } from "./routes/servers";
|
||||
import { terminalRoutes } from "./routes/terminal";
|
||||
import { userRoutes } from "./routes/users";
|
||||
|
||||
enum ReturnError {
|
||||
INVALID_USERNAME_OR_PASSWORD = "INVALID_USERNAME_OR_PASSWORD",
|
||||
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 users = await prisma.user.findMany();
|
||||
if (users.length !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
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}`);
|
||||
};
|
||||
// Register event handlers
|
||||
import "./infrastructure/event-handlers";
|
||||
|
||||
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);
|
||||
},
|
||||
.use(errorHandler)
|
||||
.onRequest(({ set }) => {
|
||||
const origin = process.env.WEB_URL || "http://localhost:3001";
|
||||
set.headers["Access-Control-Allow-Origin"] = origin;
|
||||
set.headers["Access-Control-Allow-Credentials"] = "true";
|
||||
set.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS";
|
||||
set.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, Cookie";
|
||||
})
|
||||
.group('/api', app => app
|
||||
.derive(async ({ headers, cookie: { session_token }, path }) => {
|
||||
// Skip token validation for login route
|
||||
if (path === '/api/login') {
|
||||
return {
|
||||
server: null,
|
||||
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 } }) => {
|
||||
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",
|
||||
});
|
||||
}
|
||||
})
|
||||
.options("/*", () => new Response(null, { status: 204 }))
|
||||
.all("/auth/*", ({ request }) => auth.handler(request))
|
||||
.use(bootstrapRoutes)
|
||||
.use(authPlugin)
|
||||
.group("/api", (app) =>
|
||||
app.use(userRoutes).use(serverRoutes).use(reverseProxyRoutes).use(k8sRoutes).use(terminalRoutes)
|
||||
)
|
||||
.listen(3000, async () => {
|
||||
console.log("Server is running on port 3000");
|
||||
bootstrap();
|
||||
});
|
||||
.get("/health", () => ({ status: "ok" }));
|
||||
|
||||
export type App = typeof app;
|
||||
|
||||
app.listen(3000, () => {
|
||||
console.log("Server running on http://localhost:3000");
|
||||
});
|
||||
|
||||
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}`;
|
||||
}
|
||||
}
|
||||
45
apps/backend/src/infrastructure/event-bus.ts
Normal file
45
apps/backend/src/infrastructure/event-bus.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import type { DomainEvent } from "../domain/events/domain-event";
|
||||
|
||||
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) {
|
||||
console.error(`[EventBus] Error in handler for ${eventName}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getHistory(): DomainEvent[] {
|
||||
return [...this.eventHistory];
|
||||
}
|
||||
|
||||
clearHistory(): void {
|
||||
this.eventHistory = [];
|
||||
}
|
||||
}
|
||||
|
||||
export const eventBus = new EventBus();
|
||||
4
apps/backend/src/infrastructure/event-handlers/index.ts
Normal file
4
apps/backend/src/infrastructure/event-handlers/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import "./server-event.handler";
|
||||
import "./user-event.handler";
|
||||
|
||||
console.log("[EventBus] All event handlers registered");
|
||||
@@ -0,0 +1,22 @@
|
||||
import {
|
||||
ServerCreatedEvent,
|
||||
ServerDeletedEvent,
|
||||
ServerUpdatedEvent,
|
||||
} from "../../domain/events/server-lifecycle.events";
|
||||
import { eventBus } from "../event-bus";
|
||||
import { wsService } from "../../application/di-container";
|
||||
|
||||
eventBus.subscribe(ServerCreatedEvent, async (event) => {
|
||||
console.log(`[Event] Server created: ${event.serverId} (${event.serverType})`);
|
||||
wsService.broadcast("create", event.serverType, event.serverId);
|
||||
});
|
||||
|
||||
eventBus.subscribe(ServerUpdatedEvent, async (event) => {
|
||||
console.log(`[Event] Server updated: ${event.serverId}`);
|
||||
wsService.broadcast("update", "server", event.serverId);
|
||||
});
|
||||
|
||||
eventBus.subscribe(ServerDeletedEvent, async (event) => {
|
||||
console.log(`[Event] Server deleted: ${event.serverId}`);
|
||||
wsService.broadcast("delete", "server", event.serverId);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import {
|
||||
UserSuspendedEvent,
|
||||
UserUnsuspendedEvent,
|
||||
} from "../../domain/events/server-lifecycle.events";
|
||||
import { eventBus } from "../event-bus";
|
||||
|
||||
eventBus.subscribe(UserSuspendedEvent, async (event) => {
|
||||
if (event.suspendedUntil) {
|
||||
console.log(
|
||||
`[Event] User suspended: ${event.userId} until ${event.suspendedUntil.toISOString()}`
|
||||
);
|
||||
} else {
|
||||
console.log(`[Event] User suspended: ${event.userId} indefinitely`);
|
||||
}
|
||||
});
|
||||
|
||||
eventBus.subscribe(UserUnsuspendedEvent, async (event) => {
|
||||
console.log(`[Event] User unsuspended: ${event.userId}`);
|
||||
});
|
||||
@@ -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,47 @@
|
||||
import { prisma, type UpdateSuspensionInput, type UpdateUserInput, type User } from "@minikura/db";
|
||||
import { UserRole } from "../../../domain/entities/enums";
|
||||
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();
|
||||
}
|
||||
}
|
||||
44
apps/backend/src/lib/auth-plugin.ts
Normal file
44
apps/backend/src/lib/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/lib/auth.ts
Normal file
20
apps/backend/src/lib/auth.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { betterAuth } from "better-auth";
|
||||
import { prismaAdapter } from "better-auth/adapters/prisma";
|
||||
import { prisma } from "@minikura/db";
|
||||
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;
|
||||
57
apps/backend/src/lib/authorization.ts
Normal file
57
apps/backend/src/lib/authorization.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 };
|
||||
});
|
||||
};
|
||||
33
apps/backend/src/lib/error-handler.ts
Normal file
33
apps/backend/src/lib/error-handler.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { Elysia } from "elysia";
|
||||
import { DomainError } from "../domain/errors/base.error";
|
||||
|
||||
export const errorHandler = (app: Elysia) => {
|
||||
return app.onError(({ error, set }) => {
|
||||
if (error instanceof DomainError) {
|
||||
set.status = error.statusCode;
|
||||
return {
|
||||
success: false,
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof Error && (error.name === "ValidationError" || error.name === "ZodError")) {
|
||||
set.status = 400;
|
||||
return {
|
||||
success: false,
|
||||
code: "VALIDATION_ERROR",
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
|
||||
console.error("Unhandled error:", error);
|
||||
|
||||
set.status = 500;
|
||||
return {
|
||||
success: false,
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "An unexpected error occurred",
|
||||
};
|
||||
});
|
||||
};
|
||||
9
apps/backend/src/lib/errors.ts
Normal file
9
apps/backend/src/lib/errors.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export const getErrorMessage = (error: unknown): string => {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
}
|
||||
return "Unknown error";
|
||||
};
|
||||
52
apps/backend/src/lib/fetch-patch.ts
Normal file
52
apps/backend/src/lib/fetch-patch.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import * as https from "node:https";
|
||||
import * as k8s from "@kubernetes/client-node";
|
||||
import { Agent as UndiciAgent } from "undici";
|
||||
|
||||
let clientCert: string | undefined;
|
||||
let clientKey: string | undefined;
|
||||
let caCert: string | undefined;
|
||||
|
||||
try {
|
||||
const kc = new k8s.KubeConfig();
|
||||
kc.loadFromDefault();
|
||||
const user = kc.getCurrentUser();
|
||||
const cluster = kc.getCurrentCluster();
|
||||
|
||||
if (user?.certData) {
|
||||
clientCert = Buffer.from(user.certData, "base64").toString();
|
||||
}
|
||||
if (user?.keyData) {
|
||||
clientKey = Buffer.from(user.keyData, "base64").toString();
|
||||
}
|
||||
if (cluster?.caData) {
|
||||
caCert = Buffer.from(cluster.caData, "base64").toString();
|
||||
}
|
||||
|
||||
if (clientCert && clientKey) {
|
||||
const OriginalAgent = https.Agent;
|
||||
type UndiciOptions = ConstructorParameters<typeof UndiciAgent>[0];
|
||||
const httpsModule = https as typeof https & { Agent: typeof https.Agent };
|
||||
|
||||
httpsModule.Agent = class PatchedAgent extends OriginalAgent {
|
||||
constructor(options?: https.AgentOptions) {
|
||||
super(options);
|
||||
|
||||
const undiciOptions: UndiciOptions = {
|
||||
connect: {
|
||||
cert: clientCert,
|
||||
key: clientKey,
|
||||
ca: caCert,
|
||||
rejectUnauthorized: process.env.KUBERNETES_SKIP_TLS_VERIFY !== "true",
|
||||
},
|
||||
};
|
||||
|
||||
const patched = this as unknown as { _undiciAgent?: UndiciAgent };
|
||||
patched._undiciAgent = new UndiciAgent(undiciOptions);
|
||||
}
|
||||
};
|
||||
|
||||
console.log("Patched https.Agent to use undici with client certificates");
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to patch https.Agent for Kubernetes:", err);
|
||||
}
|
||||
107
apps/backend/src/lib/kube-auth.ts
Normal file
107
apps/backend/src/lib/kube-auth.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { KubeConfig } from "@kubernetes/client-node";
|
||||
import { spawnSync } from "bun";
|
||||
import YAML from "yaml";
|
||||
|
||||
type KubeConfigDoc = {
|
||||
users?: Array<{ name: string; user: { token?: string } }>;
|
||||
contexts?: Array<{
|
||||
name: string;
|
||||
context: { cluster: string; user: string; namespace?: string };
|
||||
}>;
|
||||
clusters?: Array<{ name: string }>;
|
||||
};
|
||||
|
||||
const SA_NAME = process.env.K8S_SA_NAME || "minikura-backend";
|
||||
const NAMESPACE = process.env.KUBERNETES_NAMESPACE || "minikura";
|
||||
const TOKEN_DURATION_HOURS = Number(process.env.K8S_TOKEN_DURATION_HOURS || 24);
|
||||
const TOKEN_REFRESH_MIN = Number(process.env.K8S_TOKEN_REFRESH_MIN || 60);
|
||||
|
||||
function kubeconfigPath(): string {
|
||||
return process.env.KUBECONFIG || `${process.env.HOME || process.env.USERPROFILE}/.kube/config`;
|
||||
}
|
||||
|
||||
function refreshSaToken(): void {
|
||||
const duration = `${TOKEN_DURATION_HOURS}h`;
|
||||
const args = ["kubectl", "-n", NAMESPACE, "create", "token", SA_NAME, "--duration", duration];
|
||||
|
||||
if (process.env.KUBERNETES_SKIP_TLS_VERIFY === "true") {
|
||||
args.push("--insecure-skip-tls-verify");
|
||||
}
|
||||
|
||||
const proc = spawnSync(args);
|
||||
|
||||
if (proc.exitCode !== 0) {
|
||||
console.error("[kube-auth] kubectl create token failed:", proc.stderr.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
const token = proc.stdout.toString().trim();
|
||||
const kcPath = kubeconfigPath();
|
||||
|
||||
if (!existsSync(kcPath)) {
|
||||
console.error("[kube-auth] kubeconfig not found at:", kcPath);
|
||||
return;
|
||||
}
|
||||
|
||||
const doc = YAML.parse(readFileSync(kcPath, "utf8")) as KubeConfigDoc;
|
||||
|
||||
let user = doc.users?.find((existingUser) => existingUser.name === SA_NAME);
|
||||
if (!user) {
|
||||
user = { name: SA_NAME, user: {} };
|
||||
if (!doc.users) doc.users = [];
|
||||
doc.users.push(user);
|
||||
}
|
||||
user.user = { token };
|
||||
|
||||
let ctx = doc.contexts?.find((context) => context.name === "bun-local");
|
||||
if (!ctx) {
|
||||
const clusterName = doc.clusters?.[0]?.name || "default";
|
||||
ctx = {
|
||||
name: "bun-local",
|
||||
context: {
|
||||
cluster: clusterName,
|
||||
user: SA_NAME,
|
||||
namespace: NAMESPACE,
|
||||
},
|
||||
};
|
||||
if (!doc.contexts) doc.contexts = [];
|
||||
doc.contexts.push(ctx);
|
||||
} else {
|
||||
ctx.context.user = SA_NAME;
|
||||
ctx.context.namespace = NAMESPACE;
|
||||
}
|
||||
|
||||
writeFileSync(kcPath, YAML.stringify(doc));
|
||||
console.log(
|
||||
`[kube-auth] kubeconfig updated with fresh token for ${SA_NAME} (expires in ${duration})`
|
||||
);
|
||||
}
|
||||
|
||||
export function buildKubeConfig(): KubeConfig {
|
||||
const kc = new KubeConfig();
|
||||
|
||||
const isInCluster =
|
||||
process.env.KUBERNETES_SERVICE_HOST &&
|
||||
existsSync("/var/run/secrets/kubernetes.io/serviceaccount/token");
|
||||
|
||||
if (isInCluster) {
|
||||
console.log("[kube-auth] Running in-cluster, loading from service account");
|
||||
kc.loadFromCluster();
|
||||
return kc;
|
||||
}
|
||||
|
||||
console.log("[kube-auth] Running locally, using ServiceAccount token auth");
|
||||
refreshSaToken();
|
||||
|
||||
setInterval(refreshSaToken, TOKEN_REFRESH_MIN * 60_000);
|
||||
|
||||
kc.loadFromDefault();
|
||||
try {
|
||||
kc.setCurrentContext("bun-local");
|
||||
} catch (_error) {
|
||||
console.warn("[kube-auth] Could not set bun-local context, using default");
|
||||
}
|
||||
|
||||
return kc;
|
||||
}
|
||||
29
apps/backend/src/lib/middleware.ts
Normal file
29
apps/backend/src/lib/middleware.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
type AuthContext = {
|
||||
user?: { role?: string | null } | null;
|
||||
set: { status?: number | string; headers?: unknown };
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
type ErrorResponse = { error: string };
|
||||
|
||||
export const requireAuth = <T extends AuthContext, R>(handler: (context: T) => R) => {
|
||||
return (context: T): R | ErrorResponse => {
|
||||
if (!context.user) {
|
||||
context.set.status = 401;
|
||||
return { error: "Unauthorized" };
|
||||
}
|
||||
return handler(context);
|
||||
};
|
||||
};
|
||||
|
||||
export const requireAdmin = <T extends AuthContext, R>(handler: (context: T) => R) => {
|
||||
return (context: T): R | ErrorResponse => {
|
||||
if (!context.user || context.user.role !== "admin") {
|
||||
context.set.status = 403;
|
||||
return { error: "Admin access required" };
|
||||
}
|
||||
return handler(context);
|
||||
};
|
||||
};
|
||||
33
apps/backend/src/lib/service-utils.ts
Normal file
33
apps/backend/src/lib/service-utils.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
export function createSensitiveFieldSelector<T extends Record<string, boolean>>(
|
||||
fields: T
|
||||
): T & { api_key?: false } {
|
||||
return {
|
||||
...fields,
|
||||
api_key: false,
|
||||
} as T & { api_key?: false };
|
||||
}
|
||||
|
||||
export function pickDefined<T extends Record<string, unknown>, K extends keyof T>(
|
||||
source: T,
|
||||
keys: K[]
|
||||
): Partial<Pick<T, K>> {
|
||||
return keys.reduce(
|
||||
(result, key) => {
|
||||
if (source[key] !== undefined) {
|
||||
result[key] = source[key];
|
||||
}
|
||||
return result;
|
||||
},
|
||||
{} as Partial<Pick<T, K>>
|
||||
);
|
||||
}
|
||||
|
||||
export function generateApiKey(prefix: string): string {
|
||||
const crypto = require("node:crypto");
|
||||
let token = crypto.randomBytes(64).toString("hex");
|
||||
token = token
|
||||
.split("")
|
||||
.map((char: string) => (Math.random() > 0.5 ? char.toUpperCase() : char))
|
||||
.join("");
|
||||
return `${prefix}${token}`;
|
||||
}
|
||||
25
apps/backend/src/lib/zod-validator.ts
Normal file
25
apps/backend/src/lib/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);
|
||||
};
|
||||
}
|
||||
51
apps/backend/src/routes/bootstrap.ts
Normal file
51
apps/backend/src/routes/bootstrap.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { prisma } from "@minikura/db";
|
||||
import { Elysia } from "elysia";
|
||||
import { auth } from "../lib/auth";
|
||||
import { getErrorMessage } from "../lib/errors";
|
||||
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) {
|
||||
console.error("No user in response:", result);
|
||||
set.status = 500;
|
||||
return { message: "Failed to create user" };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (err: unknown) {
|
||||
console.error("Bootstrap setup error:", err);
|
||||
set.status = 500;
|
||||
return { message: getErrorMessage(err) };
|
||||
}
|
||||
});
|
||||
135
apps/backend/src/routes/k8s.ts
Normal file
135
apps/backend/src/routes/k8s.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { Elysia } from "elysia";
|
||||
import { authPlugin } from "../lib/auth-plugin";
|
||||
import { requireAuth } from "../lib/middleware";
|
||||
import { K8sService } from "../services/k8s";
|
||||
|
||||
export const k8sRoutes = new Elysia({ prefix: "/k8s" })
|
||||
.use(authPlugin)
|
||||
.get(
|
||||
"/status",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return k8sService.getConnectionInfo();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/pods",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getPods();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/deployments",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getDeployments();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/statefulsets",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getStatefulSets();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/services",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getServices();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/configmaps",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getConfigMaps();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/ingresses",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getIngresses();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/minecraft-servers",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getMinecraftServers();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/reverse-proxy-servers",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getReverseProxyServers();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/pods/:podName",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getPodInfo(params.podName);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/pods/:podName/logs",
|
||||
requireAuth(async ({ params, query, set }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
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",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
const labelSelector = `minikura.kirameki.cafe/server-id=${params.serverId}`;
|
||||
return await k8sService.getPodsByLabel(labelSelector);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/reverse-proxy/:serverId/pods",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
// Reverse proxy servers use either 'velocity-{id}' or 'bungeecord-{id}' pattern
|
||||
// We need to check both patterns or use the proxy-id label
|
||||
const labelSelector = `minikura.kirameki.cafe/proxy-id=${params.serverId}`;
|
||||
return await k8sService.getPodsByLabel(labelSelector);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/services/:serviceName",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getServiceInfo(params.serviceName);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/services/:serviceName/connection-info",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getServerConnectionInfo(params.serviceName);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/nodes",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getNodes();
|
||||
})
|
||||
);
|
||||
51
apps/backend/src/routes/reverse-proxy.routes.ts
Normal file
51
apps/backend/src/routes/reverse-proxy.routes.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Elysia } from "elysia";
|
||||
import { z } from "zod";
|
||||
import { reverseProxyService } from "../application/di-container";
|
||||
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" })
|
||||
.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 };
|
||||
});
|
||||
69
apps/backend/src/routes/servers.ts
Normal file
69
apps/backend/src/routes/servers.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { Elysia } from "elysia";
|
||||
import { z } from "zod";
|
||||
import { serverService, wsService } from "../application/di-container";
|
||||
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() {},
|
||||
})
|
||||
.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 };
|
||||
});
|
||||
351
apps/backend/src/routes/terminal.ts
Normal file
351
apps/backend/src/routes/terminal.ts
Normal file
@@ -0,0 +1,351 @@
|
||||
import * as k8s from "@kubernetes/client-node";
|
||||
import { Elysia } from "elysia";
|
||||
import { getErrorMessage } from "../lib/errors";
|
||||
import { K8sService } from "../services/k8s";
|
||||
|
||||
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";
|
||||
|
||||
console.log(
|
||||
`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 {
|
||||
const k8sService = K8sService.getInstance();
|
||||
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://");
|
||||
|
||||
console.log(`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 () => {
|
||||
console.log(`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) {
|
||||
console.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 {
|
||||
console.log("Unknown data type:", typeof data, "constructor:", data?.constructor?.name);
|
||||
buffer = new Uint8Array(data);
|
||||
}
|
||||
|
||||
processBuffer(buffer);
|
||||
} catch (err) {
|
||||
console.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) {
|
||||
console.error("Kubernetes error channel:", message);
|
||||
ws.send(JSON.stringify({ type: "error", data: message }));
|
||||
}
|
||||
}
|
||||
|
||||
k8sWs.onerror = (error: Event) => {
|
||||
console.error("Kubernetes WebSocket error:", error);
|
||||
const message = getErrorMessage(error);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
data: `Connection error: ${message}`,
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
k8sWs.onclose = (event: CloseEvent) => {
|
||||
console.log(`Kubernetes WebSocket closed: ${event.code} ${event.reason}`);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "close",
|
||||
data: event.reason || "Connection closed",
|
||||
})
|
||||
);
|
||||
ws.close();
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error("Error setting up terminal:", error);
|
||||
if (error instanceof Error) {
|
||||
console.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) {
|
||||
console.error("Kubernetes WebSocket not ready, state:", k8sWs?.readyState);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "input") {
|
||||
console.log("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) {
|
||||
console.error("Error handling terminal message:", error);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
data: `Error: ${getErrorMessage(error)}`,
|
||||
})
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
close: (ws: TerminalWs) => {
|
||||
console.log("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 {
|
||||
console.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 "../lib/authorization";
|
||||
|
||||
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>;
|
||||
143
apps/backend/src/schemas/server.schema.ts
Normal file
143
apps/backend/src/schemas/server.schema.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
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>;
|
||||
235
apps/backend/src/services/__tests__/session.test.ts
Normal file
235
apps/backend/src/services/__tests__/session.test.ts
Normal file
@@ -0,0 +1,235 @@
|
||||
import { describe, it, expect, beforeEach, mock } from "bun:test";
|
||||
import { SessionService } from "../session";
|
||||
|
||||
// Create mock functions
|
||||
const mockSessionFindUnique = mock();
|
||||
const mockServerFindUnique = mock();
|
||||
const mockReverseProxyFindUnique = mock();
|
||||
const mockIsUserSuspended = mock();
|
||||
|
||||
// Mock the prisma client
|
||||
mock.module("@minikura/db", () => ({
|
||||
prisma: {
|
||||
session: {
|
||||
findUnique: mockSessionFindUnique,
|
||||
},
|
||||
server: {
|
||||
findUnique: mockServerFindUnique,
|
||||
},
|
||||
reverseProxyServer: {
|
||||
findUnique: mockReverseProxyFindUnique,
|
||||
},
|
||||
},
|
||||
isUserSuspended: mockIsUserSuspended,
|
||||
}));
|
||||
|
||||
// Import mocked modules
|
||||
await import("@minikura/db");
|
||||
|
||||
describe("SessionService", () => {
|
||||
beforeEach(() => {
|
||||
mockSessionFindUnique.mockClear();
|
||||
mockServerFindUnique.mockClear();
|
||||
mockReverseProxyFindUnique.mockClear();
|
||||
mockIsUserSuspended.mockClear();
|
||||
});
|
||||
|
||||
describe("validate", () => {
|
||||
it("should return INVALID for non-existent session", async () => {
|
||||
mockSessionFindUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await SessionService.validate("invalid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.INVALID);
|
||||
expect(result.session).toBeNull();
|
||||
});
|
||||
|
||||
it("should return EXPIRED for expired session", async () => {
|
||||
const expiredDate = new Date(Date.now() - 1000);
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: expiredDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("expired-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.EXPIRED);
|
||||
});
|
||||
|
||||
it("should return USER_SUSPENDED for suspended user", async () => {
|
||||
const futureDate = new Date(Date.now() + 1000000);
|
||||
mockIsUserSuspended.mockReturnValue(true);
|
||||
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: futureDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: null,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("valid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.USER_SUSPENDED);
|
||||
});
|
||||
|
||||
it("should return VALID for valid session with active user", async () => {
|
||||
const futureDate = new Date(Date.now() + 1000000);
|
||||
mockIsUserSuspended.mockReturnValue(false);
|
||||
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: futureDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("valid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
expect(result.session).toBeDefined();
|
||||
});
|
||||
|
||||
it("should handle temporary suspension correctly", async () => {
|
||||
const futureDate = new Date(Date.now() + 1000000);
|
||||
const pastSuspensionDate = new Date(Date.now() - 1000);
|
||||
|
||||
// User was suspended but suspension has expired
|
||||
mockIsUserSuspended.mockReturnValue(false);
|
||||
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: futureDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: pastSuspensionDate,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("valid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateApiKey", () => {
|
||||
it("should return INVALID for invalid API key format", async () => {
|
||||
const result = await SessionService.validateApiKey("invalid-key");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.INVALID);
|
||||
expect(result.server).toBeNull();
|
||||
});
|
||||
|
||||
it("should return INVALID when reverse proxy server not found", async () => {
|
||||
mockReverseProxyFindUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await SessionService.validateApiKey(
|
||||
"minikura_reverse_proxy_server_api_key_invalid"
|
||||
);
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.INVALID);
|
||||
expect(result.server).toBeNull();
|
||||
});
|
||||
|
||||
it("should return valid reverse proxy server for valid API key", async () => {
|
||||
const mockServer = {
|
||||
id: "server-1",
|
||||
subdomain: "test",
|
||||
api_key: "minikura_reverse_proxy_server_api_key_valid",
|
||||
type: "VELOCITY",
|
||||
description: null,
|
||||
memory: "1G",
|
||||
external_address: "test.example.com",
|
||||
external_port: 25565,
|
||||
listen_port: 25577,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockReverseProxyFindUnique.mockResolvedValue(mockServer);
|
||||
|
||||
const result = await SessionService.validateApiKey(
|
||||
"minikura_reverse_proxy_server_api_key_valid"
|
||||
);
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
expect(result.server?.id).toBe(mockServer.id);
|
||||
});
|
||||
|
||||
it("should return valid server for valid server API key", async () => {
|
||||
const mockServer = {
|
||||
id: "server-1",
|
||||
name: "Test Server",
|
||||
api_key: "minikura_server_api_key_valid",
|
||||
type: "STATEFUL",
|
||||
description: null,
|
||||
memory: "2G",
|
||||
listen_port: 25565,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockServerFindUnique.mockResolvedValue(mockServer);
|
||||
|
||||
const result = await SessionService.validateApiKey("minikura_server_api_key_valid");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
expect(result.server?.id).toBe(mockServer.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
272
apps/backend/src/services/__tests__/user.test.ts
Normal file
272
apps/backend/src/services/__tests__/user.test.ts
Normal file
@@ -0,0 +1,272 @@
|
||||
import { beforeEach, describe, expect, it, mock } from "bun:test";
|
||||
import { UserService } from "../user";
|
||||
|
||||
// Create mock functions
|
||||
const mockFindUnique = mock();
|
||||
const mockFindMany = mock();
|
||||
const mockUpdate = mock();
|
||||
const mockDelete = mock();
|
||||
const mockIsUserSuspended = mock();
|
||||
|
||||
// Mock the prisma client
|
||||
mock.module("@minikura/db", () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
findUnique: mockFindUnique,
|
||||
findMany: mockFindMany,
|
||||
update: mockUpdate,
|
||||
delete: mockDelete,
|
||||
},
|
||||
},
|
||||
isUserSuspended: mockIsUserSuspended,
|
||||
}));
|
||||
|
||||
// Import mocked modules
|
||||
await import("@minikura/db");
|
||||
|
||||
describe("UserService", () => {
|
||||
beforeEach(() => {
|
||||
mockFindUnique.mockClear();
|
||||
mockFindMany.mockClear();
|
||||
mockUpdate.mockClear();
|
||||
mockDelete.mockClear();
|
||||
mockIsUserSuspended.mockClear();
|
||||
});
|
||||
|
||||
describe("getUserByEmail", () => {
|
||||
it("should return user when found", async () => {
|
||||
const mockUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
|
||||
const result = await UserService.getUserByEmail("test@example.com");
|
||||
|
||||
expect(mockFindUnique).toHaveBeenCalledWith({
|
||||
where: { email: "test@example.com" },
|
||||
});
|
||||
expect(result).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it("should return null when user not found", async () => {
|
||||
mockFindUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await UserService.getUserByEmail("notfound@example.com");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUserById", () => {
|
||||
it("should return user when found", async () => {
|
||||
const mockUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
|
||||
const result = await UserService.getUserById("user-1");
|
||||
|
||||
expect(result).toEqual(mockUser);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAllUsersWithSuspension", () => {
|
||||
it("should return all users with suspension info", async () => {
|
||||
const mockUsers = [
|
||||
{
|
||||
id: "user-1",
|
||||
name: "User 1",
|
||||
email: "user1@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: "user-2",
|
||||
name: "User 2",
|
||||
email: "user2@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: true,
|
||||
suspendedUntil: new Date(Date.now() + 86400000),
|
||||
createdAt: new Date(),
|
||||
},
|
||||
];
|
||||
|
||||
mockFindMany.mockResolvedValue(mockUsers);
|
||||
|
||||
const result = await UserService.getAllUsersWithSuspension();
|
||||
|
||||
expect(result).toEqual(mockUsers);
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateUser", () => {
|
||||
it("should update user basic information", async () => {
|
||||
const mockUpdatedUser = {
|
||||
id: "user-1",
|
||||
name: "Updated Name",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "admin",
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockUpdatedUser);
|
||||
|
||||
const result = await UserService.updateUser("user-1", {
|
||||
name: "Updated Name",
|
||||
role: "admin",
|
||||
});
|
||||
|
||||
expect(result).toEqual(mockUpdatedUser);
|
||||
});
|
||||
});
|
||||
|
||||
describe("suspendUser", () => {
|
||||
it("should suspend user indefinitely when no expiration provided", async () => {
|
||||
const mockSuspendedUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockSuspendedUser);
|
||||
|
||||
const result = await UserService.suspendUser("user-1");
|
||||
|
||||
expect(result.isSuspended).toBe(true);
|
||||
expect(result.suspendedUntil).toBeNull();
|
||||
});
|
||||
|
||||
it("should suspend user until specific date", async () => {
|
||||
const suspendUntil = new Date(Date.now() + 86400000); // 1 day from now
|
||||
|
||||
const mockSuspendedUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: suspendUntil,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockSuspendedUser);
|
||||
|
||||
const result = await UserService.suspendUser("user-1", suspendUntil);
|
||||
|
||||
expect(result.isSuspended).toBe(true);
|
||||
expect(result.suspendedUntil).toEqual(suspendUntil);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unsuspendUser", () => {
|
||||
it("should unsuspend a user", async () => {
|
||||
const mockUnsuspendedUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockUnsuspendedUser);
|
||||
|
||||
const result = await UserService.unsuspendUser("user-1");
|
||||
|
||||
expect(result.isSuspended).toBe(false);
|
||||
expect(result.suspendedUntil).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteUser", () => {
|
||||
it("should delete a user", async () => {
|
||||
mockDelete.mockResolvedValue({});
|
||||
|
||||
await UserService.deleteUser("user-1");
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkSuspension", () => {
|
||||
it("should return true when user is suspended", async () => {
|
||||
const mockUser = {
|
||||
isSuspended: true,
|
||||
suspendedUntil: null,
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
mockIsUserSuspended.mockReturnValue(true);
|
||||
|
||||
const result = await UserService.checkSuspension("user-1");
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when user is not suspended", async () => {
|
||||
const mockUser = {
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
mockIsUserSuspended.mockReturnValue(false);
|
||||
|
||||
const result = await UserService.checkSuspension("user-1");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should throw error when user not found", async () => {
|
||||
mockFindUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(UserService.checkSuspension("user-1")).rejects.toThrow("User not found");
|
||||
});
|
||||
});
|
||||
});
|
||||
455
apps/backend/src/services/k8s.ts
Normal file
455
apps/backend/src/services/k8s.ts
Normal file
@@ -0,0 +1,455 @@
|
||||
import * as k8s from "@kubernetes/client-node";
|
||||
import type { CustomResourceSummary } from "@minikura/api";
|
||||
import { K8sResources } from "./k8s/resources";
|
||||
|
||||
const CUSTOM_RESOURCE_GROUP = "minikura.kirameki.cafe";
|
||||
const CUSTOM_RESOURCE_VERSION = "v1alpha1";
|
||||
|
||||
export class K8sService {
|
||||
private static instance: K8sService;
|
||||
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 constructor() {
|
||||
this.kc = new k8s.KubeConfig();
|
||||
this.namespace = process.env.KUBERNETES_NAMESPACE || "minikura";
|
||||
|
||||
try {
|
||||
this.setupConfig();
|
||||
this.initializeClients();
|
||||
this.resources = new K8sResources(
|
||||
this.coreApi,
|
||||
this.appsApi,
|
||||
this.networkingApi,
|
||||
this.namespace,
|
||||
);
|
||||
this.initialized = true;
|
||||
} catch (_error) {
|
||||
this.initialized = false;
|
||||
}
|
||||
}
|
||||
|
||||
private setupConfig(): void {
|
||||
const isBun = typeof Bun !== "undefined";
|
||||
|
||||
if (isBun) {
|
||||
const { buildKubeConfig } = require("../lib/kube-auth");
|
||||
this.kc = buildKubeConfig();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.kc.loadFromDefault();
|
||||
console.log("Loaded Kubernetes config from default location");
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"Failed to load Kubernetes config from default location:",
|
||||
err,
|
||||
);
|
||||
}
|
||||
|
||||
if (!this.kc.getCurrentContext()) {
|
||||
try {
|
||||
this.kc.loadFromCluster();
|
||||
console.log("Loaded Kubernetes config from cluster");
|
||||
} catch (err) {
|
||||
console.warn("Failed to load Kubernetes config from cluster:", err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.kc.getCurrentContext()) {
|
||||
throw new Error(
|
||||
"Failed to setup Kubernetes client - no valid configuration found",
|
||||
);
|
||||
}
|
||||
|
||||
const currentCluster = this.kc.getCurrentCluster();
|
||||
if (currentCluster) {
|
||||
console.log(`Connecting to Kubernetes server: ${currentCluster.server}`);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
static getInstance(): K8sService {
|
||||
if (!K8sService.instance) {
|
||||
K8sService.instance = new K8sService();
|
||||
}
|
||||
return K8sService.instance;
|
||||
}
|
||||
|
||||
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() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listPods();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching pods:", error);
|
||||
throw new Error(`Failed to fetch pods: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getDeployments() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listDeployments();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching deployments:", error);
|
||||
throw new Error(`Failed to fetch deployments: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getStatefulSets() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listStatefulSets();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching statefulsets:", error);
|
||||
throw new Error(
|
||||
`Failed to fetch statefulsets: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getServices() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listServices();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching services:", error);
|
||||
throw new Error(`Failed to fetch services: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getConfigMaps() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listConfigMaps();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching configmaps:", error);
|
||||
throw new Error(`Failed to fetch configmaps: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getIngresses() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listIngresses();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching ingresses:", error);
|
||||
throw new Error(`Failed to fetch ingresses: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getCustomResources(
|
||||
group: string,
|
||||
version: string,
|
||||
plural: string,
|
||||
): Promise<CustomResourceSummary[]> {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
type CustomResourceItem = {
|
||||
metadata?: {
|
||||
name?: string;
|
||||
namespace?: string;
|
||||
creationTimestamp?: string;
|
||||
labels?: Record<string, string>;
|
||||
};
|
||||
spec?: Record<string, unknown>;
|
||||
status?: { phase?: string; [key: string]: unknown };
|
||||
};
|
||||
|
||||
const response = await this.customObjectsApi.listNamespacedCustomObject({
|
||||
group,
|
||||
version,
|
||||
namespace: this.namespace,
|
||||
plural,
|
||||
});
|
||||
const body = response as unknown as {
|
||||
items?: CustomResourceItem[];
|
||||
body?: { items?: CustomResourceItem[] };
|
||||
};
|
||||
const items = body.items ?? body.body?.items ?? [];
|
||||
return items.map((item) => ({
|
||||
name: item.metadata?.name,
|
||||
namespace: item.metadata?.namespace,
|
||||
age: getAge(item.metadata?.creationTimestamp),
|
||||
labels: item.metadata?.labels,
|
||||
spec: item.spec,
|
||||
status: item.status,
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching custom resources ${plural}:`, error);
|
||||
throw new Error(
|
||||
`Failed to fetch custom resources: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getMinecraftServers() {
|
||||
return this.getCustomResources(
|
||||
CUSTOM_RESOURCE_GROUP,
|
||||
CUSTOM_RESOURCE_VERSION,
|
||||
"minecraftservers",
|
||||
);
|
||||
}
|
||||
|
||||
async getReverseProxyServers() {
|
||||
return this.getCustomResources(
|
||||
CUSTOM_RESOURCE_GROUP,
|
||||
CUSTOM_RESOURCE_VERSION,
|
||||
"reverseproxyservers",
|
||||
);
|
||||
}
|
||||
|
||||
async getPodLogs(
|
||||
podName: string,
|
||||
options?: {
|
||||
container?: string;
|
||||
tailLines?: number;
|
||||
timestamps?: boolean;
|
||||
sinceSeconds?: number;
|
||||
},
|
||||
) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.coreApi.readNamespacedPodLog({
|
||||
name: podName,
|
||||
namespace: this.namespace,
|
||||
container: options?.container,
|
||||
tailLines: options?.tailLines,
|
||||
timestamps: options?.timestamps,
|
||||
sinceSeconds: options?.sinceSeconds,
|
||||
});
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching logs for pod ${podName}:`, error);
|
||||
throw new Error(`Failed to fetch pod logs: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getPodsByLabel(labelSelector: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listPodsByLabel(labelSelector);
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching pods by label:", error);
|
||||
throw new Error(
|
||||
`Failed to fetch pods by label: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getPodInfo(podName: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.getPodInfo(podName);
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching pod ${podName}:`, error);
|
||||
throw new Error(`Failed to fetch pod info: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getServiceInfo(serviceName: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.getServiceInfo(serviceName);
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching service ${serviceName}:`, error);
|
||||
throw new Error(
|
||||
`Failed to fetch service info: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getNodes() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listNodes();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching nodes:", error);
|
||||
throw new Error(`Failed to fetch nodes: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getServerConnectionInfo(serviceName: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
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",
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
`Error fetching connection info for service ${serviceName}:`,
|
||||
error,
|
||||
);
|
||||
throw new Error(
|
||||
`Failed to fetch connection info: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
getKubeConfig(): k8s.KubeConfig {
|
||||
return this.kc;
|
||||
}
|
||||
|
||||
getCoreApi(): k8s.CoreV1Api {
|
||||
return this.coreApi;
|
||||
}
|
||||
|
||||
getNamespace(): string {
|
||||
return this.namespace;
|
||||
}
|
||||
}
|
||||
|
||||
function getAge(timestamp: Date | string | undefined): string {
|
||||
if (!timestamp) return "unknown";
|
||||
const now = new Date();
|
||||
const created = new Date(timestamp);
|
||||
const diff = now.getTime() - created.getTime();
|
||||
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) return `${days}d`;
|
||||
if (hours > 0) return `${hours}h`;
|
||||
if (minutes > 0) return `${minutes}m`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
}
|
||||
return "Unknown error";
|
||||
}
|
||||
271
apps/backend/src/services/k8s/resources.ts
Normal file
271
apps/backend/src/services/k8s/resources.ts
Normal file
@@ -0,0 +1,271 @@
|
||||
import type * as k8s from "@kubernetes/client-node";
|
||||
import type {
|
||||
DeploymentInfo,
|
||||
K8sConfigMapSummary,
|
||||
K8sIngressSummary,
|
||||
K8sNodeSummary,
|
||||
K8sServiceInfo,
|
||||
K8sServicePort,
|
||||
K8sServiceSummary,
|
||||
PodDetails,
|
||||
PodInfo,
|
||||
StatefulSetInfo,
|
||||
} from "@minikura/api";
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
function getAge(timestamp: Date | string | undefined): string {
|
||||
if (!timestamp) return "unknown";
|
||||
const now = new Date();
|
||||
const created = new Date(timestamp);
|
||||
const diff = now.getTime() - created.getTime();
|
||||
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) return `${days}d`;
|
||||
if (hours > 0) return `${hours}h`;
|
||||
if (minutes > 0) return `${minutes}m`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
}
|
||||
54
apps/backend/src/services/websocket.ts
Normal file
54
apps/backend/src/services/websocket.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
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);
|
||||
console.log(`[WebSocket] Client connected (total: ${this.clients.size})`);
|
||||
}
|
||||
|
||||
removeClient(client: WebSocketClient): void {
|
||||
this.clients.delete(client);
|
||||
console.log(
|
||||
`[WebSocket] Client disconnected (total: ${this.clients.size})`,
|
||||
);
|
||||
}
|
||||
|
||||
broadcast(action: string, serverType: string, serverId: string): void {
|
||||
const message = JSON.stringify({
|
||||
type: "SERVER_CHANGE",
|
||||
action,
|
||||
serverType,
|
||||
serverId,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
|
||||
let failedClients = 0;
|
||||
this.clients.forEach((client) => {
|
||||
try {
|
||||
client.send(message);
|
||||
} catch {
|
||||
failedClients++;
|
||||
this.clients.delete(client);
|
||||
}
|
||||
});
|
||||
|
||||
if (failedClients > 0) {
|
||||
console.log(`[WebSocket] Removed ${failedClients} failed clients`);
|
||||
}
|
||||
}
|
||||
|
||||
getClientCount(): number {
|
||||
return this.clients.size;
|
||||
}
|
||||
}
|
||||
161
apps/web/app/bootstrap/page.tsx
Normal file
161
apps/web/app/bootstrap/page.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
"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";
|
||||
|
||||
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) {
|
||||
console.error("Failed to check bootstrap status:", 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>
|
||||
);
|
||||
}
|
||||
549
apps/web/app/dashboard/k8s/page.tsx
Normal file
549
apps/web/app/dashboard/k8s/page.tsx
Normal file
@@ -0,0 +1,549 @@
|
||||
"use client";
|
||||
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import type {
|
||||
CustomResourceSummary,
|
||||
DeploymentInfo,
|
||||
K8sConfigMapSummary,
|
||||
K8sServiceSummary,
|
||||
K8sStatus,
|
||||
PodInfo,
|
||||
StatefulSetInfo,
|
||||
} from "@minikura/api";
|
||||
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";
|
||||
|
||||
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);
|
||||
} else if (statusRes.status === "rejected") {
|
||||
console.error("Failed to fetch status:", statusRes.reason);
|
||||
}
|
||||
|
||||
if (podsRes.status === "fulfilled" && podsRes.value.data) {
|
||||
setPods(podsRes.value.data as PodInfo[]);
|
||||
} else if (podsRes.status === "rejected") {
|
||||
console.error("Failed to fetch pods:", podsRes.reason);
|
||||
}
|
||||
|
||||
if (deploymentsRes.status === "fulfilled" && deploymentsRes.value.data) {
|
||||
setDeployments(deploymentsRes.value.data as DeploymentInfo[]);
|
||||
} else if (deploymentsRes.status === "rejected") {
|
||||
console.error("Failed to fetch deployments:", deploymentsRes.reason);
|
||||
}
|
||||
|
||||
if (statefulSetsRes.status === "fulfilled" && statefulSetsRes.value.data) {
|
||||
setStatefulSets(statefulSetsRes.value.data as StatefulSetInfo[]);
|
||||
} else if (statefulSetsRes.status === "rejected") {
|
||||
console.error("Failed to fetch statefulsets:", statefulSetsRes.reason);
|
||||
}
|
||||
|
||||
if (servicesRes.status === "fulfilled" && servicesRes.value.data) {
|
||||
setServices(servicesRes.value.data as K8sServiceSummary[]);
|
||||
} else if (servicesRes.status === "rejected") {
|
||||
console.error("Failed to fetch services:", servicesRes.reason);
|
||||
}
|
||||
|
||||
if (configMapsRes.status === "fulfilled" && configMapsRes.value.data) {
|
||||
setConfigMaps(configMapsRes.value.data as K8sConfigMapSummary[]);
|
||||
} else if (configMapsRes.status === "rejected") {
|
||||
console.error("Failed to fetch configmaps:", configMapsRes.reason);
|
||||
}
|
||||
|
||||
if (minecraftServersRes.status === "fulfilled" && minecraftServersRes.value.data) {
|
||||
setMinecraftServers(minecraftServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (minecraftServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch minecraft servers:", minecraftServersRes.reason);
|
||||
}
|
||||
|
||||
if (reverseProxyServersRes.status === "fulfilled" && reverseProxyServersRes.value.data) {
|
||||
setReverseProxyServers(reverseProxyServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (reverseProxyServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch reverse proxy servers:", reverseProxyServersRes.reason);
|
||||
}
|
||||
} 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");
|
||||
}
|
||||
184
apps/web/app/dashboard/servers/create/page.tsx
Normal file
184
apps/web/app/dashboard/servers/create/page.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
"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";
|
||||
|
||||
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: data.difficulty,
|
||||
game_mode: 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";
|
||||
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) {
|
||||
console.error("Failed to fetch server:", 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 toServerType = (value?: string | null): ServerType => {
|
||||
if (value === "VANILLA" || value === "CUSTOM") {
|
||||
return value;
|
||||
}
|
||||
return "PAPER";
|
||||
};
|
||||
|
||||
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: data.difficulty,
|
||||
game_mode: 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>
|
||||
);
|
||||
}
|
||||
474
apps/web/app/dashboard/servers/page.tsx
Normal file
474
apps/web/app/dashboard/servers/page.tsx
Normal file
@@ -0,0 +1,474 @@
|
||||
"use client";
|
||||
|
||||
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 { 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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import type { ConnectionInfo, NormalServer, PodInfo, ReverseProxyServer } from "@minikura/api";
|
||||
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
// Server status component
|
||||
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) {
|
||||
console.error("Failed to fetch pods:", 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" || pod.ready === "1/1" || 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>
|
||||
);
|
||||
}
|
||||
|
||||
// Connection info component
|
||||
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) {
|
||||
console.error("Failed to fetch connection info:", 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) {
|
||||
console.error("Failed to fetch servers:", 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) {
|
||||
console.error("Failed to delete server:", 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>
|
||||
|
||||
{/* Normal Servers */}
|
||||
<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>
|
||||
|
||||
{/* Reverse Proxy Servers */}
|
||||
<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>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<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>
|
||||
);
|
||||
}
|
||||
348
apps/web/app/dashboard/users/page.tsx
Normal file
348
apps/web/app/dashboard/users/page.tsx
Normal file
@@ -0,0 +1,348 @@
|
||||
"use client";
|
||||
|
||||
import { Ban, CheckCircle, Edit, Trash2 } from "lucide-react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { getUserApi } from "@/lib/api-helpers";
|
||||
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";
|
||||
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) {
|
||||
console.error("Failed to fetch users:", 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) {
|
||||
console.error("Failed to update user:", 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) {
|
||||
console.error("Failed to suspend user:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUnsuspend = async (userId: string) => {
|
||||
try {
|
||||
const { error } = await getUserApi(userId).suspension.patch({
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
});
|
||||
|
||||
if (!error) {
|
||||
await fetchUsers();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to unsuspend user:", 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) {
|
||||
console.error("Failed to delete user:", 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>
|
||||
|
||||
{/* Edit Dialog */}
|
||||
<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>
|
||||
|
||||
{/* Suspend 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>
|
||||
|
||||
{/* Delete 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({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
|
||||
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 (
|
||||
<html lang="en">
|
||||
<body>{children}</body>
|
||||
<body className="antialiased">{children}</body>
|
||||
</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() {
|
||||
const response = await api.index.get();
|
||||
return response;
|
||||
}
|
||||
|
||||
export default async function Page() {
|
||||
const data = await fetchData();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>Hello React</h1>
|
||||
<pre>{JSON.stringify(data, null, 2)}</pre>
|
||||
</div>
|
||||
);
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
|
||||
const api = treaty<App>(apiUrl);
|
||||
|
||||
export default async function HomePage() {
|
||||
const { data } = await api.bootstrap.status.get();
|
||||
|
||||
if (data?.needsSetup) {
|
||||
redirect("/bootstrap");
|
||||
} else {
|
||||
redirect("/login");
|
||||
}
|
||||
}
|
||||
|
||||
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": {}
|
||||
}
|
||||
177
apps/web/components/dashboard-layout.tsx
Normal file
177
apps/web/components/dashboard-layout.tsx
Normal file
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
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" },
|
||||
];
|
||||
|
||||
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
314
apps/web/components/terminal.tsx
Normal file
314
apps/web/components/terminal.tsx
Normal file
@@ -0,0 +1,314 @@
|
||||
"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) {
|
||||
console.warn("Ligatures addon not available:", e);
|
||||
}
|
||||
|
||||
fitAddon.fit();
|
||||
|
||||
xtermRef.current = term;
|
||||
fitAddonRef.current = fitAddon;
|
||||
searchAddonRef.current = searchAddon;
|
||||
|
||||
setTimeout(() => {
|
||||
try {
|
||||
const webglAddon = new WebglAddon();
|
||||
term.loadAddon(webglAddon);
|
||||
console.log("WebGL renderer loaded successfully");
|
||||
} catch (e) {
|
||||
console.warn("WebGL renderer not available, using canvas fallback:", 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 = () => {
|
||||
console.log("WebSocket connected");
|
||||
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) {
|
||||
console.error("Error parsing WebSocket message:", err);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = (err) => {
|
||||
console.error("WebSocket error:", err);
|
||||
term.writeln("\r\n\x1b[1;31mWebSocket error\x1b[0m\r\n");
|
||||
setError("Connection error");
|
||||
setConnected(false);
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
console.log("WebSocket closed");
|
||||
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>
|
||||
);
|
||||
}
|
||||
58
apps/web/components/ui/accordion.tsx
Normal file
58
apps/web/components/ui/accordion.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||
import { ChevronDown } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
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 type * as React from "react";
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
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 type * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
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 type * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
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/utils";
|
||||
|
||||
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 };
|
||||
30
apps/web/components/ui/checkbox.tsx
Normal file
30
apps/web/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { Check } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
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 type * as React from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
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 type * as React from "react";
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
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,
|
||||
};
|
||||
152
apps/web/components/ui/form.tsx
Normal file
152
apps/web/components/ui/form.tsx
Normal file
@@ -0,0 +1,152 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import type * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
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/utils";
|
||||
|
||||
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 type * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
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 };
|
||||
175
apps/web/components/ui/select.tsx
Normal file
175
apps/web/components/ui/select.tsx
Normal file
@@ -0,0 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "item-aligned",
|
||||
align = "center",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 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 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
data-slot="select-item-indicator"
|
||||
className="absolute right-2 flex size-3.5 items-center justify-center"
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
};
|
||||
28
apps/web/components/ui/separator.tsx
Normal file
28
apps/web/components/ui/separator.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator };
|
||||
130
apps/web/components/ui/sheet.tsx
Normal file
130
apps/web/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
|
||||
}
|
||||
|
||||
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
|
||||
}
|
||||
|
||||
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-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 SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left";
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary 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">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
};
|
||||
682
apps/web/components/ui/sidebar.tsx
Normal file
682
apps/web/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,682 @@
|
||||
"use client";
|
||||
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { PanelLeftIcon } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
const SIDEBAR_WIDTH = "16rem";
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem";
|
||||
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed";
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
openMobile: boolean;
|
||||
setOpenMobile: (open: boolean) => void;
|
||||
toggleSidebar: () => void;
|
||||
};
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext);
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.");
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}) {
|
||||
const [openMobile, setOpenMobile] = React.useState(false);
|
||||
|
||||
const [_open, _setOpen] = React.useState(defaultOpen);
|
||||
const open = openProp ?? _open;
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value;
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState);
|
||||
} else {
|
||||
_setOpen(openState);
|
||||
}
|
||||
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
|
||||
},
|
||||
[setOpenProp, open]
|
||||
);
|
||||
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
if (typeof window !== "undefined" && window.innerWidth < 768) {
|
||||
setOpenMobile((open) => !open);
|
||||
} else {
|
||||
setOpen((open) => !open);
|
||||
}
|
||||
}, [setOpen, setOpenMobile]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
toggleSidebar();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [toggleSidebar]);
|
||||
|
||||
const state = open ? "expanded" : "collapsed";
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, openMobile, setOpenMobile, toggleSidebar]
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right";
|
||||
variant?: "sidebar" | "floating" | "inset";
|
||||
collapsible?: "offcanvas" | "icon" | "none";
|
||||
}) {
|
||||
const { state, openMobile, setOpenMobile } = useSidebar();
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="md:hidden">
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
toggleSidebar();
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col min-w-0",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean;
|
||||
isActive?: boolean;
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
const { state } = useSidebar();
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
if (!tooltip) {
|
||||
return button;
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
className="md:hidden"
|
||||
hidden={state !== "collapsed"}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean;
|
||||
showOnHover?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean;
|
||||
}) {
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean;
|
||||
size?: "sm" | "md";
|
||||
isActive?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
};
|
||||
13
apps/web/components/ui/skeleton.tsx
Normal file
13
apps/web/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Skeleton };
|
||||
92
apps/web/components/ui/table.tsx
Normal file
92
apps/web/components/ui/table.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div data-slot="table-container" className="relative w-full overflow-x-auto">
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return <thead data-slot="table-header" className={cn("[&_tr]:border-b", className)} {...props} />;
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn("bg-muted/50 border-t font-medium [&>tr]:last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableCaption({ className, ...props }: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("text-muted-foreground mt-4 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
|
||||
66
apps/web/components/ui/tabs.tsx
Normal file
66
apps/web/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
24
apps/web/components/ui/textarea.tsx
Normal file
24
apps/web/components/ui/textarea.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface TextareaProps
|
||||
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Textarea.displayName = "Textarea";
|
||||
|
||||
export { Textarea };
|
||||
57
apps/web/components/ui/tooltip.tsx
Normal file
57
apps/web/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||
112
apps/web/hooks/use-k8s-resources.ts
Normal file
112
apps/web/hooks/use-k8s-resources.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import type {
|
||||
CustomResourceSummary,
|
||||
DeploymentInfo,
|
||||
K8sConfigMapSummary,
|
||||
K8sServiceSummary,
|
||||
K8sStatus,
|
||||
StatefulSetInfo,
|
||||
} from "@minikura/api";
|
||||
import { LABEL_PREFIX } from "@minikura/api";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export function useK8sResources() {
|
||||
const [statefulSets, setStatefulSets] = useState<StatefulSetInfo[]>([]);
|
||||
const [deployments, setDeployments] = useState<DeploymentInfo[]>([]);
|
||||
const [services, setServices] = useState<K8sServiceSummary[]>([]);
|
||||
const [configMaps, setConfigMaps] = useState<K8sConfigMapSummary[]>([]);
|
||||
const [minecraftServers, setMinecraftServers] = useState<CustomResourceSummary[]>([]);
|
||||
const [reverseProxyServers, setReverseProxyServers] = useState<CustomResourceSummary[]>([]);
|
||||
const [status, setStatus] = useState<K8sStatus>({ initialized: false });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
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 (statefulSetsRes.status === "fulfilled" && statefulSetsRes.value.data) {
|
||||
setStatefulSets(statefulSetsRes.value.data as StatefulSetInfo[]);
|
||||
} else if (statefulSetsRes.status === "rejected") {
|
||||
console.error("Failed to fetch statefulsets:", statefulSetsRes.reason);
|
||||
}
|
||||
|
||||
if (deploymentsRes.status === "fulfilled" && deploymentsRes.value.data) {
|
||||
setDeployments(deploymentsRes.value.data as DeploymentInfo[]);
|
||||
} else if (deploymentsRes.status === "rejected") {
|
||||
console.error("Failed to fetch deployments:", deploymentsRes.reason);
|
||||
}
|
||||
|
||||
if (servicesRes.status === "fulfilled" && servicesRes.value.data) {
|
||||
setServices(servicesRes.value.data as K8sServiceSummary[]);
|
||||
} else if (servicesRes.status === "rejected") {
|
||||
console.error("Failed to fetch services:", servicesRes.reason);
|
||||
}
|
||||
|
||||
if (configMapsRes.status === "fulfilled" && configMapsRes.value.data) {
|
||||
setConfigMaps(configMapsRes.value.data as K8sConfigMapSummary[]);
|
||||
} else if (configMapsRes.status === "rejected") {
|
||||
console.error("Failed to fetch configmaps:", configMapsRes.reason);
|
||||
}
|
||||
|
||||
if (minecraftServersRes.status === "fulfilled" && minecraftServersRes.value.data) {
|
||||
setMinecraftServers(minecraftServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (minecraftServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch minecraft servers:", minecraftServersRes.reason);
|
||||
}
|
||||
|
||||
if (reverseProxyServersRes.status === "fulfilled" && reverseProxyServersRes.value.data) {
|
||||
setReverseProxyServers(reverseProxyServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (reverseProxyServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch reverse proxy servers:", reverseProxyServersRes.reason);
|
||||
}
|
||||
} 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);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
statefulSets,
|
||||
deployments,
|
||||
services,
|
||||
configMaps,
|
||||
minecraftServers,
|
||||
reverseProxyServers,
|
||||
status,
|
||||
loading,
|
||||
error,
|
||||
refresh: fetchData,
|
||||
labelPrefix: LABEL_PREFIX,
|
||||
};
|
||||
}
|
||||
61
apps/web/hooks/use-server-list.ts
Normal file
61
apps/web/hooks/use-server-list.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import type { NormalServer, ReverseProxyServer } from "@minikura/api";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export function useServerList() {
|
||||
const [normalServers, setNormalServers] = useState<NormalServer[]>([]);
|
||||
const [reverseProxies, setReverseProxies] = useState<ReverseProxyServer[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchServers = useCallback(async () => {
|
||||
try {
|
||||
const [normalRes, proxyRes] = await Promise.all([
|
||||
api.api.servers.get(),
|
||||
getReverseProxyApi().get(),
|
||||
]);
|
||||
|
||||
if (normalRes.data) {
|
||||
setNormalServers(normalRes.data as unknown as NormalServer[]);
|
||||
}
|
||||
if (proxyRes.data) {
|
||||
setReverseProxies(proxyRes.data as unknown as ReverseProxyServer[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch servers:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const deleteServer = useCallback(
|
||||
async (id: string, type: "normal" | "proxy") => {
|
||||
try {
|
||||
if (type === "normal") {
|
||||
await api.api.servers({ id }).delete();
|
||||
} else {
|
||||
await getReverseProxyApi()({ id }).delete();
|
||||
}
|
||||
await fetchServers();
|
||||
} catch (error) {
|
||||
console.error("Failed to delete server:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
[fetchServers]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchServers();
|
||||
}, [fetchServers]);
|
||||
|
||||
return {
|
||||
normalServers,
|
||||
reverseProxies,
|
||||
loading,
|
||||
refresh: fetchServers,
|
||||
deleteServer,
|
||||
};
|
||||
}
|
||||
95
apps/web/hooks/use-server-logs.ts
Normal file
95
apps/web/hooks/use-server-logs.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import type {
|
||||
ConnectionInfo,
|
||||
DeploymentInfo,
|
||||
PodInfo,
|
||||
StatefulSetInfo,
|
||||
} from "@minikura/api";
|
||||
import { labelKeys } from "@minikura/api";
|
||||
import { useCallback, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export function useServerLogs(serverId: string) {
|
||||
const [pods, setPods] = useState<PodInfo[]>([]);
|
||||
const [statefulSetInfo, setStatefulSetInfo] = useState<StatefulSetInfo | null>(null);
|
||||
const [deploymentInfo, setDeploymentInfo] = useState<DeploymentInfo | null>(null);
|
||||
const [connectionInfo, setConnectionInfo] = useState<ConnectionInfo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchPods = useCallback(async () => {
|
||||
try {
|
||||
const response = await api.api.k8s.pods.get();
|
||||
if (response.data) {
|
||||
setPods(response.data as PodInfo[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch pods:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchStatefulSetInfo = useCallback(async () => {
|
||||
try {
|
||||
const response = await api.api.k8s.statefulsets.get();
|
||||
if (response.data) {
|
||||
const statefulSets = response.data as StatefulSetInfo[];
|
||||
const serverStatefulSet = statefulSets.find(
|
||||
(s) => s.labels?.[labelKeys.serverId] === serverId
|
||||
);
|
||||
if (serverStatefulSet) {
|
||||
setStatefulSetInfo(serverStatefulSet);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch StatefulSet info:", error);
|
||||
}
|
||||
}, [serverId]);
|
||||
|
||||
const fetchDeploymentInfo = useCallback(async () => {
|
||||
try {
|
||||
const response = await api.api.k8s.deployments.get();
|
||||
if (response.data) {
|
||||
const deployments = response.data as DeploymentInfo[];
|
||||
const serverDeployment = deployments.find(
|
||||
(d) => d.labels?.[labelKeys.serverId] === serverId
|
||||
);
|
||||
if (serverDeployment) {
|
||||
setDeploymentInfo(serverDeployment);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch Deployment info:", error);
|
||||
}
|
||||
}, [serverId]);
|
||||
|
||||
const fetchConnectionInfo = useCallback(async () => {
|
||||
try {
|
||||
const response = await api.api.servers({ id: serverId })["connection-info"].get();
|
||||
if (response.data) {
|
||||
setConnectionInfo(response.data as ConnectionInfo);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch connection info:", error);
|
||||
}
|
||||
}, [serverId]);
|
||||
|
||||
const refreshAll = useCallback(async () => {
|
||||
await Promise.all([
|
||||
fetchPods(),
|
||||
fetchStatefulSetInfo(),
|
||||
fetchDeploymentInfo(),
|
||||
fetchConnectionInfo(),
|
||||
]);
|
||||
}, [fetchPods, fetchStatefulSetInfo, fetchDeploymentInfo, fetchConnectionInfo]);
|
||||
|
||||
return {
|
||||
pods,
|
||||
statefulSetInfo,
|
||||
deploymentInfo,
|
||||
connectionInfo,
|
||||
loading,
|
||||
refresh: refreshAll,
|
||||
};
|
||||
}
|
||||
24
apps/web/lib/api-helpers.ts
Normal file
24
apps/web/lib/api-helpers.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
type ReverseProxyApi = {
|
||||
get: () => Promise<{ data?: unknown }>;
|
||||
(params: { id: string }): {
|
||||
delete: () => Promise<{ data?: unknown; error?: unknown }>;
|
||||
"connection-info": { get: () => Promise<{ data?: unknown }> };
|
||||
};
|
||||
};
|
||||
|
||||
type UserSuspensionApi = {
|
||||
suspension: {
|
||||
patch: (body: { isSuspended: boolean; suspendedUntil: string | null }) => Promise<{ error?: unknown }>;
|
||||
};
|
||||
};
|
||||
|
||||
export const getReverseProxyApi = (): ReverseProxyApi => {
|
||||
const apiRoot = api.api as unknown as { "reverse-proxy": ReverseProxyApi };
|
||||
return apiRoot["reverse-proxy"];
|
||||
};
|
||||
|
||||
export const getUserApi = (id: string): UserSuspensionApi => {
|
||||
return api.api.users({ id }) as unknown as UserSuspensionApi;
|
||||
};
|
||||
12
apps/web/lib/api.ts
Normal file
12
apps/web/lib/api.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { treaty } from "@elysiajs/eden";
|
||||
import type { App } from "@minikura/backend";
|
||||
|
||||
const baseUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
|
||||
|
||||
export const api = treaty<App>(baseUrl, {
|
||||
fetch: {
|
||||
credentials: "include",
|
||||
},
|
||||
});
|
||||
|
||||
export type Api = typeof api;
|
||||
10
apps/web/lib/auth-client.ts
Normal file
10
apps/web/lib/auth-client.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { createAuthClient } from "better-auth/react";
|
||||
import { adminClient } from "better-auth/client/plugins";
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000",
|
||||
basePath: "/auth",
|
||||
plugins: [adminClient()],
|
||||
});
|
||||
|
||||
export const { useSession, signIn, signOut, signUp } = authClient;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user