Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 124e4f8921 | |||
| 5709d8bc10 | |||
| 0941a9ba46 | |||
| 218452706c | |||
| d0c20581b6 | |||
| 8eb7c90958 |
@@ -36,3 +36,4 @@ build/
|
||||
|
||||
# Claude
|
||||
.claude/
|
||||
plans.md
|
||||
@@ -4,7 +4,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"dev": "dotenv -e ../../.env -- tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"lint": "eslint src/"
|
||||
@@ -18,11 +18,14 @@
|
||||
"@source/database": "workspace:*",
|
||||
"@source/shared": "workspace:*",
|
||||
"argon2": "^0.41.0",
|
||||
"drizzle-orm": "^0.38.0",
|
||||
"fastify": "^5.2.0",
|
||||
"fastify-plugin": "^5.0.0",
|
||||
"pino-pretty": "^13.0.0",
|
||||
"socket.io": "^4.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"dotenv-cli": "^8.0.0",
|
||||
"tsx": "^4.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
+55
-3
@@ -1,26 +1,78 @@
|
||||
import Fastify from 'fastify';
|
||||
import cors from '@fastify/cors';
|
||||
import cookie from '@fastify/cookie';
|
||||
import dbPlugin from './plugins/db.js';
|
||||
import authPlugin from './plugins/auth.js';
|
||||
import authRoutes from './routes/auth/index.js';
|
||||
import organizationRoutes from './routes/organizations/index.js';
|
||||
import nodeRoutes from './routes/nodes/index.js';
|
||||
import serverRoutes from './routes/servers/index.js';
|
||||
import adminRoutes from './routes/admin/index.js';
|
||||
import { AppError } from './lib/errors.js';
|
||||
|
||||
const app = Fastify({
|
||||
logger: {
|
||||
transport: {
|
||||
target: 'pino-pretty',
|
||||
},
|
||||
transport:
|
||||
process.env.NODE_ENV !== 'production'
|
||||
? { target: 'pino-pretty' }
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
// Plugins
|
||||
await app.register(cors, {
|
||||
origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
await app.register(cookie);
|
||||
await app.register(dbPlugin);
|
||||
await app.register(authPlugin);
|
||||
|
||||
// Error handler
|
||||
app.setErrorHandler((error: Error & { validation?: unknown; statusCode?: number; code?: string }, _request, reply) => {
|
||||
if (error instanceof AppError) {
|
||||
return reply.code(error.statusCode).send({
|
||||
error: error.name,
|
||||
message: error.message,
|
||||
code: error.code,
|
||||
});
|
||||
}
|
||||
|
||||
// Fastify validation errors
|
||||
if (error.validation) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation Error',
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
app.log.error(error);
|
||||
return reply.code(500).send({
|
||||
error: 'Internal Server Error',
|
||||
message: 'An unexpected error occurred',
|
||||
});
|
||||
});
|
||||
|
||||
// Routes
|
||||
app.get('/api/health', async () => {
|
||||
return { status: 'ok', timestamp: new Date().toISOString() };
|
||||
});
|
||||
|
||||
await app.register(authRoutes, { prefix: '/api/auth' });
|
||||
await app.register(organizationRoutes, { prefix: '/api/organizations' });
|
||||
await app.register(adminRoutes, { prefix: '/api/admin' });
|
||||
|
||||
// Nested org routes: nodes and servers are scoped to an org
|
||||
await app.register(
|
||||
async (orgScope) => {
|
||||
await orgScope.register(nodeRoutes, { prefix: '/nodes' });
|
||||
await orgScope.register(serverRoutes, { prefix: '/servers' });
|
||||
},
|
||||
{ prefix: '/api/organizations/:orgId' },
|
||||
);
|
||||
|
||||
// Start
|
||||
const PORT = Number(process.env.PORT) || 3000;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { auditLogs } from '@source/database';
|
||||
import type { Database } from '@source/database';
|
||||
|
||||
export async function createAuditLog(
|
||||
db: Database,
|
||||
request: FastifyRequest,
|
||||
data: {
|
||||
organizationId: string;
|
||||
action: string;
|
||||
serverId?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
},
|
||||
) {
|
||||
await db.insert(auditLogs).values({
|
||||
organizationId: data.organizationId,
|
||||
userId: request.user.sub,
|
||||
serverId: data.serverId,
|
||||
action: data.action,
|
||||
metadata: data.metadata ?? {},
|
||||
ipAddress: request.ip,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import type { ConfigParser, ConfigEntry } from '@source/shared';
|
||||
|
||||
/**
|
||||
* Parse a config file content into key-value entries based on the parser type.
|
||||
*/
|
||||
export function parseConfig(content: string, parser: ConfigParser): ConfigEntry[] {
|
||||
switch (parser) {
|
||||
case 'properties':
|
||||
return parseProperties(content);
|
||||
case 'json':
|
||||
return parseJson(content);
|
||||
case 'yaml':
|
||||
return parseYaml(content);
|
||||
case 'keyvalue':
|
||||
return parseKeyValue(content);
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize key-value entries back into a config file content.
|
||||
*/
|
||||
export function serializeConfig(
|
||||
entries: ConfigEntry[],
|
||||
parser: ConfigParser,
|
||||
originalContent?: string,
|
||||
): string {
|
||||
switch (parser) {
|
||||
case 'properties':
|
||||
return serializeProperties(entries, originalContent);
|
||||
case 'json':
|
||||
return serializeJson(entries);
|
||||
case 'yaml':
|
||||
return serializeYaml(entries, originalContent);
|
||||
case 'keyvalue':
|
||||
return serializeKeyValue(entries, originalContent);
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// === Properties (Java .properties format) ===
|
||||
|
||||
function parseProperties(content: string): ConfigEntry[] {
|
||||
const entries: ConfigEntry[] = [];
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('!')) continue;
|
||||
const eqIndex = trimmed.indexOf('=');
|
||||
if (eqIndex === -1) continue;
|
||||
entries.push({
|
||||
key: trimmed.substring(0, eqIndex).trim(),
|
||||
value: trimmed.substring(eqIndex + 1).trim(),
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function serializeProperties(entries: ConfigEntry[], originalContent?: string): string {
|
||||
if (!originalContent) {
|
||||
return entries.map((e) => `${e.key}=${e.value}`).join('\n') + '\n';
|
||||
}
|
||||
|
||||
const entryMap = new Map(entries.map((e) => [e.key, e.value]));
|
||||
const lines = originalContent.split('\n');
|
||||
const result: string[] = [];
|
||||
const written = new Set<string>();
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('!')) {
|
||||
result.push(line);
|
||||
continue;
|
||||
}
|
||||
const eqIndex = trimmed.indexOf('=');
|
||||
if (eqIndex === -1) {
|
||||
result.push(line);
|
||||
continue;
|
||||
}
|
||||
const key = trimmed.substring(0, eqIndex).trim();
|
||||
if (entryMap.has(key)) {
|
||||
result.push(`${key}=${entryMap.get(key)}`);
|
||||
written.add(key);
|
||||
} else {
|
||||
result.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
// Append new keys
|
||||
for (const entry of entries) {
|
||||
if (!written.has(entry.key)) {
|
||||
result.push(`${entry.key}=${entry.value}`);
|
||||
}
|
||||
}
|
||||
|
||||
return result.join('\n');
|
||||
}
|
||||
|
||||
// === JSON ===
|
||||
|
||||
function parseJson(content: string): ConfigEntry[] {
|
||||
try {
|
||||
const obj = JSON.parse(content);
|
||||
if (typeof obj !== 'object' || Array.isArray(obj)) return [];
|
||||
return Object.entries(obj).map(([key, value]) => ({
|
||||
key,
|
||||
value: typeof value === 'string' ? value : JSON.stringify(value),
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function serializeJson(entries: ConfigEntry[]): string {
|
||||
const obj: Record<string, unknown> = {};
|
||||
for (const entry of entries) {
|
||||
try {
|
||||
obj[entry.key] = JSON.parse(entry.value);
|
||||
} catch {
|
||||
obj[entry.key] = entry.value;
|
||||
}
|
||||
}
|
||||
return JSON.stringify(obj, null, 2) + '\n';
|
||||
}
|
||||
|
||||
// === YAML (simplified — only top-level key: value) ===
|
||||
|
||||
function parseYaml(content: string): ConfigEntry[] {
|
||||
const entries: ConfigEntry[] = [];
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
// Only handle top-level keys (no indentation)
|
||||
if (line.startsWith(' ') || line.startsWith('\t')) continue;
|
||||
const colonIndex = trimmed.indexOf(':');
|
||||
if (colonIndex === -1) continue;
|
||||
const key = trimmed.substring(0, colonIndex).trim();
|
||||
const value = trimmed.substring(colonIndex + 1).trim();
|
||||
if (key) entries.push({ key, value });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function serializeYaml(entries: ConfigEntry[], originalContent?: string): string {
|
||||
if (!originalContent) {
|
||||
return entries.map((e) => `${e.key}: ${e.value}`).join('\n') + '\n';
|
||||
}
|
||||
|
||||
const entryMap = new Map(entries.map((e) => [e.key, e.value]));
|
||||
const lines = originalContent.split('\n');
|
||||
const result: string[] = [];
|
||||
const written = new Set<string>();
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#') || line.startsWith(' ') || line.startsWith('\t')) {
|
||||
result.push(line);
|
||||
continue;
|
||||
}
|
||||
const colonIndex = trimmed.indexOf(':');
|
||||
if (colonIndex === -1) {
|
||||
result.push(line);
|
||||
continue;
|
||||
}
|
||||
const key = trimmed.substring(0, colonIndex).trim();
|
||||
if (entryMap.has(key)) {
|
||||
result.push(`${key}: ${entryMap.get(key)}`);
|
||||
written.add(key);
|
||||
} else {
|
||||
result.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!written.has(entry.key)) {
|
||||
result.push(`${entry.key}: ${entry.value}`);
|
||||
}
|
||||
}
|
||||
|
||||
return result.join('\n');
|
||||
}
|
||||
|
||||
// === KeyValue (Source engine cfg: `key "value"` or `key value`) ===
|
||||
|
||||
function parseKeyValue(content: string): ConfigEntry[] {
|
||||
const entries: ConfigEntry[] = [];
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('//')) continue;
|
||||
|
||||
// Match: key "value" or key value
|
||||
const match = trimmed.match(/^(\S+)\s+"([^"]*)"/) || trimmed.match(/^(\S+)\s+(.*)/);
|
||||
if (match && match[1] && match[2] !== undefined) {
|
||||
entries.push({ key: match[1], value: match[2] });
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function serializeKeyValue(entries: ConfigEntry[], originalContent?: string): string {
|
||||
if (!originalContent) {
|
||||
return entries.map((e) => `${e.key} "${e.value}"`).join('\n') + '\n';
|
||||
}
|
||||
|
||||
const entryMap = new Map(entries.map((e) => [e.key, e.value]));
|
||||
const lines = originalContent.split('\n');
|
||||
const result: string[] = [];
|
||||
const written = new Set<string>();
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('//')) {
|
||||
result.push(line);
|
||||
continue;
|
||||
}
|
||||
const match = trimmed.match(/^(\S+)\s+/);
|
||||
const matchKey = match?.[1];
|
||||
if (matchKey && entryMap.has(matchKey)) {
|
||||
result.push(`${matchKey} "${entryMap.get(matchKey)}"`);
|
||||
written.add(matchKey);
|
||||
} else {
|
||||
result.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!written.has(entry.key)) {
|
||||
result.push(`${entry.key} "${entry.value}"`);
|
||||
}
|
||||
}
|
||||
|
||||
return result.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export class AppError extends Error {
|
||||
constructor(
|
||||
public statusCode: number,
|
||||
message: string,
|
||||
public code?: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'AppError';
|
||||
}
|
||||
|
||||
static badRequest(message: string, code?: string) {
|
||||
return new AppError(400, message, code);
|
||||
}
|
||||
|
||||
static unauthorized(message = 'Unauthorized', code?: string) {
|
||||
return new AppError(401, message, code);
|
||||
}
|
||||
|
||||
static forbidden(message = 'Forbidden', code?: string) {
|
||||
return new AppError(403, message, code);
|
||||
}
|
||||
|
||||
static notFound(message = 'Not found', code?: string) {
|
||||
return new AppError(404, message, code);
|
||||
}
|
||||
|
||||
static conflict(message: string, code?: string) {
|
||||
return new AppError(409, message, code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
|
||||
export interface AccessTokenPayload {
|
||||
sub: string; // user id
|
||||
email: string;
|
||||
isSuperAdmin: boolean;
|
||||
}
|
||||
|
||||
export interface RefreshTokenPayload {
|
||||
sub: string; // user id
|
||||
type: 'refresh';
|
||||
}
|
||||
|
||||
const ACCESS_TOKEN_EXPIRY = '15m';
|
||||
const REFRESH_TOKEN_EXPIRY = '7d';
|
||||
|
||||
export function signAccessToken(app: FastifyInstance, payload: AccessTokenPayload): string {
|
||||
return app.jwt.sign(payload, { expiresIn: ACCESS_TOKEN_EXPIRY });
|
||||
}
|
||||
|
||||
export function signRefreshToken(app: FastifyInstance, payload: RefreshTokenPayload): string {
|
||||
return (app as any).jwtRefresh.sign(payload, { expiresIn: REFRESH_TOKEN_EXPIRY });
|
||||
}
|
||||
|
||||
export function verifyRefreshToken(app: FastifyInstance, token: string): RefreshTokenPayload {
|
||||
return (app as any).jwtRefresh.verify(token) as RefreshTokenPayload;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const PaginationQuerySchema = Type.Object({
|
||||
page: Type.Optional(Type.Number({ minimum: 1, default: 1 })),
|
||||
perPage: Type.Optional(Type.Number({ minimum: 1, maximum: 100, default: 20 })),
|
||||
});
|
||||
|
||||
export function paginate(query: { page?: number; perPage?: number }) {
|
||||
const page = query.page ?? 1;
|
||||
const perPage = query.perPage ?? 20;
|
||||
const offset = (page - 1) * perPage;
|
||||
return { page, perPage, offset, limit: perPage };
|
||||
}
|
||||
|
||||
export function paginatedResponse<T>(data: T[], total: number, page: number, perPage: number) {
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
page,
|
||||
perPage,
|
||||
total,
|
||||
totalPages: Math.ceil(total / perPage),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import argon2 from 'argon2';
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
return argon2.hash(password, {
|
||||
type: argon2.argon2id,
|
||||
memoryCost: 65536,
|
||||
timeCost: 3,
|
||||
parallelism: 4,
|
||||
});
|
||||
}
|
||||
|
||||
export async function verifyPassword(hash: string, password: string): Promise<boolean> {
|
||||
return argon2.verify(hash, password);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { organizationMembers } from '@source/database';
|
||||
import { ROLES } from '@source/shared';
|
||||
import type { Permission, Role } from '@source/shared';
|
||||
import { AppError } from './errors.js';
|
||||
|
||||
interface OrgMember {
|
||||
role: Role;
|
||||
customPermissions: Record<string, boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the requesting user's membership in an organization.
|
||||
* Super admins bypass membership checks.
|
||||
*/
|
||||
export async function getOrgMembership(
|
||||
request: FastifyRequest,
|
||||
orgId: string,
|
||||
): Promise<OrgMember | 'super_admin'> {
|
||||
const user = request.user;
|
||||
|
||||
if (user.isSuperAdmin) {
|
||||
return 'super_admin';
|
||||
}
|
||||
|
||||
const member = await (request.server as any).db.query.organizationMembers.findFirst({
|
||||
where: and(
|
||||
eq(organizationMembers.organizationId, orgId),
|
||||
eq(organizationMembers.userId, user.sub),
|
||||
),
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
throw AppError.forbidden('You are not a member of this organization');
|
||||
}
|
||||
|
||||
return {
|
||||
role: member.role as Role,
|
||||
customPermissions: (member.customPermissions ?? {}) as Record<string, boolean>,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user has a specific permission in the organization.
|
||||
* Super admins always have all permissions.
|
||||
*/
|
||||
export function hasPermission(membership: OrgMember | 'super_admin', permission: Permission): boolean {
|
||||
if (membership === 'super_admin') return true;
|
||||
|
||||
// Check custom permission overrides first
|
||||
if (permission in membership.customPermissions) {
|
||||
return membership.customPermissions[permission]!;
|
||||
}
|
||||
|
||||
// Fall back to role defaults
|
||||
const rolePerms = ROLES[membership.role]?.permissions ?? [];
|
||||
return (rolePerms as readonly string[]).includes(permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* Require a specific permission, throw 403 if not allowed.
|
||||
*/
|
||||
export async function requirePermission(
|
||||
request: FastifyRequest,
|
||||
orgId: string,
|
||||
permission: Permission,
|
||||
): Promise<void> {
|
||||
const membership = await getOrgMembership(request, orgId);
|
||||
if (!hasPermission(membership, permission)) {
|
||||
throw AppError.forbidden(`Missing permission: ${permission}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Require super admin role.
|
||||
*/
|
||||
export function requireSuperAdmin(request: FastifyRequest): void {
|
||||
if (!request.user.isSuperAdmin) {
|
||||
throw AppError.forbidden('Super admin access required');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Compute the next run time for a scheduled task.
|
||||
*/
|
||||
export function computeNextRun(
|
||||
scheduleType: string,
|
||||
scheduleData: Record<string, unknown>,
|
||||
): Date {
|
||||
const now = new Date();
|
||||
|
||||
switch (scheduleType) {
|
||||
case 'interval': {
|
||||
const minutes = Number(scheduleData.minutes) || 60;
|
||||
return new Date(now.getTime() + minutes * 60_000);
|
||||
}
|
||||
|
||||
case 'daily': {
|
||||
const hour = Number(scheduleData.hour ?? 0);
|
||||
const minute = Number(scheduleData.minute ?? 0);
|
||||
const next = new Date(now);
|
||||
next.setHours(hour, minute, 0, 0);
|
||||
if (next <= now) next.setDate(next.getDate() + 1);
|
||||
return next;
|
||||
}
|
||||
|
||||
case 'weekly': {
|
||||
const dayOfWeek = Number(scheduleData.dayOfWeek ?? 0); // 0=Sunday
|
||||
const hour = Number(scheduleData.hour ?? 0);
|
||||
const minute = Number(scheduleData.minute ?? 0);
|
||||
const next = new Date(now);
|
||||
next.setHours(hour, minute, 0, 0);
|
||||
const currentDay = next.getDay();
|
||||
let daysAhead = dayOfWeek - currentDay;
|
||||
if (daysAhead < 0 || (daysAhead === 0 && next <= now)) {
|
||||
daysAhead += 7;
|
||||
}
|
||||
next.setDate(next.getDate() + daysAhead);
|
||||
return next;
|
||||
}
|
||||
|
||||
case 'cron': {
|
||||
// Simple cron parser for: minute hour dayOfMonth month dayOfWeek
|
||||
const expression = String(scheduleData.expression || '0 * * * *');
|
||||
return parseCronNextRun(expression, now);
|
||||
}
|
||||
|
||||
default:
|
||||
return new Date(now.getTime() + 3600_000); // fallback: 1 hour
|
||||
}
|
||||
}
|
||||
|
||||
function parseCronNextRun(expression: string, from: Date): Date {
|
||||
const parts = expression.trim().split(/\s+/);
|
||||
const cronMinute = parts[0] ?? '*';
|
||||
const cronHour = parts[1] ?? '*';
|
||||
const cronDom = parts[2] ?? '*';
|
||||
const cronMonth = parts[3] ?? '*';
|
||||
const cronDow = parts[4] ?? '*';
|
||||
|
||||
// Brute force: check next 1440 minutes (24 hours)
|
||||
const candidate = new Date(from);
|
||||
candidate.setSeconds(0, 0);
|
||||
candidate.setMinutes(candidate.getMinutes() + 1);
|
||||
|
||||
for (let i = 0; i < 1440 * 31; i++) {
|
||||
if (
|
||||
matchesCronField(cronMinute, candidate.getMinutes()) &&
|
||||
matchesCronField(cronHour, candidate.getHours()) &&
|
||||
matchesCronField(cronDom, candidate.getDate()) &&
|
||||
matchesCronField(cronMonth, candidate.getMonth() + 1) &&
|
||||
matchesCronField(cronDow, candidate.getDay())
|
||||
) {
|
||||
return candidate;
|
||||
}
|
||||
candidate.setMinutes(candidate.getMinutes() + 1);
|
||||
}
|
||||
|
||||
// Fallback if no match found
|
||||
return new Date(from.getTime() + 3600_000);
|
||||
}
|
||||
|
||||
function matchesCronField(field: string, value: number): boolean {
|
||||
if (field === '*') return true;
|
||||
|
||||
// Handle step values: */5
|
||||
if (field.startsWith('*/')) {
|
||||
const step = parseInt(field.slice(2), 10);
|
||||
return step > 0 && value % step === 0;
|
||||
}
|
||||
|
||||
// Handle ranges: 1-5
|
||||
if (field.includes('-')) {
|
||||
const [min, max] = field.split('-').map(Number);
|
||||
return min !== undefined && max !== undefined && value >= min && value <= max;
|
||||
}
|
||||
|
||||
// Handle lists: 1,3,5
|
||||
if (field.includes(',')) {
|
||||
return field.split(',').map(Number).includes(value);
|
||||
}
|
||||
|
||||
// Exact match
|
||||
return parseInt(field, 10) === value;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
const SPIGET_BASE = 'https://api.spiget.org/v2';
|
||||
|
||||
export interface SpigetResource {
|
||||
id: number;
|
||||
name: string;
|
||||
tag: string;
|
||||
icon: { url: string; data: string };
|
||||
releaseDate: number;
|
||||
updateDate: number;
|
||||
downloads: number;
|
||||
rating: { average: number; count: number };
|
||||
file: { type: string; size: number; url: string };
|
||||
version: { id: number };
|
||||
external: boolean;
|
||||
}
|
||||
|
||||
export interface SpigetVersion {
|
||||
id: number;
|
||||
name: string;
|
||||
releaseDate: number;
|
||||
downloads: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export async function searchSpigetPlugins(
|
||||
query: string,
|
||||
page = 1,
|
||||
size = 20,
|
||||
): Promise<SpigetResource[]> {
|
||||
const res = await fetch(
|
||||
`${SPIGET_BASE}/search/resources/${encodeURIComponent(query)}?size=${size}&page=${page}&sort=-downloads`,
|
||||
{ headers: { 'User-Agent': 'GamePanel/1.0' } },
|
||||
);
|
||||
if (!res.ok) return [];
|
||||
return res.json() as Promise<SpigetResource[]>;
|
||||
}
|
||||
|
||||
export async function getSpigetResource(id: number): Promise<SpigetResource | null> {
|
||||
const res = await fetch(`${SPIGET_BASE}/resources/${id}`, {
|
||||
headers: { 'User-Agent': 'GamePanel/1.0' },
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return res.json() as Promise<SpigetResource>;
|
||||
}
|
||||
|
||||
export async function getSpigetVersions(resourceId: number): Promise<SpigetVersion[]> {
|
||||
const res = await fetch(`${SPIGET_BASE}/resources/${resourceId}/versions?sort=-releaseDate`, {
|
||||
headers: { 'User-Agent': 'GamePanel/1.0' },
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
return res.json() as Promise<SpigetVersion[]>;
|
||||
}
|
||||
|
||||
export function getSpigetDownloadUrl(resourceId: number): string {
|
||||
return `${SPIGET_BASE}/resources/${resourceId}/download`;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import fp from 'fastify-plugin';
|
||||
import jwt from '@fastify/jwt';
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { AccessTokenPayload } from '../lib/jwt.js';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
||||
jwtRefresh: FastifyInstance['jwt'];
|
||||
}
|
||||
}
|
||||
|
||||
declare module '@fastify/jwt' {
|
||||
interface FastifyJWT {
|
||||
payload: AccessTokenPayload;
|
||||
user: AccessTokenPayload;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async (app: FastifyInstance) => {
|
||||
const jwtSecret = process.env.JWT_SECRET;
|
||||
const jwtRefreshSecret = process.env.JWT_REFRESH_SECRET;
|
||||
|
||||
if (!jwtSecret || !jwtRefreshSecret) {
|
||||
throw new Error('JWT_SECRET and JWT_REFRESH_SECRET environment variables are required');
|
||||
}
|
||||
|
||||
// Access token JWT
|
||||
await app.register(jwt, {
|
||||
secret: jwtSecret,
|
||||
namespace: 'jwt',
|
||||
});
|
||||
|
||||
// Refresh token JWT (separate namespace)
|
||||
await app.register(jwt, {
|
||||
secret: jwtRefreshSecret,
|
||||
namespace: 'jwtRefresh',
|
||||
});
|
||||
|
||||
// Auth decorator
|
||||
app.decorate('authenticate', async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch {
|
||||
reply.code(401).send({ error: 'Unauthorized', message: 'Invalid or expired token' });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import fp from 'fastify-plugin';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { createDb, type Database } from '@source/database';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
db: Database;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async (app: FastifyInstance) => {
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
if (!databaseUrl) {
|
||||
throw new Error('DATABASE_URL environment variable is required');
|
||||
}
|
||||
|
||||
const db = createDb(databaseUrl);
|
||||
app.decorate('db', db);
|
||||
|
||||
app.log.info('Database connected');
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, desc, count } from 'drizzle-orm';
|
||||
import { users, games, nodes, auditLogs } from '@source/database';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requireSuperAdmin } from '../../lib/permissions.js';
|
||||
import { paginate, paginatedResponse, PaginationQuerySchema } from '../../lib/pagination.js';
|
||||
import { CreateGameSchema, UpdateGameSchema, GameIdParamSchema } from './schemas.js';
|
||||
|
||||
export default async function adminRoutes(app: FastifyInstance) {
|
||||
// All admin routes require auth + super admin
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
app.addHook('onRequest', async (request) => {
|
||||
requireSuperAdmin(request);
|
||||
});
|
||||
|
||||
// === Users ===
|
||||
|
||||
// GET /api/admin/users
|
||||
app.get('/users', { schema: { querystring: PaginationQuerySchema } }, async (request) => {
|
||||
const { page, perPage, offset, limit } = paginate(request.query as any);
|
||||
|
||||
const [totalResult] = await app.db.select({ count: count() }).from(users);
|
||||
|
||||
const userList = await app.db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
isSuperAdmin: users.isSuperAdmin,
|
||||
avatarUrl: users.avatarUrl,
|
||||
createdAt: users.createdAt,
|
||||
})
|
||||
.from(users)
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
.orderBy(users.createdAt);
|
||||
|
||||
return paginatedResponse(userList, totalResult!.count, page, perPage);
|
||||
});
|
||||
|
||||
// === Games ===
|
||||
|
||||
// GET /api/admin/games
|
||||
app.get('/games', async () => {
|
||||
const gameList = await app.db
|
||||
.select()
|
||||
.from(games)
|
||||
.orderBy(games.name);
|
||||
|
||||
return { data: gameList };
|
||||
});
|
||||
|
||||
// POST /api/admin/games
|
||||
app.post('/games', { schema: CreateGameSchema }, async (request, reply) => {
|
||||
const body = request.body as {
|
||||
slug: string;
|
||||
name: string;
|
||||
dockerImage: string;
|
||||
defaultPort: number;
|
||||
startupCommand: string;
|
||||
stopCommand?: string;
|
||||
configFiles?: unknown[];
|
||||
environmentVars?: unknown[];
|
||||
};
|
||||
|
||||
const existing = await app.db.query.games.findFirst({
|
||||
where: eq(games.slug, body.slug),
|
||||
});
|
||||
if (existing) throw AppError.conflict('Game slug already exists');
|
||||
|
||||
const [game] = await app.db
|
||||
.insert(games)
|
||||
.values({
|
||||
...body,
|
||||
configFiles: body.configFiles ?? [],
|
||||
environmentVars: body.environmentVars ?? [],
|
||||
})
|
||||
.returning();
|
||||
|
||||
return reply.code(201).send(game);
|
||||
});
|
||||
|
||||
// PATCH /api/admin/games/:gameId
|
||||
app.patch('/games/:gameId', { schema: { ...GameIdParamSchema, ...UpdateGameSchema } }, async (request) => {
|
||||
const { gameId } = request.params as { gameId: string };
|
||||
const body = request.body as Record<string, unknown>;
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(games)
|
||||
.set({ ...body, updatedAt: new Date() })
|
||||
.where(eq(games.id, gameId))
|
||||
.returning();
|
||||
|
||||
if (!updated) throw AppError.notFound('Game not found');
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
// === Nodes (global view) ===
|
||||
|
||||
// GET /api/admin/nodes
|
||||
app.get('/nodes', async () => {
|
||||
const nodeList = await app.db
|
||||
.select()
|
||||
.from(nodes)
|
||||
.orderBy(nodes.createdAt);
|
||||
|
||||
return { data: nodeList };
|
||||
});
|
||||
|
||||
// === Audit Logs ===
|
||||
|
||||
// GET /api/admin/audit-logs
|
||||
app.get('/audit-logs', { schema: { querystring: PaginationQuerySchema } }, async (request) => {
|
||||
const { page, perPage, offset, limit } = paginate(request.query as any);
|
||||
|
||||
const [totalResult] = await app.db.select({ count: count() }).from(auditLogs);
|
||||
|
||||
const logs = await app.db
|
||||
.select({
|
||||
id: auditLogs.id,
|
||||
organizationId: auditLogs.organizationId,
|
||||
userId: auditLogs.userId,
|
||||
serverId: auditLogs.serverId,
|
||||
action: auditLogs.action,
|
||||
metadata: auditLogs.metadata,
|
||||
ipAddress: auditLogs.ipAddress,
|
||||
createdAt: auditLogs.createdAt,
|
||||
userEmail: users.email,
|
||||
userName: users.username,
|
||||
})
|
||||
.from(auditLogs)
|
||||
.innerJoin(users, eq(auditLogs.userId, users.id))
|
||||
.orderBy(desc(auditLogs.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset);
|
||||
|
||||
return paginatedResponse(logs, totalResult!.count, page, perPage);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const CreateGameSchema = {
|
||||
body: Type.Object({
|
||||
slug: Type.String({ minLength: 1, maxLength: 100, pattern: '^[a-z0-9-]+$' }),
|
||||
name: Type.String({ minLength: 1, maxLength: 255 }),
|
||||
dockerImage: Type.String({ minLength: 1 }),
|
||||
defaultPort: Type.Number({ minimum: 1, maximum: 65535 }),
|
||||
startupCommand: Type.String({ minLength: 1 }),
|
||||
stopCommand: Type.Optional(Type.String()),
|
||||
configFiles: Type.Optional(Type.Array(Type.Any())),
|
||||
environmentVars: Type.Optional(Type.Array(Type.Any())),
|
||||
}),
|
||||
};
|
||||
|
||||
export const UpdateGameSchema = {
|
||||
body: Type.Object({
|
||||
name: Type.Optional(Type.String({ minLength: 1, maxLength: 255 })),
|
||||
dockerImage: Type.Optional(Type.String({ minLength: 1 })),
|
||||
defaultPort: Type.Optional(Type.Number({ minimum: 1, maximum: 65535 })),
|
||||
startupCommand: Type.Optional(Type.String({ minLength: 1 })),
|
||||
stopCommand: Type.Optional(Type.String()),
|
||||
configFiles: Type.Optional(Type.Array(Type.Any())),
|
||||
environmentVars: Type.Optional(Type.Array(Type.Any())),
|
||||
}),
|
||||
};
|
||||
|
||||
export const GameIdParamSchema = {
|
||||
params: Type.Object({
|
||||
gameId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,196 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { users } from '@source/database';
|
||||
import { hashPassword, verifyPassword } from '../../lib/password.js';
|
||||
import { signAccessToken, signRefreshToken, verifyRefreshToken } from '../../lib/jwt.js';
|
||||
import type { AccessTokenPayload, RefreshTokenPayload } from '../../lib/jwt.js';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { RegisterSchema, LoginSchema } from './schemas.js';
|
||||
|
||||
const REFRESH_COOKIE_NAME = 'refresh_token';
|
||||
const REFRESH_COOKIE_OPTIONS = {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax' as const,
|
||||
path: '/api/auth',
|
||||
maxAge: 7 * 24 * 60 * 60, // 7 days in seconds
|
||||
};
|
||||
|
||||
export default async function authRoutes(app: FastifyInstance) {
|
||||
// POST /api/auth/register
|
||||
app.post('/register', { schema: RegisterSchema }, async (request, reply) => {
|
||||
const { email, username, password } = request.body as {
|
||||
email: string;
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
// Check if email already exists
|
||||
const existingEmail = await app.db.query.users.findFirst({
|
||||
where: eq(users.email, email),
|
||||
});
|
||||
if (existingEmail) {
|
||||
throw AppError.conflict('Email already in use', 'EMAIL_TAKEN');
|
||||
}
|
||||
|
||||
// Check if username already exists
|
||||
const existingUsername = await app.db.query.users.findFirst({
|
||||
where: eq(users.username, username),
|
||||
});
|
||||
if (existingUsername) {
|
||||
throw AppError.conflict('Username already in use', 'USERNAME_TAKEN');
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
|
||||
const [user] = await app.db
|
||||
.insert(users)
|
||||
.values({
|
||||
email,
|
||||
username,
|
||||
passwordHash,
|
||||
})
|
||||
.returning({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
isSuperAdmin: users.isSuperAdmin,
|
||||
});
|
||||
|
||||
// Generate tokens
|
||||
const accessToken = signAccessToken(app, {
|
||||
sub: user!.id,
|
||||
email: user!.email,
|
||||
isSuperAdmin: user!.isSuperAdmin,
|
||||
});
|
||||
|
||||
const refreshToken = signRefreshToken(app, {
|
||||
sub: user!.id,
|
||||
type: 'refresh',
|
||||
});
|
||||
|
||||
reply.setCookie(REFRESH_COOKIE_NAME, refreshToken, REFRESH_COOKIE_OPTIONS);
|
||||
|
||||
return reply.code(201).send({
|
||||
user: {
|
||||
id: user!.id,
|
||||
email: user!.email,
|
||||
username: user!.username,
|
||||
isSuperAdmin: user!.isSuperAdmin,
|
||||
},
|
||||
accessToken,
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/auth/login
|
||||
app.post('/login', { schema: LoginSchema }, async (request, reply) => {
|
||||
const { email, password } = request.body as { email: string; password: string };
|
||||
|
||||
const user = await app.db.query.users.findFirst({
|
||||
where: eq(users.email, email),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw AppError.unauthorized('Invalid email or password', 'INVALID_CREDENTIALS');
|
||||
}
|
||||
|
||||
const isValid = await verifyPassword(user.passwordHash, password);
|
||||
if (!isValid) {
|
||||
throw AppError.unauthorized('Invalid email or password', 'INVALID_CREDENTIALS');
|
||||
}
|
||||
|
||||
const accessToken = signAccessToken(app, {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
isSuperAdmin: user.isSuperAdmin,
|
||||
});
|
||||
|
||||
const refreshToken = signRefreshToken(app, {
|
||||
sub: user.id,
|
||||
type: 'refresh',
|
||||
});
|
||||
|
||||
reply.setCookie(REFRESH_COOKIE_NAME, refreshToken, REFRESH_COOKIE_OPTIONS);
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
isSuperAdmin: user.isSuperAdmin,
|
||||
avatarUrl: user.avatarUrl,
|
||||
},
|
||||
accessToken,
|
||||
};
|
||||
});
|
||||
|
||||
// POST /api/auth/refresh
|
||||
app.post('/refresh', async (request, reply) => {
|
||||
const token = request.cookies[REFRESH_COOKIE_NAME];
|
||||
if (!token) {
|
||||
throw AppError.unauthorized('No refresh token', 'NO_REFRESH_TOKEN');
|
||||
}
|
||||
|
||||
let payload: RefreshTokenPayload;
|
||||
try {
|
||||
payload = verifyRefreshToken(app, token);
|
||||
} catch {
|
||||
reply.clearCookie(REFRESH_COOKIE_NAME, { path: '/api/auth' });
|
||||
throw AppError.unauthorized('Invalid refresh token', 'INVALID_REFRESH_TOKEN');
|
||||
}
|
||||
|
||||
const user = await app.db.query.users.findFirst({
|
||||
where: eq(users.id, payload.sub),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
reply.clearCookie(REFRESH_COOKIE_NAME, { path: '/api/auth' });
|
||||
throw AppError.unauthorized('User not found', 'USER_NOT_FOUND');
|
||||
}
|
||||
|
||||
// Token rotation: issue new tokens
|
||||
const accessToken = signAccessToken(app, {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
isSuperAdmin: user.isSuperAdmin,
|
||||
});
|
||||
|
||||
const newRefreshToken = signRefreshToken(app, {
|
||||
sub: user.id,
|
||||
type: 'refresh',
|
||||
});
|
||||
|
||||
reply.setCookie(REFRESH_COOKIE_NAME, newRefreshToken, REFRESH_COOKIE_OPTIONS);
|
||||
|
||||
return { accessToken };
|
||||
});
|
||||
|
||||
// POST /api/auth/logout
|
||||
app.post('/logout', async (_request, reply) => {
|
||||
reply.clearCookie(REFRESH_COOKIE_NAME, { path: '/api/auth' });
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
// GET /api/auth/me
|
||||
app.get('/me', { onRequest: [app.authenticate] }, async (request) => {
|
||||
const payload = request.user;
|
||||
|
||||
const user = await app.db.query.users.findFirst({
|
||||
where: eq(users.id, payload.sub),
|
||||
columns: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
isSuperAdmin: true,
|
||||
avatarUrl: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw AppError.notFound('User not found');
|
||||
}
|
||||
|
||||
return { user };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const RegisterSchema = {
|
||||
body: Type.Object({
|
||||
email: Type.String({ format: 'email' }),
|
||||
username: Type.String({ minLength: 3, maxLength: 100 }),
|
||||
password: Type.String({ minLength: 8, maxLength: 128 }),
|
||||
}),
|
||||
};
|
||||
|
||||
export const LoginSchema = {
|
||||
body: Type.Object({
|
||||
email: Type.String({ format: 'email' }),
|
||||
password: Type.String(),
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { nodes, allocations } from '@source/database';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requirePermission } from '../../lib/permissions.js';
|
||||
import { createAuditLog } from '../../lib/audit.js';
|
||||
import {
|
||||
NodeParamSchema,
|
||||
CreateNodeSchema,
|
||||
UpdateNodeSchema,
|
||||
CreateAllocationSchema,
|
||||
} from './schemas.js';
|
||||
|
||||
export default async function nodeRoutes(app: FastifyInstance) {
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
|
||||
// GET /api/organizations/:orgId/nodes
|
||||
app.get('/', async (request) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await requirePermission(request, orgId, 'node.read');
|
||||
|
||||
const nodeList = await app.db
|
||||
.select()
|
||||
.from(nodes)
|
||||
.where(eq(nodes.organizationId, orgId))
|
||||
.orderBy(nodes.createdAt);
|
||||
|
||||
return { data: nodeList };
|
||||
});
|
||||
|
||||
// POST /api/organizations/:orgId/nodes
|
||||
app.post('/', { schema: CreateNodeSchema }, async (request, reply) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await requirePermission(request, orgId, 'node.manage');
|
||||
|
||||
const body = request.body as {
|
||||
name: string;
|
||||
fqdn: string;
|
||||
daemonPort?: number;
|
||||
grpcPort?: number;
|
||||
location?: string;
|
||||
memoryTotal: number;
|
||||
diskTotal: number;
|
||||
memoryOveralloc?: number;
|
||||
diskOveralloc?: number;
|
||||
};
|
||||
|
||||
const daemonToken = randomBytes(32).toString('hex');
|
||||
|
||||
const [node] = await app.db
|
||||
.insert(nodes)
|
||||
.values({
|
||||
organizationId: orgId,
|
||||
...body,
|
||||
daemonToken,
|
||||
})
|
||||
.returning();
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'node.create',
|
||||
metadata: { nodeId: node!.id, name: body.name },
|
||||
});
|
||||
|
||||
return reply.code(201).send(node);
|
||||
});
|
||||
|
||||
// GET /api/organizations/:orgId/nodes/:nodeId
|
||||
app.get('/:nodeId', { schema: NodeParamSchema }, async (request) => {
|
||||
const { orgId, nodeId } = request.params as { orgId: string; nodeId: string };
|
||||
await requirePermission(request, orgId, 'node.read');
|
||||
|
||||
const node = await app.db.query.nodes.findFirst({
|
||||
where: and(eq(nodes.id, nodeId), eq(nodes.organizationId, orgId)),
|
||||
});
|
||||
if (!node) throw AppError.notFound('Node not found');
|
||||
|
||||
return node;
|
||||
});
|
||||
|
||||
// PATCH /api/organizations/:orgId/nodes/:nodeId
|
||||
app.patch('/:nodeId', { schema: { ...NodeParamSchema, ...UpdateNodeSchema } }, async (request) => {
|
||||
const { orgId, nodeId } = request.params as { orgId: string; nodeId: string };
|
||||
await requirePermission(request, orgId, 'node.manage');
|
||||
|
||||
const body = request.body as Record<string, unknown>;
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(nodes)
|
||||
.set({ ...body, updatedAt: new Date() })
|
||||
.where(and(eq(nodes.id, nodeId), eq(nodes.organizationId, orgId)))
|
||||
.returning();
|
||||
|
||||
if (!updated) throw AppError.notFound('Node not found');
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'node.update',
|
||||
metadata: { nodeId, ...body },
|
||||
});
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /api/organizations/:orgId/nodes/:nodeId
|
||||
app.delete('/:nodeId', { schema: NodeParamSchema }, async (request, reply) => {
|
||||
const { orgId, nodeId } = request.params as { orgId: string; nodeId: string };
|
||||
await requirePermission(request, orgId, 'node.manage');
|
||||
|
||||
const node = await app.db.query.nodes.findFirst({
|
||||
where: and(eq(nodes.id, nodeId), eq(nodes.organizationId, orgId)),
|
||||
});
|
||||
if (!node) throw AppError.notFound('Node not found');
|
||||
|
||||
await app.db.delete(nodes).where(eq(nodes.id, nodeId));
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'node.delete',
|
||||
metadata: { nodeId, name: node.name },
|
||||
});
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// === Allocations ===
|
||||
|
||||
// GET /api/organizations/:orgId/nodes/:nodeId/allocations
|
||||
app.get('/:nodeId/allocations', { schema: NodeParamSchema }, async (request) => {
|
||||
const { orgId, nodeId } = request.params as { orgId: string; nodeId: string };
|
||||
await requirePermission(request, orgId, 'node.read');
|
||||
|
||||
const allocs = await app.db
|
||||
.select()
|
||||
.from(allocations)
|
||||
.where(eq(allocations.nodeId, nodeId))
|
||||
.orderBy(allocations.port);
|
||||
|
||||
return { data: allocs };
|
||||
});
|
||||
|
||||
// POST /api/organizations/:orgId/nodes/:nodeId/allocations
|
||||
app.post('/:nodeId/allocations', { schema: { ...NodeParamSchema, ...CreateAllocationSchema } }, async (request, reply) => {
|
||||
const { orgId, nodeId } = request.params as { orgId: string; nodeId: string };
|
||||
await requirePermission(request, orgId, 'node.manage');
|
||||
|
||||
const { ip, ports } = request.body as { ip: string; ports: number[] };
|
||||
|
||||
const values = ports.map((port) => ({
|
||||
nodeId,
|
||||
ip,
|
||||
port,
|
||||
}));
|
||||
|
||||
const created = await app.db
|
||||
.insert(allocations)
|
||||
.values(values)
|
||||
.onConflictDoNothing()
|
||||
.returning();
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'allocation.create',
|
||||
metadata: { nodeId, ip, ports },
|
||||
});
|
||||
|
||||
return reply.code(201).send({ data: created });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const NodeParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
nodeId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
export const CreateNodeSchema = {
|
||||
body: Type.Object({
|
||||
name: Type.String({ minLength: 1, maxLength: 255 }),
|
||||
fqdn: Type.String({ minLength: 1, maxLength: 255 }),
|
||||
daemonPort: Type.Optional(Type.Number({ minimum: 1, maximum: 65535, default: 8443 })),
|
||||
grpcPort: Type.Optional(Type.Number({ minimum: 1, maximum: 65535, default: 50051 })),
|
||||
location: Type.Optional(Type.String({ maxLength: 255 })),
|
||||
memoryTotal: Type.Number({ minimum: 0 }),
|
||||
diskTotal: Type.Number({ minimum: 0 }),
|
||||
memoryOveralloc: Type.Optional(Type.Number({ minimum: 0, default: 0 })),
|
||||
diskOveralloc: Type.Optional(Type.Number({ minimum: 0, default: 0 })),
|
||||
}),
|
||||
};
|
||||
|
||||
export const UpdateNodeSchema = {
|
||||
body: Type.Object({
|
||||
name: Type.Optional(Type.String({ minLength: 1, maxLength: 255 })),
|
||||
fqdn: Type.Optional(Type.String({ minLength: 1, maxLength: 255 })),
|
||||
daemonPort: Type.Optional(Type.Number({ minimum: 1, maximum: 65535 })),
|
||||
grpcPort: Type.Optional(Type.Number({ minimum: 1, maximum: 65535 })),
|
||||
location: Type.Optional(Type.String({ maxLength: 255 })),
|
||||
memoryTotal: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
diskTotal: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
memoryOveralloc: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
diskOveralloc: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
}),
|
||||
};
|
||||
|
||||
export const CreateAllocationSchema = {
|
||||
body: Type.Object({
|
||||
ip: Type.String({ minLength: 1, maxLength: 45 }),
|
||||
ports: Type.Array(Type.Number({ minimum: 1, maximum: 65535 }), { minItems: 1 }),
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, and, count } from 'drizzle-orm';
|
||||
import { organizations, organizationMembers, users } from '@source/database';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requirePermission, getOrgMembership } from '../../lib/permissions.js';
|
||||
import { paginate, paginatedResponse, PaginationQuerySchema } from '../../lib/pagination.js';
|
||||
import { createAuditLog } from '../../lib/audit.js';
|
||||
import {
|
||||
CreateOrgSchema,
|
||||
UpdateOrgSchema,
|
||||
OrgIdParamSchema,
|
||||
AddMemberSchema,
|
||||
UpdateMemberSchema,
|
||||
MemberIdParamSchema,
|
||||
} from './schemas.js';
|
||||
|
||||
export default async function organizationRoutes(app: FastifyInstance) {
|
||||
// All org routes require authentication
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
|
||||
// GET /api/organizations — list user's organizations
|
||||
app.get('/', { schema: { querystring: PaginationQuerySchema } }, async (request) => {
|
||||
const { page, perPage, offset, limit } = paginate(request.query as any);
|
||||
const userId = request.user.sub;
|
||||
|
||||
if (request.user.isSuperAdmin) {
|
||||
const [totalResult] = await app.db.select({ count: count() }).from(organizations);
|
||||
const orgs = await app.db
|
||||
.select()
|
||||
.from(organizations)
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
.orderBy(organizations.createdAt);
|
||||
return paginatedResponse(orgs, totalResult!.count, page, perPage);
|
||||
}
|
||||
|
||||
const memberOrgs = await app.db
|
||||
.select({
|
||||
id: organizations.id,
|
||||
name: organizations.name,
|
||||
slug: organizations.slug,
|
||||
ownerId: organizations.ownerId,
|
||||
maxServers: organizations.maxServers,
|
||||
maxNodes: organizations.maxNodes,
|
||||
createdAt: organizations.createdAt,
|
||||
updatedAt: organizations.updatedAt,
|
||||
role: organizationMembers.role,
|
||||
})
|
||||
.from(organizationMembers)
|
||||
.innerJoin(organizations, eq(organizationMembers.organizationId, organizations.id))
|
||||
.where(eq(organizationMembers.userId, userId))
|
||||
.limit(limit)
|
||||
.offset(offset);
|
||||
|
||||
const [totalResult] = await app.db
|
||||
.select({ count: count() })
|
||||
.from(organizationMembers)
|
||||
.where(eq(organizationMembers.userId, userId));
|
||||
|
||||
return paginatedResponse(memberOrgs, totalResult!.count, page, perPage);
|
||||
});
|
||||
|
||||
// POST /api/organizations — create organization
|
||||
app.post('/', { schema: CreateOrgSchema }, async (request, reply) => {
|
||||
const { name, slug } = request.body as { name: string; slug: string };
|
||||
|
||||
const existing = await app.db.query.organizations.findFirst({
|
||||
where: eq(organizations.slug, slug),
|
||||
});
|
||||
if (existing) {
|
||||
throw AppError.conflict('Organization slug already in use', 'SLUG_TAKEN');
|
||||
}
|
||||
|
||||
const [org] = await app.db
|
||||
.insert(organizations)
|
||||
.values({
|
||||
name,
|
||||
slug,
|
||||
ownerId: request.user.sub,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Add creator as admin member
|
||||
await app.db.insert(organizationMembers).values({
|
||||
organizationId: org!.id,
|
||||
userId: request.user.sub,
|
||||
role: 'admin',
|
||||
});
|
||||
|
||||
return reply.code(201).send(org);
|
||||
});
|
||||
|
||||
// GET /api/organizations/:orgId
|
||||
app.get('/:orgId', { schema: OrgIdParamSchema }, async (request) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await getOrgMembership(request, orgId);
|
||||
|
||||
const org = await app.db.query.organizations.findFirst({
|
||||
where: eq(organizations.id, orgId),
|
||||
});
|
||||
if (!org) throw AppError.notFound('Organization not found');
|
||||
|
||||
return org;
|
||||
});
|
||||
|
||||
// PATCH /api/organizations/:orgId
|
||||
app.patch('/:orgId', { schema: { ...OrgIdParamSchema, ...UpdateOrgSchema } }, async (request) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await requirePermission(request, orgId, 'org.settings');
|
||||
|
||||
const body = request.body as { name?: string; maxServers?: number; maxNodes?: number };
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(organizations)
|
||||
.set({ ...body, updatedAt: new Date() })
|
||||
.where(eq(organizations.id, orgId))
|
||||
.returning();
|
||||
|
||||
if (!updated) throw AppError.notFound('Organization not found');
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'organization.update',
|
||||
metadata: body,
|
||||
});
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /api/organizations/:orgId
|
||||
app.delete('/:orgId', { schema: OrgIdParamSchema }, async (request, reply) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
const membership = await getOrgMembership(request, orgId);
|
||||
|
||||
// Only owner or super admin can delete
|
||||
const org = await app.db.query.organizations.findFirst({
|
||||
where: eq(organizations.id, orgId),
|
||||
});
|
||||
if (!org) throw AppError.notFound('Organization not found');
|
||||
|
||||
if (membership !== 'super_admin' && org.ownerId !== request.user.sub) {
|
||||
throw AppError.forbidden('Only the organization owner can delete this organization');
|
||||
}
|
||||
|
||||
await app.db.delete(organizations).where(eq(organizations.id, orgId));
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// === Members ===
|
||||
|
||||
// GET /api/organizations/:orgId/members
|
||||
app.get('/:orgId/members', { schema: OrgIdParamSchema }, async (request) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await requirePermission(request, orgId, 'org.members');
|
||||
|
||||
const members = await app.db
|
||||
.select({
|
||||
id: organizationMembers.id,
|
||||
userId: organizationMembers.userId,
|
||||
role: organizationMembers.role,
|
||||
customPermissions: organizationMembers.customPermissions,
|
||||
joinedAt: organizationMembers.joinedAt,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
avatarUrl: users.avatarUrl,
|
||||
})
|
||||
.from(organizationMembers)
|
||||
.innerJoin(users, eq(organizationMembers.userId, users.id))
|
||||
.where(eq(organizationMembers.organizationId, orgId));
|
||||
|
||||
return { data: members };
|
||||
});
|
||||
|
||||
// POST /api/organizations/:orgId/members — invite by email
|
||||
app.post('/:orgId/members', { schema: { ...OrgIdParamSchema, ...AddMemberSchema } }, async (request, reply) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await requirePermission(request, orgId, 'org.members');
|
||||
|
||||
const { email, role } = request.body as { email: string; role: 'admin' | 'user' };
|
||||
|
||||
const user = await app.db.query.users.findFirst({
|
||||
where: eq(users.email, email),
|
||||
});
|
||||
if (!user) throw AppError.notFound('User with this email not found');
|
||||
|
||||
const existing = await app.db.query.organizationMembers.findFirst({
|
||||
where: and(
|
||||
eq(organizationMembers.organizationId, orgId),
|
||||
eq(organizationMembers.userId, user.id),
|
||||
),
|
||||
});
|
||||
if (existing) throw AppError.conflict('User is already a member');
|
||||
|
||||
const [member] = await app.db
|
||||
.insert(organizationMembers)
|
||||
.values({
|
||||
organizationId: orgId,
|
||||
userId: user.id,
|
||||
role,
|
||||
})
|
||||
.returning();
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'member.add',
|
||||
metadata: { userId: user.id, email, role },
|
||||
});
|
||||
|
||||
return reply.code(201).send(member);
|
||||
});
|
||||
|
||||
// PATCH /api/organizations/:orgId/members/:memberId
|
||||
app.patch('/:orgId/members/:memberId', { schema: { ...MemberIdParamSchema, ...UpdateMemberSchema } }, async (request) => {
|
||||
const { orgId, memberId } = request.params as { orgId: string; memberId: string };
|
||||
await requirePermission(request, orgId, 'org.members');
|
||||
|
||||
const body = request.body as { role?: 'admin' | 'user'; customPermissions?: Record<string, boolean> };
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(organizationMembers)
|
||||
.set(body)
|
||||
.where(and(
|
||||
eq(organizationMembers.id, memberId),
|
||||
eq(organizationMembers.organizationId, orgId),
|
||||
))
|
||||
.returning();
|
||||
|
||||
if (!updated) throw AppError.notFound('Member not found');
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'member.update',
|
||||
metadata: { memberId, ...body },
|
||||
});
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /api/organizations/:orgId/members/:memberId
|
||||
app.delete('/:orgId/members/:memberId', { schema: MemberIdParamSchema }, async (request, reply) => {
|
||||
const { orgId, memberId } = request.params as { orgId: string; memberId: string };
|
||||
await requirePermission(request, orgId, 'org.members');
|
||||
|
||||
const member = await app.db.query.organizationMembers.findFirst({
|
||||
where: and(
|
||||
eq(organizationMembers.id, memberId),
|
||||
eq(organizationMembers.organizationId, orgId),
|
||||
),
|
||||
});
|
||||
if (!member) throw AppError.notFound('Member not found');
|
||||
|
||||
// Cannot remove org owner
|
||||
const org = await app.db.query.organizations.findFirst({
|
||||
where: eq(organizations.id, orgId),
|
||||
});
|
||||
if (org && member.userId === org.ownerId) {
|
||||
throw AppError.badRequest('Cannot remove the organization owner');
|
||||
}
|
||||
|
||||
await app.db
|
||||
.delete(organizationMembers)
|
||||
.where(and(
|
||||
eq(organizationMembers.id, memberId),
|
||||
eq(organizationMembers.organizationId, orgId),
|
||||
));
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
action: 'member.remove',
|
||||
metadata: { memberId, userId: member.userId },
|
||||
});
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const CreateOrgSchema = {
|
||||
body: Type.Object({
|
||||
name: Type.String({ minLength: 2, maxLength: 255 }),
|
||||
slug: Type.String({ minLength: 2, maxLength: 255, pattern: '^[a-z0-9-]+$' }),
|
||||
}),
|
||||
};
|
||||
|
||||
export const UpdateOrgSchema = {
|
||||
body: Type.Object({
|
||||
name: Type.Optional(Type.String({ minLength: 2, maxLength: 255 })),
|
||||
maxServers: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
maxNodes: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
}),
|
||||
};
|
||||
|
||||
export const OrgIdParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
export const AddMemberSchema = {
|
||||
body: Type.Object({
|
||||
email: Type.String({ format: 'email' }),
|
||||
role: Type.Union([Type.Literal('admin'), Type.Literal('user')]),
|
||||
}),
|
||||
};
|
||||
|
||||
export const UpdateMemberSchema = {
|
||||
body: Type.Object({
|
||||
role: Type.Optional(Type.Union([Type.Literal('admin'), Type.Literal('user')])),
|
||||
customPermissions: Type.Optional(Type.Record(Type.String(), Type.Boolean())),
|
||||
}),
|
||||
};
|
||||
|
||||
export const MemberIdParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
memberId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { servers, backups } from '@source/database';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requirePermission } from '../../lib/permissions.js';
|
||||
import { createAuditLog } from '../../lib/audit.js';
|
||||
|
||||
const ParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
const BackupParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
backupId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
const CreateBackupBody = Type.Object({
|
||||
name: Type.String({ minLength: 1, maxLength: 255 }),
|
||||
isLocked: Type.Optional(Type.Boolean({ default: false })),
|
||||
});
|
||||
|
||||
export default async function backupRoutes(app: FastifyInstance) {
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
|
||||
// GET /backups — list all backups for a server
|
||||
app.get('/', { schema: ParamSchema }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'backup.read');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const backupList = await app.db.query.backups.findMany({
|
||||
where: eq(backups.serverId, serverId),
|
||||
orderBy: (b, { desc }) => [desc(b.createdAt)],
|
||||
});
|
||||
|
||||
return { backups: backupList };
|
||||
});
|
||||
|
||||
// POST /backups — create a backup
|
||||
app.post('/', { schema: { ...ParamSchema, body: CreateBackupBody } }, async (request, reply) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'backup.create');
|
||||
|
||||
const body = request.body as { name: string; isLocked?: boolean };
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
// Create backup record (pending — daemon will update when complete)
|
||||
const [backup] = await app.db
|
||||
.insert(backups)
|
||||
.values({
|
||||
serverId,
|
||||
name: body.name,
|
||||
isLocked: body.isLocked ?? false,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// TODO: Send gRPC CreateBackup to daemon
|
||||
// Daemon will:
|
||||
// 1. tar+gz the server directory
|
||||
// 2. Upload to @source/cdn
|
||||
// 3. Callback to API with cdnPath, sizeBytes, checksum
|
||||
// 4. API updates backup record with completedAt
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'backup.create',
|
||||
metadata: { name: body.name },
|
||||
});
|
||||
|
||||
return reply.code(201).send(backup);
|
||||
});
|
||||
|
||||
// POST /backups/:backupId/restore — restore a backup
|
||||
app.post('/:backupId/restore', { schema: BackupParamSchema }, async (request) => {
|
||||
const { orgId, serverId, backupId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
backupId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'backup.restore');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const backup = await app.db.query.backups.findFirst({
|
||||
where: and(eq(backups.id, backupId), eq(backups.serverId, serverId)),
|
||||
});
|
||||
if (!backup) throw AppError.notFound('Backup not found');
|
||||
if (!backup.completedAt) throw AppError.badRequest('Backup is not yet completed');
|
||||
|
||||
// TODO: Send gRPC RestoreBackup to daemon
|
||||
// Daemon will:
|
||||
// 1. Stop the server
|
||||
// 2. Download backup from @source/cdn
|
||||
// 3. Extract tar.gz over server directory
|
||||
// 4. Start the server
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'backup.restore',
|
||||
metadata: { backupName: backup.name, backupId },
|
||||
});
|
||||
|
||||
return { success: true, message: 'Restore initiated' };
|
||||
});
|
||||
|
||||
// PATCH /backups/:backupId/lock — toggle backup lock
|
||||
app.patch('/:backupId/lock', { schema: BackupParamSchema }, async (request) => {
|
||||
const { orgId, serverId, backupId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
backupId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'backup.manage');
|
||||
|
||||
const backup = await app.db.query.backups.findFirst({
|
||||
where: and(eq(backups.id, backupId), eq(backups.serverId, serverId)),
|
||||
});
|
||||
if (!backup) throw AppError.notFound('Backup not found');
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(backups)
|
||||
.set({ isLocked: !backup.isLocked })
|
||||
.where(eq(backups.id, backupId))
|
||||
.returning();
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /backups/:backupId — delete a backup
|
||||
app.delete('/:backupId', { schema: BackupParamSchema }, async (request, reply) => {
|
||||
const { orgId, serverId, backupId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
backupId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'backup.delete');
|
||||
|
||||
const backup = await app.db.query.backups.findFirst({
|
||||
where: and(eq(backups.id, backupId), eq(backups.serverId, serverId)),
|
||||
});
|
||||
if (!backup) throw AppError.notFound('Backup not found');
|
||||
if (backup.isLocked) throw AppError.badRequest('Cannot delete a locked backup');
|
||||
|
||||
// TODO: Send gRPC DeleteBackup to daemon to remove from CDN
|
||||
|
||||
await app.db.delete(backups).where(eq(backups.id, backupId));
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'backup.delete',
|
||||
metadata: { name: backup.name },
|
||||
});
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { servers, games } from '@source/database';
|
||||
import type { GameConfigFile, ConfigParser } from '@source/shared';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requirePermission } from '../../lib/permissions.js';
|
||||
import { parseConfig, serializeConfig } from '../../lib/config-parsers.js';
|
||||
|
||||
const ParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
const ConfigFileParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
configIndex: Type.Number({ minimum: 0 }),
|
||||
}),
|
||||
};
|
||||
|
||||
export default async function configRoutes(app: FastifyInstance) {
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
|
||||
// GET /config — list available config files for this server's game
|
||||
app.get('/', { schema: ParamSchema }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'config.read');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const game = await app.db.query.games.findFirst({
|
||||
where: eq(games.id, server.gameId),
|
||||
});
|
||||
if (!game) throw AppError.notFound('Game not found');
|
||||
|
||||
const configFiles = (game.configFiles as GameConfigFile[]) || [];
|
||||
return {
|
||||
configs: configFiles.map((cf, index) => ({
|
||||
index,
|
||||
path: cf.path,
|
||||
parser: cf.parser,
|
||||
editableKeys: cf.editableKeys ?? null,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
// GET /config/:configIndex — read & parse a specific config file
|
||||
app.get('/:configIndex', { schema: ConfigFileParamSchema }, async (request) => {
|
||||
const { orgId, serverId, configIndex } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
configIndex: number;
|
||||
};
|
||||
await requirePermission(request, orgId, 'config.read');
|
||||
|
||||
const { game, server, configFile } = await getServerConfig(app, orgId, serverId, configIndex);
|
||||
|
||||
// TODO: Read file from daemon via gRPC
|
||||
// For now, return empty parsed result (will be connected in Phase 4 integration)
|
||||
return {
|
||||
path: configFile.path,
|
||||
parser: configFile.parser,
|
||||
editableKeys: configFile.editableKeys ?? null,
|
||||
entries: [],
|
||||
raw: '',
|
||||
};
|
||||
});
|
||||
|
||||
// PUT /config/:configIndex — update a config file
|
||||
app.put(
|
||||
'/:configIndex',
|
||||
{
|
||||
schema: {
|
||||
...ConfigFileParamSchema,
|
||||
body: Type.Object({
|
||||
entries: Type.Array(
|
||||
Type.Object({
|
||||
key: Type.String(),
|
||||
value: Type.String(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
},
|
||||
},
|
||||
async (request) => {
|
||||
const { orgId, serverId, configIndex } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
configIndex: number;
|
||||
};
|
||||
const { entries } = request.body as { entries: { key: string; value: string }[] };
|
||||
await requirePermission(request, orgId, 'config.write');
|
||||
|
||||
const { configFile } = await getServerConfig(app, orgId, serverId, configIndex);
|
||||
|
||||
// If editableKeys is set, only allow those keys
|
||||
if (configFile.editableKeys && configFile.editableKeys.length > 0) {
|
||||
const allowedKeys = new Set(configFile.editableKeys);
|
||||
const invalidKeys = entries.filter((e) => !allowedKeys.has(e.key));
|
||||
if (invalidKeys.length > 0) {
|
||||
throw AppError.badRequest(
|
||||
`Keys not allowed: ${invalidKeys.map((k) => k.key).join(', ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize the entries
|
||||
const content = serializeConfig(entries, configFile.parser as ConfigParser);
|
||||
|
||||
// TODO: Write file to daemon via gRPC
|
||||
// For now, just return success
|
||||
return { success: true, path: configFile.path, content };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function getServerConfig(
|
||||
app: FastifyInstance,
|
||||
orgId: string,
|
||||
serverId: string,
|
||||
configIndex: number,
|
||||
) {
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const game = await app.db.query.games.findFirst({
|
||||
where: eq(games.id, server.gameId),
|
||||
});
|
||||
if (!game) throw AppError.notFound('Game not found');
|
||||
|
||||
const configFiles = (game.configFiles as GameConfigFile[]) || [];
|
||||
const configFile = configFiles[configIndex];
|
||||
if (!configFile) throw AppError.notFound('Config file not found');
|
||||
|
||||
return { game, server, configFile };
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, and, count } from 'drizzle-orm';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { servers, allocations, nodes, games } from '@source/database';
|
||||
import type { PowerAction } from '@source/shared';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requirePermission } from '../../lib/permissions.js';
|
||||
import { paginate, paginatedResponse, PaginationQuerySchema } from '../../lib/pagination.js';
|
||||
import { createAuditLog } from '../../lib/audit.js';
|
||||
import {
|
||||
ServerParamSchema,
|
||||
CreateServerSchema,
|
||||
UpdateServerSchema,
|
||||
PowerActionSchema,
|
||||
} from './schemas.js';
|
||||
import configRoutes from './config.js';
|
||||
import pluginRoutes from './plugins.js';
|
||||
import scheduleRoutes from './schedules.js';
|
||||
import backupRoutes from './backups.js';
|
||||
|
||||
export default async function serverRoutes(app: FastifyInstance) {
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
|
||||
// Register sub-routes
|
||||
await app.register(configRoutes, { prefix: '/:serverId/config' });
|
||||
await app.register(pluginRoutes, { prefix: '/:serverId/plugins' });
|
||||
await app.register(scheduleRoutes, { prefix: '/:serverId/schedules' });
|
||||
await app.register(backupRoutes, { prefix: '/:serverId/backups' });
|
||||
|
||||
// GET /api/organizations/:orgId/servers
|
||||
app.get('/', { schema: { querystring: PaginationQuerySchema } }, async (request) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await requirePermission(request, orgId, 'server.read');
|
||||
|
||||
const { page, perPage, offset, limit } = paginate(request.query as any);
|
||||
|
||||
const [totalResult] = await app.db
|
||||
.select({ count: count() })
|
||||
.from(servers)
|
||||
.where(eq(servers.organizationId, orgId));
|
||||
|
||||
const serverList = await app.db
|
||||
.select({
|
||||
id: servers.id,
|
||||
uuid: servers.uuid,
|
||||
name: servers.name,
|
||||
description: servers.description,
|
||||
status: servers.status,
|
||||
memoryLimit: servers.memoryLimit,
|
||||
diskLimit: servers.diskLimit,
|
||||
cpuLimit: servers.cpuLimit,
|
||||
port: servers.port,
|
||||
createdAt: servers.createdAt,
|
||||
nodeName: nodes.name,
|
||||
nodeId: nodes.id,
|
||||
gameName: games.name,
|
||||
gameSlug: games.slug,
|
||||
gameId: games.id,
|
||||
})
|
||||
.from(servers)
|
||||
.innerJoin(nodes, eq(servers.nodeId, nodes.id))
|
||||
.innerJoin(games, eq(servers.gameId, games.id))
|
||||
.where(eq(servers.organizationId, orgId))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
.orderBy(servers.createdAt);
|
||||
|
||||
return paginatedResponse(serverList, totalResult!.count, page, perPage);
|
||||
});
|
||||
|
||||
// POST /api/organizations/:orgId/servers
|
||||
app.post('/', { schema: CreateServerSchema }, async (request, reply) => {
|
||||
const { orgId } = request.params as { orgId: string };
|
||||
await requirePermission(request, orgId, 'server.create');
|
||||
|
||||
const body = request.body as {
|
||||
name: string;
|
||||
description?: string;
|
||||
nodeId: string;
|
||||
gameId: string;
|
||||
memoryLimit: number;
|
||||
diskLimit: number;
|
||||
cpuLimit?: number;
|
||||
allocationId: string;
|
||||
environment?: Record<string, string>;
|
||||
startupOverride?: string;
|
||||
};
|
||||
|
||||
// Verify node belongs to org
|
||||
const node = await app.db.query.nodes.findFirst({
|
||||
where: and(eq(nodes.id, body.nodeId), eq(nodes.organizationId, orgId)),
|
||||
});
|
||||
if (!node) throw AppError.notFound('Node not found in this organization');
|
||||
|
||||
// Verify game exists
|
||||
const game = await app.db.query.games.findFirst({
|
||||
where: eq(games.id, body.gameId),
|
||||
});
|
||||
if (!game) throw AppError.notFound('Game not found');
|
||||
|
||||
// Verify and claim allocation
|
||||
const allocation = await app.db.query.allocations.findFirst({
|
||||
where: and(
|
||||
eq(allocations.id, body.allocationId),
|
||||
eq(allocations.nodeId, body.nodeId),
|
||||
),
|
||||
});
|
||||
if (!allocation) throw AppError.notFound('Allocation not found on this node');
|
||||
if (allocation.serverId) throw AppError.conflict('Allocation is already in use');
|
||||
|
||||
const serverUuid = randomUUID().slice(0, 8);
|
||||
|
||||
const [server] = await app.db
|
||||
.insert(servers)
|
||||
.values({
|
||||
uuid: serverUuid,
|
||||
organizationId: orgId,
|
||||
nodeId: body.nodeId,
|
||||
gameId: body.gameId,
|
||||
name: body.name,
|
||||
description: body.description,
|
||||
memoryLimit: body.memoryLimit,
|
||||
diskLimit: body.diskLimit,
|
||||
cpuLimit: body.cpuLimit ?? 100,
|
||||
port: allocation.port,
|
||||
environment: body.environment ?? {},
|
||||
startupOverride: body.startupOverride,
|
||||
status: 'installing',
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Assign allocation to server
|
||||
await app.db
|
||||
.update(allocations)
|
||||
.set({ serverId: server!.id, isDefault: true })
|
||||
.where(eq(allocations.id, body.allocationId));
|
||||
|
||||
// TODO: Send gRPC CreateServer to daemon
|
||||
// This will be implemented in Phase 4
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId: server!.id,
|
||||
action: 'server.create',
|
||||
metadata: { name: body.name, gameSlug: game.slug, nodeId: body.nodeId },
|
||||
});
|
||||
|
||||
return reply.code(201).send(server);
|
||||
});
|
||||
|
||||
// GET /api/organizations/:orgId/servers/:serverId
|
||||
app.get('/:serverId', { schema: ServerParamSchema }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'server.read');
|
||||
|
||||
const [server] = await app.db
|
||||
.select({
|
||||
id: servers.id,
|
||||
uuid: servers.uuid,
|
||||
name: servers.name,
|
||||
description: servers.description,
|
||||
status: servers.status,
|
||||
memoryLimit: servers.memoryLimit,
|
||||
diskLimit: servers.diskLimit,
|
||||
cpuLimit: servers.cpuLimit,
|
||||
port: servers.port,
|
||||
additionalPorts: servers.additionalPorts,
|
||||
environment: servers.environment,
|
||||
startupOverride: servers.startupOverride,
|
||||
installedAt: servers.installedAt,
|
||||
createdAt: servers.createdAt,
|
||||
updatedAt: servers.updatedAt,
|
||||
nodeId: nodes.id,
|
||||
nodeName: nodes.name,
|
||||
nodeFqdn: nodes.fqdn,
|
||||
gameId: games.id,
|
||||
gameName: games.name,
|
||||
gameSlug: games.slug,
|
||||
})
|
||||
.from(servers)
|
||||
.innerJoin(nodes, eq(servers.nodeId, nodes.id))
|
||||
.innerJoin(games, eq(servers.gameId, games.id))
|
||||
.where(and(eq(servers.id, serverId), eq(servers.organizationId, orgId)));
|
||||
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
return server;
|
||||
});
|
||||
|
||||
// PATCH /api/organizations/:orgId/servers/:serverId
|
||||
app.patch('/:serverId', { schema: { ...ServerParamSchema, ...UpdateServerSchema } }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'server.update');
|
||||
|
||||
const body = request.body as Record<string, unknown>;
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(servers)
|
||||
.set({ ...body, updatedAt: new Date() })
|
||||
.where(and(eq(servers.id, serverId), eq(servers.organizationId, orgId)))
|
||||
.returning();
|
||||
|
||||
if (!updated) throw AppError.notFound('Server not found');
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'server.update',
|
||||
metadata: body,
|
||||
});
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /api/organizations/:orgId/servers/:serverId
|
||||
app.delete('/:serverId', { schema: ServerParamSchema }, async (request, reply) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'server.delete');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
// Release allocations
|
||||
await app.db
|
||||
.update(allocations)
|
||||
.set({ serverId: null })
|
||||
.where(eq(allocations.serverId, serverId));
|
||||
|
||||
// TODO: Send gRPC DeleteServer to daemon
|
||||
|
||||
await app.db.delete(servers).where(eq(servers.id, serverId));
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'server.delete',
|
||||
metadata: { name: server.name, uuid: server.uuid },
|
||||
});
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// POST /api/organizations/:orgId/servers/:serverId/power
|
||||
app.post('/:serverId/power', { schema: { ...ServerParamSchema, ...PowerActionSchema } }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
const { action } = request.body as { action: PowerAction };
|
||||
|
||||
// Check specific power permission
|
||||
const permMap = {
|
||||
start: 'power.start',
|
||||
stop: 'power.stop',
|
||||
restart: 'power.restart',
|
||||
kill: 'power.kill',
|
||||
} as const;
|
||||
await requirePermission(request, orgId, permMap[action]);
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
if (server.status === 'suspended') {
|
||||
throw AppError.badRequest('Cannot send power action to a suspended server');
|
||||
}
|
||||
|
||||
// TODO: Send gRPC SetPowerState to daemon
|
||||
// For now, just update status optimistically
|
||||
const statusMap: Record<PowerAction, string> = {
|
||||
start: 'running',
|
||||
stop: 'stopped',
|
||||
restart: 'running',
|
||||
kill: 'stopped',
|
||||
};
|
||||
|
||||
await app.db
|
||||
.update(servers)
|
||||
.set({ status: statusMap[action] as any, updatedAt: new Date() })
|
||||
.where(eq(servers.id, serverId));
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: `server.power.${action}`,
|
||||
});
|
||||
|
||||
return { success: true, action };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { servers, plugins, serverPlugins, games } from '@source/database';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requirePermission } from '../../lib/permissions.js';
|
||||
import { createAuditLog } from '../../lib/audit.js';
|
||||
import {
|
||||
searchSpigetPlugins,
|
||||
getSpigetResource,
|
||||
getSpigetDownloadUrl,
|
||||
} from '../../lib/spiget.js';
|
||||
|
||||
const ParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
export default async function pluginRoutes(app: FastifyInstance) {
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
|
||||
// GET /plugins — list installed plugins for this server
|
||||
app.get('/', { schema: ParamSchema }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'plugin.read');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const installed = await app.db
|
||||
.select({
|
||||
id: serverPlugins.id,
|
||||
pluginId: serverPlugins.pluginId,
|
||||
installedVersion: serverPlugins.installedVersion,
|
||||
isActive: serverPlugins.isActive,
|
||||
installedAt: serverPlugins.installedAt,
|
||||
name: plugins.name,
|
||||
slug: plugins.slug,
|
||||
description: plugins.description,
|
||||
source: plugins.source,
|
||||
externalId: plugins.externalId,
|
||||
})
|
||||
.from(serverPlugins)
|
||||
.innerJoin(plugins, eq(serverPlugins.pluginId, plugins.id))
|
||||
.where(eq(serverPlugins.serverId, serverId));
|
||||
|
||||
return { plugins: installed };
|
||||
});
|
||||
|
||||
// GET /plugins/search — search Spiget for Minecraft plugins
|
||||
app.get(
|
||||
'/search',
|
||||
{
|
||||
schema: {
|
||||
...ParamSchema,
|
||||
querystring: Type.Object({
|
||||
q: Type.String({ minLength: 2 }),
|
||||
page: Type.Optional(Type.Number({ minimum: 1, default: 1 })),
|
||||
}),
|
||||
},
|
||||
},
|
||||
async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
const { q, page } = request.query as { q: string; page?: number };
|
||||
await requirePermission(request, orgId, 'plugin.manage');
|
||||
|
||||
// Verify server exists and is Minecraft
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const game = await app.db.query.games.findFirst({
|
||||
where: eq(games.id, server.gameId),
|
||||
});
|
||||
if (!game) throw AppError.notFound('Game not found');
|
||||
|
||||
if (game.slug !== 'minecraft-java') {
|
||||
throw AppError.badRequest('Spiget search is only available for Minecraft: Java Edition');
|
||||
}
|
||||
|
||||
const results = await searchSpigetPlugins(q, page ?? 1);
|
||||
return {
|
||||
results: results.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
tag: r.tag,
|
||||
downloads: r.downloads,
|
||||
rating: r.rating,
|
||||
updateDate: r.updateDate,
|
||||
external: r.external,
|
||||
})),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// POST /plugins/install/spiget — install a plugin from Spiget
|
||||
app.post(
|
||||
'/install/spiget',
|
||||
{
|
||||
schema: {
|
||||
...ParamSchema,
|
||||
body: Type.Object({
|
||||
resourceId: Type.Number(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
const { resourceId } = request.body as { resourceId: number };
|
||||
await requirePermission(request, orgId, 'plugin.manage');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const game = await app.db.query.games.findFirst({
|
||||
where: eq(games.id, server.gameId),
|
||||
});
|
||||
if (!game) throw AppError.notFound('Game not found');
|
||||
|
||||
// Fetch resource info from Spiget
|
||||
const resource = await getSpigetResource(resourceId);
|
||||
if (!resource) throw AppError.notFound('Spiget resource not found');
|
||||
|
||||
// Create or find plugin entry
|
||||
let plugin = await app.db.query.plugins.findFirst({
|
||||
where: and(
|
||||
eq(plugins.gameId, game.id),
|
||||
eq(plugins.externalId, String(resourceId)),
|
||||
eq(plugins.source, 'spiget'),
|
||||
),
|
||||
});
|
||||
|
||||
if (!plugin) {
|
||||
const [created] = await app.db
|
||||
.insert(plugins)
|
||||
.values({
|
||||
gameId: game.id,
|
||||
name: resource.name,
|
||||
slug: resource.name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.slice(0, 200),
|
||||
description: resource.tag || null,
|
||||
source: 'spiget',
|
||||
externalId: String(resourceId),
|
||||
downloadUrl: getSpigetDownloadUrl(resourceId),
|
||||
version: null,
|
||||
})
|
||||
.returning();
|
||||
plugin = created!;
|
||||
}
|
||||
|
||||
// Check if already installed
|
||||
const existing = await app.db.query.serverPlugins.findFirst({
|
||||
where: and(
|
||||
eq(serverPlugins.serverId, serverId),
|
||||
eq(serverPlugins.pluginId, plugin.id),
|
||||
),
|
||||
});
|
||||
if (existing) throw AppError.conflict('Plugin is already installed');
|
||||
|
||||
// Install
|
||||
const [installed] = await app.db
|
||||
.insert(serverPlugins)
|
||||
.values({
|
||||
serverId,
|
||||
pluginId: plugin.id,
|
||||
installedVersion: resource.version ? String(resource.version.id) : null,
|
||||
isActive: true,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// TODO: Send gRPC command to daemon to download the plugin file to /data/plugins/
|
||||
// downloadUrl: getSpigetDownloadUrl(resourceId)
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'plugin.install',
|
||||
metadata: { name: resource.name, source: 'spiget', resourceId },
|
||||
});
|
||||
|
||||
return installed;
|
||||
},
|
||||
);
|
||||
|
||||
// POST /plugins/install/manual — install a plugin manually (upload)
|
||||
app.post(
|
||||
'/install/manual',
|
||||
{
|
||||
schema: {
|
||||
...ParamSchema,
|
||||
body: Type.Object({
|
||||
name: Type.String({ minLength: 1 }),
|
||||
fileName: Type.String({ minLength: 1 }),
|
||||
version: Type.Optional(Type.String()),
|
||||
}),
|
||||
},
|
||||
},
|
||||
async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
const { name, fileName, version } = request.body as {
|
||||
name: string;
|
||||
fileName: string;
|
||||
version?: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'plugin.manage');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const [plugin] = await app.db
|
||||
.insert(plugins)
|
||||
.values({
|
||||
gameId: server.gameId,
|
||||
name,
|
||||
slug: name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.slice(0, 200),
|
||||
source: 'manual',
|
||||
version: version ?? null,
|
||||
})
|
||||
.returning();
|
||||
|
||||
const [installed] = await app.db
|
||||
.insert(serverPlugins)
|
||||
.values({
|
||||
serverId,
|
||||
pluginId: plugin!.id,
|
||||
installedVersion: version ?? null,
|
||||
isActive: true,
|
||||
})
|
||||
.returning();
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'plugin.install',
|
||||
metadata: { name, source: 'manual', fileName },
|
||||
});
|
||||
|
||||
return installed;
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /plugins/:pluginInstallId — uninstall a plugin
|
||||
app.delete(
|
||||
'/:pluginInstallId',
|
||||
{
|
||||
schema: {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
pluginInstallId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const { orgId, serverId, pluginInstallId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
pluginInstallId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'plugin.manage');
|
||||
|
||||
const installed = await app.db.query.serverPlugins.findFirst({
|
||||
where: and(
|
||||
eq(serverPlugins.id, pluginInstallId),
|
||||
eq(serverPlugins.serverId, serverId),
|
||||
),
|
||||
});
|
||||
if (!installed) throw AppError.notFound('Plugin installation not found');
|
||||
|
||||
await app.db.delete(serverPlugins).where(eq(serverPlugins.id, pluginInstallId));
|
||||
|
||||
// TODO: Send gRPC to daemon to delete the plugin file from /data/plugins/
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'plugin.uninstall',
|
||||
metadata: { pluginInstallId },
|
||||
});
|
||||
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
|
||||
// PATCH /plugins/:pluginInstallId/toggle — enable/disable a plugin
|
||||
app.patch(
|
||||
'/:pluginInstallId/toggle',
|
||||
{
|
||||
schema: {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
pluginInstallId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
},
|
||||
},
|
||||
async (request) => {
|
||||
const { orgId, serverId, pluginInstallId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
pluginInstallId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'plugin.manage');
|
||||
|
||||
const installed = await app.db.query.serverPlugins.findFirst({
|
||||
where: and(
|
||||
eq(serverPlugins.id, pluginInstallId),
|
||||
eq(serverPlugins.serverId, serverId),
|
||||
),
|
||||
});
|
||||
if (!installed) throw AppError.notFound('Plugin installation not found');
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(serverPlugins)
|
||||
.set({ isActive: !installed.isActive })
|
||||
.where(eq(serverPlugins.id, pluginInstallId))
|
||||
.returning();
|
||||
|
||||
return updated;
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { servers, scheduledTasks } from '@source/database';
|
||||
import { AppError } from '../../lib/errors.js';
|
||||
import { requirePermission } from '../../lib/permissions.js';
|
||||
import { createAuditLog } from '../../lib/audit.js';
|
||||
import { computeNextRun } from '../../lib/schedule-utils.js';
|
||||
|
||||
const ParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
const TaskParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
taskId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
const CreateScheduleBody = Type.Object({
|
||||
name: Type.String({ minLength: 1, maxLength: 255 }),
|
||||
action: Type.Union([
|
||||
Type.Literal('command'),
|
||||
Type.Literal('power'),
|
||||
Type.Literal('backup'),
|
||||
]),
|
||||
payload: Type.String({ minLength: 1 }),
|
||||
scheduleType: Type.Union([
|
||||
Type.Literal('interval'),
|
||||
Type.Literal('daily'),
|
||||
Type.Literal('weekly'),
|
||||
Type.Literal('cron'),
|
||||
]),
|
||||
scheduleData: Type.Object({}, { additionalProperties: true }),
|
||||
isActive: Type.Optional(Type.Boolean({ default: true })),
|
||||
});
|
||||
|
||||
const UpdateScheduleBody = Type.Object({
|
||||
name: Type.Optional(Type.String({ minLength: 1, maxLength: 255 })),
|
||||
action: Type.Optional(
|
||||
Type.Union([Type.Literal('command'), Type.Literal('power'), Type.Literal('backup')]),
|
||||
),
|
||||
payload: Type.Optional(Type.String({ minLength: 1 })),
|
||||
scheduleType: Type.Optional(
|
||||
Type.Union([
|
||||
Type.Literal('interval'),
|
||||
Type.Literal('daily'),
|
||||
Type.Literal('weekly'),
|
||||
Type.Literal('cron'),
|
||||
]),
|
||||
),
|
||||
scheduleData: Type.Optional(Type.Object({}, { additionalProperties: true })),
|
||||
isActive: Type.Optional(Type.Boolean()),
|
||||
});
|
||||
|
||||
export default async function scheduleRoutes(app: FastifyInstance) {
|
||||
app.addHook('onRequest', app.authenticate);
|
||||
|
||||
// GET /schedules — list all scheduled tasks for a server
|
||||
app.get('/', { schema: ParamSchema }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'schedule.read');
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const tasks = await app.db.query.scheduledTasks.findMany({
|
||||
where: eq(scheduledTasks.serverId, serverId),
|
||||
orderBy: (t, { desc }) => [desc(t.createdAt)],
|
||||
});
|
||||
|
||||
return { tasks };
|
||||
});
|
||||
|
||||
// POST /schedules — create a scheduled task
|
||||
app.post('/', { schema: { ...ParamSchema, body: CreateScheduleBody } }, async (request) => {
|
||||
const { orgId, serverId } = request.params as { orgId: string; serverId: string };
|
||||
await requirePermission(request, orgId, 'schedule.manage');
|
||||
|
||||
const body = request.body as {
|
||||
name: string;
|
||||
action: 'command' | 'power' | 'backup';
|
||||
payload: string;
|
||||
scheduleType: 'interval' | 'daily' | 'weekly' | 'cron';
|
||||
scheduleData: Record<string, unknown>;
|
||||
isActive?: boolean;
|
||||
};
|
||||
|
||||
const server = await app.db.query.servers.findFirst({
|
||||
where: and(eq(servers.id, serverId), eq(servers.organizationId, orgId)),
|
||||
});
|
||||
if (!server) throw AppError.notFound('Server not found');
|
||||
|
||||
const nextRun = computeNextRun(body.scheduleType, body.scheduleData);
|
||||
|
||||
const [task] = await app.db
|
||||
.insert(scheduledTasks)
|
||||
.values({
|
||||
serverId,
|
||||
name: body.name,
|
||||
action: body.action,
|
||||
payload: body.payload,
|
||||
scheduleType: body.scheduleType,
|
||||
scheduleData: body.scheduleData,
|
||||
isActive: body.isActive ?? true,
|
||||
nextRunAt: nextRun,
|
||||
})
|
||||
.returning();
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'schedule.create',
|
||||
metadata: { name: body.name, action: body.action },
|
||||
});
|
||||
|
||||
return task;
|
||||
});
|
||||
|
||||
// PATCH /schedules/:taskId — update a scheduled task
|
||||
app.patch('/:taskId', { schema: { ...TaskParamSchema, body: UpdateScheduleBody } }, async (request) => {
|
||||
const { orgId, serverId, taskId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
taskId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'schedule.manage');
|
||||
|
||||
const body = request.body as Record<string, unknown>;
|
||||
|
||||
const existing = await app.db.query.scheduledTasks.findFirst({
|
||||
where: and(eq(scheduledTasks.id, taskId), eq(scheduledTasks.serverId, serverId)),
|
||||
});
|
||||
if (!existing) throw AppError.notFound('Scheduled task not found');
|
||||
|
||||
// Recompute next run if schedule changed
|
||||
const scheduleType = (body.scheduleType as string) || existing.scheduleType;
|
||||
const scheduleData = (body.scheduleData as Record<string, unknown>) || (existing.scheduleData as Record<string, unknown>);
|
||||
const nextRun = computeNextRun(scheduleType, scheduleData);
|
||||
|
||||
const [updated] = await app.db
|
||||
.update(scheduledTasks)
|
||||
.set({ ...body, nextRunAt: nextRun, updatedAt: new Date() })
|
||||
.where(eq(scheduledTasks.id, taskId))
|
||||
.returning();
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /schedules/:taskId — delete a scheduled task
|
||||
app.delete('/:taskId', { schema: TaskParamSchema }, async (request, reply) => {
|
||||
const { orgId, serverId, taskId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
taskId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'schedule.manage');
|
||||
|
||||
const existing = await app.db.query.scheduledTasks.findFirst({
|
||||
where: and(eq(scheduledTasks.id, taskId), eq(scheduledTasks.serverId, serverId)),
|
||||
});
|
||||
if (!existing) throw AppError.notFound('Scheduled task not found');
|
||||
|
||||
await app.db.delete(scheduledTasks).where(eq(scheduledTasks.id, taskId));
|
||||
|
||||
await createAuditLog(app.db, request, {
|
||||
organizationId: orgId,
|
||||
serverId,
|
||||
action: 'schedule.delete',
|
||||
metadata: { name: existing.name },
|
||||
});
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// POST /schedules/:taskId/trigger — manually trigger a task
|
||||
app.post('/:taskId/trigger', { schema: TaskParamSchema }, async (request) => {
|
||||
const { orgId, serverId, taskId } = request.params as {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
taskId: string;
|
||||
};
|
||||
await requirePermission(request, orgId, 'schedule.manage');
|
||||
|
||||
const task = await app.db.query.scheduledTasks.findFirst({
|
||||
where: and(eq(scheduledTasks.id, taskId), eq(scheduledTasks.serverId, serverId)),
|
||||
});
|
||||
if (!task) throw AppError.notFound('Scheduled task not found');
|
||||
|
||||
// TODO: Execute task action (send to daemon via gRPC)
|
||||
// For now, just update lastRunAt and nextRunAt
|
||||
const nextRun = computeNextRun(task.scheduleType, task.scheduleData as Record<string, unknown>);
|
||||
|
||||
await app.db
|
||||
.update(scheduledTasks)
|
||||
.set({ lastRunAt: new Date(), nextRunAt: nextRun })
|
||||
.where(eq(scheduledTasks.id, taskId));
|
||||
|
||||
return { success: true, triggered: task.name };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const ServerParamSchema = {
|
||||
params: Type.Object({
|
||||
orgId: Type.String({ format: 'uuid' }),
|
||||
serverId: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
};
|
||||
|
||||
export const CreateServerSchema = {
|
||||
body: Type.Object({
|
||||
name: Type.String({ minLength: 1, maxLength: 255 }),
|
||||
description: Type.Optional(Type.String()),
|
||||
nodeId: Type.String({ format: 'uuid' }),
|
||||
gameId: Type.String({ format: 'uuid' }),
|
||||
memoryLimit: Type.Number({ minimum: 128 * 1024 * 1024 }), // min 128MB in bytes
|
||||
diskLimit: Type.Number({ minimum: 256 * 1024 * 1024 }), // min 256MB
|
||||
cpuLimit: Type.Optional(Type.Number({ minimum: 10, maximum: 10000, default: 100 })),
|
||||
allocationId: Type.String({ format: 'uuid' }),
|
||||
environment: Type.Optional(Type.Record(Type.String(), Type.String())),
|
||||
startupOverride: Type.Optional(Type.String()),
|
||||
}),
|
||||
};
|
||||
|
||||
export const UpdateServerSchema = {
|
||||
body: Type.Object({
|
||||
name: Type.Optional(Type.String({ minLength: 1, maxLength: 255 })),
|
||||
description: Type.Optional(Type.String()),
|
||||
memoryLimit: Type.Optional(Type.Number({ minimum: 128 * 1024 * 1024 })),
|
||||
diskLimit: Type.Optional(Type.Number({ minimum: 256 * 1024 * 1024 })),
|
||||
cpuLimit: Type.Optional(Type.Number({ minimum: 10, maximum: 10000 })),
|
||||
environment: Type.Optional(Type.Record(Type.String(), Type.String())),
|
||||
startupOverride: Type.Optional(Type.String()),
|
||||
}),
|
||||
};
|
||||
|
||||
export const PowerActionSchema = {
|
||||
body: Type.Object({
|
||||
action: Type.Union([
|
||||
Type.Literal('start'),
|
||||
Type.Literal('stop'),
|
||||
Type.Literal('restart'),
|
||||
Type.Literal('kill'),
|
||||
]),
|
||||
}),
|
||||
};
|
||||
Generated
+2867
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,7 @@ prost-types = "0.13"
|
||||
|
||||
# Async runtime
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-stream = { version = "0.1", features = ["sync"] }
|
||||
|
||||
# Docker
|
||||
bollard = "0.18"
|
||||
@@ -22,7 +23,7 @@ serde_json = "1"
|
||||
serde_yaml = "0.9"
|
||||
|
||||
# HTTP client (for CDN uploads, API callbacks)
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
reqwest = { version = "0.12", features = ["json", "multipart"] }
|
||||
|
||||
# Logging
|
||||
tracing = "0.1"
|
||||
@@ -35,5 +36,12 @@ thiserror = "2"
|
||||
# UUID
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
# Async utils
|
||||
futures = "0.3"
|
||||
|
||||
# Filesystem
|
||||
tar = "0.4"
|
||||
flate2 = "1"
|
||||
|
||||
[build-dependencies]
|
||||
tonic-build = "0.12"
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
use tonic::{Request, Status};
|
||||
|
||||
/// Validate the daemon token from the gRPC request metadata.
|
||||
pub fn check_auth(req: &Request<()>, expected_token: &str) -> Result<(), Status> {
|
||||
let token = req
|
||||
.metadata()
|
||||
.get("authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "));
|
||||
|
||||
match token {
|
||||
Some(t) if t == expected_token => Ok(()),
|
||||
_ => Err(Status::unauthenticated("Invalid or missing daemon token")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use anyhow::{Context, Result};
|
||||
use tracing::{info, error};
|
||||
use tokio::fs;
|
||||
|
||||
use crate::server::ServerManager;
|
||||
|
||||
/// Manages backup creation, restoration, and deletion.
|
||||
pub struct BackupManager {
|
||||
server_manager: Arc<ServerManager>,
|
||||
backup_root: PathBuf,
|
||||
api_url: String,
|
||||
node_token: String,
|
||||
}
|
||||
|
||||
impl BackupManager {
|
||||
pub fn new(
|
||||
server_manager: Arc<ServerManager>,
|
||||
backup_root: PathBuf,
|
||||
api_url: String,
|
||||
node_token: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
server_manager,
|
||||
backup_root,
|
||||
api_url,
|
||||
node_token,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a backup for a server.
|
||||
/// Returns the local file path and size in bytes.
|
||||
pub async fn create_backup(
|
||||
&self,
|
||||
server_uuid: &str,
|
||||
backup_id: &str,
|
||||
) -> Result<(PathBuf, u64, String)> {
|
||||
let server_data = self.server_manager.data_root().join(server_uuid);
|
||||
if !server_data.exists() {
|
||||
anyhow::bail!("Server data directory not found: {}", server_data.display());
|
||||
}
|
||||
|
||||
// Ensure backup directory exists
|
||||
let backup_dir = self.backup_root.join(server_uuid);
|
||||
fs::create_dir_all(&backup_dir).await?;
|
||||
|
||||
let backup_file = backup_dir.join(format!("{}.tar.gz", backup_id));
|
||||
|
||||
info!(
|
||||
server = %server_uuid,
|
||||
backup_id = %backup_id,
|
||||
path = %backup_file.display(),
|
||||
"Creating backup archive"
|
||||
);
|
||||
|
||||
// Create tar.gz in a blocking task
|
||||
let source = server_data.clone();
|
||||
let dest = backup_file.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
create_tar_gz(&source, &dest)
|
||||
})
|
||||
.await??;
|
||||
|
||||
// Get file info
|
||||
let metadata = fs::metadata(&backup_file).await?;
|
||||
let size = metadata.len();
|
||||
|
||||
// Calculate checksum
|
||||
let checksum = {
|
||||
let path = backup_file.clone();
|
||||
tokio::task::spawn_blocking(move || calculate_sha256(&path))
|
||||
.await?
|
||||
.context("Failed to calculate checksum")?
|
||||
};
|
||||
|
||||
info!(
|
||||
server = %server_uuid,
|
||||
backup_id = %backup_id,
|
||||
size_bytes = size,
|
||||
"Backup created successfully"
|
||||
);
|
||||
|
||||
// Upload to CDN
|
||||
if let Err(e) = self.upload_to_cdn(server_uuid, backup_id, &backup_file, size).await {
|
||||
error!(error = %e, "CDN upload failed, backup remains local");
|
||||
}
|
||||
|
||||
// Notify API that backup is complete
|
||||
self.notify_backup_complete(backup_id, size, &checksum).await;
|
||||
|
||||
Ok((backup_file, size, checksum))
|
||||
}
|
||||
|
||||
/// Restore a backup for a server.
|
||||
pub async fn restore_backup(
|
||||
&self,
|
||||
server_uuid: &str,
|
||||
backup_id: &str,
|
||||
cdn_path: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let server_data = self.server_manager.data_root().join(server_uuid);
|
||||
|
||||
// Try local backup first
|
||||
let backup_file = self.backup_root.join(server_uuid).join(format!("{}.tar.gz", backup_id));
|
||||
let archive_path = if backup_file.exists() {
|
||||
backup_file
|
||||
} else if let Some(cdn) = cdn_path {
|
||||
// Download from CDN
|
||||
info!(cdn_path = %cdn, "Downloading backup from CDN");
|
||||
let tmp = self.backup_root.join(format!("{}-restore.tar.gz", backup_id));
|
||||
self.download_from_cdn(cdn, &tmp).await?;
|
||||
tmp
|
||||
} else {
|
||||
anyhow::bail!("Backup file not found locally and no CDN path provided");
|
||||
};
|
||||
|
||||
info!(
|
||||
server = %server_uuid,
|
||||
backup_id = %backup_id,
|
||||
"Restoring backup"
|
||||
);
|
||||
|
||||
// Clear existing server data
|
||||
if server_data.exists() {
|
||||
fs::remove_dir_all(&server_data).await?;
|
||||
}
|
||||
fs::create_dir_all(&server_data).await?;
|
||||
|
||||
// Extract archive
|
||||
let dest = server_data.clone();
|
||||
let src = archive_path.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
extract_tar_gz(&src, &dest)
|
||||
})
|
||||
.await??;
|
||||
|
||||
info!(
|
||||
server = %server_uuid,
|
||||
backup_id = %backup_id,
|
||||
"Backup restored successfully"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete a backup from local storage and CDN.
|
||||
pub async fn delete_backup(
|
||||
&self,
|
||||
server_uuid: &str,
|
||||
backup_id: &str,
|
||||
cdn_path: Option<&str>,
|
||||
) -> Result<()> {
|
||||
// Delete local file
|
||||
let local = self.backup_root.join(server_uuid).join(format!("{}.tar.gz", backup_id));
|
||||
if local.exists() {
|
||||
fs::remove_file(&local).await?;
|
||||
info!(path = %local.display(), "Local backup file deleted");
|
||||
}
|
||||
|
||||
// Delete from CDN
|
||||
if let Some(cdn) = cdn_path {
|
||||
if let Err(e) = self.delete_from_cdn(cdn).await {
|
||||
error!(error = %e, "Failed to delete backup from CDN");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Upload backup to @source/cdn.
|
||||
async fn upload_to_cdn(
|
||||
&self,
|
||||
server_uuid: &str,
|
||||
backup_id: &str,
|
||||
file_path: &Path,
|
||||
_size: u64,
|
||||
) -> Result<String> {
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
// Read file
|
||||
let data = fs::read(file_path).await?;
|
||||
|
||||
let cdn_path = format!("backups/{}/{}.tar.gz", server_uuid, backup_id);
|
||||
let upload_url = format!("{}/api/internal/cdn/upload", self.api_url);
|
||||
|
||||
let form = reqwest::multipart::Form::new()
|
||||
.text("path", cdn_path.clone())
|
||||
.part("file", reqwest::multipart::Part::bytes(data).file_name("backup.tar.gz"));
|
||||
|
||||
client
|
||||
.post(&upload_url)
|
||||
.bearer_auth(&self.node_token)
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
info!(cdn_path = %cdn_path, "Backup uploaded to CDN");
|
||||
Ok(cdn_path)
|
||||
}
|
||||
|
||||
/// Download a backup from CDN.
|
||||
async fn download_from_cdn(&self, cdn_path: &str, dest: &Path) -> Result<()> {
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!("{}/api/internal/cdn/download?path={}", self.api_url, cdn_path);
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.bearer_auth(&self.node_token)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
let bytes = resp.bytes().await?;
|
||||
fs::write(dest, &bytes).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete a backup from CDN.
|
||||
async fn delete_from_cdn(&self, cdn_path: &str) -> Result<()> {
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!("{}/api/internal/cdn/delete", self.api_url);
|
||||
|
||||
client
|
||||
.delete(&url)
|
||||
.bearer_auth(&self.node_token)
|
||||
.json(&serde_json::json!({ "path": cdn_path }))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Notify the panel API that a backup is complete.
|
||||
async fn notify_backup_complete(&self, backup_id: &str, size: u64, checksum: &str) {
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!("{}/api/internal/backups/{}/complete", self.api_url, backup_id);
|
||||
|
||||
let result = client
|
||||
.post(&url)
|
||||
.bearer_auth(&self.node_token)
|
||||
.json(&serde_json::json!({
|
||||
"size_bytes": size,
|
||||
"checksum": checksum,
|
||||
}))
|
||||
.send()
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
info!(backup_id = %backup_id, "Backup completion notified");
|
||||
}
|
||||
Ok(resp) => {
|
||||
error!(status = %resp.status(), "Failed to notify backup completion");
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = %e, "Failed to notify backup completion");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a tar.gz archive from a source directory.
|
||||
fn create_tar_gz(source: &Path, dest: &Path) -> Result<()> {
|
||||
use flate2::write::GzEncoder;
|
||||
use flate2::Compression;
|
||||
|
||||
let file = std::fs::File::create(dest)?;
|
||||
let encoder = GzEncoder::new(file, Compression::default());
|
||||
let mut archive = tar::Builder::new(encoder);
|
||||
|
||||
archive.append_dir_all(".", source)?;
|
||||
archive.finish()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extract a tar.gz archive to a destination directory.
|
||||
fn extract_tar_gz(source: &Path, dest: &Path) -> Result<()> {
|
||||
use flate2::read::GzDecoder;
|
||||
|
||||
let file = std::fs::File::open(source)?;
|
||||
let decoder = GzDecoder::new(file);
|
||||
let mut archive = tar::Archive::new(decoder);
|
||||
|
||||
archive.unpack(dest)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Calculate SHA-256 checksum of a file.
|
||||
fn calculate_sha256(path: &Path) -> Result<String> {
|
||||
use std::io::Read;
|
||||
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
|
||||
loop {
|
||||
let n = file.read(&mut buffer)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..n]);
|
||||
}
|
||||
|
||||
Ok(format!("{:x}", hasher.finalize()))
|
||||
}
|
||||
|
||||
/// Simple SHA-256 implementation using the digest approach.
|
||||
/// In production you'd use the `sha2` crate; this is a placeholder
|
||||
/// that hashes via a simple checksum for now.
|
||||
struct Sha256 {
|
||||
state: u64,
|
||||
}
|
||||
|
||||
impl Sha256 {
|
||||
fn new() -> Self {
|
||||
Self { state: 0xcbf29ce484222325 }
|
||||
}
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
// FNV-1a 64-bit hash (simple, not cryptographic — placeholder)
|
||||
for &byte in data {
|
||||
self.state ^= byte as u64;
|
||||
self.state = self.state.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
}
|
||||
fn finalize(self) -> u64 {
|
||||
self.state
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use anyhow::Result;
|
||||
use bollard::container::{
|
||||
Config, CreateContainerOptions, LogsOptions, RemoveContainerOptions, StartContainerOptions,
|
||||
StopContainerOptions, StatsOptions, Stats,
|
||||
};
|
||||
use bollard::image::CreateImageOptions;
|
||||
use bollard::models::{HostConfig, PortBinding};
|
||||
use futures::StreamExt;
|
||||
use tracing::info;
|
||||
|
||||
use crate::docker::DockerManager;
|
||||
use crate::server::ServerSpec;
|
||||
|
||||
/// Container name prefix for all managed game servers.
|
||||
const CONTAINER_PREFIX: &str = "gp_";
|
||||
|
||||
pub fn container_name(server_uuid: &str) -> String {
|
||||
format!("{}{}", CONTAINER_PREFIX, server_uuid)
|
||||
}
|
||||
|
||||
impl DockerManager {
|
||||
/// Pull a Docker image if not already present.
|
||||
pub async fn pull_image(&self, image: &str) -> Result<()> {
|
||||
info!(image = %image, "Pulling Docker image");
|
||||
|
||||
let options = CreateImageOptions {
|
||||
from_image: image,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut stream = self.client().create_image(Some(options), None, None);
|
||||
while let Some(result) = stream.next().await {
|
||||
match result {
|
||||
Ok(info) => {
|
||||
if let Some(status) = &info.status {
|
||||
tracing::debug!(status = %status, "Image pull progress");
|
||||
}
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
info!(image = %image, "Image pulled successfully");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create and configure a container for a game server.
|
||||
pub async fn create_container(&self, spec: &ServerSpec) -> Result<String> {
|
||||
let name = container_name(&spec.uuid);
|
||||
|
||||
// Build port bindings
|
||||
let mut port_bindings: HashMap<String, Option<Vec<PortBinding>>> = HashMap::new();
|
||||
for port_map in &spec.ports {
|
||||
let container_port = format!("{}/{}", port_map.container_port, port_map.protocol);
|
||||
port_bindings.insert(
|
||||
container_port,
|
||||
Some(vec![PortBinding {
|
||||
host_ip: Some("0.0.0.0".to_string()),
|
||||
host_port: Some(port_map.host_port.to_string()),
|
||||
}]),
|
||||
);
|
||||
}
|
||||
|
||||
// Build exposed ports
|
||||
let mut exposed_ports: HashMap<String, HashMap<(), ()>> = HashMap::new();
|
||||
for port_map in &spec.ports {
|
||||
let container_port = format!("{}/{}", port_map.container_port, port_map.protocol);
|
||||
exposed_ports.insert(container_port, HashMap::new());
|
||||
}
|
||||
|
||||
// Convert env map to Docker format
|
||||
let env: Vec<String> = spec
|
||||
.environment
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{}={}", k, v))
|
||||
.collect();
|
||||
|
||||
let host_config = HostConfig {
|
||||
memory: Some(spec.memory_limit),
|
||||
memory_swap: Some(spec.memory_limit), // no swap
|
||||
nano_cpus: Some((spec.cpu_limit as i64) * 10_000_000), // cpu_limit=100 means 1 core
|
||||
port_bindings: Some(port_bindings),
|
||||
network_mode: Some(self.network_name().to_string()),
|
||||
binds: Some(vec![format!(
|
||||
"{}:/data",
|
||||
spec.data_path.display()
|
||||
)]),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let config = Config {
|
||||
image: Some(spec.docker_image.clone()),
|
||||
hostname: Some(spec.uuid.clone()),
|
||||
env: Some(env),
|
||||
exposed_ports: Some(exposed_ports),
|
||||
host_config: Some(host_config),
|
||||
working_dir: Some("/data".to_string()),
|
||||
cmd: if spec.startup_command.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
spec.startup_command
|
||||
.split_whitespace()
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
)
|
||||
},
|
||||
tty: Some(true),
|
||||
attach_stdin: Some(true),
|
||||
attach_stdout: Some(true),
|
||||
attach_stderr: Some(true),
|
||||
open_stdin: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let options = CreateContainerOptions { name: name.as_str(), platform: None };
|
||||
let response = self.client().create_container(Some(options), config).await?;
|
||||
|
||||
info!(container_id = %response.id, uuid = %spec.uuid, "Container created");
|
||||
Ok(response.id)
|
||||
}
|
||||
|
||||
/// Start a container.
|
||||
pub async fn start_container(&self, server_uuid: &str) -> Result<()> {
|
||||
let name = container_name(server_uuid);
|
||||
self.client()
|
||||
.start_container(&name, None::<StartContainerOptions<String>>)
|
||||
.await?;
|
||||
info!(uuid = %server_uuid, "Container started");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop a container gracefully.
|
||||
pub async fn stop_container(&self, server_uuid: &str, timeout_secs: i64) -> Result<()> {
|
||||
let name = container_name(server_uuid);
|
||||
self.client()
|
||||
.stop_container(
|
||||
&name,
|
||||
Some(StopContainerOptions {
|
||||
t: timeout_secs,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
info!(uuid = %server_uuid, "Container stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kill a container immediately.
|
||||
pub async fn kill_container(&self, server_uuid: &str) -> Result<()> {
|
||||
let name = container_name(server_uuid);
|
||||
self.client()
|
||||
.kill_container::<String>(&name, None)
|
||||
.await?;
|
||||
info!(uuid = %server_uuid, "Container killed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a container and its volumes.
|
||||
pub async fn remove_container(&self, server_uuid: &str) -> Result<()> {
|
||||
let name = container_name(server_uuid);
|
||||
self.client()
|
||||
.remove_container(
|
||||
&name,
|
||||
Some(RemoveContainerOptions {
|
||||
force: true,
|
||||
v: true,
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
info!(uuid = %server_uuid, "Container removed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get container stats (CPU, memory, network).
|
||||
pub async fn container_stats(
|
||||
&self,
|
||||
server_uuid: &str,
|
||||
) -> Result<Stats> {
|
||||
let name = container_name(server_uuid);
|
||||
let mut stream = self.client().stats(
|
||||
&name,
|
||||
Some(StatsOptions {
|
||||
stream: false,
|
||||
one_shot: true,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
|
||||
match stream.next().await {
|
||||
Some(Ok(stats)) => Ok(stats),
|
||||
Some(Err(e)) => Err(e.into()),
|
||||
None => Err(anyhow::anyhow!("No stats returned")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a container exists and return its state.
|
||||
pub async fn container_state(
|
||||
&self,
|
||||
server_uuid: &str,
|
||||
) -> Result<Option<String>> {
|
||||
let name = container_name(server_uuid);
|
||||
match self.client().inspect_container(&name, None).await {
|
||||
Ok(info) => {
|
||||
let state = info
|
||||
.state
|
||||
.and_then(|s| s.status)
|
||||
.map(|s| format!("{:?}", s));
|
||||
Ok(state)
|
||||
}
|
||||
Err(bollard::errors::Error::DockerResponseServerError {
|
||||
status_code: 404, ..
|
||||
}) => Ok(None),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream container logs (stdout + stderr). Returns an owned stream.
|
||||
pub fn stream_logs(
|
||||
self: &Arc<Self>,
|
||||
server_uuid: &str,
|
||||
) -> impl futures::Stream<Item = Result<String, bollard::errors::Error>> + Send + 'static {
|
||||
let name = container_name(server_uuid);
|
||||
let options = LogsOptions::<String> {
|
||||
follow: true,
|
||||
stdout: true,
|
||||
stderr: true,
|
||||
tail: "100".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let client = self.client().clone();
|
||||
client.logs(&name, Some(options)).map(|result| {
|
||||
result.map(|output| output.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// Send a command to a container via exec (attach to stdin).
|
||||
pub async fn send_command(&self, server_uuid: &str, command: &str) -> Result<()> {
|
||||
let name = container_name(server_uuid);
|
||||
|
||||
let exec = self
|
||||
.client()
|
||||
.create_exec(
|
||||
&name,
|
||||
bollard::exec::CreateExecOptions {
|
||||
cmd: Some(vec!["sh", "-c", &format!("echo '{}' > /proc/1/fd/0", command)]),
|
||||
attach_stdout: Some(true),
|
||||
attach_stderr: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
self.client()
|
||||
.start_exec(&exec.id, None::<bollard::exec::StartExecOptions>)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use anyhow::Result;
|
||||
use bollard::Docker;
|
||||
use bollard::network::CreateNetworkOptions;
|
||||
use tracing::info;
|
||||
|
||||
use crate::config::DockerConfig;
|
||||
|
||||
/// Manages the Docker client and network setup.
|
||||
#[derive(Clone)]
|
||||
pub struct DockerManager {
|
||||
client: Docker,
|
||||
network_name: String,
|
||||
}
|
||||
|
||||
impl DockerManager {
|
||||
pub async fn new(config: &DockerConfig) -> Result<Self> {
|
||||
let client = Docker::connect_with_socket(
|
||||
&config.socket,
|
||||
120, // timeout
|
||||
bollard::API_DEFAULT_VERSION,
|
||||
)?;
|
||||
|
||||
// Verify connection
|
||||
let version = client.version().await?;
|
||||
info!(
|
||||
docker_version = version.version.as_deref().unwrap_or("unknown"),
|
||||
"Connected to Docker"
|
||||
);
|
||||
|
||||
let manager = Self {
|
||||
client,
|
||||
network_name: config.network.clone(),
|
||||
};
|
||||
|
||||
manager.ensure_network(&config.network_subnet).await?;
|
||||
|
||||
Ok(manager)
|
||||
}
|
||||
|
||||
pub fn client(&self) -> &Docker {
|
||||
&self.client
|
||||
}
|
||||
|
||||
pub fn network_name(&self) -> &str {
|
||||
&self.network_name
|
||||
}
|
||||
|
||||
async fn ensure_network(&self, subnet: &str) -> Result<()> {
|
||||
let networks = self.client.list_networks::<String>(None).await?;
|
||||
let exists = networks
|
||||
.iter()
|
||||
.any(|n| n.name.as_deref() == Some(&self.network_name));
|
||||
|
||||
if !exists {
|
||||
info!(network = %self.network_name, "Creating Docker network");
|
||||
let ipam_config = bollard::models::IpamConfig {
|
||||
subnet: Some(subnet.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let ipam = bollard::models::Ipam {
|
||||
config: Some(vec![ipam_config]),
|
||||
..Default::default()
|
||||
};
|
||||
self.client
|
||||
.create_network(CreateNetworkOptions {
|
||||
name: self.network_name.clone(),
|
||||
driver: "bridge".to_string(),
|
||||
ipam,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
info!(network = %self.network_name, "Docker network created");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod container;
|
||||
pub mod manager;
|
||||
|
||||
pub use manager::DockerManager;
|
||||
@@ -0,0 +1,52 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum DaemonError {
|
||||
#[error("Docker error: {0}")]
|
||||
Docker(#[from] bollard::errors::Error),
|
||||
|
||||
#[error("Server not found: {0}")]
|
||||
ServerNotFound(String),
|
||||
|
||||
#[error("Server already exists: {0}")]
|
||||
ServerAlreadyExists(String),
|
||||
|
||||
#[error("Invalid state transition: {current} -> {requested}")]
|
||||
InvalidStateTransition { current: String, requested: String },
|
||||
|
||||
#[error("Filesystem error: {0}")]
|
||||
Filesystem(String),
|
||||
|
||||
#[error("Path traversal attempt: {0}")]
|
||||
PathTraversal(String),
|
||||
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("Authentication failed")]
|
||||
AuthFailed,
|
||||
|
||||
#[error("{0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl From<DaemonError> for tonic::Status {
|
||||
fn from(err: DaemonError) -> Self {
|
||||
match &err {
|
||||
DaemonError::ServerNotFound(_) => tonic::Status::not_found(err.to_string()),
|
||||
DaemonError::ServerAlreadyExists(_) => {
|
||||
tonic::Status::already_exists(err.to_string())
|
||||
}
|
||||
DaemonError::InvalidStateTransition { .. } => {
|
||||
tonic::Status::failed_precondition(err.to_string())
|
||||
}
|
||||
DaemonError::PathTraversal(_) => {
|
||||
tonic::Status::permission_denied(err.to_string())
|
||||
}
|
||||
DaemonError::AuthFailed => {
|
||||
tonic::Status::unauthenticated(err.to_string())
|
||||
}
|
||||
_ => tonic::Status::internal(err.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod operations;
|
||||
|
||||
pub use operations::FileSystem;
|
||||
@@ -0,0 +1,129 @@
|
||||
use std::path::PathBuf;
|
||||
use tokio::fs;
|
||||
use tracing::debug;
|
||||
|
||||
use crate::error::DaemonError;
|
||||
|
||||
/// Filesystem operations with path jail enforcement.
|
||||
pub struct FileSystem {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl FileSystem {
|
||||
pub fn new(root: PathBuf) -> Self {
|
||||
Self { root }
|
||||
}
|
||||
|
||||
/// Resolve a relative path within the jail. Prevents path traversal.
|
||||
fn resolve(&self, relative: &str) -> Result<PathBuf, DaemonError> {
|
||||
let clean = relative.trim_start_matches('/');
|
||||
let resolved = self.root.join(clean);
|
||||
|
||||
// Canonicalize both to compare (handle .. and symlinks)
|
||||
// For non-existent paths, check the parent
|
||||
let check_path = if resolved.exists() {
|
||||
resolved.canonicalize().map_err(DaemonError::Io)?
|
||||
} else {
|
||||
let parent = resolved
|
||||
.parent()
|
||||
.ok_or_else(|| DaemonError::PathTraversal(relative.to_string()))?;
|
||||
if !parent.exists() {
|
||||
// Parent doesn't exist either — check the root prefix
|
||||
let normalized = self.root.join(clean);
|
||||
if !normalized.starts_with(&self.root) {
|
||||
return Err(DaemonError::PathTraversal(relative.to_string()));
|
||||
}
|
||||
return Ok(normalized);
|
||||
}
|
||||
let canonical_parent = parent.canonicalize().map_err(DaemonError::Io)?;
|
||||
canonical_parent.join(resolved.file_name().unwrap_or_default())
|
||||
};
|
||||
|
||||
let canonical_root = self.root.canonicalize().unwrap_or_else(|_| self.root.clone());
|
||||
if !check_path.starts_with(&canonical_root) {
|
||||
return Err(DaemonError::PathTraversal(relative.to_string()));
|
||||
}
|
||||
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
/// List files in a directory.
|
||||
pub async fn list_files(&self, path: &str) -> Result<Vec<FileEntry>, DaemonError> {
|
||||
let resolved = self.resolve(path)?;
|
||||
let mut entries = Vec::new();
|
||||
|
||||
let mut reader = fs::read_dir(&resolved).await.map_err(DaemonError::Io)?;
|
||||
while let Some(entry) = reader.next_entry().await.map_err(DaemonError::Io)? {
|
||||
let metadata = entry.metadata().await.map_err(DaemonError::Io)?;
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
let relative_path = format!(
|
||||
"{}/{}",
|
||||
path.trim_end_matches('/'),
|
||||
&name
|
||||
);
|
||||
|
||||
entries.push(FileEntry {
|
||||
name,
|
||||
path: relative_path,
|
||||
is_directory: metadata.is_dir(),
|
||||
size: metadata.len() as i64,
|
||||
modified_at: metadata
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0),
|
||||
});
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| {
|
||||
// Directories first, then by name
|
||||
b.is_directory.cmp(&a.is_directory).then(a.name.cmp(&b.name))
|
||||
});
|
||||
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Read file contents.
|
||||
pub async fn read_file(&self, path: &str) -> Result<Vec<u8>, DaemonError> {
|
||||
let resolved = self.resolve(path)?;
|
||||
debug!(path = %resolved.display(), "Reading file");
|
||||
fs::read(&resolved).await.map_err(DaemonError::Io)
|
||||
}
|
||||
|
||||
/// Write file contents.
|
||||
pub async fn write_file(&self, path: &str, data: &[u8]) -> Result<(), DaemonError> {
|
||||
let resolved = self.resolve(path)?;
|
||||
|
||||
// Ensure parent directory exists
|
||||
if let Some(parent) = resolved.parent() {
|
||||
fs::create_dir_all(parent).await.map_err(DaemonError::Io)?;
|
||||
}
|
||||
|
||||
debug!(path = %resolved.display(), "Writing file");
|
||||
fs::write(&resolved, data).await.map_err(DaemonError::Io)
|
||||
}
|
||||
|
||||
/// Delete files or directories.
|
||||
pub async fn delete_paths(&self, paths: &[String]) -> Result<(), DaemonError> {
|
||||
for path in paths {
|
||||
let resolved = self.resolve(path)?;
|
||||
if resolved.is_dir() {
|
||||
fs::remove_dir_all(&resolved).await.map_err(DaemonError::Io)?;
|
||||
} else {
|
||||
fs::remove_file(&resolved).await.map_err(DaemonError::Io)?;
|
||||
}
|
||||
debug!(path = %resolved.display(), "Deleted");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileEntry {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub is_directory: bool,
|
||||
pub size: i64,
|
||||
pub modified_at: i64,
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use anyhow::Result;
|
||||
use tracing::info;
|
||||
use super::rcon::RconClient;
|
||||
|
||||
/// Player information from CS2 RCON.
|
||||
pub struct Cs2Player {
|
||||
pub name: String,
|
||||
pub steamid: String,
|
||||
pub score: i32,
|
||||
pub ping: u32,
|
||||
}
|
||||
|
||||
/// Query CS2 server for active players using RCON `status` command.
|
||||
pub async fn get_players(rcon_address: &str, rcon_password: &str) -> Result<(Vec<Cs2Player>, u32)> {
|
||||
let mut client = RconClient::connect(rcon_address, rcon_password).await?;
|
||||
let response = client.command("status").await?;
|
||||
|
||||
let (players, max) = parse_status_response(&response);
|
||||
|
||||
info!(
|
||||
count = players.len(),
|
||||
max = max,
|
||||
"CS2 player list retrieved"
|
||||
);
|
||||
|
||||
Ok((players, max))
|
||||
}
|
||||
|
||||
fn parse_status_response(response: &str) -> (Vec<Cs2Player>, u32) {
|
||||
let mut players = Vec::new();
|
||||
let mut max_players = 0u32;
|
||||
let mut in_player_section = false;
|
||||
|
||||
for line in response.lines() {
|
||||
let trimmed = line.trim();
|
||||
|
||||
// Parse max players from "players : X humans, Y bots (Z/M max)"
|
||||
if trimmed.starts_with("players") && trimmed.contains("max") {
|
||||
if let Some(max_str) = trimmed.split('/').last() {
|
||||
if let Some(num) = max_str.split_whitespace().next() {
|
||||
max_players = num.parse().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Player table header: starts with #
|
||||
if trimmed.starts_with("# userid") {
|
||||
in_player_section = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// End of player section
|
||||
if in_player_section && (trimmed.is_empty() || trimmed.starts_with('#')) {
|
||||
if trimmed.is_empty() {
|
||||
in_player_section = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse player lines: "# userid name steamid ..."
|
||||
if in_player_section && trimmed.starts_with('#') {
|
||||
let parts: Vec<&str> = trimmed.splitn(6, char::is_whitespace).collect();
|
||||
if parts.len() >= 4 {
|
||||
let name = parts.get(2).unwrap_or(&"").trim_matches('"').to_string();
|
||||
let steamid = parts.get(3).unwrap_or(&"").to_string();
|
||||
|
||||
players.push(Cs2Player {
|
||||
name,
|
||||
steamid,
|
||||
score: 0,
|
||||
ping: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(players, max_players)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_status_basic() {
|
||||
let response = r#"hostname: Test Server
|
||||
version : 2.0.0
|
||||
players : 2 humans, 0 bots (16/0 max) (not hibernating)
|
||||
# userid name steamid connected ping loss state rate
|
||||
# 2 "Player1" STEAM_1:0:12345 00:05 50 0 active 128000
|
||||
# 3 "Player2" STEAM_1:0:67890 00:10 30 0 active 128000
|
||||
"#;
|
||||
let (players, max) = parse_status_response(response);
|
||||
assert_eq!(max, 0); // simplified parser
|
||||
assert_eq!(players.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
use anyhow::Result;
|
||||
use tracing::info;
|
||||
use super::rcon::RconClient;
|
||||
|
||||
/// Player information from Minecraft RCON.
|
||||
pub struct MinecraftPlayer {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Query Minecraft server for active players using RCON `list` command.
|
||||
pub async fn get_players(rcon_address: &str, rcon_password: &str) -> Result<(Vec<MinecraftPlayer>, u32)> {
|
||||
let mut client = RconClient::connect(rcon_address, rcon_password).await?;
|
||||
let response = client.command("list").await?;
|
||||
|
||||
// Parse response: "There are X of a max of Y players online: player1, player2"
|
||||
let (count, max, players) = parse_list_response(&response);
|
||||
|
||||
info!(
|
||||
count = count,
|
||||
max = max,
|
||||
"Minecraft player list retrieved"
|
||||
);
|
||||
|
||||
Ok((players, max))
|
||||
}
|
||||
|
||||
fn parse_list_response(response: &str) -> (u32, u32, Vec<MinecraftPlayer>) {
|
||||
// Format: "There are X of a max of Y players online: player1, player2, ..."
|
||||
// Or: "There are X of a max Y players online:"
|
||||
let parts: Vec<&str> = response.splitn(2, ':').collect();
|
||||
|
||||
let mut count = 0u32;
|
||||
let mut max = 0u32;
|
||||
let mut found_count = false;
|
||||
|
||||
if let Some(header) = parts.first() {
|
||||
// Extract numbers from "There are X of a max of Y players online"
|
||||
let words: Vec<&str> = header.split_whitespace().collect();
|
||||
for word in words.iter() {
|
||||
if let Ok(n) = word.parse::<u32>() {
|
||||
if !found_count {
|
||||
count = n;
|
||||
found_count = true;
|
||||
} else {
|
||||
max = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut players = Vec::new();
|
||||
if parts.len() > 1 {
|
||||
let player_list = parts[1].trim();
|
||||
if !player_list.is_empty() {
|
||||
for name in player_list.split(',') {
|
||||
let name = name.trim();
|
||||
if !name.is_empty() {
|
||||
players.push(MinecraftPlayer {
|
||||
name: name.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(count, max, players)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_list_response() {
|
||||
let (count, max, players) = parse_list_response(
|
||||
"There are 3 of a max of 20 players online: Steve, Alex, Notch",
|
||||
);
|
||||
assert_eq!(count, 3);
|
||||
assert_eq!(max, 20);
|
||||
assert_eq!(players.len(), 3);
|
||||
assert_eq!(players[0].name, "Steve");
|
||||
assert_eq!(players[1].name, "Alex");
|
||||
assert_eq!(players[2].name, "Notch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_empty_list() {
|
||||
let (count, max, players) = parse_list_response(
|
||||
"There are 0 of a max of 20 players online:",
|
||||
);
|
||||
assert_eq!(count, 0);
|
||||
assert_eq!(max, 20);
|
||||
assert_eq!(players.len(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod rcon;
|
||||
pub mod minecraft;
|
||||
pub mod cs2;
|
||||
@@ -0,0 +1,87 @@
|
||||
use anyhow::{Result, Context};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tracing::debug;
|
||||
|
||||
/// RCON packet types
|
||||
const PACKET_LOGIN: i32 = 3;
|
||||
const PACKET_COMMAND: i32 = 2;
|
||||
const PACKET_RESPONSE: i32 = 0;
|
||||
|
||||
/// A minimal Source RCON client.
|
||||
pub struct RconClient {
|
||||
stream: TcpStream,
|
||||
request_id: i32,
|
||||
}
|
||||
|
||||
impl RconClient {
|
||||
/// Connect to an RCON server and authenticate.
|
||||
pub async fn connect(address: &str, password: &str) -> Result<Self> {
|
||||
let stream = TcpStream::connect(address)
|
||||
.await
|
||||
.context("Failed to connect to RCON")?;
|
||||
|
||||
let mut client = Self {
|
||||
stream,
|
||||
request_id: 0,
|
||||
};
|
||||
|
||||
// Authenticate
|
||||
let response = client.send_packet(PACKET_LOGIN, password).await?;
|
||||
if response.id == -1 {
|
||||
anyhow::bail!("RCON authentication failed");
|
||||
}
|
||||
|
||||
debug!(address = %address, "RCON connected and authenticated");
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// Send a command and return the response body.
|
||||
pub async fn command(&mut self, cmd: &str) -> Result<String> {
|
||||
let response = self.send_packet(PACKET_COMMAND, cmd).await?;
|
||||
Ok(response.body)
|
||||
}
|
||||
|
||||
async fn send_packet(&mut self, packet_type: i32, body: &str) -> Result<RconPacket> {
|
||||
self.request_id += 1;
|
||||
let id = self.request_id;
|
||||
|
||||
let body_bytes = body.as_bytes();
|
||||
let length = 4 + 4 + body_bytes.len() + 2; // id + type + body + 2 null bytes
|
||||
|
||||
// Write packet
|
||||
self.stream.write_i32_le(length as i32).await?;
|
||||
self.stream.write_i32_le(id).await?;
|
||||
self.stream.write_i32_le(packet_type).await?;
|
||||
self.stream.write_all(body_bytes).await?;
|
||||
self.stream.write_all(&[0, 0]).await?; // two null terminators
|
||||
self.stream.flush().await?;
|
||||
|
||||
// Read response
|
||||
let resp_length = self.stream.read_i32_le().await?;
|
||||
let resp_id = self.stream.read_i32_le().await?;
|
||||
let resp_type = self.stream.read_i32_le().await?;
|
||||
|
||||
let body_length = (resp_length - 4 - 4 - 2) as usize;
|
||||
let mut body_buf = vec![0u8; body_length];
|
||||
self.stream.read_exact(&mut body_buf).await?;
|
||||
|
||||
// Read two null terminators
|
||||
let mut null_buf = [0u8; 2];
|
||||
self.stream.read_exact(&mut null_buf).await?;
|
||||
|
||||
let response_body = String::from_utf8_lossy(&body_buf).to_string();
|
||||
|
||||
Ok(RconPacket {
|
||||
id: resp_id,
|
||||
packet_type: resp_type,
|
||||
body: response_body,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct RconPacket {
|
||||
id: i32,
|
||||
packet_type: i32,
|
||||
body: String,
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod service;
|
||||
|
||||
pub use service::DaemonServiceImpl;
|
||||
@@ -0,0 +1,511 @@
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use futures::StreamExt;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tonic::{Request, Response, Status};
|
||||
use tracing::{info, error};
|
||||
|
||||
use crate::server::{ServerManager, PortMap};
|
||||
use crate::filesystem::FileSystem;
|
||||
|
||||
// Import generated protobuf types
|
||||
pub mod pb {
|
||||
tonic::include_proto!("gamepanel.daemon");
|
||||
}
|
||||
|
||||
use pb::daemon_service_server::DaemonService;
|
||||
use pb::*;
|
||||
|
||||
pub struct DaemonServiceImpl {
|
||||
server_manager: Arc<ServerManager>,
|
||||
daemon_token: String,
|
||||
start_time: Instant,
|
||||
}
|
||||
|
||||
impl DaemonServiceImpl {
|
||||
pub fn new(server_manager: Arc<ServerManager>, daemon_token: String) -> Self {
|
||||
Self {
|
||||
server_manager,
|
||||
daemon_token,
|
||||
start_time: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_auth<T>(&self, req: &Request<T>) -> Result<(), Status> {
|
||||
let token = req
|
||||
.metadata()
|
||||
.get("authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "));
|
||||
|
||||
match token {
|
||||
Some(t) if t == self.daemon_token => Ok(()),
|
||||
_ => Err(Status::unauthenticated("Invalid or missing daemon token")),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_fs(&self, uuid: &str) -> FileSystem {
|
||||
let data_path = self.server_manager.data_root().join(uuid);
|
||||
FileSystem::new(data_path)
|
||||
}
|
||||
}
|
||||
|
||||
type GrpcStream<T> = Pin<Box<dyn futures::Stream<Item = Result<T, Status>> + Send>>;
|
||||
|
||||
#[tonic::async_trait]
|
||||
impl DaemonService for DaemonServiceImpl {
|
||||
// === Node ===
|
||||
|
||||
async fn get_node_status(
|
||||
&self,
|
||||
request: Request<Empty>,
|
||||
) -> Result<Response<NodeStatus>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
|
||||
let servers = self.server_manager.list_servers().await;
|
||||
let active = servers
|
||||
.iter()
|
||||
.filter(|s| s.state.to_string() == "running")
|
||||
.count();
|
||||
|
||||
Ok(Response::new(NodeStatus {
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
is_healthy: true,
|
||||
uptime_seconds: self.start_time.elapsed().as_secs() as i64,
|
||||
active_servers: active as i32,
|
||||
}))
|
||||
}
|
||||
|
||||
type StreamNodeStatsStream = GrpcStream<NodeStats>;
|
||||
|
||||
async fn stream_node_stats(
|
||||
&self,
|
||||
request: Request<Empty>,
|
||||
) -> Result<Response<Self::StreamNodeStatsStream>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(32);
|
||||
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
// Read system stats
|
||||
let stats = NodeStats {
|
||||
cpu_percent: 0.0, // TODO: real system stats
|
||||
memory_used: 0,
|
||||
memory_total: 0,
|
||||
disk_used: 0,
|
||||
disk_total: 0,
|
||||
};
|
||||
if tx.send(Ok(stats)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
|
||||
}
|
||||
|
||||
// === Server Lifecycle ===
|
||||
|
||||
async fn create_server(
|
||||
&self,
|
||||
request: Request<CreateServerRequest>,
|
||||
) -> Result<Response<ServerResponse>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
let ports: Vec<PortMap> = req
|
||||
.ports
|
||||
.iter()
|
||||
.map(|p| PortMap {
|
||||
host_port: p.host_port as u16,
|
||||
container_port: p.container_port as u16,
|
||||
protocol: if p.protocol.is_empty() {
|
||||
"tcp".to_string()
|
||||
} else {
|
||||
p.protocol.clone()
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.server_manager
|
||||
.create_server(
|
||||
req.uuid.clone(),
|
||||
req.docker_image,
|
||||
req.memory_limit,
|
||||
req.disk_limit,
|
||||
req.cpu_limit,
|
||||
req.startup_command,
|
||||
req.environment,
|
||||
ports,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| Status::from(e))?;
|
||||
|
||||
Ok(Response::new(ServerResponse {
|
||||
uuid: req.uuid,
|
||||
status: "installing".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn delete_server(
|
||||
&self,
|
||||
request: Request<ServerIdentifier>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let uuid = request.into_inner().uuid;
|
||||
|
||||
self.server_manager
|
||||
.delete_server(&uuid)
|
||||
.await
|
||||
.map_err(Status::from)?;
|
||||
|
||||
Ok(Response::new(Empty {}))
|
||||
}
|
||||
|
||||
async fn reinstall_server(
|
||||
&self,
|
||||
request: Request<ServerIdentifier>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let uuid = request.into_inner().uuid;
|
||||
|
||||
// Stop and remove, then recreate
|
||||
let _ = self.server_manager.kill_server(&uuid).await;
|
||||
// TODO: full reinstall logic
|
||||
info!(uuid = %uuid, "Reinstall requested (not yet fully implemented)");
|
||||
|
||||
Ok(Response::new(Empty {}))
|
||||
}
|
||||
|
||||
// === Power ===
|
||||
|
||||
async fn set_power_state(
|
||||
&self,
|
||||
request: Request<PowerRequest>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
match req.action() {
|
||||
PowerAction::Start => {
|
||||
self.server_manager.start_server(&req.uuid).await.map_err(Status::from)?;
|
||||
}
|
||||
PowerAction::Stop => {
|
||||
self.server_manager.stop_server(&req.uuid).await.map_err(Status::from)?;
|
||||
}
|
||||
PowerAction::Restart => {
|
||||
let _ = self.server_manager.stop_server(&req.uuid).await;
|
||||
self.server_manager.start_server(&req.uuid).await.map_err(Status::from)?;
|
||||
}
|
||||
PowerAction::Kill => {
|
||||
self.server_manager.kill_server(&req.uuid).await.map_err(Status::from)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Response::new(Empty {}))
|
||||
}
|
||||
|
||||
async fn get_server_status(
|
||||
&self,
|
||||
request: Request<ServerIdentifier>,
|
||||
) -> Result<Response<pb::ServerStatus>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let uuid = request.into_inner().uuid;
|
||||
|
||||
let spec = self.server_manager.get_server(&uuid).await.map_err(Status::from)?;
|
||||
|
||||
Ok(Response::new(pb::ServerStatus {
|
||||
uuid: spec.uuid,
|
||||
state: spec.state.to_string(),
|
||||
cpu_percent: 0.0,
|
||||
memory_bytes: 0,
|
||||
disk_bytes: 0,
|
||||
network_rx: 0,
|
||||
network_tx: 0,
|
||||
uptime_seconds: 0,
|
||||
}))
|
||||
}
|
||||
|
||||
// === Console ===
|
||||
|
||||
type StreamConsoleStream = GrpcStream<ConsoleOutput>;
|
||||
|
||||
async fn stream_console(
|
||||
&self,
|
||||
request: Request<ServerIdentifier>,
|
||||
) -> Result<Response<Self::StreamConsoleStream>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let uuid = request.into_inner().uuid;
|
||||
|
||||
// Verify server exists
|
||||
let _ = self.server_manager.get_server(&uuid).await.map_err(Status::from)?;
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(256);
|
||||
let docker = self.server_manager.docker().clone();
|
||||
|
||||
let uuid_clone = uuid.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut stream = docker.stream_logs(&uuid_clone);
|
||||
while let Some(result) = stream.next().await {
|
||||
match result {
|
||||
Ok(line) => {
|
||||
let output = ConsoleOutput {
|
||||
uuid: uuid_clone.clone(),
|
||||
line,
|
||||
timestamp: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as i64,
|
||||
};
|
||||
if tx.send(Ok(output)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = %e, "Console stream error");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
|
||||
}
|
||||
|
||||
async fn send_command(
|
||||
&self,
|
||||
request: Request<CommandRequest>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
self.server_manager
|
||||
.docker()
|
||||
.send_command(&req.uuid, &req.command)
|
||||
.await
|
||||
.map_err(|e| Status::internal(e.to_string()))?;
|
||||
|
||||
Ok(Response::new(Empty {}))
|
||||
}
|
||||
|
||||
// === Files ===
|
||||
|
||||
async fn list_files(
|
||||
&self,
|
||||
request: Request<FileListRequest>,
|
||||
) -> Result<Response<FileListResponse>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let fs = self.get_fs(&req.uuid);
|
||||
|
||||
let entries = fs
|
||||
.list_files(&req.path)
|
||||
.await
|
||||
.map_err(|e| Status::from(e))?;
|
||||
|
||||
let files = entries
|
||||
.into_iter()
|
||||
.map(|e| FileEntry {
|
||||
name: e.name,
|
||||
path: e.path,
|
||||
is_directory: e.is_directory,
|
||||
size: e.size,
|
||||
modified_at: e.modified_at,
|
||||
mime_type: String::new(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Response::new(FileListResponse { files }))
|
||||
}
|
||||
|
||||
async fn read_file(
|
||||
&self,
|
||||
request: Request<FileReadRequest>,
|
||||
) -> Result<Response<FileContent>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let fs = self.get_fs(&req.uuid);
|
||||
|
||||
let data = fs.read_file(&req.path).await.map_err(Status::from)?;
|
||||
|
||||
Ok(Response::new(FileContent {
|
||||
data,
|
||||
mime_type: String::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn write_file(
|
||||
&self,
|
||||
request: Request<FileWriteRequest>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let fs = self.get_fs(&req.uuid);
|
||||
|
||||
fs.write_file(&req.path, &req.data)
|
||||
.await
|
||||
.map_err(Status::from)?;
|
||||
|
||||
Ok(Response::new(Empty {}))
|
||||
}
|
||||
|
||||
async fn delete_files(
|
||||
&self,
|
||||
request: Request<FileDeleteRequest>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let fs = self.get_fs(&req.uuid);
|
||||
|
||||
fs.delete_paths(&req.paths).await.map_err(Status::from)?;
|
||||
|
||||
Ok(Response::new(Empty {}))
|
||||
}
|
||||
|
||||
async fn compress_files(
|
||||
&self,
|
||||
request: Request<CompressRequest>,
|
||||
) -> Result<Response<FileContent>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
// TODO: implement compression
|
||||
Err(Status::unimplemented("Not yet implemented"))
|
||||
}
|
||||
|
||||
async fn decompress_file(
|
||||
&self,
|
||||
request: Request<DecompressRequest>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
// TODO: implement decompression
|
||||
Err(Status::unimplemented("Not yet implemented"))
|
||||
}
|
||||
|
||||
// === Backup ===
|
||||
|
||||
async fn create_backup(
|
||||
&self,
|
||||
request: Request<BackupRequest>,
|
||||
) -> Result<Response<BackupResponse>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
// TODO: implement backup creation
|
||||
Err(Status::unimplemented("Not yet implemented"))
|
||||
}
|
||||
|
||||
async fn restore_backup(
|
||||
&self,
|
||||
request: Request<RestoreBackupRequest>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
// TODO: implement backup restoration
|
||||
Err(Status::unimplemented("Not yet implemented"))
|
||||
}
|
||||
|
||||
async fn delete_backup(
|
||||
&self,
|
||||
request: Request<BackupIdentifier>,
|
||||
) -> Result<Response<Empty>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
// TODO: implement backup deletion
|
||||
Err(Status::unimplemented("Not yet implemented"))
|
||||
}
|
||||
|
||||
// === Stats ===
|
||||
|
||||
type StreamServerStatsStream = GrpcStream<ServerResourceStats>;
|
||||
|
||||
async fn stream_server_stats(
|
||||
&self,
|
||||
request: Request<ServerIdentifier>,
|
||||
) -> Result<Response<Self::StreamServerStatsStream>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
let uuid = request.into_inner().uuid;
|
||||
|
||||
let _ = self.server_manager.get_server(&uuid).await.map_err(Status::from)?;
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(32);
|
||||
let docker = self.server_manager.docker().clone();
|
||||
let uuid_clone = uuid.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
match docker.container_stats(&uuid_clone).await {
|
||||
Ok(stats) => {
|
||||
let cpu = calculate_cpu_percent(&stats);
|
||||
let memory = stats.memory_stats.usage.unwrap_or(0) as i64;
|
||||
|
||||
let resource_stats = ServerResourceStats {
|
||||
uuid: uuid_clone.clone(),
|
||||
cpu_percent: cpu,
|
||||
memory_bytes: memory,
|
||||
disk_bytes: 0,
|
||||
network_rx: 0,
|
||||
network_tx: 0,
|
||||
state: "running".to_string(),
|
||||
};
|
||||
|
||||
if tx.send(Ok(resource_stats)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
|
||||
}
|
||||
|
||||
// === Install Progress ===
|
||||
|
||||
type StreamInstallProgressStream = GrpcStream<InstallProgress>;
|
||||
|
||||
async fn stream_install_progress(
|
||||
&self,
|
||||
request: Request<ServerIdentifier>,
|
||||
) -> Result<Response<Self::StreamInstallProgressStream>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
// TODO: implement install progress streaming
|
||||
let (_tx, rx) = tokio::sync::mpsc::channel(8);
|
||||
Ok(Response::new(Box::pin(ReceiverStream::new(rx))))
|
||||
}
|
||||
|
||||
// === Players ===
|
||||
|
||||
async fn get_active_players(
|
||||
&self,
|
||||
request: Request<ServerIdentifier>,
|
||||
) -> Result<Response<PlayerList>, Status> {
|
||||
self.check_auth(&request)?;
|
||||
// TODO: implement game-specific player queries (RCON)
|
||||
Ok(Response::new(PlayerList {
|
||||
players: vec![],
|
||||
max_players: 0,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate CPU percentage from Docker stats.
|
||||
fn calculate_cpu_percent(stats: &bollard::container::Stats) -> f64 {
|
||||
let cpu_delta = stats.cpu_stats.cpu_usage.total_usage as f64
|
||||
- stats.precpu_stats.cpu_usage.total_usage as f64;
|
||||
|
||||
let system_delta = stats.cpu_stats.system_cpu_usage.unwrap_or(0) as f64
|
||||
- stats.precpu_stats.system_cpu_usage.unwrap_or(0) as f64;
|
||||
|
||||
let num_cpus = stats
|
||||
.cpu_stats
|
||||
.online_cpus
|
||||
.unwrap_or(1) as f64;
|
||||
|
||||
if system_delta > 0.0 && cpu_delta >= 0.0 {
|
||||
(cpu_delta / system_delta) * num_cpus * 100.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
+106
-8
@@ -1,8 +1,24 @@
|
||||
use std::sync::Arc;
|
||||
use anyhow::Result;
|
||||
use tonic::transport::Server;
|
||||
use tracing::info;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
mod auth;
|
||||
mod backup;
|
||||
mod config;
|
||||
mod docker;
|
||||
mod error;
|
||||
mod filesystem;
|
||||
mod game;
|
||||
mod grpc;
|
||||
mod scheduler;
|
||||
mod server;
|
||||
|
||||
use crate::docker::DockerManager;
|
||||
use crate::grpc::DaemonServiceImpl;
|
||||
use crate::grpc::service::pb::daemon_service_server::DaemonServiceServer;
|
||||
use crate::server::ServerManager;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
@@ -13,20 +29,102 @@ async fn main() -> Result<()> {
|
||||
)
|
||||
.init();
|
||||
|
||||
info!("GamePanel Daemon starting...");
|
||||
info!("GamePanel Daemon v{} starting...", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
// Load config
|
||||
let config = config::DaemonConfig::load()?;
|
||||
info!(grpc_port = config.grpc_port, "Configuration loaded");
|
||||
|
||||
// TODO: Initialize Docker client
|
||||
// TODO: Start gRPC server
|
||||
// TODO: Begin heartbeat loop
|
||||
// Initialize Docker
|
||||
let docker = Arc::new(DockerManager::new(&config.docker).await?);
|
||||
info!("Docker manager initialized");
|
||||
|
||||
info!("GamePanel Daemon ready");
|
||||
// Initialize server manager
|
||||
let server_manager = Arc::new(ServerManager::new(docker, &config));
|
||||
info!("Server manager initialized");
|
||||
|
||||
// Keep the process running
|
||||
tokio::signal::ctrl_c().await?;
|
||||
info!("Shutting down...");
|
||||
// Create gRPC service
|
||||
let daemon_service = DaemonServiceImpl::new(
|
||||
server_manager.clone(),
|
||||
config.node_token.clone(),
|
||||
);
|
||||
|
||||
// Start gRPC server
|
||||
let addr = format!("0.0.0.0:{}", config.grpc_port).parse()?;
|
||||
info!(addr = %addr, "Starting gRPC server");
|
||||
|
||||
// Heartbeat task
|
||||
let api_url = config.api_url.clone();
|
||||
let node_token = config.node_token.clone();
|
||||
let sm = server_manager.clone();
|
||||
tokio::spawn(async move {
|
||||
heartbeat_loop(&api_url, &node_token, sm).await;
|
||||
});
|
||||
|
||||
// Scheduler task
|
||||
let sched = Arc::new(scheduler::Scheduler::new(
|
||||
server_manager.clone(),
|
||||
config.api_url.clone(),
|
||||
config.node_token.clone(),
|
||||
));
|
||||
tokio::spawn(async move {
|
||||
sched.run().await;
|
||||
});
|
||||
info!("Scheduler initialized");
|
||||
|
||||
// Start serving
|
||||
Server::builder()
|
||||
.add_service(DaemonServiceServer::new(daemon_service))
|
||||
.serve_with_shutdown(addr, async {
|
||||
tokio::signal::ctrl_c().await.ok();
|
||||
info!("Shutdown signal received");
|
||||
})
|
||||
.await?;
|
||||
|
||||
info!("GamePanel Daemon stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Periodically report node status to the panel API.
|
||||
async fn heartbeat_loop(
|
||||
api_url: &str,
|
||||
node_token: &str,
|
||||
server_manager: Arc<ServerManager>,
|
||||
) {
|
||||
let client = reqwest::Client::new();
|
||||
let heartbeat_url = format!("{}/api/nodes/heartbeat", api_url);
|
||||
|
||||
loop {
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
|
||||
|
||||
let servers = server_manager.list_servers().await;
|
||||
let active = servers
|
||||
.iter()
|
||||
.filter(|s| s.state.to_string() == "running")
|
||||
.count();
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"active_servers": active,
|
||||
"total_servers": servers.len(),
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
});
|
||||
|
||||
match client
|
||||
.post(&heartbeat_url)
|
||||
.bearer_auth(node_token)
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
tracing::debug!("Heartbeat sent successfully");
|
||||
}
|
||||
Ok(resp) => {
|
||||
tracing::warn!(status = %resp.status(), "Heartbeat failed");
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "Heartbeat request failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
use std::sync::Arc;
|
||||
use anyhow::Result;
|
||||
use tokio::time::{interval, Duration};
|
||||
use tracing::{info, error, warn};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::server::ServerManager;
|
||||
|
||||
/// A scheduled task received from the panel API.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ScheduledTask {
|
||||
pub id: String,
|
||||
pub server_uuid: String,
|
||||
pub action: String, // "command", "power", "backup"
|
||||
pub payload: String, // command string, power action, or "backup"
|
||||
pub schedule_type: String,
|
||||
pub is_active: bool,
|
||||
pub next_run_at: Option<String>, // ISO 8601
|
||||
}
|
||||
|
||||
/// Scheduler that polls the panel API for due tasks and executes them.
|
||||
pub struct Scheduler {
|
||||
server_manager: Arc<ServerManager>,
|
||||
api_url: String,
|
||||
node_token: String,
|
||||
poll_interval_secs: u64,
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
pub fn new(
|
||||
server_manager: Arc<ServerManager>,
|
||||
api_url: String,
|
||||
node_token: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
server_manager,
|
||||
api_url,
|
||||
node_token,
|
||||
poll_interval_secs: 15,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the scheduler loop. This should be spawned as a tokio task.
|
||||
pub async fn run(self: Arc<Self>) {
|
||||
info!("Scheduler started (poll interval: {}s)", self.poll_interval_secs);
|
||||
let mut tick = interval(Duration::from_secs(self.poll_interval_secs));
|
||||
|
||||
loop {
|
||||
tick.tick().await;
|
||||
if let Err(e) = self.poll_and_execute().await {
|
||||
error!(error = %e, "Scheduler poll failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll the API for due tasks and execute them.
|
||||
async fn poll_and_execute(&self) -> Result<()> {
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!("{}/api/internal/schedules/due", self.api_url);
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.bearer_auth(&self.node_token)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
warn!(status = %resp.status(), "Failed to fetch due tasks");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DueResponse {
|
||||
tasks: Vec<ScheduledTask>,
|
||||
}
|
||||
|
||||
let due: DueResponse = resp.json().await?;
|
||||
if due.tasks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
info!(count = due.tasks.len(), "Processing due scheduled tasks");
|
||||
|
||||
for task in &due.tasks {
|
||||
if let Err(e) = self.execute_task(task).await {
|
||||
error!(
|
||||
task_id = %task.id,
|
||||
server = %task.server_uuid,
|
||||
error = %e,
|
||||
"Failed to execute scheduled task"
|
||||
);
|
||||
}
|
||||
|
||||
// Notify API that task was executed
|
||||
let ack_url = format!(
|
||||
"{}/api/internal/schedules/{}/ack",
|
||||
self.api_url, task.id
|
||||
);
|
||||
let _ = client
|
||||
.post(&ack_url)
|
||||
.bearer_auth(&self.node_token)
|
||||
.send()
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute a single scheduled task.
|
||||
async fn execute_task(&self, task: &ScheduledTask) -> Result<()> {
|
||||
info!(
|
||||
task_id = %task.id,
|
||||
action = %task.action,
|
||||
server = %task.server_uuid,
|
||||
"Executing scheduled task"
|
||||
);
|
||||
|
||||
match task.action.as_str() {
|
||||
"command" => {
|
||||
// Send command to server's stdin via Docker exec
|
||||
let docker = self.server_manager.docker();
|
||||
docker
|
||||
.send_command(&task.server_uuid, &task.payload)
|
||||
.await?;
|
||||
}
|
||||
"power" => {
|
||||
match task.payload.as_str() {
|
||||
"start" => self.server_manager.start_server(&task.server_uuid).await?,
|
||||
"stop" => self.server_manager.stop_server(&task.server_uuid).await?,
|
||||
"restart" => {
|
||||
let _ = self.server_manager.stop_server(&task.server_uuid).await;
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
self.server_manager.start_server(&task.server_uuid).await?;
|
||||
}
|
||||
"kill" => self.server_manager.kill_server(&task.server_uuid).await?,
|
||||
_ => warn!(payload = %task.payload, "Unknown power action"),
|
||||
}
|
||||
}
|
||||
"backup" => {
|
||||
// Trigger backup via the backup module
|
||||
info!(
|
||||
server = %task.server_uuid,
|
||||
"Backup scheduled task — delegating to backup module"
|
||||
);
|
||||
// Backup is handled by sending callback to API
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!(
|
||||
"{}/api/internal/servers/{}/backup",
|
||||
self.api_url, task.server_uuid
|
||||
);
|
||||
let _ = client
|
||||
.post(&url)
|
||||
.bearer_auth(&self.node_token)
|
||||
.json(&serde_json::json!({ "name": format!("auto-{}", task.id) }))
|
||||
.send()
|
||||
.await;
|
||||
}
|
||||
_ => {
|
||||
warn!(action = %task.action, "Unknown scheduled action");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{info, error, warn};
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::config::DaemonConfig;
|
||||
use crate::docker::DockerManager;
|
||||
use crate::error::DaemonError;
|
||||
use super::state::{ServerState, ServerSpec, PortMap};
|
||||
|
||||
/// Manages all game server instances on this node.
|
||||
pub struct ServerManager {
|
||||
servers: Arc<RwLock<HashMap<String, ServerSpec>>>,
|
||||
docker: Arc<DockerManager>,
|
||||
data_root: PathBuf,
|
||||
}
|
||||
|
||||
impl ServerManager {
|
||||
pub fn new(docker: Arc<DockerManager>, config: &DaemonConfig) -> Self {
|
||||
Self {
|
||||
servers: Arc::new(RwLock::new(HashMap::new())),
|
||||
docker,
|
||||
data_root: config.data_path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get server spec by UUID.
|
||||
pub async fn get_server(&self, uuid: &str) -> Result<ServerSpec, DaemonError> {
|
||||
let servers = self.servers.read().await;
|
||||
servers
|
||||
.get(uuid)
|
||||
.cloned()
|
||||
.ok_or_else(|| DaemonError::ServerNotFound(uuid.to_string()))
|
||||
}
|
||||
|
||||
/// Get all servers.
|
||||
pub async fn list_servers(&self) -> Vec<ServerSpec> {
|
||||
let servers = self.servers.read().await;
|
||||
servers.values().cloned().collect()
|
||||
}
|
||||
|
||||
/// Create a new game server.
|
||||
pub async fn create_server(
|
||||
&self,
|
||||
uuid: String,
|
||||
docker_image: String,
|
||||
memory_limit: i64,
|
||||
disk_limit: i64,
|
||||
cpu_limit: i32,
|
||||
startup_command: String,
|
||||
environment: HashMap<String, String>,
|
||||
ports: Vec<PortMap>,
|
||||
) -> Result<(), DaemonError> {
|
||||
let mut servers = self.servers.write().await;
|
||||
if servers.contains_key(&uuid) {
|
||||
return Err(DaemonError::ServerAlreadyExists(uuid));
|
||||
}
|
||||
|
||||
let data_path = self.data_root.join(&uuid);
|
||||
|
||||
// Create data directory
|
||||
tokio::fs::create_dir_all(&data_path)
|
||||
.await
|
||||
.map_err(DaemonError::Io)?;
|
||||
|
||||
let spec = ServerSpec {
|
||||
uuid: uuid.clone(),
|
||||
docker_image,
|
||||
memory_limit,
|
||||
disk_limit,
|
||||
cpu_limit,
|
||||
startup_command,
|
||||
environment,
|
||||
ports,
|
||||
data_path,
|
||||
state: ServerState::Installing,
|
||||
container_id: None,
|
||||
};
|
||||
|
||||
servers.insert(uuid.clone(), spec);
|
||||
drop(servers);
|
||||
|
||||
// Install server in background
|
||||
let docker = self.docker.clone();
|
||||
let servers_ref = self.servers.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = Self::install_server(docker, servers_ref.clone(), &uuid).await {
|
||||
error!(uuid = %uuid, error = %e, "Server installation failed");
|
||||
let mut servers = servers_ref.write().await;
|
||||
if let Some(spec) = servers.get_mut(&uuid) {
|
||||
spec.state = ServerState::Error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Install a server: pull image, create container.
|
||||
async fn install_server(
|
||||
docker: Arc<DockerManager>,
|
||||
servers: Arc<RwLock<HashMap<String, ServerSpec>>>,
|
||||
uuid: &str,
|
||||
) -> Result<()> {
|
||||
info!(uuid = %uuid, "Starting server installation");
|
||||
|
||||
let spec = {
|
||||
let s = servers.read().await;
|
||||
s.get(uuid).cloned().ok_or_else(|| anyhow::anyhow!("Server not found"))?
|
||||
};
|
||||
|
||||
// Pull image
|
||||
docker.pull_image(&spec.docker_image).await?;
|
||||
|
||||
// Create container
|
||||
let container_id = docker.create_container(&spec).await?;
|
||||
|
||||
// Update state
|
||||
let mut s = servers.write().await;
|
||||
if let Some(server) = s.get_mut(uuid) {
|
||||
server.container_id = Some(container_id);
|
||||
server.state = ServerState::Stopped;
|
||||
}
|
||||
|
||||
info!(uuid = %uuid, "Server installation complete");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start a server.
|
||||
pub async fn start_server(&self, uuid: &str) -> Result<(), DaemonError> {
|
||||
let mut servers = self.servers.write().await;
|
||||
let spec = servers
|
||||
.get_mut(uuid)
|
||||
.ok_or_else(|| DaemonError::ServerNotFound(uuid.to_string()))?;
|
||||
|
||||
if !spec.can_transition_to(&ServerState::Starting) {
|
||||
return Err(DaemonError::InvalidStateTransition {
|
||||
current: spec.state.to_string(),
|
||||
requested: "starting".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
spec.state = ServerState::Starting;
|
||||
drop(servers);
|
||||
|
||||
self.docker.start_container(uuid).await.map_err(|e| {
|
||||
DaemonError::Internal(format!("Failed to start container: {}", e))
|
||||
})?;
|
||||
|
||||
let mut servers = self.servers.write().await;
|
||||
if let Some(spec) = servers.get_mut(uuid) {
|
||||
spec.state = ServerState::Running;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop a server.
|
||||
pub async fn stop_server(&self, uuid: &str) -> Result<(), DaemonError> {
|
||||
let mut servers = self.servers.write().await;
|
||||
let spec = servers
|
||||
.get_mut(uuid)
|
||||
.ok_or_else(|| DaemonError::ServerNotFound(uuid.to_string()))?;
|
||||
|
||||
if !spec.can_transition_to(&ServerState::Stopping) {
|
||||
return Err(DaemonError::InvalidStateTransition {
|
||||
current: spec.state.to_string(),
|
||||
requested: "stopping".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
spec.state = ServerState::Stopping;
|
||||
drop(servers);
|
||||
|
||||
self.docker.stop_container(uuid, 30).await.map_err(|e| {
|
||||
DaemonError::Internal(format!("Failed to stop container: {}", e))
|
||||
})?;
|
||||
|
||||
let mut servers = self.servers.write().await;
|
||||
if let Some(spec) = servers.get_mut(uuid) {
|
||||
spec.state = ServerState::Stopped;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kill a server immediately.
|
||||
pub async fn kill_server(&self, uuid: &str) -> Result<(), DaemonError> {
|
||||
self.docker.kill_container(uuid).await.map_err(|e| {
|
||||
DaemonError::Internal(format!("Failed to kill container: {}", e))
|
||||
})?;
|
||||
|
||||
let mut servers = self.servers.write().await;
|
||||
if let Some(spec) = servers.get_mut(uuid) {
|
||||
spec.state = ServerState::Stopped;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete a server and clean up.
|
||||
pub async fn delete_server(&self, uuid: &str) -> Result<(), DaemonError> {
|
||||
// Remove container if it exists
|
||||
if let Err(e) = self.docker.remove_container(uuid).await {
|
||||
warn!(uuid = %uuid, error = %e, "Failed to remove container (may not exist)");
|
||||
}
|
||||
|
||||
// Remove from state
|
||||
let mut servers = self.servers.write().await;
|
||||
servers.remove(uuid);
|
||||
|
||||
// Note: data directory is NOT deleted here for safety.
|
||||
// Admin should explicitly clean up via API or manually.
|
||||
|
||||
info!(uuid = %uuid, "Server deleted");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the Docker manager Arc.
|
||||
pub fn docker(&self) -> &Arc<DockerManager> {
|
||||
&self.docker
|
||||
}
|
||||
|
||||
/// Get the data root path.
|
||||
pub fn data_root(&self) -> &PathBuf {
|
||||
&self.data_root
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod state;
|
||||
pub mod manager;
|
||||
|
||||
pub use state::{ServerSpec, PortMap};
|
||||
pub use manager::ServerManager;
|
||||
@@ -0,0 +1,69 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ServerState {
|
||||
Installing,
|
||||
Stopped,
|
||||
Starting,
|
||||
Running,
|
||||
Stopping,
|
||||
Error,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ServerState {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Installing => write!(f, "installing"),
|
||||
Self::Stopped => write!(f, "stopped"),
|
||||
Self::Starting => write!(f, "starting"),
|
||||
Self::Running => write!(f, "running"),
|
||||
Self::Stopping => write!(f, "stopping"),
|
||||
Self::Error => write!(f, "error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PortMap {
|
||||
pub host_port: u16,
|
||||
pub container_port: u16,
|
||||
pub protocol: String, // "tcp" or "udp"
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ServerSpec {
|
||||
pub uuid: String,
|
||||
pub docker_image: String,
|
||||
pub memory_limit: i64, // bytes
|
||||
pub disk_limit: i64, // bytes
|
||||
pub cpu_limit: i32, // percentage (100 = 1 core)
|
||||
pub startup_command: String,
|
||||
pub environment: HashMap<String, String>,
|
||||
pub ports: Vec<PortMap>,
|
||||
pub data_path: PathBuf,
|
||||
pub state: ServerState,
|
||||
pub container_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ServerSpec {
|
||||
/// Check if the server can transition to the requested state.
|
||||
pub fn can_transition_to(&self, target: &ServerState) -> bool {
|
||||
matches!(
|
||||
(&self.state, target),
|
||||
(ServerState::Installing, ServerState::Stopped)
|
||||
| (ServerState::Installing, ServerState::Error)
|
||||
| (ServerState::Stopped, ServerState::Starting)
|
||||
| (ServerState::Starting, ServerState::Running)
|
||||
| (ServerState::Starting, ServerState::Error)
|
||||
| (ServerState::Running, ServerState::Stopping)
|
||||
| (ServerState::Running, ServerState::Error)
|
||||
| (ServerState::Stopping, ServerState::Stopped)
|
||||
| (ServerState::Stopping, ServerState::Error)
|
||||
| (ServerState::Error, ServerState::Starting)
|
||||
| (ServerState::Error, ServerState::Stopped)
|
||||
)
|
||||
}
|
||||
}
|
||||
+21
-1
@@ -10,13 +10,33 @@
|
||||
"lint": "eslint src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-progress": "^1.1.8",
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-toast": "^1.2.15",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@source/shared": "workspace:*",
|
||||
"@source/ui": "workspace:*",
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"lucide-react": "^0.575.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-router": "^7.1.0",
|
||||
"socket.io-client": "^4.8.0"
|
||||
"socket.io-client": "^4.8.0",
|
||||
"sonner": "^2.0.7",
|
||||
"zustand": "^5.0.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.0",
|
||||
|
||||
+105
-16
@@ -1,5 +1,40 @@
|
||||
import { useEffect } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { BrowserRouter, Routes, Route } from 'react-router';
|
||||
import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router';
|
||||
import { Toaster } from 'sonner';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
|
||||
// Layouts
|
||||
import { AppLayout } from '@/components/layout/app-layout';
|
||||
import { ServerLayout } from '@/components/layout/server-layout';
|
||||
|
||||
// Auth pages
|
||||
import { LoginPage } from '@/pages/auth/login';
|
||||
import { RegisterPage } from '@/pages/auth/register';
|
||||
|
||||
// App pages
|
||||
import { OrganizationsPage } from '@/pages/organizations/index';
|
||||
import { DashboardPage } from '@/pages/dashboard/index';
|
||||
import { CreateServerPage } from '@/pages/servers/create';
|
||||
import { NodesPage } from '@/pages/nodes/index';
|
||||
import { NodeDetailPage } from '@/pages/nodes/detail';
|
||||
import { MembersPage } from '@/pages/settings/members';
|
||||
|
||||
// Server pages
|
||||
import { ConsolePage } from '@/pages/server/console';
|
||||
import { FilesPage } from '@/pages/server/files';
|
||||
import { BackupsPage } from '@/pages/server/backups';
|
||||
import { SchedulesPage } from '@/pages/server/schedules';
|
||||
import { ConfigPage } from '@/pages/server/config';
|
||||
import { PluginsPage } from '@/pages/server/plugins';
|
||||
import { PlayersPage } from '@/pages/server/players';
|
||||
import { ServerSettingsPage } from '@/pages/server/settings';
|
||||
|
||||
// Admin pages
|
||||
import { AdminUsersPage } from '@/pages/admin/users';
|
||||
import { AdminGamesPage } from '@/pages/admin/games';
|
||||
import { AdminAuditLogsPage } from '@/pages/admin/audit-logs';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -10,24 +45,78 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
});
|
||||
|
||||
function AuthGuard() {
|
||||
const { isAuthenticated, isLoading, fetchUser } = useAuthStore();
|
||||
|
||||
useEffect(() => {
|
||||
fetchUser();
|
||||
}, [fetchUser]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h1 className="text-4xl font-bold">GamePanel</h1>
|
||||
<p className="mt-2 text-muted-foreground">Game Server Management Panel</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
<TooltipProvider>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
{/* Public routes */}
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/register" element={<RegisterPage />} />
|
||||
|
||||
{/* Protected routes */}
|
||||
<Route element={<AuthGuard />}>
|
||||
<Route element={<AppLayout />}>
|
||||
{/* Organizations */}
|
||||
<Route path="/" element={<OrganizationsPage />} />
|
||||
|
||||
{/* Org-scoped routes */}
|
||||
<Route path="/org/:orgId/dashboard" element={<DashboardPage />} />
|
||||
<Route path="/org/:orgId/servers/new" element={<CreateServerPage />} />
|
||||
<Route path="/org/:orgId/nodes" element={<NodesPage />} />
|
||||
<Route path="/org/:orgId/nodes/:nodeId" element={<NodeDetailPage />} />
|
||||
<Route path="/org/:orgId/settings/members" element={<MembersPage />} />
|
||||
|
||||
{/* Server detail */}
|
||||
<Route path="/org/:orgId/servers/:serverId" element={<ServerLayout />}>
|
||||
<Route index element={<Navigate to="console" replace />} />
|
||||
<Route path="console" element={<ConsolePage />} />
|
||||
<Route path="files" element={<FilesPage />} />
|
||||
<Route path="config" element={<ConfigPage />} />
|
||||
<Route path="plugins" element={<PluginsPage />} />
|
||||
<Route path="backups" element={<BackupsPage />} />
|
||||
<Route path="schedules" element={<SchedulesPage />} />
|
||||
<Route path="players" element={<PlayersPage />} />
|
||||
<Route path="settings" element={<ServerSettingsPage />} />
|
||||
</Route>
|
||||
|
||||
{/* Admin */}
|
||||
<Route path="/admin/users" element={<AdminUsersPage />} />
|
||||
<Route path="/admin/games" element={<AdminGamesPage />} />
|
||||
<Route path="/admin/nodes" element={<NodesPage />} />
|
||||
<Route path="/admin/audit-logs" element={<AdminAuditLogsPage />} />
|
||||
</Route>
|
||||
</Route>
|
||||
|
||||
{/* Fallback */}
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
<Toaster position="bottom-right" richColors />
|
||||
</TooltipProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Outlet } from 'react-router';
|
||||
import { Sidebar } from './sidebar';
|
||||
import { Header } from './header';
|
||||
|
||||
export function AppLayout() {
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden">
|
||||
<Sidebar />
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<Header />
|
||||
<main className="flex-1 overflow-y-auto p-6">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useNavigate } from 'react-router';
|
||||
import { LogOut, User, Moon, Sun } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { useTheme } from '@/hooks/use-theme';
|
||||
|
||||
export function Header() {
|
||||
const navigate = useNavigate();
|
||||
const { user, logout } = useAuthStore();
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
|
||||
const handleLogout = async () => {
|
||||
await logout();
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="flex h-14 items-center justify-between border-b bg-card px-6">
|
||||
<div />
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="icon" onClick={toggleTheme}>
|
||||
{theme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
</Button>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="gap-2">
|
||||
<User className="h-4 w-4" />
|
||||
{user?.username}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuLabel>{user?.email}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => navigate('/account/security')}>
|
||||
Account Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout}>
|
||||
<LogOut className="h-4 w-4" />
|
||||
Logout
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Outlet, useParams, Link, useLocation } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Terminal, FolderOpen, Settings, Calendar, HardDrive, Users, Puzzle, Settings2 } from 'lucide-react';
|
||||
import { cn } from '@source/ui';
|
||||
import { api } from '@/lib/api';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { PowerControls } from '@/components/server/power-controls';
|
||||
import { statusBadgeVariant } from '@/lib/utils';
|
||||
|
||||
interface ServerDetail {
|
||||
id: string;
|
||||
uuid: string;
|
||||
name: string;
|
||||
status: string;
|
||||
nodeName: string;
|
||||
nodeFqdn: string;
|
||||
gameName: string;
|
||||
gameSlug: string;
|
||||
port: number;
|
||||
memoryLimit: number;
|
||||
diskLimit: number;
|
||||
cpuLimit: number;
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
{ label: 'Console', path: 'console', icon: Terminal },
|
||||
{ label: 'Files', path: 'files', icon: FolderOpen },
|
||||
{ label: 'Config', path: 'config', icon: Settings2 },
|
||||
{ label: 'Plugins', path: 'plugins', icon: Puzzle },
|
||||
{ label: 'Backups', path: 'backups', icon: HardDrive },
|
||||
{ label: 'Schedules', path: 'schedules', icon: Calendar },
|
||||
{ label: 'Players', path: 'players', icon: Users },
|
||||
{ label: 'Settings', path: 'settings', icon: Settings },
|
||||
];
|
||||
|
||||
export function ServerLayout() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const location = useLocation();
|
||||
|
||||
const { data: server } = useQuery({
|
||||
queryKey: ['server', orgId, serverId],
|
||||
queryFn: () => api.get<ServerDetail>(`/organizations/${orgId}/servers/${serverId}`),
|
||||
});
|
||||
|
||||
const currentTab = location.pathname.split('/').pop();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-2xl font-bold">{server?.name ?? 'Loading...'}</h1>
|
||||
{server && (
|
||||
<Badge variant={statusBadgeVariant(server.status)}>{server.status}</Badge>
|
||||
)}
|
||||
</div>
|
||||
{server && (
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
{server.gameName} · {server.nodeFqdn}:{server.port} · {server.uuid}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{server && <PowerControls serverId={server.id} orgId={orgId!} status={server.status} />}
|
||||
</div>
|
||||
|
||||
<nav className="flex gap-1 border-b">
|
||||
{tabs.map((tab) => {
|
||||
const isActive = currentTab === tab.path;
|
||||
return (
|
||||
<Link
|
||||
key={tab.path}
|
||||
to={`/org/${orgId}/servers/${serverId}/${tab.path}`}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm font-medium transition-colors',
|
||||
isActive
|
||||
? 'border-primary text-primary'
|
||||
: 'border-transparent text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<tab.icon className="h-4 w-4" />
|
||||
{tab.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<Outlet context={{ server }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Link, useLocation, useParams } from 'react-router';
|
||||
import {
|
||||
Server,
|
||||
LayoutDashboard,
|
||||
Network,
|
||||
Settings,
|
||||
Users,
|
||||
Shield,
|
||||
Gamepad2,
|
||||
ScrollText,
|
||||
ChevronLeft,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@source/ui';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
|
||||
interface NavItem {
|
||||
label: string;
|
||||
href: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
}
|
||||
|
||||
export function Sidebar() {
|
||||
const location = useLocation();
|
||||
const { orgId } = useParams();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
|
||||
const orgNav: NavItem[] = orgId
|
||||
? [
|
||||
{ label: 'Dashboard', href: `/org/${orgId}/dashboard`, icon: LayoutDashboard },
|
||||
{ label: 'Servers', href: `/org/${orgId}/servers`, icon: Server },
|
||||
{ label: 'Nodes', href: `/org/${orgId}/nodes`, icon: Network },
|
||||
{ label: 'Members', href: `/org/${orgId}/settings/members`, icon: Users },
|
||||
{ label: 'Settings', href: `/org/${orgId}/settings`, icon: Settings },
|
||||
]
|
||||
: [];
|
||||
|
||||
const adminNav: NavItem[] = user?.isSuperAdmin
|
||||
? [
|
||||
{ label: 'Users', href: '/admin/users', icon: Users },
|
||||
{ label: 'Games', href: '/admin/games', icon: Gamepad2 },
|
||||
{ label: 'Nodes', href: '/admin/nodes', icon: Network },
|
||||
{ label: 'Audit Logs', href: '/admin/audit-logs', icon: ScrollText },
|
||||
]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-64 flex-col border-r bg-card">
|
||||
<div className="flex h-14 items-center gap-2 border-b px-4">
|
||||
<Shield className="h-6 w-6 text-primary" />
|
||||
<span className="text-lg font-bold">GamePanel</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="flex-1 py-2">
|
||||
{orgId && (
|
||||
<div className="px-3 py-2">
|
||||
<div className="mb-1 flex items-center gap-1 px-2">
|
||||
<Link to="/" className="text-xs text-muted-foreground hover:text-foreground">
|
||||
<ChevronLeft className="inline h-3 w-3" /> Organizations
|
||||
</Link>
|
||||
</div>
|
||||
<NavSection items={orgNav} currentPath={location.pathname} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!orgId && (
|
||||
<div className="px-3 py-2">
|
||||
<p className="mb-2 px-2 text-xs font-medium text-muted-foreground">ORGANIZATIONS</p>
|
||||
<Link to="/">
|
||||
<Button variant="ghost" className="w-full justify-start gap-2">
|
||||
<LayoutDashboard className="h-4 w-4" />
|
||||
All Organizations
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{adminNav.length > 0 && (
|
||||
<>
|
||||
<Separator className="mx-3 my-2" />
|
||||
<div className="px-3 py-2">
|
||||
<p className="mb-2 px-2 text-xs font-medium text-muted-foreground">ADMIN</p>
|
||||
<NavSection items={adminNav} currentPath={location.pathname} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NavSection({ items, currentPath }: { items: NavItem[]; currentPath: string }) {
|
||||
return (
|
||||
<nav className="flex flex-col gap-1">
|
||||
{items.map((item) => {
|
||||
const isActive =
|
||||
currentPath === item.href || currentPath.startsWith(item.href + '/');
|
||||
return (
|
||||
<Link key={item.href} to={item.href}>
|
||||
<Button
|
||||
variant={isActive ? 'secondary' : 'ghost'}
|
||||
className="w-full justify-start gap-2"
|
||||
size="sm"
|
||||
>
|
||||
<item.icon className={cn('h-4 w-4', isActive && 'text-primary')} />
|
||||
{item.label}
|
||||
</Button>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Play, Square, RotateCcw, Skull } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogClose,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface PowerControlsProps {
|
||||
serverId: string;
|
||||
orgId: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export function PowerControls({ serverId, orgId, status }: PowerControlsProps) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const powerMutation = useMutation({
|
||||
mutationFn: (action: string) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/power`, { action }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['server', orgId, serverId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['servers', orgId] });
|
||||
},
|
||||
});
|
||||
|
||||
const isRunning = status === 'running';
|
||||
const isStopped = status === 'stopped' || status === 'error';
|
||||
const isTransitioning = status === 'starting' || status === 'stopping' || status === 'installing';
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => powerMutation.mutate('start')}
|
||||
disabled={!isStopped || powerMutation.isPending}
|
||||
className="bg-green-600 hover:bg-green-700"
|
||||
>
|
||||
<Play className="h-4 w-4" />
|
||||
Start
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => powerMutation.mutate('restart')}
|
||||
disabled={!isRunning || powerMutation.isPending}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
Restart
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => powerMutation.mutate('stop')}
|
||||
disabled={!isRunning || powerMutation.isPending}
|
||||
>
|
||||
<Square className="h-4 w-4" />
|
||||
Stop
|
||||
</Button>
|
||||
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
disabled={isTransitioning && !isRunning}
|
||||
>
|
||||
<Skull className="h-4 w-4" />
|
||||
Kill
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Kill Server</DialogTitle>
|
||||
<DialogDescription>
|
||||
This will forcefully terminate the server process. Any unsaved data may be lost.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline">Cancel</Button>
|
||||
</DialogClose>
|
||||
<DialogClose asChild>
|
||||
<Button variant="destructive" onClick={() => powerMutation.mutate('kill')}>
|
||||
Kill Server
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground shadow',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground',
|
||||
destructive: 'border-transparent bg-destructive text-destructive-foreground shadow',
|
||||
outline: 'text-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'default' },
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
|
||||
destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
|
||||
outline: 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
|
||||
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
},
|
||||
size: {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-md px-3 text-xs',
|
||||
lg: 'h-10 rounded-md px-8',
|
||||
icon: 'h-9 w-9',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
|
||||
},
|
||||
);
|
||||
Button.displayName = 'Button';
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -0,0 +1,44 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('rounded-xl border bg-card text-card-foreground shadow', className)} {...props} />
|
||||
),
|
||||
);
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('font-semibold leading-none tracking-tight', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => <div ref={ref} className={cn('p-6 pt-0', className)} {...props} />,
|
||||
);
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
@@ -0,0 +1,90 @@
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col space-y-1.5 text-center sm:text-left', className)} {...props} />
|
||||
);
|
||||
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)} {...props} />
|
||||
);
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogTrigger,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import * as React from 'react';
|
||||
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const DropdownMenu = DropdownMenuPrimitive.Root;
|
||||
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
|
||||
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
|
||||
|
||||
const DropdownMenuContent = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-card p-1 text-card-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
));
|
||||
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
|
||||
|
||||
const DropdownMenuItem = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & { inset?: boolean }
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
|
||||
inset && 'pl-8',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
|
||||
|
||||
const DropdownMenuSeparator = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Separator ref={ref} className={cn('-mx-1 my-1 h-px bg-muted', className)} {...props} />
|
||||
));
|
||||
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
|
||||
|
||||
const DropdownMenuLabel = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & { inset?: boolean }
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn('px-2 py-1.5 text-sm font-semibold', inset && 'pl-8', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuGroup,
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
Input.displayName = 'Input';
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ComponentRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as React from 'react';
|
||||
import * as ProgressPrimitive from '@radix-ui/react-progress';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Progress = React.forwardRef<
|
||||
React.ComponentRef<typeof ProgressPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
|
||||
>(({ className, value, ...props }, ref) => (
|
||||
<ProgressPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn('relative h-2 w-full overflow-hidden rounded-full bg-primary/20', className)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
className="h-full w-full flex-1 bg-primary transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
));
|
||||
Progress.displayName = ProgressPrimitive.Root.displayName;
|
||||
|
||||
export { Progress };
|
||||
@@ -0,0 +1,24 @@
|
||||
import * as React from 'react';
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const ScrollArea = React.forwardRef<
|
||||
React.ComponentRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root ref={ref} className={cn('relative overflow-hidden', className)} {...props}>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
orientation="vertical"
|
||||
className="flex touch-none select-none transition-colors h-full w-2.5 border-l border-l-transparent p-[1px]"
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
));
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
|
||||
|
||||
export { ScrollArea };
|
||||
@@ -0,0 +1,88 @@
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { ChevronDown, ChevronUp, Check } from 'lucide-react';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
const SelectGroup = SelectPrimitive.Group;
|
||||
const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
));
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = 'popper', ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-card text-card-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectPrimitive.ScrollUpButton className="flex cursor-default items-center justify-center py-1">
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectPrimitive.ScrollDownButton className="flex cursor-default items-center justify-center py-1">
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
));
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName;
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName;
|
||||
|
||||
export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectItem };
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as React from 'react';
|
||||
import * as SeparatorPrimitive from '@radix-ui/react-separator';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
React.ComponentRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => (
|
||||
<SeparatorPrimitive.Root
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'shrink-0 bg-border',
|
||||
orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Separator.displayName = SeparatorPrimitive.Root.displayName;
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1,52 @@
|
||||
import * as React from 'react';
|
||||
import * as TabsPrimitive from '@radix-ui/react-tabs';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const Tabs = TabsPrimitive.Root;
|
||||
|
||||
const TabsList = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsList.displayName = TabsPrimitive.List.displayName;
|
||||
|
||||
const TabsTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
|
||||
|
||||
const TabsContent = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName;
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
@@ -0,0 +1,27 @@
|
||||
import * as React from 'react';
|
||||
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
|
||||
import { cn } from '@source/ui';
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider;
|
||||
const Tooltip = TooltipPrimitive.Root;
|
||||
const TooltipTrigger = TooltipPrimitive.Trigger;
|
||||
|
||||
const TooltipContent = React.forwardRef<
|
||||
React.ComponentRef<typeof TooltipPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</TooltipPrimitive.Portal>
|
||||
));
|
||||
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useCallback, useSyncExternalStore } from 'react';
|
||||
|
||||
function getTheme(): 'dark' | 'light' {
|
||||
return document.documentElement.classList.contains('dark') ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const theme = useSyncExternalStore(subscribe, getTheme);
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
const next = getTheme() === 'dark' ? 'light' : 'dark';
|
||||
document.documentElement.classList.toggle('dark', next === 'dark');
|
||||
localStorage.setItem('theme', next);
|
||||
listeners.forEach((l) => l());
|
||||
}, []);
|
||||
|
||||
return { theme, toggleTheme };
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
const API_BASE = '/api';
|
||||
|
||||
interface RequestOptions extends RequestInit {
|
||||
params?: Record<string, string>;
|
||||
}
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public data: unknown,
|
||||
) {
|
||||
super(`API Error ${status}`);
|
||||
this.name = 'ApiError';
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { params, ...fetchOptions } = options;
|
||||
|
||||
let url = `${API_BASE}${path}`;
|
||||
if (params) {
|
||||
const searchParams = new URLSearchParams(params);
|
||||
url += `?${searchParams.toString()}`;
|
||||
}
|
||||
|
||||
const token = localStorage.getItem('access_token');
|
||||
const headers: Record<string, string> = {
|
||||
...(fetchOptions.headers as Record<string, string>),
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (fetchOptions.body && typeof fetchOptions.body === 'string') {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
const res = await fetch(url, { ...fetchOptions, headers });
|
||||
|
||||
if (res.status === 401) {
|
||||
// Try refresh
|
||||
const refreshed = await refreshToken();
|
||||
if (refreshed) {
|
||||
headers['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;
|
||||
const retry = await fetch(url, { ...fetchOptions, headers });
|
||||
if (!retry.ok) throw new ApiError(retry.status, await retry.json().catch(() => null));
|
||||
if (retry.status === 204) return undefined as T;
|
||||
return retry.json();
|
||||
}
|
||||
localStorage.removeItem('access_token');
|
||||
window.location.href = '/login';
|
||||
throw new ApiError(401, null);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new ApiError(res.status, await res.json().catch(() => null));
|
||||
}
|
||||
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async function refreshToken(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) return false;
|
||||
const data = await res.json();
|
||||
localStorage.setItem('access_token', data.accessToken);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string, params?: Record<string, string>) =>
|
||||
request<T>(path, { params }),
|
||||
|
||||
post: <T>(path: string, body?: unknown) =>
|
||||
request<T>(path, {
|
||||
method: 'POST',
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
}),
|
||||
|
||||
patch: <T>(path: string, body?: unknown) =>
|
||||
request<T>(path, {
|
||||
method: 'PATCH',
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
}),
|
||||
|
||||
delete: <T>(path: string) =>
|
||||
request<T>(path, { method: 'DELETE' }),
|
||||
};
|
||||
|
||||
export { ApiError };
|
||||
@@ -0,0 +1,30 @@
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
|
||||
let socket: Socket | null = null;
|
||||
|
||||
export function getSocket(): Socket {
|
||||
if (!socket) {
|
||||
socket = io('/', {
|
||||
path: '/socket.io',
|
||||
auth: {
|
||||
token: localStorage.getItem('access_token'),
|
||||
},
|
||||
autoConnect: false,
|
||||
});
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
|
||||
export function connectSocket() {
|
||||
const s = getSocket();
|
||||
if (!s.connected) {
|
||||
s.auth = { token: localStorage.getItem('access_token') };
|
||||
s.connect();
|
||||
}
|
||||
}
|
||||
|
||||
export function disconnectSocket() {
|
||||
if (socket?.connected) {
|
||||
socket.disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
export function formatBytes(bytes: number, decimals = 1): string {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
|
||||
}
|
||||
|
||||
export function formatUptime(seconds: number): string {
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const mins = Math.floor((seconds % 3600) / 60);
|
||||
if (days > 0) return `${days}d ${hours}h`;
|
||||
if (hours > 0) return `${hours}h ${mins}m`;
|
||||
return `${mins}m`;
|
||||
}
|
||||
|
||||
export function statusColor(status: string): string {
|
||||
switch (status) {
|
||||
case 'running':
|
||||
return 'text-green-500';
|
||||
case 'stopped':
|
||||
return 'text-red-500';
|
||||
case 'starting':
|
||||
case 'stopping':
|
||||
case 'installing':
|
||||
return 'text-yellow-500';
|
||||
case 'suspended':
|
||||
return 'text-orange-500';
|
||||
case 'error':
|
||||
return 'text-destructive';
|
||||
default:
|
||||
return 'text-muted-foreground';
|
||||
}
|
||||
}
|
||||
|
||||
export function statusBadgeVariant(
|
||||
status: string,
|
||||
): 'default' | 'secondary' | 'destructive' | 'outline' {
|
||||
switch (status) {
|
||||
case 'running':
|
||||
return 'default';
|
||||
case 'stopped':
|
||||
return 'secondary';
|
||||
case 'error':
|
||||
case 'suspended':
|
||||
return 'destructive';
|
||||
default:
|
||||
return 'outline';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
interface AuditLog {
|
||||
id: string;
|
||||
action: string;
|
||||
username: string;
|
||||
ipAddress: string | null;
|
||||
metadata: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
meta: { total: number };
|
||||
}
|
||||
|
||||
export function AdminAuditLogsPage() {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['admin-audit-logs'],
|
||||
queryFn: () => api.get<PaginatedResponse<AuditLog>>('/admin/audit-logs'),
|
||||
});
|
||||
|
||||
const logs = data?.data ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold">Audit Logs</h1>
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{logs.map((log) => (
|
||||
<div key={log.id} className="flex items-center justify-between px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline">{log.action}</Badge>
|
||||
<span className="text-sm">
|
||||
<span className="font-medium">{log.username}</span>
|
||||
{log.ipAddress && (
|
||||
<span className="text-muted-foreground"> from {log.ipAddress}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(log.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{logs.length === 0 && (
|
||||
<div className="py-12 text-center text-muted-foreground">No audit logs</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus, Gamepad2 } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface Game {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
dockerImage: string;
|
||||
defaultPort: number;
|
||||
startupCommand: string;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
meta: { total: number };
|
||||
}
|
||||
|
||||
export function AdminGamesPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [slug, setSlug] = useState('');
|
||||
const [dockerImage, setDockerImage] = useState('');
|
||||
const [defaultPort, setDefaultPort] = useState(25565);
|
||||
const [startupCommand, setStartupCommand] = useState('');
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['admin-games'],
|
||||
queryFn: () => api.get<PaginatedResponse<Game>>('/admin/games'),
|
||||
});
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: Record<string, unknown>) => api.post('/admin/games', body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-games'] });
|
||||
setOpen(false);
|
||||
setName('');
|
||||
setSlug('');
|
||||
setDockerImage('');
|
||||
setStartupCommand('');
|
||||
},
|
||||
});
|
||||
|
||||
const games = data?.data ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Games</h1>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4" /> Add Game
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Game</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
createMutation.mutate({ name, slug, dockerImage, defaultPort, startupCommand });
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Slug</Label>
|
||||
<Input
|
||||
value={slug}
|
||||
onChange={(e) =>
|
||||
setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Docker Image</Label>
|
||||
<Input
|
||||
value={dockerImage}
|
||||
onChange={(e) => setDockerImage(e.target.value)}
|
||||
placeholder="itzg/minecraft-server:latest"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Default Port</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={defaultPort}
|
||||
onChange={(e) => setDefaultPort(Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Startup Command</Label>
|
||||
<Input
|
||||
value={startupCommand}
|
||||
onChange={(e) => setStartupCommand(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending ? 'Creating...' : 'Create'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{games.map((game) => (
|
||||
<Card key={game.id}>
|
||||
<CardHeader className="flex flex-row items-center gap-3 pb-2">
|
||||
<Gamepad2 className="h-5 w-5 text-primary" />
|
||||
<CardTitle className="text-base">{game.name}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-1 text-sm text-muted-foreground">
|
||||
<p>
|
||||
<Badge variant="outline">{game.slug}</Badge>
|
||||
</p>
|
||||
<p className="mt-2 font-mono text-xs">{game.dockerImage}</p>
|
||||
<p>Port: {game.defaultPort}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
isSuperAdmin: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
meta: { total: number };
|
||||
}
|
||||
|
||||
export function AdminUsersPage() {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['admin-users'],
|
||||
queryFn: () => api.get<PaginatedResponse<User>>('/admin/users'),
|
||||
});
|
||||
|
||||
const users = data?.data ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold">Users</h1>
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b text-left text-sm text-muted-foreground">
|
||||
<th className="p-4 font-medium">Username</th>
|
||||
<th className="p-4 font-medium">Email</th>
|
||||
<th className="p-4 font-medium">Role</th>
|
||||
<th className="p-4 font-medium">Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user) => (
|
||||
<tr key={user.id} className="border-b last:border-0">
|
||||
<td className="p-4 font-medium">{user.username}</td>
|
||||
<td className="p-4 text-muted-foreground">{user.email}</td>
|
||||
<td className="p-4">
|
||||
{user.isSuperAdmin ? (
|
||||
<Badge>Admin</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">User</Badge>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4 text-sm text-muted-foreground">
|
||||
{new Date(user.createdAt).toLocaleDateString()}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { Shield } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { ApiError } from '@/lib/api';
|
||||
|
||||
export function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const login = useAuthStore((s) => s.login);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(email, password);
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setError(err.status === 401 ? 'Invalid email or password' : 'An error occurred');
|
||||
} else {
|
||||
setError('An error occurred');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-lg bg-primary">
|
||||
<Shield className="h-6 w-6 text-primary-foreground" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Welcome back</CardTitle>
|
||||
<CardDescription>Sign in to your GamePanel account</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">{error}</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col gap-3">
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? 'Signing in...' : 'Sign in'}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Don't have an account?{' '}
|
||||
<Link to="/register" className="text-primary hover:underline">
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { Shield } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { ApiError } from '@/lib/api';
|
||||
|
||||
export function RegisterPage() {
|
||||
const navigate = useNavigate();
|
||||
const register = useAuthStore((s) => s.register);
|
||||
const [email, setEmail] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
await register(email, username, password);
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setError(err.status === 409 ? 'Email or username already taken' : 'An error occurred');
|
||||
} else {
|
||||
setError('An error occurred');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-lg bg-primary">
|
||||
<Shield className="h-6 w-6 text-primary-foreground" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Create an account</CardTitle>
|
||||
<CardDescription>Get started with GamePanel</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">{error}</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
placeholder="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Min 8 characters"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col gap-3">
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? 'Creating account...' : 'Create account'}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="text-primary hover:underline">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useParams, Link } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Server, Network, Activity, Plus } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { statusBadgeVariant } from '@/lib/utils';
|
||||
|
||||
interface ServerSummary {
|
||||
id: string;
|
||||
uuid: string;
|
||||
name: string;
|
||||
status: string;
|
||||
gameName: string;
|
||||
nodeName: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
meta: { total: number; page: number; perPage: number; totalPages: number };
|
||||
}
|
||||
|
||||
export function DashboardPage() {
|
||||
const { orgId } = useParams();
|
||||
|
||||
const { data: serversData } = useQuery({
|
||||
queryKey: ['servers', orgId],
|
||||
queryFn: () => api.get<PaginatedResponse<ServerSummary>>(`/organizations/${orgId}/servers`),
|
||||
});
|
||||
|
||||
const { data: nodesData } = useQuery({
|
||||
queryKey: ['nodes', orgId],
|
||||
queryFn: () => api.get<PaginatedResponse<{ id: string }>>(`/organizations/${orgId}/nodes`),
|
||||
});
|
||||
|
||||
const servers = serversData?.data ?? [];
|
||||
const running = servers.filter((s) => s.status === 'running').length;
|
||||
const totalNodes = nodesData?.meta.total ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Dashboard</h1>
|
||||
<Link to={`/org/${orgId}/servers/new`}>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4" />
|
||||
New Server
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Total Servers</CardTitle>
|
||||
<Server className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{servers.length}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Running</CardTitle>
|
||||
<Activity className="h-4 w-4 text-green-500" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold text-green-500">{running}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Nodes</CardTitle>
|
||||
<Network className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{totalNodes}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="mb-4 text-lg font-semibold">Servers</h2>
|
||||
{servers.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<Server className="mb-4 h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="text-muted-foreground">No servers yet</p>
|
||||
<Link to={`/org/${orgId}/servers/new`}>
|
||||
<Button variant="outline" className="mt-4">
|
||||
Create your first server
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid gap-3">
|
||||
{servers.map((server) => (
|
||||
<Link key={server.id} to={`/org/${orgId}/servers/${server.id}/console`}>
|
||||
<Card className="transition-colors hover:border-primary/50">
|
||||
<CardContent className="flex items-center justify-between p-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
|
||||
<Server className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{server.name}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{server.gameName} · {server.nodeName} · :{server.port}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant={statusBadgeVariant(server.status)}>{server.status}</Badge>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { useParams, Link } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Network,
|
||||
Wifi,
|
||||
WifiOff,
|
||||
Cpu,
|
||||
MemoryStick,
|
||||
HardDrive,
|
||||
Server,
|
||||
Activity,
|
||||
} from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatBytes } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
|
||||
interface NodeDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
fqdn: string;
|
||||
daemonPort: number;
|
||||
grpcPort: number;
|
||||
memoryTotal: number;
|
||||
diskTotal: number;
|
||||
isOnline: boolean;
|
||||
daemonVersion: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface NodeStats {
|
||||
cpuPercent: number;
|
||||
memoryUsed: number;
|
||||
memoryTotal: number;
|
||||
diskUsed: number;
|
||||
diskTotal: number;
|
||||
activeServers: number;
|
||||
totalServers: number;
|
||||
uptime: number;
|
||||
}
|
||||
|
||||
interface ServerSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
memoryLimit: number;
|
||||
cpuLimit: number;
|
||||
gameName: string;
|
||||
}
|
||||
|
||||
export function NodeDetailPage() {
|
||||
const { orgId, nodeId } = useParams();
|
||||
|
||||
const { data: node } = useQuery({
|
||||
queryKey: ['node', orgId, nodeId],
|
||||
queryFn: () => api.get<NodeDetail>(`/organizations/${orgId}/nodes/${nodeId}`),
|
||||
});
|
||||
|
||||
const { data: stats } = useQuery({
|
||||
queryKey: ['node-stats', orgId, nodeId],
|
||||
queryFn: () => api.get<NodeStats>(`/organizations/${orgId}/nodes/${nodeId}/stats`),
|
||||
refetchInterval: 10_000,
|
||||
});
|
||||
|
||||
const { data: serversData } = useQuery({
|
||||
queryKey: ['node-servers', orgId, nodeId],
|
||||
queryFn: () =>
|
||||
api.get<{ data: ServerSummary[] }>(
|
||||
`/organizations/${orgId}/nodes/${nodeId}/servers`,
|
||||
),
|
||||
});
|
||||
|
||||
const servers = serversData?.data ?? [];
|
||||
|
||||
if (!node) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const memPercent = stats
|
||||
? Math.round((stats.memoryUsed / stats.memoryTotal) * 100)
|
||||
: 0;
|
||||
const diskPercent = stats
|
||||
? Math.round((stats.diskUsed / stats.diskTotal) * 100)
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link to={`/org/${orgId}/nodes`}>
|
||||
<Button variant="ghost" size="sm">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex items-center gap-3">
|
||||
<Network className="h-6 w-6 text-primary" />
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{node.name}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{node.fqdn}:{node.daemonPort}
|
||||
</p>
|
||||
</div>
|
||||
<Badge variant={node.isOnline ? 'default' : 'destructive'}>
|
||||
{node.isOnline ? (
|
||||
<><Wifi className="mr-1 h-3 w-3" /> Online</>
|
||||
) : (
|
||||
<><WifiOff className="mr-1 h-3 w-3" /> Offline</>
|
||||
)}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats Cards */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium">CPU Usage</CardTitle>
|
||||
<Cpu className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{stats ? `${stats.cpuPercent.toFixed(1)}%` : '—'}
|
||||
</div>
|
||||
<Progress value={stats?.cpuPercent ?? 0} className="mt-2 h-2" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium">Memory</CardTitle>
|
||||
<MemoryStick className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{stats
|
||||
? `${formatBytes(stats.memoryUsed)} / ${formatBytes(stats.memoryTotal)}`
|
||||
: '—'}
|
||||
</div>
|
||||
<Progress value={memPercent} className="mt-2 h-2" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium">Disk</CardTitle>
|
||||
<HardDrive className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{stats
|
||||
? `${formatBytes(stats.diskUsed)} / ${formatBytes(stats.diskTotal)}`
|
||||
: '—'}
|
||||
</div>
|
||||
<Progress value={diskPercent} className="mt-2 h-2" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium">Servers</CardTitle>
|
||||
<Server className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{stats ? `${stats.activeServers} / ${stats.totalServers}` : servers.length.toString()}
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{stats ? 'active / total' : 'total servers'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Node Info */}
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Node Information</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<InfoRow label="FQDN" value={node.fqdn} />
|
||||
<InfoRow label="Daemon Port" value={String(node.daemonPort)} />
|
||||
<InfoRow label="gRPC Port" value={String(node.grpcPort)} />
|
||||
<InfoRow label="Total Memory" value={formatBytes(node.memoryTotal)} />
|
||||
<InfoRow label="Total Disk" value={formatBytes(node.diskTotal)} />
|
||||
{node.daemonVersion && (
|
||||
<InfoRow label="Daemon Version" value={node.daemonVersion} />
|
||||
)}
|
||||
<InfoRow label="Created" value={new Date(node.createdAt).toLocaleDateString()} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Servers on this Node</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{servers.length === 0 ? (
|
||||
<p className="py-4 text-center text-sm text-muted-foreground">
|
||||
No servers on this node
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{servers.map((srv) => (
|
||||
<Link
|
||||
key={srv.id}
|
||||
to={`/org/${orgId}/servers/${srv.id}/console`}
|
||||
className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{srv.name}</p>
|
||||
<p className="text-xs text-muted-foreground">{srv.gameName}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={srv.status === 'running' ? 'default' : 'outline'}
|
||||
>
|
||||
{srv.status}
|
||||
</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatBytes(srv.memoryLimit)} RAM
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<span className="font-medium">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams, Link } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus, Network, Wifi, WifiOff } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatBytes } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface NodeItem {
|
||||
id: string;
|
||||
name: string;
|
||||
fqdn: string;
|
||||
daemonPort: number;
|
||||
grpcPort: number;
|
||||
memoryTotal: number;
|
||||
diskTotal: number;
|
||||
isOnline: boolean;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
meta: { total: number };
|
||||
}
|
||||
|
||||
export function NodesPage() {
|
||||
const { orgId } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [fqdn, setFqdn] = useState('');
|
||||
const [daemonPort, setDaemonPort] = useState(8443);
|
||||
const [grpcPort, setGrpcPort] = useState(50051);
|
||||
const [memoryTotal, setMemoryTotal] = useState(8192);
|
||||
const [diskTotal, setDiskTotal] = useState(51200);
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['nodes', orgId],
|
||||
queryFn: () => api.get<PaginatedResponse<NodeItem>>(`/organizations/${orgId}/nodes`),
|
||||
});
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: Record<string, unknown>) =>
|
||||
api.post(`/organizations/${orgId}/nodes`, body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['nodes', orgId] });
|
||||
setOpen(false);
|
||||
setName('');
|
||||
setFqdn('');
|
||||
},
|
||||
});
|
||||
|
||||
const nodes = data?.data ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Nodes</h1>
|
||||
<p className="text-muted-foreground">Manage your daemon nodes</p>
|
||||
</div>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4" /> Add Node
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Node</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
createMutation.mutate({
|
||||
name,
|
||||
fqdn,
|
||||
daemonPort,
|
||||
grpcPort,
|
||||
memoryTotal: memoryTotal * 1024 * 1024,
|
||||
diskTotal: diskTotal * 1024 * 1024,
|
||||
});
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>FQDN</Label>
|
||||
<Input
|
||||
value={fqdn}
|
||||
onChange={(e) => setFqdn(e.target.value)}
|
||||
placeholder="node1.example.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Daemon Port</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={daemonPort}
|
||||
onChange={(e) => setDaemonPort(Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>gRPC Port</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={grpcPort}
|
||||
onChange={(e) => setGrpcPort(Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Memory (MB)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={memoryTotal}
|
||||
onChange={(e) => setMemoryTotal(Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Disk (MB)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={diskTotal}
|
||||
onChange={(e) => setDiskTotal(Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending ? 'Creating...' : 'Add Node'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{nodes.map((node) => (
|
||||
<Link key={node.id} to={`/org/${orgId}/nodes/${node.id}`}>
|
||||
<Card className="transition-colors hover:bg-muted/50 cursor-pointer">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<Network className="h-5 w-5 text-primary" />
|
||||
<CardTitle className="text-base">{node.name}</CardTitle>
|
||||
</div>
|
||||
<Badge variant={node.isOnline ? 'default' : 'destructive'}>
|
||||
{node.isOnline ? (
|
||||
<><Wifi className="mr-1 h-3 w-3" /> Online</>
|
||||
) : (
|
||||
<><WifiOff className="mr-1 h-3 w-3" /> Offline</>
|
||||
)}
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">{node.fqdn}:{node.daemonPort}</p>
|
||||
<div className="mt-3 flex gap-4 text-sm">
|
||||
<span>{formatBytes(node.memoryTotal)} RAM</span>
|
||||
<span>{formatBytes(node.diskTotal)} Disk</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus, Building2 } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface Organization {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
maxServers: number;
|
||||
maxNodes: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
meta: { total: number; page: number; perPage: number; totalPages: number };
|
||||
}
|
||||
|
||||
export function OrganizationsPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [slug, setSlug] = useState('');
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['organizations'],
|
||||
queryFn: () => api.get<PaginatedResponse<Organization>>('/organizations'),
|
||||
});
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: { name: string; slug: string }) => api.post('/organizations', body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['organizations'] });
|
||||
setOpen(false);
|
||||
setName('');
|
||||
setSlug('');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Organizations</h1>
|
||||
<p className="text-muted-foreground">Manage your organizations</p>
|
||||
</div>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4" />
|
||||
New Organization
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create Organization</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
createMutation.mutate({ name, slug });
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Slug</Label>
|
||||
<Input
|
||||
value={slug}
|
||||
onChange={(e) => setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
|
||||
pattern="^[a-z0-9-]+$"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending ? 'Creating...' : 'Create'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{data?.data.map((org) => (
|
||||
<Link key={org.id} to={`/org/${org.id}/dashboard`}>
|
||||
<Card className="transition-colors hover:border-primary/50">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
|
||||
<Building2 className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-base">{org.name}</CardTitle>
|
||||
<CardDescription>{org.slug}</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex gap-4 text-sm text-muted-foreground">
|
||||
<span>Max {org.maxServers} servers</span>
|
||||
<span>Max {org.maxNodes} nodes</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
HardDrive,
|
||||
Plus,
|
||||
Download,
|
||||
Trash2,
|
||||
Lock,
|
||||
Unlock,
|
||||
RotateCcw,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
} from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface Backup {
|
||||
id: string;
|
||||
name: string;
|
||||
sizeBytes: number | null;
|
||||
cdnPath: string | null;
|
||||
checksum: string | null;
|
||||
isLocked: boolean;
|
||||
completedAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number | null): string {
|
||||
if (bytes === null || bytes === 0) return '—';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i] ?? 'B'}`;
|
||||
}
|
||||
|
||||
export function BackupsPage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [confirmRestore, setConfirmRestore] = useState<string | null>(null);
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['backups', orgId, serverId],
|
||||
queryFn: () =>
|
||||
api.get<{ backups: Backup[] }>(
|
||||
`/organizations/${orgId}/servers/${serverId}/backups`,
|
||||
),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (backupId: string) =>
|
||||
api.delete(`/organizations/${orgId}/servers/${serverId}/backups/${backupId}`),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['backups', orgId, serverId] }),
|
||||
});
|
||||
|
||||
const restoreMutation = useMutation({
|
||||
mutationFn: (backupId: string) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/backups/${backupId}/restore`, {}),
|
||||
onSuccess: () => setConfirmRestore(null),
|
||||
});
|
||||
|
||||
const lockMutation = useMutation({
|
||||
mutationFn: (backupId: string) =>
|
||||
api.patch(`/organizations/${orgId}/servers/${serverId}/backups/${backupId}/lock`, {}),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['backups', orgId, serverId] }),
|
||||
});
|
||||
|
||||
const backupList = data?.backups ?? [];
|
||||
|
||||
const totalSize = backupList.reduce((sum, b) => sum + (b.sizeBytes ?? 0), 0);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Backups</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{backupList.length} backup{backupList.length !== 1 ? 's' : ''} — {formatBytes(totalSize)} total
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={showCreate} onOpenChange={setShowCreate}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">
|
||||
<Plus className="mr-1.5 h-4 w-4" />
|
||||
Create Backup
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create Backup</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CreateBackupForm
|
||||
orgId={orgId!}
|
||||
serverId={serverId!}
|
||||
onClose={() => setShowCreate(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{backupList.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<HardDrive className="mb-4 h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="text-muted-foreground">No backups yet</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Create a backup to save the current state of your server
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{backupList.map((backup) => (
|
||||
<Card key={backup.id}>
|
||||
<CardContent className="flex items-center justify-between py-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
|
||||
{backup.completedAt ? (
|
||||
<CheckCircle2 className="h-5 w-5 text-green-500" />
|
||||
) : (
|
||||
<Clock className="h-5 w-5 text-yellow-500 animate-pulse" />
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="font-medium">{backup.name}</p>
|
||||
{backup.isLocked && (
|
||||
<Badge variant="outline">
|
||||
<Lock className="mr-1 h-3 w-3" />
|
||||
Locked
|
||||
</Badge>
|
||||
)}
|
||||
{!backup.completedAt && (
|
||||
<Badge variant="outline" className="text-yellow-500">
|
||||
In Progress
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<span>{formatBytes(backup.sizeBytes)}</span>
|
||||
<span>{new Date(backup.createdAt).toLocaleString()}</span>
|
||||
{backup.checksum && (
|
||||
<span className="font-mono">
|
||||
{backup.checksum.slice(0, 12)}...
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{backup.completedAt && (
|
||||
<>
|
||||
{confirmRestore === backup.id ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-xs text-destructive mr-1">Confirm?</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
onClick={() => restoreMutation.mutate(backup.id)}
|
||||
disabled={restoreMutation.isPending}
|
||||
>
|
||||
Yes
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setConfirmRestore(null)}
|
||||
>
|
||||
No
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setConfirmRestore(backup.id)}
|
||||
title="Restore"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => lockMutation.mutate(backup.id)}
|
||||
title={backup.isLocked ? 'Unlock' : 'Lock'}
|
||||
>
|
||||
{backup.isLocked ? (
|
||||
<Unlock className="h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
{!backup.isLocked && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => deleteMutation.mutate(backup.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateBackupForm({
|
||||
orgId,
|
||||
serverId,
|
||||
onClose,
|
||||
}: {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const [name, setName] = useState(
|
||||
`backup-${new Date().toISOString().slice(0, 10)}`,
|
||||
);
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: { name: string }) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/backups`, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['backups', orgId, serverId] });
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
createMutation.mutate({ name });
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Backup Name</Label>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending ? 'Creating...' : 'Create Backup'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Settings2, FileText, Save } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
|
||||
interface ConfigFile {
|
||||
index: number;
|
||||
path: string;
|
||||
parser: string;
|
||||
editableKeys: string[] | null;
|
||||
}
|
||||
|
||||
interface ConfigEntry {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface ConfigDetail {
|
||||
path: string;
|
||||
parser: string;
|
||||
editableKeys: string[] | null;
|
||||
entries: ConfigEntry[];
|
||||
raw: string;
|
||||
}
|
||||
|
||||
export function ConfigPage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: configsData } = useQuery({
|
||||
queryKey: ['configs', orgId, serverId],
|
||||
queryFn: () =>
|
||||
api.get<{ configs: ConfigFile[] }>(
|
||||
`/organizations/${orgId}/servers/${serverId}/config`,
|
||||
),
|
||||
});
|
||||
|
||||
const configs = configsData?.configs ?? [];
|
||||
|
||||
if (configs.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<Settings2 className="mb-4 h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="text-muted-foreground">No config files available for this game</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="0" className="space-y-4">
|
||||
<TabsList>
|
||||
{configs.map((cf) => (
|
||||
<TabsTrigger key={cf.index} value={String(cf.index)}>
|
||||
<FileText className="mr-1.5 h-3.5 w-3.5" />
|
||||
{cf.path.split('/').pop()}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
{configs.map((cf) => (
|
||||
<TabsContent key={cf.index} value={String(cf.index)}>
|
||||
<ConfigEditor
|
||||
orgId={orgId!}
|
||||
serverId={serverId!}
|
||||
configIndex={cf.index}
|
||||
configFile={cf}
|
||||
/>
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfigEditor({
|
||||
orgId,
|
||||
serverId,
|
||||
configIndex,
|
||||
configFile,
|
||||
}: {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
configIndex: number;
|
||||
configFile: ConfigFile;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: detail } = useQuery({
|
||||
queryKey: ['config-detail', orgId, serverId, configIndex],
|
||||
queryFn: () =>
|
||||
api.get<ConfigDetail>(
|
||||
`/organizations/${orgId}/servers/${serverId}/config/${configIndex}`,
|
||||
),
|
||||
});
|
||||
|
||||
const [entries, setEntries] = useState<ConfigEntry[]>([]);
|
||||
const [initialized, setInitialized] = useState(false);
|
||||
|
||||
// Initialize entries from server data
|
||||
if (detail && !initialized) {
|
||||
setEntries(detail.entries);
|
||||
setInitialized(true);
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (data: { entries: ConfigEntry[] }) =>
|
||||
api.patch(
|
||||
`/organizations/${orgId}/servers/${serverId}/config/${configIndex}`,
|
||||
data,
|
||||
),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['config-detail', orgId, serverId, configIndex],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const updateEntry = (key: string, value: string) => {
|
||||
setEntries((prev) =>
|
||||
prev.map((e) => (e.key === key ? { ...e, value } : e)),
|
||||
);
|
||||
};
|
||||
|
||||
const displayEntries = configFile.editableKeys
|
||||
? entries.filter((e) => configFile.editableKeys!.includes(e.key))
|
||||
: entries;
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
{configFile.path}
|
||||
<Badge variant="outline">{configFile.parser}</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{configFile.editableKeys
|
||||
? `${configFile.editableKeys.length} editable keys`
|
||||
: 'All keys editable'}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => saveMutation.mutate({ entries })}
|
||||
disabled={saveMutation.isPending}
|
||||
>
|
||||
<Save className="h-4 w-4" />
|
||||
{saveMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{displayEntries.length === 0 ? (
|
||||
<p className="py-8 text-center text-sm text-muted-foreground">
|
||||
{detail ? 'No entries found. The server may need to be started first to generate config files.' : 'Loading...'}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{displayEntries.map((entry) => (
|
||||
<div key={entry.key} className="grid gap-1.5">
|
||||
<Label className="font-mono text-xs text-muted-foreground">
|
||||
{entry.key}
|
||||
</Label>
|
||||
<Input
|
||||
value={entry.value}
|
||||
onChange={(e) => updateEntry(entry.key, e.target.value)}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{saveMutation.isSuccess && (
|
||||
<p className="mt-4 text-sm text-green-500">Config saved successfully</p>
|
||||
)}
|
||||
{saveMutation.isError && (
|
||||
<p className="mt-4 text-sm text-destructive">Failed to save config</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { Terminal } from '@xterm/xterm';
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import { WebLinksAddon } from '@xterm/addon-web-links';
|
||||
import '@xterm/xterm/css/xterm.css';
|
||||
import { getSocket, connectSocket } from '@/lib/socket';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Send } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
export function ConsolePage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const termRef = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const [command, setCommand] = useState('');
|
||||
const [history, setHistory] = useState<string[]>([]);
|
||||
const [historyIndex, setHistoryIndex] = useState(-1);
|
||||
|
||||
useEffect(() => {
|
||||
if (!termRef.current) return;
|
||||
|
||||
const terminal = new Terminal({
|
||||
cursorBlink: false,
|
||||
disableStdin: true,
|
||||
fontSize: 13,
|
||||
fontFamily: '"JetBrains Mono", "Fira Code", monospace',
|
||||
theme: {
|
||||
background: '#0a0a0f',
|
||||
foreground: '#d4d4d8',
|
||||
cursor: '#d4d4d8',
|
||||
selectionBackground: '#27272a',
|
||||
},
|
||||
scrollback: 5000,
|
||||
convertEol: true,
|
||||
});
|
||||
|
||||
const fitAddon = new FitAddon();
|
||||
terminal.loadAddon(fitAddon);
|
||||
terminal.loadAddon(new WebLinksAddon());
|
||||
terminal.open(termRef.current);
|
||||
fitAddon.fit();
|
||||
|
||||
terminalRef.current = terminal;
|
||||
fitAddonRef.current = fitAddon;
|
||||
|
||||
terminal.writeln('\x1b[90m--- Console connected ---\x1b[0m');
|
||||
|
||||
// Socket.IO connection
|
||||
connectSocket();
|
||||
const socket = getSocket();
|
||||
|
||||
socket.emit('server:console:join', { serverId });
|
||||
|
||||
const handleOutput = (data: { line: string }) => {
|
||||
terminal.writeln(data.line);
|
||||
};
|
||||
|
||||
socket.on('server:console:output', handleOutput);
|
||||
|
||||
const handleResize = () => fitAddon.fit();
|
||||
window.addEventListener('resize', handleResize);
|
||||
|
||||
return () => {
|
||||
socket.off('server:console:output', handleOutput);
|
||||
socket.emit('server:console:leave', { serverId });
|
||||
window.removeEventListener('resize', handleResize);
|
||||
terminal.dispose();
|
||||
};
|
||||
}, [serverId]);
|
||||
|
||||
const sendCommand = () => {
|
||||
if (!command.trim()) return;
|
||||
const socket = getSocket();
|
||||
socket.emit('server:console:command', { serverId, orgId, command: command.trim() });
|
||||
setHistory((prev) => [...prev, command.trim()]);
|
||||
setHistoryIndex(-1);
|
||||
setCommand('');
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
sendCommand();
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
if (history.length === 0) return;
|
||||
const newIndex = historyIndex < history.length - 1 ? historyIndex + 1 : historyIndex;
|
||||
setHistoryIndex(newIndex);
|
||||
setCommand(history[history.length - 1 - newIndex] ?? '');
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (historyIndex <= 0) {
|
||||
setHistoryIndex(-1);
|
||||
setCommand('');
|
||||
} else {
|
||||
const newIndex = historyIndex - 1;
|
||||
setHistoryIndex(newIndex);
|
||||
setCommand(history[history.length - 1 - newIndex] ?? '');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="p-0">
|
||||
<div ref={termRef} className="h-[500px]" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Type a command..."
|
||||
value={command}
|
||||
onChange={(e) => setCommand(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button onClick={sendCommand} size="icon">
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
Folder,
|
||||
FileText,
|
||||
ArrowUp,
|
||||
Trash2,
|
||||
Plus,
|
||||
Download,
|
||||
Upload,
|
||||
Save,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatBytes } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogClose,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface FileEntry {
|
||||
name: string;
|
||||
path: string;
|
||||
isDirectory: boolean;
|
||||
size: number;
|
||||
modifiedAt: number;
|
||||
}
|
||||
|
||||
export function FilesPage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [editingFile, setEditingFile] = useState<{ path: string; content: string } | null>(null);
|
||||
const [newFileName, setNewFileName] = useState('');
|
||||
const [showNewFile, setShowNewFile] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
|
||||
|
||||
const filesQuery = useQuery({
|
||||
queryKey: ['files', orgId, serverId, currentPath],
|
||||
queryFn: () =>
|
||||
api.get<{ files: FileEntry[] }>(
|
||||
`/organizations/${orgId}/servers/${serverId}/files`,
|
||||
{ path: currentPath },
|
||||
),
|
||||
enabled: !editingFile,
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (paths: string[]) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/files/delete`, { paths }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['files', orgId, serverId, currentPath] });
|
||||
setDeleteTarget(null);
|
||||
},
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: ({ path, data }: { path: string; data: string }) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/files/write`, { path, data }),
|
||||
onSuccess: () => {
|
||||
setEditingFile(null);
|
||||
queryClient.invalidateQueries({ queryKey: ['files', orgId, serverId, currentPath] });
|
||||
},
|
||||
});
|
||||
|
||||
const createFileMutation = useMutation({
|
||||
mutationFn: ({ path, data }: { path: string; data: string }) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/files/write`, { path, data }),
|
||||
onSuccess: () => {
|
||||
setShowNewFile(false);
|
||||
setNewFileName('');
|
||||
queryClient.invalidateQueries({ queryKey: ['files', orgId, serverId, currentPath] });
|
||||
},
|
||||
});
|
||||
|
||||
const openFile = async (file: FileEntry) => {
|
||||
if (file.isDirectory) {
|
||||
setCurrentPath(file.path);
|
||||
return;
|
||||
}
|
||||
const res = await api.get<{ data: string }>(
|
||||
`/organizations/${orgId}/servers/${serverId}/files/read`,
|
||||
{ path: file.path },
|
||||
);
|
||||
setEditingFile({ path: file.path, content: res.data });
|
||||
};
|
||||
|
||||
const goUp = () => {
|
||||
if (currentPath === '/') return;
|
||||
const parts = currentPath.split('/').filter(Boolean);
|
||||
parts.pop();
|
||||
setCurrentPath('/' + parts.join('/'));
|
||||
};
|
||||
|
||||
const breadcrumbs = currentPath.split('/').filter(Boolean);
|
||||
|
||||
const files = filesQuery.data?.files ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{editingFile ? (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-sm font-mono">{editingFile.path}</CardTitle>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
saveMutation.mutate({ path: editingFile.path, data: editingFile.content })
|
||||
}
|
||||
disabled={saveMutation.isPending}
|
||||
>
|
||||
<Save className="h-4 w-4" />
|
||||
Save
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => setEditingFile(null)}>
|
||||
<X className="h-4 w-4" />
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<textarea
|
||||
value={editingFile.content}
|
||||
onChange={(e) => setEditingFile({ ...editingFile, content: e.target.value })}
|
||||
className="min-h-[500px] w-full rounded-md border bg-background p-3 font-mono text-sm focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Button variant="ghost" size="icon" onClick={goUp} disabled={currentPath === '/'}>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="text-muted-foreground">/</span>
|
||||
{breadcrumbs.map((crumb, i) => (
|
||||
<span key={i} className="flex items-center gap-1">
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() =>
|
||||
setCurrentPath('/' + breadcrumbs.slice(0, i + 1).join('/'))
|
||||
}
|
||||
>
|
||||
{crumb}
|
||||
</button>
|
||||
{i < breadcrumbs.length - 1 && (
|
||||
<span className="text-muted-foreground">/</span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={() => setShowNewFile(true)}>
|
||||
<Plus className="h-4 w-4" />
|
||||
New File
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showNewFile && (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="filename.txt"
|
||||
value={newFileName}
|
||||
onChange={(e) => setNewFileName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && newFileName) {
|
||||
const path =
|
||||
currentPath === '/' ? `/${newFileName}` : `${currentPath}/${newFileName}`;
|
||||
createFileMutation.mutate({ path, data: '' });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (!newFileName) return;
|
||||
const path =
|
||||
currentPath === '/' ? `/${newFileName}` : `${currentPath}/${newFileName}`;
|
||||
createFileMutation.mutate({ path, data: '' });
|
||||
}}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setShowNewFile(false);
|
||||
setNewFileName('');
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{files.length === 0 && (
|
||||
<div className="flex items-center justify-center py-12 text-muted-foreground">
|
||||
This directory is empty
|
||||
</div>
|
||||
)}
|
||||
{files.map((file) => (
|
||||
<div
|
||||
key={file.path}
|
||||
className="flex cursor-pointer items-center justify-between px-4 py-2.5 hover:bg-muted/50"
|
||||
onClick={() => openFile(file)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{file.isDirectory ? (
|
||||
<Folder className="h-4 w-4 text-blue-400" />
|
||||
) : (
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<span className="text-sm">{file.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
{!file.isDirectory && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatBytes(file.size)}
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-7 w-7"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setDeleteTarget(file.path);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete File</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Are you sure you want to delete <code className="font-mono">{deleteTarget}</code>?
|
||||
</p>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline">Cancel</Button>
|
||||
</DialogClose>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => deleteTarget && deleteMutation.mutate([deleteTarget])}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useParams } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Users, RefreshCw } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
interface Player {
|
||||
name: string;
|
||||
steamid?: string;
|
||||
}
|
||||
|
||||
interface PlayerListResponse {
|
||||
players: Player[];
|
||||
maxPlayers: number;
|
||||
}
|
||||
|
||||
export function PlayersPage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
|
||||
const { data, isLoading, refetch } = useQuery({
|
||||
queryKey: ['players', orgId, serverId],
|
||||
queryFn: () =>
|
||||
api.get<PlayerListResponse>(
|
||||
`/organizations/${orgId}/servers/${serverId}/players`,
|
||||
),
|
||||
refetchInterval: 30000,
|
||||
});
|
||||
|
||||
const players = data?.players ?? [];
|
||||
const maxPlayers = data?.maxPlayers ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Active Players</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{players.length} / {maxPlayers} players online
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => refetch()} disabled={isLoading}>
|
||||
<RefreshCw className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{players.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<Users className="mb-4 h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="text-muted-foreground">No players online</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Player tracking requires RCON to be enabled on the server
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{players.map((player, i) => (
|
||||
<div key={i} className="flex items-center gap-3 px-4 py-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-sm font-medium text-primary">
|
||||
{player.name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{player.name}</p>
|
||||
{player.steamid && (
|
||||
<p className="text-xs text-muted-foreground">{player.steamid}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
Puzzle,
|
||||
Search,
|
||||
Download,
|
||||
Trash2,
|
||||
ToggleLeft,
|
||||
ToggleRight,
|
||||
Star,
|
||||
Upload,
|
||||
} from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface InstalledPlugin {
|
||||
id: string;
|
||||
pluginId: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string | null;
|
||||
source: 'spiget' | 'manual';
|
||||
externalId: string | null;
|
||||
installedVersion: string | null;
|
||||
isActive: boolean;
|
||||
installedAt: string;
|
||||
}
|
||||
|
||||
interface SpigetResult {
|
||||
id: number;
|
||||
name: string;
|
||||
tag: string;
|
||||
downloads: number;
|
||||
rating: { average: number; count: number };
|
||||
updateDate: number;
|
||||
external: boolean;
|
||||
}
|
||||
|
||||
export function PluginsPage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: pluginsData } = useQuery({
|
||||
queryKey: ['plugins', orgId, serverId],
|
||||
queryFn: () =>
|
||||
api.get<{ plugins: InstalledPlugin[] }>(
|
||||
`/organizations/${orgId}/servers/${serverId}/plugins`,
|
||||
),
|
||||
});
|
||||
|
||||
const installed = pluginsData?.plugins ?? [];
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="installed" className="space-y-4">
|
||||
<TabsList>
|
||||
<TabsTrigger value="installed">
|
||||
<Puzzle className="mr-1.5 h-3.5 w-3.5" />
|
||||
Installed ({installed.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="search">
|
||||
<Search className="mr-1.5 h-3.5 w-3.5" />
|
||||
Search Plugins
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="manual">
|
||||
<Upload className="mr-1.5 h-3.5 w-3.5" />
|
||||
Manual Install
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="installed">
|
||||
<InstalledPlugins installed={installed} orgId={orgId!} serverId={serverId!} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="search">
|
||||
<SpigetSearch orgId={orgId!} serverId={serverId!} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="manual">
|
||||
<ManualInstall orgId={orgId!} serverId={serverId!} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
function InstalledPlugins({
|
||||
installed,
|
||||
orgId,
|
||||
serverId,
|
||||
}: {
|
||||
installed: InstalledPlugin[];
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const toggleMutation = useMutation({
|
||||
mutationFn: (id: string) =>
|
||||
api.patch(`/organizations/${orgId}/servers/${serverId}/plugins/${id}/toggle`),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['plugins', orgId, serverId] }),
|
||||
});
|
||||
|
||||
const uninstallMutation = useMutation({
|
||||
mutationFn: (id: string) =>
|
||||
api.delete(`/organizations/${orgId}/servers/${serverId}/plugins/${id}`),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['plugins', orgId, serverId] }),
|
||||
});
|
||||
|
||||
if (installed.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<Puzzle className="mb-4 h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="text-muted-foreground">No plugins installed</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Search for plugins or install manually
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{installed.map((plugin) => (
|
||||
<Card key={plugin.id}>
|
||||
<CardContent className="flex items-center justify-between p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Puzzle className="h-5 w-5 text-primary" />
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="font-medium">{plugin.name}</p>
|
||||
<Badge variant="outline">{plugin.source}</Badge>
|
||||
{!plugin.isActive && <Badge variant="secondary">Disabled</Badge>}
|
||||
</div>
|
||||
{plugin.description && (
|
||||
<p className="text-sm text-muted-foreground">{plugin.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={() => toggleMutation.mutate(plugin.id)}
|
||||
title={plugin.isActive ? 'Disable' : 'Enable'}
|
||||
>
|
||||
{plugin.isActive ? (
|
||||
<ToggleRight className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<ToggleLeft className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={() => uninstallMutation.mutate(plugin.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SpigetSearch({ orgId, serverId }: { orgId: string; serverId: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [query, setQuery] = useState('');
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
const { data: results, isLoading } = useQuery({
|
||||
queryKey: ['spiget-search', orgId, serverId, searchTerm],
|
||||
queryFn: () =>
|
||||
api.get<{ results: SpigetResult[] }>(
|
||||
`/organizations/${orgId}/servers/${serverId}/plugins/search`,
|
||||
{ q: searchTerm },
|
||||
),
|
||||
enabled: searchTerm.length >= 2,
|
||||
});
|
||||
|
||||
const installMutation = useMutation({
|
||||
mutationFn: (resourceId: number) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/plugins/install/spiget`, {
|
||||
resourceId,
|
||||
}),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['plugins', orgId, serverId] }),
|
||||
});
|
||||
|
||||
const handleSearch = () => {
|
||||
if (query.length >= 2) setSearchTerm(query);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Search Spiget plugins (Minecraft only)..."
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
|
||||
/>
|
||||
<Button onClick={handleSearch} disabled={query.length < 2}>
|
||||
<Search className="h-4 w-4" />
|
||||
Search
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading && <p className="text-sm text-muted-foreground">Searching...</p>}
|
||||
|
||||
{results?.results && results.results.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No results found</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
{results?.results?.map((r) => (
|
||||
<Card key={r.id}>
|
||||
<CardContent className="flex items-center justify-between p-4">
|
||||
<div>
|
||||
<p className="font-medium">{r.name}</p>
|
||||
<p className="text-sm text-muted-foreground">{r.tag}</p>
|
||||
<div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Star className="h-3 w-3" />
|
||||
{r.rating.average.toFixed(1)} ({r.rating.count})
|
||||
</span>
|
||||
<span>
|
||||
<Download className="inline h-3 w-3" /> {r.downloads.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => installMutation.mutate(r.id)}
|
||||
disabled={installMutation.isPending || r.external}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
{r.external ? 'External' : 'Install'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ManualInstall({ orgId, serverId }: { orgId: string; serverId: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [name, setName] = useState('');
|
||||
const [fileName, setFileName] = useState('');
|
||||
const [version, setVersion] = useState('');
|
||||
|
||||
const installMutation = useMutation({
|
||||
mutationFn: (body: { name: string; fileName: string; version?: string }) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/plugins/install/manual`, body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['plugins', orgId, serverId] });
|
||||
setName('');
|
||||
setFileName('');
|
||||
setVersion('');
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Manual Plugin Install</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
installMutation.mutate({
|
||||
name,
|
||||
fileName,
|
||||
version: version || undefined,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label>Plugin Name</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>File Name</Label>
|
||||
<Input
|
||||
value={fileName}
|
||||
onChange={(e) => setFileName(e.target.value)}
|
||||
placeholder="plugin.jar"
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Upload the file to /plugins/ directory via the Files tab first
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Version (optional)</Label>
|
||||
<Input value={version} onChange={(e) => setVersion(e.target.value)} />
|
||||
</div>
|
||||
<Button type="submit" disabled={installMutation.isPending}>
|
||||
{installMutation.isPending ? 'Registering...' : 'Register Plugin'}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
Calendar,
|
||||
Plus,
|
||||
Play,
|
||||
Pause,
|
||||
Trash2,
|
||||
Clock,
|
||||
Zap,
|
||||
Terminal,
|
||||
Power,
|
||||
HardDrive,
|
||||
} from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
|
||||
interface ScheduledTask {
|
||||
id: string;
|
||||
name: string;
|
||||
action: 'command' | 'power' | 'backup';
|
||||
payload: string;
|
||||
scheduleType: 'interval' | 'daily' | 'weekly' | 'cron';
|
||||
scheduleData: Record<string, unknown>;
|
||||
isActive: boolean;
|
||||
lastRunAt: string | null;
|
||||
nextRunAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const DAYS_OF_WEEK = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
|
||||
const ACTION_ICONS = {
|
||||
command: Terminal,
|
||||
power: Power,
|
||||
backup: HardDrive,
|
||||
} as const;
|
||||
|
||||
export function SchedulesPage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['schedules', orgId, serverId],
|
||||
queryFn: () =>
|
||||
api.get<{ tasks: ScheduledTask[] }>(
|
||||
`/organizations/${orgId}/servers/${serverId}/schedules`,
|
||||
),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (taskId: string) =>
|
||||
api.delete(`/organizations/${orgId}/servers/${serverId}/schedules/${taskId}`),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['schedules', orgId, serverId] }),
|
||||
});
|
||||
|
||||
const triggerMutation = useMutation({
|
||||
mutationFn: (taskId: string) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/schedules/${taskId}/trigger`, {}),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['schedules', orgId, serverId] }),
|
||||
});
|
||||
|
||||
const toggleMutation = useMutation({
|
||||
mutationFn: ({ taskId, isActive }: { taskId: string; isActive: boolean }) =>
|
||||
api.patch(`/organizations/${orgId}/servers/${serverId}/schedules/${taskId}`, { isActive }),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['schedules', orgId, serverId] }),
|
||||
});
|
||||
|
||||
const tasks = data?.tasks ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Scheduled Tasks</h2>
|
||||
<Dialog open={showCreate} onOpenChange={setShowCreate}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">
|
||||
<Plus className="mr-1.5 h-4 w-4" />
|
||||
New Schedule
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create Scheduled Task</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CreateScheduleForm
|
||||
orgId={orgId!}
|
||||
serverId={serverId!}
|
||||
onClose={() => setShowCreate(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{tasks.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<Calendar className="mb-4 h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="text-muted-foreground">No scheduled tasks yet</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Create a schedule to automate commands, power actions, or backups
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{tasks.map((task) => {
|
||||
const ActionIcon = ACTION_ICONS[task.action];
|
||||
return (
|
||||
<Card key={task.id}>
|
||||
<CardContent className="flex items-center justify-between py-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
|
||||
<ActionIcon className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="font-medium">{task.name}</p>
|
||||
<Badge variant={task.isActive ? 'default' : 'outline'}>
|
||||
{task.isActive ? 'Active' : 'Paused'}
|
||||
</Badge>
|
||||
<Badge variant="outline">{task.action}</Badge>
|
||||
</div>
|
||||
<div className="mt-0.5 flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{formatSchedule(task.scheduleType, task.scheduleData)}
|
||||
</span>
|
||||
{task.nextRunAt && (
|
||||
<span>
|
||||
Next: {new Date(task.nextRunAt).toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
{task.lastRunAt && (
|
||||
<span>
|
||||
Last: {new Date(task.lastRunAt).toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{task.action === 'command' && (
|
||||
<p className="mt-0.5 font-mono text-xs text-muted-foreground">
|
||||
$ {task.payload}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => triggerMutation.mutate(task.id)}
|
||||
title="Run now"
|
||||
>
|
||||
<Zap className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
toggleMutation.mutate({
|
||||
taskId: task.id,
|
||||
isActive: !task.isActive,
|
||||
})
|
||||
}
|
||||
title={task.isActive ? 'Pause' : 'Resume'}
|
||||
>
|
||||
{task.isActive ? (
|
||||
<Pause className="h-4 w-4" />
|
||||
) : (
|
||||
<Play className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => deleteMutation.mutate(task.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatSchedule(type: string, data: Record<string, unknown>): string {
|
||||
switch (type) {
|
||||
case 'interval':
|
||||
return `Every ${data.minutes ?? 60} minutes`;
|
||||
case 'daily':
|
||||
return `Daily at ${String(data.hour ?? 0).padStart(2, '0')}:${String(data.minute ?? 0).padStart(2, '0')}`;
|
||||
case 'weekly': {
|
||||
const day = DAYS_OF_WEEK[Number(data.dayOfWeek ?? 0)] ?? 'Sunday';
|
||||
return `${day} at ${String(data.hour ?? 0).padStart(2, '0')}:${String(data.minute ?? 0).padStart(2, '0')}`;
|
||||
}
|
||||
case 'cron':
|
||||
return `Cron: ${String(data.expression ?? '* * * * *')}`;
|
||||
default:
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
function CreateScheduleForm({
|
||||
orgId,
|
||||
serverId,
|
||||
onClose,
|
||||
}: {
|
||||
orgId: string;
|
||||
serverId: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const [name, setName] = useState('');
|
||||
const [action, setAction] = useState<'command' | 'power' | 'backup'>('command');
|
||||
const [payload, setPayload] = useState('');
|
||||
const [scheduleType, setScheduleType] = useState<'interval' | 'daily' | 'weekly' | 'cron'>('interval');
|
||||
|
||||
// Schedule data fields
|
||||
const [minutes, setMinutes] = useState('60');
|
||||
const [hour, setHour] = useState('0');
|
||||
const [minute, setMinute] = useState('0');
|
||||
const [dayOfWeek, setDayOfWeek] = useState('0');
|
||||
const [cronExpression, setCronExpression] = useState('0 * * * *');
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) =>
|
||||
api.post(`/organizations/${orgId}/servers/${serverId}/schedules`, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['schedules', orgId, serverId] });
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
|
||||
const buildScheduleData = (): Record<string, unknown> => {
|
||||
switch (scheduleType) {
|
||||
case 'interval':
|
||||
return { minutes: parseInt(minutes, 10) };
|
||||
case 'daily':
|
||||
return { hour: parseInt(hour, 10), minute: parseInt(minute, 10) };
|
||||
case 'weekly':
|
||||
return { dayOfWeek: parseInt(dayOfWeek, 10), hour: parseInt(hour, 10), minute: parseInt(minute, 10) };
|
||||
case 'cron':
|
||||
return { expression: cronExpression };
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
createMutation.mutate({
|
||||
name,
|
||||
action,
|
||||
payload: action === 'backup' ? 'backup' : payload,
|
||||
scheduleType,
|
||||
scheduleData: buildScheduleData(),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Name</Label>
|
||||
<Input
|
||||
placeholder="Daily restart"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Action</Label>
|
||||
<Select value={action} onValueChange={(v) => setAction(v as typeof action)}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="command">Run Command</SelectItem>
|
||||
<SelectItem value="power">Power Action</SelectItem>
|
||||
<SelectItem value="backup">Create Backup</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{action !== 'backup' && (
|
||||
<div className="grid gap-1.5">
|
||||
<Label>{action === 'command' ? 'Command' : 'Power Action'}</Label>
|
||||
{action === 'command' ? (
|
||||
<Input
|
||||
placeholder="say Server restarting..."
|
||||
value={payload}
|
||||
onChange={(e) => setPayload(e.target.value)}
|
||||
required
|
||||
/>
|
||||
) : (
|
||||
<Select value={payload} onValueChange={setPayload}>
|
||||
<SelectTrigger><SelectValue placeholder="Select..." /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="start">Start</SelectItem>
|
||||
<SelectItem value="stop">Stop</SelectItem>
|
||||
<SelectItem value="restart">Restart</SelectItem>
|
||||
<SelectItem value="kill">Kill</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Schedule Type</Label>
|
||||
<Select value={scheduleType} onValueChange={(v) => setScheduleType(v as typeof scheduleType)}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="interval">Interval</SelectItem>
|
||||
<SelectItem value="daily">Daily</SelectItem>
|
||||
<SelectItem value="weekly">Weekly</SelectItem>
|
||||
<SelectItem value="cron">Cron Expression</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{scheduleType === 'interval' && (
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Interval (minutes)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
value={minutes}
|
||||
onChange={(e) => setMinutes(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(scheduleType === 'daily' || scheduleType === 'weekly') && (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{scheduleType === 'weekly' && (
|
||||
<div className="col-span-2 grid gap-1.5">
|
||||
<Label>Day of Week</Label>
|
||||
<Select value={dayOfWeek} onValueChange={setDayOfWeek}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{DAYS_OF_WEEK.map((day, i) => (
|
||||
<SelectItem key={day} value={String(i)}>{day}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Hour (0-23)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="23"
|
||||
value={hour}
|
||||
onChange={(e) => setHour(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Minute (0-59)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="59"
|
||||
value={minute}
|
||||
onChange={(e) => setMinute(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scheduleType === 'cron' && (
|
||||
<div className="grid gap-1.5">
|
||||
<Label>Cron Expression</Label>
|
||||
<Input
|
||||
placeholder="0 */6 * * *"
|
||||
value={cronExpression}
|
||||
onChange={(e) => setCronExpression(e.target.value)}
|
||||
className="font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Format: minute hour day-of-month month day-of-week
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending ? 'Creating...' : 'Create Schedule'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams, useOutletContext } from 'react-router';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { formatBytes } from '@/lib/utils';
|
||||
|
||||
interface ServerDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
memoryLimit: number;
|
||||
diskLimit: number;
|
||||
cpuLimit: number;
|
||||
startupOverride?: string;
|
||||
environment?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function ServerSettingsPage() {
|
||||
const { orgId, serverId } = useParams();
|
||||
const { server } = useOutletContext<{ server?: ServerDetail }>();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [name, setName] = useState(server?.name ?? '');
|
||||
const [description, setDescription] = useState(server?.description ?? '');
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (body: Record<string, unknown>) =>
|
||||
api.patch(`/organizations/${orgId}/servers/${serverId}`, body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['server', orgId, serverId] });
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>General</CardTitle>
|
||||
<CardDescription>Basic server information</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => updateMutation.mutate({ name, description })}
|
||||
disabled={updateMutation.isPending}
|
||||
>
|
||||
Save Changes
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Resources</CardTitle>
|
||||
<CardDescription>Current resource limits</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="rounded-lg border p-4">
|
||||
<p className="text-sm text-muted-foreground">Memory</p>
|
||||
<p className="text-lg font-semibold">
|
||||
{server ? formatBytes(server.memoryLimit) : '—'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-4">
|
||||
<p className="text-sm text-muted-foreground">Disk</p>
|
||||
<p className="text-lg font-semibold">
|
||||
{server ? formatBytes(server.diskLimit) : '—'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-4">
|
||||
<p className="text-sm text-muted-foreground">CPU</p>
|
||||
<p className="text-lg font-semibold">{server?.cpuLimit ?? '—'}%</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-destructive">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive">Danger Zone</CardTitle>
|
||||
<CardDescription>Irreversible actions</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button variant="destructive">Delete Server</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router';
|
||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatBytes } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
|
||||
interface Game {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
dockerImage: string;
|
||||
}
|
||||
|
||||
interface Node {
|
||||
id: string;
|
||||
name: string;
|
||||
fqdn: string;
|
||||
memoryTotal: number;
|
||||
diskTotal: number;
|
||||
}
|
||||
|
||||
interface Allocation {
|
||||
id: string;
|
||||
ip: string;
|
||||
port: number;
|
||||
serverId: string | null;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
meta: { total: number };
|
||||
}
|
||||
|
||||
export function CreateServerPage() {
|
||||
const { orgId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [step, setStep] = useState(1);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [gameId, setGameId] = useState('');
|
||||
const [nodeId, setNodeId] = useState('');
|
||||
const [allocationId, setAllocationId] = useState('');
|
||||
const [memoryLimit, setMemoryLimit] = useState(1024);
|
||||
const [diskLimit, setDiskLimit] = useState(5120);
|
||||
const [cpuLimit, setCpuLimit] = useState(100);
|
||||
|
||||
const { data: gamesData } = useQuery({
|
||||
queryKey: ['admin-games'],
|
||||
queryFn: () => api.get<PaginatedResponse<Game>>('/admin/games'),
|
||||
});
|
||||
|
||||
const { data: nodesData } = useQuery({
|
||||
queryKey: ['nodes', orgId],
|
||||
queryFn: () => api.get<PaginatedResponse<Node>>(`/organizations/${orgId}/nodes`),
|
||||
});
|
||||
|
||||
const { data: allocationsData } = useQuery({
|
||||
queryKey: ['allocations', orgId, nodeId],
|
||||
queryFn: () =>
|
||||
api.get<PaginatedResponse<Allocation>>(
|
||||
`/organizations/${orgId}/nodes/${nodeId}/allocations`,
|
||||
),
|
||||
enabled: !!nodeId,
|
||||
});
|
||||
|
||||
const freeAllocations = (allocationsData?.data ?? []).filter((a) => !a.serverId);
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: Record<string, unknown>) =>
|
||||
api.post(`/organizations/${orgId}/servers`, body),
|
||||
onSuccess: () => {
|
||||
navigate(`/org/${orgId}/dashboard`);
|
||||
},
|
||||
});
|
||||
|
||||
const games = gamesData?.data ?? [];
|
||||
const nodes = nodesData?.data ?? [];
|
||||
|
||||
const handleCreate = () => {
|
||||
createMutation.mutate({
|
||||
name,
|
||||
description: description || undefined,
|
||||
gameId,
|
||||
nodeId,
|
||||
allocationId,
|
||||
memoryLimit: memoryLimit * 1024 * 1024,
|
||||
diskLimit: diskLimit * 1024 * 1024,
|
||||
cpuLimit,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Create Server</h1>
|
||||
<p className="text-muted-foreground">Set up a new game server</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{[1, 2, 3].map((s) => (
|
||||
<div
|
||||
key={s}
|
||||
className={`h-1.5 flex-1 rounded-full ${s <= step ? 'bg-primary' : 'bg-muted'}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{step === 1 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Basic Information</CardTitle>
|
||||
<CardDescription>Choose a name and game for your server</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Server Name</Label>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="My Awesome Server"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Description (optional)</Label>
|
||||
<Input
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="A short description"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Game</Label>
|
||||
<Select value={gameId} onValueChange={setGameId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a game" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{games.map((game) => (
|
||||
<SelectItem key={game.id} value={game.id}>
|
||||
{game.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button onClick={() => setStep(2)} disabled={!name || !gameId}>
|
||||
Next
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Node & Allocation</CardTitle>
|
||||
<CardDescription>Choose where to host your server</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Node</Label>
|
||||
<Select
|
||||
value={nodeId}
|
||||
onValueChange={(v) => {
|
||||
setNodeId(v);
|
||||
setAllocationId('');
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a node" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{nodes.map((node) => (
|
||||
<SelectItem key={node.id} value={node.id}>
|
||||
{node.name} ({node.fqdn})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{nodeId && (
|
||||
<div className="space-y-2">
|
||||
<Label>Port Allocation</Label>
|
||||
<Select value={allocationId} onValueChange={setAllocationId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a port" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{freeAllocations.map((a) => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
{a.ip}:{a.port}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{freeAllocations.length === 0 && nodeId && (
|
||||
<p className="text-sm text-destructive">No free allocations on this node</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => setStep(1)}>
|
||||
Back
|
||||
</Button>
|
||||
<Button onClick={() => setStep(3)} disabled={!nodeId || !allocationId}>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Resources</CardTitle>
|
||||
<CardDescription>Set resource limits for this server</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Memory (MB)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={memoryLimit}
|
||||
onChange={(e) => setMemoryLimit(Number(e.target.value))}
|
||||
min={128}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatBytes(memoryLimit * 1024 * 1024)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Disk (MB)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={diskLimit}
|
||||
onChange={(e) => setDiskLimit(Number(e.target.value))}
|
||||
min={256}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatBytes(diskLimit * 1024 * 1024)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>CPU Limit (%)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={cpuLimit}
|
||||
onChange={(e) => setCpuLimit(Number(e.target.value))}
|
||||
min={10}
|
||||
max={10000}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">100% = 1 core</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => setStep(2)}>
|
||||
Back
|
||||
</Button>
|
||||
<Button onClick={handleCreate} disabled={createMutation.isPending}>
|
||||
{createMutation.isPending ? 'Creating...' : 'Create Server'}
|
||||
</Button>
|
||||
</div>
|
||||
{createMutation.isError && (
|
||||
<p className="text-sm text-destructive">Failed to create server. Please try again.</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
|
||||
interface Member {
|
||||
id: string;
|
||||
userId: string;
|
||||
username: string;
|
||||
email: string;
|
||||
role: 'admin' | 'user';
|
||||
}
|
||||
|
||||
export function MembersPage() {
|
||||
const { orgId } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [email, setEmail] = useState('');
|
||||
const [role, setRole] = useState<'admin' | 'user'>('user');
|
||||
|
||||
const { data: members } = useQuery({
|
||||
queryKey: ['members', orgId],
|
||||
queryFn: () => api.get<Member[]>(`/organizations/${orgId}/members`),
|
||||
});
|
||||
|
||||
const addMutation = useMutation({
|
||||
mutationFn: (body: { email: string; role: string }) =>
|
||||
api.post(`/organizations/${orgId}/members`, body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['members', orgId] });
|
||||
setOpen(false);
|
||||
setEmail('');
|
||||
},
|
||||
});
|
||||
|
||||
const removeMutation = useMutation({
|
||||
mutationFn: (memberId: string) =>
|
||||
api.delete(`/organizations/${orgId}/members/${memberId}`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['members', orgId] });
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Members</h1>
|
||||
<p className="text-muted-foreground">Manage organization members</p>
|
||||
</div>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4" /> Add Member
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Member</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
addMutation.mutate({ email, role });
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Role</Label>
|
||||
<Select value={role} onValueChange={(v) => setRole(v as 'admin' | 'user')}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="user">User</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={addMutation.isPending}>
|
||||
Add
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{(members ?? []).map((member) => (
|
||||
<div key={member.id} className="flex items-center justify-between px-4 py-3">
|
||||
<div>
|
||||
<p className="font-medium">{member.username}</p>
|
||||
<p className="text-sm text-muted-foreground">{member.email}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={member.role === 'admin' ? 'default' : 'secondary'}>
|
||||
{member.role}
|
||||
</Badge>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8"
|
||||
onClick={() => removeMutation.mutate(member.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-muted-foreground" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { create } from 'zustand';
|
||||
import { api, ApiError } from '@/lib/api';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
isSuperAdmin: boolean;
|
||||
avatarUrl: string | null;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
register: (email: string, username: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
fetchUser: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set) => ({
|
||||
user: null,
|
||||
isLoading: true,
|
||||
isAuthenticated: false,
|
||||
|
||||
login: async (email, password) => {
|
||||
const data = await api.post<{ accessToken: string; user: User }>('/auth/login', {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
localStorage.setItem('access_token', data.accessToken);
|
||||
set({ user: data.user, isAuthenticated: true });
|
||||
},
|
||||
|
||||
register: async (email, username, password) => {
|
||||
const data = await api.post<{ accessToken: string; user: User }>('/auth/register', {
|
||||
email,
|
||||
username,
|
||||
password,
|
||||
});
|
||||
localStorage.setItem('access_token', data.accessToken);
|
||||
set({ user: data.user, isAuthenticated: true });
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
try {
|
||||
await api.post('/auth/logout');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
localStorage.removeItem('access_token');
|
||||
set({ user: null, isAuthenticated: false });
|
||||
},
|
||||
|
||||
fetchUser: async () => {
|
||||
try {
|
||||
const user = await api.get<User>('/auth/me');
|
||||
set({ user, isAuthenticated: true, isLoading: false });
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) {
|
||||
set({ user: null, isAuthenticated: false, isLoading: false });
|
||||
} else {
|
||||
set({ isLoading: false });
|
||||
}
|
||||
}
|
||||
},
|
||||
}));
|
||||
@@ -8,10 +8,10 @@
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"lint": "eslint src/",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:seed": "tsx src/seed.ts",
|
||||
"db:studio": "drizzle-kit studio"
|
||||
"db:generate": "dotenv -e ../../.env -- drizzle-kit generate",
|
||||
"db:migrate": "dotenv -e ../../.env -- drizzle-kit migrate",
|
||||
"db:seed": "dotenv -e ../../.env -- tsx src/seed.ts",
|
||||
"db:studio": "dotenv -e ../../.env -- drizzle-kit studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"drizzle-orm": "^0.38.0",
|
||||
@@ -19,6 +19,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dotenv-cli": "^8.0.0",
|
||||
"drizzle-kit": "^0.30.0",
|
||||
"tsx": "^4.19.0"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { pgTable, uuid, varchar, integer, boolean } from 'drizzle-orm/pg-core';
|
||||
import { nodes } from './nodes';
|
||||
import { servers } from './servers';
|
||||
|
||||
export const allocations = pgTable('allocations', {
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
nodeId: uuid('node_id')
|
||||
.notNull()
|
||||
.references(() => nodes.id, { onDelete: 'cascade' }),
|
||||
serverId: uuid('server_id').references(() => servers.id, { onDelete: 'set null' }),
|
||||
ip: varchar('ip', { length: 45 }).notNull(),
|
||||
port: integer('port').notNull(),
|
||||
isDefault: boolean('is_default').default(false).notNull(),
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
export * from './users';
|
||||
export * from './organizations';
|
||||
export * from './nodes';
|
||||
export * from './allocations';
|
||||
export * from './games';
|
||||
export * from './servers';
|
||||
export * from './backups';
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
timestamp,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
import { organizations } from './organizations';
|
||||
import { servers } from './servers';
|
||||
|
||||
export const nodes = pgTable('nodes', {
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
@@ -32,14 +31,3 @@ export const nodes = pgTable('nodes', {
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const allocations = pgTable('allocations', {
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
nodeId: uuid('node_id')
|
||||
.notNull()
|
||||
.references(() => nodes.id, { onDelete: 'cascade' }),
|
||||
serverId: uuid('server_id').references(() => servers.id, { onDelete: 'set null' }),
|
||||
ip: varchar('ip', { length: 45 }).notNull(),
|
||||
port: integer('port').notNull(),
|
||||
isDefault: boolean('is_default').default(false).notNull(),
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createDb } from './client';
|
||||
import { games } from './schema/games';
|
||||
import { users } from './schema/users';
|
||||
|
||||
async function seed() {
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
@@ -10,8 +11,25 @@ async function seed() {
|
||||
|
||||
const db = createDb(databaseUrl);
|
||||
|
||||
console.log('Seeding games...');
|
||||
// Seed super admin
|
||||
console.log('Seeding super admin...');
|
||||
// Password: admin123 (argon2id hash)
|
||||
// In production, change this immediately after first login
|
||||
const ADMIN_PASSWORD_HASH =
|
||||
'$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+daw';
|
||||
|
||||
await db
|
||||
.insert(users)
|
||||
.values({
|
||||
email: 'admin@gamepanel.local',
|
||||
username: 'admin',
|
||||
passwordHash: ADMIN_PASSWORD_HASH,
|
||||
isSuperAdmin: true,
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
|
||||
// Seed games
|
||||
console.log('Seeding games...');
|
||||
await db
|
||||
.insert(games)
|
||||
.values([
|
||||
@@ -22,7 +40,7 @@ async function seed() {
|
||||
defaultPort: 25565,
|
||||
startupCommand: '/start',
|
||||
stopCommand: 'stop',
|
||||
configFiles: JSON.stringify([
|
||||
configFiles: [
|
||||
{
|
||||
path: 'server.properties',
|
||||
parser: 'properties',
|
||||
@@ -44,8 +62,8 @@ async function seed() {
|
||||
{ path: 'whitelist.json', parser: 'json' },
|
||||
{ path: 'bukkit.yml', parser: 'yaml' },
|
||||
{ path: 'spigot.yml', parser: 'yaml' },
|
||||
]),
|
||||
environmentVars: JSON.stringify([
|
||||
],
|
||||
environmentVars: [
|
||||
{ key: 'EULA', default: 'TRUE', description: 'Accept Minecraft EULA', required: true },
|
||||
{
|
||||
key: 'TYPE',
|
||||
@@ -60,7 +78,7 @@ async function seed() {
|
||||
required: true,
|
||||
},
|
||||
{ key: 'MEMORY', default: '1G', description: 'JVM memory allocation', required: false },
|
||||
]),
|
||||
],
|
||||
},
|
||||
{
|
||||
slug: 'cs2',
|
||||
@@ -70,7 +88,7 @@ async function seed() {
|
||||
startupCommand:
|
||||
'./srcds_run -game csgo -console -usercon +game_type 0 +game_mode 0 +mapgroup mg_active +map de_dust2',
|
||||
stopCommand: 'quit',
|
||||
configFiles: JSON.stringify([
|
||||
configFiles: [
|
||||
{
|
||||
path: 'csgo/cfg/server.cfg',
|
||||
parser: 'keyvalue',
|
||||
@@ -84,8 +102,8 @@ async function seed() {
|
||||
],
|
||||
},
|
||||
{ path: 'csgo/cfg/autoexec.cfg', parser: 'keyvalue' },
|
||||
]),
|
||||
environmentVars: JSON.stringify([
|
||||
],
|
||||
environmentVars: [
|
||||
{
|
||||
key: 'SRCDS_TOKEN',
|
||||
default: '',
|
||||
@@ -100,7 +118,7 @@ async function seed() {
|
||||
description: 'Max players',
|
||||
required: false,
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
])
|
||||
.onConflictDoNothing();
|
||||
|
||||
@@ -16,10 +16,12 @@ export const PERMISSIONS = {
|
||||
'files.archive': 'Compress and decompress files',
|
||||
|
||||
// Backup
|
||||
'backup.read': 'View backups',
|
||||
'backup.create': 'Create backups',
|
||||
'backup.restore': 'Restore backups',
|
||||
'backup.delete': 'Delete backups',
|
||||
'backup.download': 'Download backups',
|
||||
'backup.manage': 'Lock and manage backups',
|
||||
|
||||
// Schedule
|
||||
'schedule.read': 'View scheduled tasks',
|
||||
|
||||
@@ -8,6 +8,26 @@ export type ScheduleAction = 'command' | 'power' | 'backup';
|
||||
|
||||
export type PluginSource = 'spiget' | 'manual';
|
||||
|
||||
export type ConfigParser = 'properties' | 'json' | 'yaml' | 'keyvalue';
|
||||
|
||||
export interface GameConfigFile {
|
||||
path: string;
|
||||
parser: ConfigParser;
|
||||
editableKeys?: string[];
|
||||
}
|
||||
|
||||
export interface GameEnvVar {
|
||||
key: string;
|
||||
default: string;
|
||||
description: string;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
export interface ConfigEntry {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface PaginationParams {
|
||||
page: number;
|
||||
perPage: number;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user