From 26a62a2fa3f71113cfa1dbae5b76b6c0b6fa792a Mon Sep 17 00:00:00 2001 From: TheBlueBurger <58081413+TheBlueBurger@users.noreply.github.com> Date: Sun, 5 Nov 2023 19:35:32 +0100 Subject: [PATCH] Improve login, begin work on new plugin integrator --- Integrator/.gitignore | 4 + Integrator/build.gradle | 47 ++++ Integrator/gradle.properties | 0 Integrator/gradlew | 245 ++++++++++++++++++ Integrator/gradlew.bat | 92 +++++++ Integrator/settings.gradle | 1 + .../BurgerPanelIntegrator.java | 61 +++++ Integrator/src/main/resources/plugin.yml | 4 + .../buildTools/makeAPITypes/testingplswork.ts | 2 - Server/src/config.ts | 9 + Server/src/index.ts | 38 ++- Server/src/logger.ts | 29 ++- Server/src/plugin.ts | 4 +- Server/src/serverIntegrator.ts | 67 +++++ Server/src/serverManager.ts | 5 + Server/test/testUtil.ts | 4 +- Share/Logging.ts | 3 +- Web/src/App.vue | 61 +---- Web/src/stores/user.ts | 39 ++- 19 files changed, 631 insertions(+), 84 deletions(-) create mode 100644 Integrator/.gitignore create mode 100644 Integrator/build.gradle create mode 100644 Integrator/gradle.properties create mode 100755 Integrator/gradlew create mode 100644 Integrator/gradlew.bat create mode 100644 Integrator/settings.gradle create mode 100644 Integrator/src/main/java/io/github/theblueburger/burgerpanelintegrator/BurgerPanelIntegrator.java create mode 100644 Integrator/src/main/resources/plugin.yml delete mode 100644 Server/buildTools/makeAPITypes/testingplswork.ts create mode 100644 Server/src/serverIntegrator.ts diff --git a/Integrator/.gitignore b/Integrator/.gitignore new file mode 100644 index 0000000..9418009 --- /dev/null +++ b/Integrator/.gitignore @@ -0,0 +1,4 @@ +build +.gradle +.idea +gradle \ No newline at end of file diff --git a/Integrator/build.gradle b/Integrator/build.gradle new file mode 100644 index 0000000..470302e --- /dev/null +++ b/Integrator/build.gradle @@ -0,0 +1,47 @@ +plugins { + id 'java' +} + +group = 'io.github.theblueburger' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + name = "papermc-repo" + url = "https://repo.papermc.io/repository/maven-public/" + } + maven { + name = "sonatype" + url = "https://oss.sonatype.org/content/groups/public/" + } +} + +dependencies { + compileOnly "io.papermc.paper:paper-api:1.20.2-R0.1-SNAPSHOT" +} + +def targetJavaVersion = 17 +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + sourceCompatibility = javaVersion + targetCompatibility = javaVersion + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } +} + +tasks.withType(JavaCompile).configureEach { + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + options.release = targetJavaVersion + } +} + +processResources { + def props = [version: version] + inputs.properties props + filteringCharset 'UTF-8' + filesMatching('plugin.yml') { + expand props + } +} diff --git a/Integrator/gradle.properties b/Integrator/gradle.properties new file mode 100644 index 0000000..e69de29 diff --git a/Integrator/gradlew b/Integrator/gradlew new file mode 100755 index 0000000..aeb74cb --- /dev/null +++ b/Integrator/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/Integrator/gradlew.bat b/Integrator/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/Integrator/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/Integrator/settings.gradle b/Integrator/settings.gradle new file mode 100644 index 0000000..14f110f --- /dev/null +++ b/Integrator/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'BurgerPanelIntegrator' diff --git a/Integrator/src/main/java/io/github/theblueburger/burgerpanelintegrator/BurgerPanelIntegrator.java b/Integrator/src/main/java/io/github/theblueburger/burgerpanelintegrator/BurgerPanelIntegrator.java new file mode 100644 index 0000000..c659664 --- /dev/null +++ b/Integrator/src/main/java/io/github/theblueburger/burgerpanelintegrator/BurgerPanelIntegrator.java @@ -0,0 +1,61 @@ +package io.github.theblueburger.burgerpanelintegrator; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; +import org.json.simple.JSONObject; +import org.slf4j.Logger; + +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.nio.charset.Charset; +import java.nio.file.Path; + +public final class BurgerPanelIntegrator extends JavaPlugin { + static String burgerpanelID; + static String burgerpanelSocketPath; + static Logger logger; + SocketChannel client; + @Override + public void onEnable() { + logger = this.getSLF4JLogger(); + burgerpanelSocketPath = System.getenv("BURGERPANEL_INTEGRATOR_PATH"); + burgerpanelID = System.getenv("BURGERPANEL_INTEGRATOR_SERVER_ID"); + if(burgerpanelID == null || burgerpanelSocketPath == null) { + logger.error("Can't find server id or integrator path for burgerpanel, is it running from burgerpanel properly?"); + this.setEnabled(false); + } + Path integratorSocketPath = Path.of(burgerpanelSocketPath); + UnixDomainSocketAddress socketAddress = UnixDomainSocketAddress.of(integratorSocketPath); + try { + client = SocketChannel.open(StandardProtocolFamily.UNIX); + } catch (IOException e) { + throw new RuntimeException(e); + } + try { + client.connect(socketAddress); + } catch (IOException e) { + throw new RuntimeException(e); + } + JSONObject authObj = new JSONObject(); + authObj.put("dataType", "request"); + authObj.put("type", "setID"); + authObj.put("id", burgerpanelID); + try { + write(authObj); + } catch (IOException e) { + throw new RuntimeException(e); + } + logger.info("Connected to the BurgerPanel!"); + } + + @Override + public void onDisable() { + // Plugin shutdown logic + } + public void write(JSONObject obj) throws IOException { + client.write(ByteBuffer.wrap(obj.toJSONString().getBytes(Charset.defaultCharset()))); + } +} diff --git a/Integrator/src/main/resources/plugin.yml b/Integrator/src/main/resources/plugin.yml new file mode 100644 index 0000000..234b23d --- /dev/null +++ b/Integrator/src/main/resources/plugin.yml @@ -0,0 +1,4 @@ +name: BurgerPanelIntegrator +version: '${version}' +main: io.github.theblueburger.burgerpanelintegrator.BurgerPanelIntegrator +api-version: '1.20' diff --git a/Server/buildTools/makeAPITypes/testingplswork.ts b/Server/buildTools/makeAPITypes/testingplswork.ts deleted file mode 100644 index ad36751..0000000 --- a/Server/buildTools/makeAPITypes/testingplswork.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type {PluginEssentials} from "../../src/plugin"; -export {PluginEssentials}; \ No newline at end of file diff --git a/Server/src/config.ts b/Server/src/config.ts index 985d37a..6140c54 100644 --- a/Server/src/config.ts +++ b/Server/src/config.ts @@ -121,8 +121,17 @@ export async function setSetting(key: K, value: Config[K // Set it in the database with upsert await settings.upsert({key}, {value: value.toString()}); cachedSettings[key] = value; + if(afterSetList[key]) afterSetList[key].forEach(cb => cb(value)); return value; } +let afterSetList: { + [a: string]: ((a: any) => void)[] +} = {}; +export function afterSet(key: K, cb: (newVal: any) => void) { + if(!afterSetList[key]) afterSetList[key] = [cb]; + else afterSetList[key].push(cb); +} + export async function getAllSettings(): Promise<{[key in keyof Config]: ConfigValue}> { let result: { [key in keyof Config]?: ConfigValue } = {}; for (let key in defaultConfig) { diff --git a/Server/src/index.ts b/Server/src/index.ts index 7a64a98..0983d43 100644 --- a/Server/src/index.ts +++ b/Server/src/index.ts @@ -6,7 +6,7 @@ import fs from "node:fs"; import path from "node:path"; import { User } from '../../Share/User.js'; import url from "node:url"; -import { getSetting, isValidKey, setSetting } from './config.js'; +import { afterSet, getSetting, isValidKey, setSetting } from './config.js'; import { once } from "node:events"; import serverManager from './serverManager.js'; import { makeToken, servers, users } from './db.js'; @@ -16,6 +16,7 @@ import hasPermission from './util/permission.js'; import logger, { LogLevel } from './logger.js'; import {buildInfo} from "../../Share/BuildInfo.js"; import pluginHandler, {mixinHandler} from "./plugin.js"; +import { exists } from "./util/exists.js"; // a export const isProd = process.env.NODE_ENV == "production"; @@ -357,7 +358,36 @@ export async function exit(signal?: string) { } process.on("SIGINT", () => exit("INT")); process.on("SIGTERM", () => exit("TERM")); +async function findLogPath() { + let logLocationInConfig = await getSetting("logging_logDir"); + if(typeof logLocationInConfig != "string") return null; + if(logLocationInConfig == "") { + let logDir = path.join(__dirname, "logs"); + logLocationInConfig = logDir; + if(!await exists(logLocationInConfig)) fs.mkdirSync(logLocationInConfig); + await setSetting("logging_logDir", logDir); + } else if(logLocationInConfig == "disabled") { + return null; + } + if(!await exists(logLocationInConfig)) fs.mkdirSync(logLocationInConfig); + let filePath = path.join(logLocationInConfig, `BurgerPanel ${logger.makeNiceDate(process.platform == "win32")}`); + if(await exists(filePath + ".log")) { // how would this even trigger it changes every second + let i = 0; + while(await exists(filePath + i + ".log")) { + i++; + } + filePath = filePath + i; + } + return filePath + ".log"; +} packetHandler.init().then(async () => { + logger.setupWriteStream(await findLogPath()); + afterSet("logging_DisabledIDs", newVal => { + logger.ignoredLogs = newVal; + }); + afterSet("logging_DiscordWebHookURL", newVal => { + logger.webhookURL = newVal; + }); logger.log(`BurgerPanel v${buildInfo.version} (${buildInfo.gitHash} on ${buildInfo.branch})`, "start", LogLevel.INFO); let port: number | undefined; portTry: try { @@ -524,8 +554,10 @@ packetHandler.init().then(async () => { await logger.log("Created admin user with ID " + adminUser._id + " and token " + adminUser.token, "start", LogLevel.INFO, false); } }); -process.on("uncaughtException", errHandler); -process.on("unhandledRejection", errHandler); +if(isProd) { + process.on("uncaughtException", errHandler); + process.on("unhandledRejection", errHandler); +} function errHandler(err: any) { logger.log("Uncaught error: " + err, "error", LogLevel.ERROR, false, true, true).catch((err2) => { console.log("Error while logging error?!?!?: " + err2 + ". Original error: " + err); diff --git a/Server/src/logger.ts b/Server/src/logger.ts index 526c997..6d04e9a 100644 --- a/Server/src/logger.ts +++ b/Server/src/logger.ts @@ -1,6 +1,6 @@ import chalk from "chalk"; import {IDs} from "../../Share/Logging.js"; -import { getSetting, setSetting } from "./config.js"; +//import { getSetting, setSetting } from "./config.js"; import fs from "node:fs"; import fsp from "node:fs/promises"; import url from "node:url"; @@ -21,13 +21,13 @@ let colors: {[level: string]: Function} = { let __dirname = url.fileURLToPath(new URL('.', import.meta.url)); export default new class Logger { writeStream: fs.WriteStream | null = null; + webhookURL: string | undefined; + ignoredLogs: string | undefined; constructor() { - this.setupWriteStream(); } - async setupWriteStream() { - if(process.env.SKIP_BURGERPANEL_LOGFILE) return; - let location = await this.getLogLocation(); + async setupWriteStream(location: string | null) { if(!location) return; + if(process.env.SKIP_BURGERPANEL_LOGFILE) return; this.writeStream = fs.createWriteStream(location); this.log("Logging to " + location, "info", LogLevel.DEBUG, false, false) } @@ -37,16 +37,17 @@ export default new class Logger { return dateString; } async getLogLocation(): Promise { - let logLocationInConfig = await getSetting("logging_logDir"); + /*let logLocationInConfig = await getSetting("logging_logDir"); if(typeof logLocationInConfig != "string") return null; if(logLocationInConfig == "") { - let logDir = path.join(__dirname, "logs") - if(!await exists(logDir)) await fsp.mkdir(logDir); + let logDir = path.join(__dirname, "logs"); + if(!await exists(logLocationInConfig)) await fsp.mkdir(logLocationInConfig); await setSetting("logging_logDir", logDir); logLocationInConfig = logDir; } else if(logLocationInConfig == "disabled") { return null; } + if(!await exists(logLocationInConfig)) await fsp.mkdir(logLocationInConfig); let filePath = path.join(logLocationInConfig, `BurgerPanel ${this.makeNiceDate(process.platform == "win32")}`); if(await exists(filePath + ".log")) { // how would this even trigger it changes every second let i = 0; @@ -55,7 +56,8 @@ export default new class Logger { } filePath = filePath + i; } - return filePath + ".log"; + return filePath + ".log";*/ + return null; } async log(message: string, id: IDs, level: LogLevel = LogLevel.INFO, emitWebhook: boolean = true, logToFile: boolean = true, logNoMatterWhat: boolean = false) { if(!id) return; @@ -69,17 +71,15 @@ export default new class Logger { return useColors ? colors[level ?? LogLevel.INFO](str) : str; } async isDisabled(id: IDs): Promise { - return (await getSetting("logging_DisabledIDs"))?.toString().split(",").includes(id as string) || false; + return this.ignoredLogs?.toString().split(",").includes(id as string) || false; } async sendDiscordWebhook(message: string, id: IDs, level: LogLevel) { - let discordWebHookURL = await getSetting("logging_DiscordWebHookURL"); - if(!discordWebHookURL) return; - if(typeof discordWebHookURL != "string" || discordWebHookURL == "disabled") return; + if(typeof this.webhookURL != "string" || this.webhookURL == "disabled") return; let headers = new Headers(); headers.append("Content-Type", "application/json"); headers.append("X-BurgerPanel-ID", id); headers.append("X-BurgerPanel-LogLevel", LogLevel[level ?? LogLevel.INFO]); - await fetch(discordWebHookURL, { + await fetch(this.webhookURL, { method: "post", headers, body: JSON.stringify({ @@ -94,5 +94,6 @@ export default new class Logger { }).catch((err) => { this.log("Error while sending to webhook: " + err, "error", LogLevel.ERROR, false); }); + return; } } \ No newline at end of file diff --git a/Server/src/plugin.ts b/Server/src/plugin.ts index 932091b..13454a3 100644 --- a/Server/src/plugin.ts +++ b/Server/src/plugin.ts @@ -30,9 +30,10 @@ export class PluginEssentials { constructor(name: string) { this.name = name; } - getExports(name: string) { + getExport(name: string) { switch(name) { case "serverManager": return import("./serverManager.js") + case "serverIntegrator": return import("./serverIntegrator.js") case "logger": return import("./logger.js") case "index": return import("./index.js") case "db": return import("./db.js") @@ -40,6 +41,7 @@ export class PluginEssentials { default: throw new Error("invalid export") } } + getExports(name: string) {return this.getExport(name)} get mixinHandler() { return mixinHandler; } diff --git a/Server/src/serverIntegrator.ts b/Server/src/serverIntegrator.ts new file mode 100644 index 0000000..da44197 --- /dev/null +++ b/Server/src/serverIntegrator.ts @@ -0,0 +1,67 @@ +const isProd = process.env.NODE_ENV == "production"; +import fsSync from "node:fs"; +import net from "node:net"; +import url from "node:url"; +import fs from "node:fs/promises"; +import logger, { LogLevel } from "./logger.js"; +import type { Server } from "../../Share/Server.js"; +interface OurIntegratorClient extends net.Socket { + burgerpanelData: { + server?: string + } +} +let __dirname = url.fileURLToPath(new URL('.', import.meta.url)); +export default new class ServerIntegrator { + path = (isProd ? __dirname : process.cwd()) + "/connector.burgerpanelsock"; + requestCallbacks: { + [id: string]: (resp: any) => void + } = {}; + server: net.Server = undefined as any as net.Server; + servers: { + [id: string]: { + server: Server, + client?: net.Socket + } + } = {}; + constructor() { + if(fsSync.existsSync(this.path)) fsSync.rmSync(this.path); + this.listen(); + } + private listen() { + let server = net.createServer(_c => { + let c = _c as OurIntegratorClient; + c.burgerpanelData = {}; + c.on("data", d => { + let json; + try { + json = JSON.parse(d.toString()); + } catch(err) { + logger.log(`Client sent invalid JSON, server id is ${c.burgerpanelData.server}`, "server.integrator", LogLevel.ERROR); + return; + } + if(Array.isArray(json)) return; + if(!["request", "response"].includes(json.dataType)) return; + if(json.dataType == "response") { + if(!this.requestCallbacks[json.id]) return; + this.requestCallbacks[json.id](json.data); + return; + } + // todo: proper handler + switch(json.type) { + case "setID": + if(!this.servers[json.id]) return; + c.burgerpanelData.server = json.id; + logger.log(`Server ${json.id} connected`, "server.integrator"); + break; + } + }); + }); + this.server = server; + server.listen(this.path); + } + prepareServer(server: Server) { + this.servers[server._id] = { + server + }; + } +} diff --git a/Server/src/serverManager.ts b/Server/src/serverManager.ts index 6b8b18f..b15f79f 100644 --- a/Server/src/serverManager.ts +++ b/Server/src/serverManager.ts @@ -11,6 +11,7 @@ import { userHasAccessToServer as _userHasAccessToServer } from "../../Share/Per import logger, { LogLevel } from "./logger.js"; import isValidMCVersion from "./util/isValidMCVersion.js"; import { promiseSleep } from "blueutilities"; +import serverIntegrator from "./serverIntegrator.js"; export default new class ServerManager { servers: { @@ -119,6 +120,10 @@ enforce-secure-profile=false let childProcess = spawn("java", args, { cwd: server.path, stdio: "pipe", + env: { + BURGERPANEL_INTEGRATOR_PATH: serverIntegrator.path, + BURGERPANEL_INTEGRATOR_SERVER_ID: server._id + } }); serverEntry.childProcess = childProcess; childProcess.stdout.on("data", d => this.handleServerLog(server, d.toString())); diff --git a/Server/test/testUtil.ts b/Server/test/testUtil.ts index 6470579..4f85d4b 100644 --- a/Server/test/testUtil.ts +++ b/Server/test/testUtil.ts @@ -37,8 +37,7 @@ export default new class TestUtil { fs.mkdirSync(path.join(__dirname, "..", "test-context")); } catch {} fs.mkdirSync(path.join(__dirname, "..", "test-context", this.port.toString())); - let nodePath = fs.readlinkSync("/proc/self/exe"); - let newProcess = spawn(nodePath, ["burgerpanel.mjs"], { + let newProcess = spawn(process.execPath, ["burgerpanel.mjs"], { cwd: path.join(__dirname, "..", "_build"), env: { PORT: this.port.toString(), @@ -118,6 +117,7 @@ export default new class TestUtil { let adminClient = await this.getClient(true); let user = await adminClient.req("createUser", {username}); let token = (await adminClient.req("getUserToken", {id: user.user._id})); + adminClient.close(); let newClient = await this.getClient(); await newClient.req("auth", { token: token.token diff --git a/Share/Logging.ts b/Share/Logging.ts index a624fc0..1155d10 100644 --- a/Share/Logging.ts +++ b/Share/Logging.ts @@ -44,6 +44,7 @@ export let IDs = [ "server.file.move", "api", "debug", - "plugin.download" + "plugin.download", + "server.integrator" ] as const; export type IDs = typeof IDs[number]; \ No newline at end of file diff --git a/Web/src/App.vue b/Web/src/App.vue index 191f85e..1d0b2b8 100644 --- a/Web/src/App.vue +++ b/Web/src/App.vue @@ -126,50 +126,6 @@ onUnmounted(() => { unmountAborter.abort(); }); - - -async function login(usingTokenOverride: boolean = false) { - let authResp: void | RequestResponses["auth"]; - if (usingTokenLogin.value || usingTokenOverride) { - authResp = await ws.sendRequest("auth", { - token: token.value - }, false).catch((err) => { - loginMsg.value = err; - token.value = ""; - localStorage.removeItem("token"); - showLoginScreen.value = true; - }); - } else { - authResp = await ws.sendRequest("auth", { - username: loginUsername.value, - password: loginPassword.value - }, false).catch((err) => { - loginMsg.value = err; - showLoginScreen.value = true; - }) - } - if (!authResp) { - showLoginScreen.value = true; - return; - } - if (!authResp.user) { - console.log("User doesn't exist, but login was successful. Probably already authenticated."); - return; - } - user.user = authResp.user; - console.log("Logged in as " + authResp.user.username); - localStorage.setItem("token", authResp.user.token); - let servers = useServers(); - if (authResp.servers) servers.addServers(authResp.servers); - if (lastID.value != authResp.user._id) createNotification("Welcome, " + authResp.user.username + "!"); - lastID.value = authResp.user._id; - if (authResp.statuses) servers.addStatuses(authResp.statuses); - queuedPackets.forEach(queuedPacket => { - console.log("Sending queued request", queuedPacket) - ws.send(JSON.stringify(queuedPacket)); - }); - queuedPackets = []; -} let token = ref(""); ws.listenForEvent("logout", () => { @@ -224,9 +180,12 @@ router.beforeEach(async (guard, fromGuard) => { console.timeEnd(); console.log("Readystate is", ws.ws?.readyState) console.log("Connected, logging in..."); - token.value = guard.query.useToken as string; showLoginScreen.value = false; - login(true); + try { + user.loginToken(guard.query.useToken as string); + } catch { + showLoginScreen.value = true; + } console.log("Token used, removing from query."); router.push({ path: guard.path, @@ -257,6 +216,14 @@ let hideMainContentMsg = computed(() => { if(user.user?.setupPending && router.currentRoute.value.name != "userSetup") return "Redirecting to user setup"; }); let shouldHideMainContent = computed(() => typeof hideMainContentMsg.value == "string"); +async function login() { + try { + if(usingTokenLogin.value) await user.loginToken(token.value); + else await user.loginUsernamePass(loginUsername.value, loginPassword.value); + } catch(err) { + loginMsg.value = err+""; + } +}