mirror of
https://github.com/YuzuZensai/Minikura.git
synced 2026-03-30 18:27:35 +00:00
✨ feat: initial prototype
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user