first commit
This commit is contained in:
commit
eac573c682
26 changed files with 1262 additions and 0 deletions
8
api/.env.example
Normal file
8
api/.env.example
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
prometheusHost=https://..
|
||||
prometheusPassword=..
|
||||
prometheusUsername=..
|
||||
rconHost=..:3000
|
||||
rconPassword=..
|
||||
|
||||
port=8499
|
||||
host=0.0.0.0
|
||||
175
api/.gitignore
vendored
Normal file
175
api/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
|
||||
|
||||
# Logs
|
||||
|
||||
logs
|
||||
_.log
|
||||
npm-debug.log_
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Caches
|
||||
|
||||
.cache
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# Runtime data
|
||||
|
||||
pids
|
||||
_.pid
|
||||
_.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
|
||||
.temp
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
|
||||
# IntelliJ based IDEs
|
||||
.idea
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
15
api/README.md
Normal file
15
api/README.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# api
|
||||
|
||||
To install dependencies:
|
||||
|
||||
```bash
|
||||
bun install
|
||||
```
|
||||
|
||||
To run:
|
||||
|
||||
```bash
|
||||
bun run index.ts
|
||||
```
|
||||
|
||||
This project was created using `bun init` in bun v1.1.42. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
|
||||
BIN
api/bun.lockb
Executable file
BIN
api/bun.lockb
Executable file
Binary file not shown.
117
api/index.ts
Normal file
117
api/index.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
/*
|
||||
Ziedu Vija, armija, Ziedu Vija leģions
|
||||
Pagāju garām es tavai kucei, zivju paviljons
|
||||
Ēdu sēnes, šampinjons
|
||||
Tu neēd neko, tu ir bomzis
|
||||
Nomirs badā paļubom
|
||||
Nomirs badā paļubom
|
||||
|
||||
2025 sad.ovh dev
|
||||
|
||||
*/
|
||||
|
||||
import express, { type Request, type Response, type NextFunction } from 'express';
|
||||
import { InstantVector, PrometheusDriver, ResponseType, SampleValue } from 'prometheus-query';
|
||||
import { PacketType, Rcon } from "./rcon";
|
||||
|
||||
if(!process.env.prometheusHost) {
|
||||
throw new Error("missing prometheus host")
|
||||
}
|
||||
if(process.env.prometheusUsername || process.env.prometheusPassword) {
|
||||
if(!process.env.prometheusUsername) {
|
||||
throw new Error("missing prometheus username")
|
||||
}
|
||||
if(!process.env.prometheusPassword) {
|
||||
throw new Error("missing prometheus password")
|
||||
}
|
||||
}
|
||||
if(!process.env.rconHost || !process.env.rconPassword) {
|
||||
throw new Error("missing rcon host or rcon password")
|
||||
}
|
||||
const rcon = new Rcon(process.env.rconHost.split(":")[0], +process.env.rconHost.split(":")[1], process.env.rconPassword);
|
||||
let rconReconnectTimeout: Timer | null | undefined;
|
||||
let whitelistedPlayers: string[] = [];
|
||||
let lastRequested = 0;
|
||||
|
||||
const playerRegex = /There are \d* whitelisted player\(s\): /gm;
|
||||
|
||||
rcon.on("connect", () => {
|
||||
console.log("RCON connected.");
|
||||
});
|
||||
|
||||
rcon.on("auth", () => {
|
||||
console.log("RCON authenicated.");
|
||||
});
|
||||
|
||||
rcon.on("response", (a: string) => {
|
||||
if (playerRegex.test(a)) {
|
||||
whitelistedPlayers = a.replace(playerRegex, "").split(", ");
|
||||
}
|
||||
})
|
||||
|
||||
rcon.on("end", () => {
|
||||
console.log("RCON ended. Reconnecting in 2000ms.")
|
||||
if(rconReconnectTimeout) {
|
||||
clearTimeout(rconReconnectTimeout);
|
||||
}
|
||||
rconReconnectTimeout = setTimeout(() => {
|
||||
rcon.connect()
|
||||
}, 2000)
|
||||
})
|
||||
const app = express();
|
||||
|
||||
//@ts-expect-error
|
||||
app.use((req, res, next) => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
||||
if (req.method === 'OPTIONS') {
|
||||
return res.sendStatus(200);
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
const host = process.env.host || "localhost";
|
||||
const port = +(process.env.port || 3000);
|
||||
|
||||
const prom = new PrometheusDriver({
|
||||
endpoint: process.env.prometheusHost,
|
||||
auth: process.env.prometheusUsername ? {
|
||||
username: process.env.prometheusUsername!,
|
||||
password: process.env.prometheusPassword!
|
||||
} : undefined
|
||||
})
|
||||
|
||||
app.get("/api/getTps", async (req, res) => {
|
||||
const query = await prom.instantQuery(`minecraft_tps`);
|
||||
const value = (query.result[0] as InstantVector).value as SampleValue;
|
||||
res.json(value.value)
|
||||
})
|
||||
|
||||
app.get("/api/getPlayersOnline", async (req, res) => {
|
||||
const query = await prom.instantQuery(`sum(minecraft_players_online{instance="172.18.0.1:25585", job="prometheus"})`);
|
||||
const value = (query.result[0] as InstantVector).value as SampleValue;
|
||||
res.json(value.value)
|
||||
})
|
||||
|
||||
app.get("/api/uptime", async (req, res) => {
|
||||
const query = await prom.instantQuery(`process_start_time_seconds`);
|
||||
const value = (query.result[0] as InstantVector).value as SampleValue;
|
||||
res.json(Date.now() - (value.value*1000))
|
||||
})
|
||||
|
||||
app.get("/api/whitelist", async (req, res) => {
|
||||
if ( Date.now() - lastRequested > 60000) {
|
||||
lastRequested = Date.now();
|
||||
rcon.send("whitelist list", PacketType.COMMAND);
|
||||
rcon.once("response", () => {
|
||||
res.json(whitelistedPlayers);
|
||||
});
|
||||
} else {
|
||||
res.json(whitelistedPlayers);
|
||||
}
|
||||
})
|
||||
app.listen(port, host, () => {
|
||||
rcon.connect()
|
||||
console.log(`Server is running on http://${host}:${port}`);
|
||||
});
|
||||
17
api/package.json
Normal file
17
api/package.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "api",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/express": "^5.0.0",
|
||||
"express": "^4.21.2",
|
||||
"prometheus-query": "^3.4.1",
|
||||
"typed-emitter": "^2.1.0"
|
||||
}
|
||||
}
|
||||
235
api/rcon.ts
Normal file
235
api/rcon.ts
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
import EventEmitter from "events";
|
||||
import * as net from "net";
|
||||
import * as dgram from "dgram";
|
||||
import { Buffer } from "buffer";
|
||||
import type TypedEmitter from "typed-emitter";
|
||||
|
||||
type Events = {
|
||||
error: (error: Error) => void;
|
||||
auth: () => void;
|
||||
response: (response: string) => void;
|
||||
connect: () => void;
|
||||
end: () => void;
|
||||
done: () => void;
|
||||
};
|
||||
|
||||
export const PacketType = {
|
||||
COMMAND: 0x02,
|
||||
AUTH: 0x03,
|
||||
RESPONSE_VALUE: 0x00,
|
||||
RESPONSE_AUTH: 0x02,
|
||||
};
|
||||
|
||||
interface Options {
|
||||
tcp?: boolean;
|
||||
challenge?: boolean;
|
||||
id?: number;
|
||||
}
|
||||
export class Rcon extends (EventEmitter as new () => TypedEmitter<Events>) {
|
||||
private host: string;
|
||||
private port: number;
|
||||
private password: string;
|
||||
private rconId: number;
|
||||
private hasAuthed: boolean;
|
||||
private outstandingData: Uint8Array | null;
|
||||
private tcp: boolean;
|
||||
private challenge: boolean;
|
||||
private _challengeToken: string;
|
||||
private _tcpSocket!: net.Socket;
|
||||
private _udpSocket!: dgram.Socket;
|
||||
|
||||
constructor(host: string, port: number, password: string, options?: Options) {
|
||||
super();
|
||||
options = options || {};
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.password = password;
|
||||
this.rconId = options.id || 0x0012d4a6; // This is arbitrary in most cases
|
||||
this.hasAuthed = false;
|
||||
this.outstandingData = null;
|
||||
this.tcp = options.tcp ? options.tcp : true;
|
||||
this.challenge = options.challenge ? options.challenge : true;
|
||||
this._challengeToken = "";
|
||||
}
|
||||
|
||||
public send = (data: string, cmd?: number, id?: number): void => {
|
||||
let sendBuf: Buffer;
|
||||
if (this.tcp) {
|
||||
cmd = cmd || PacketType.COMMAND;
|
||||
id = id || this.rconId;
|
||||
|
||||
const length = Buffer.byteLength(data);
|
||||
sendBuf = Buffer.alloc(length + 14);
|
||||
sendBuf.writeInt32LE(length + 10, 0);
|
||||
sendBuf.writeInt32LE(id, 4);
|
||||
sendBuf.writeInt32LE(cmd, 8);
|
||||
sendBuf.write(data, 12);
|
||||
sendBuf.writeInt16LE(0, length + 12);
|
||||
} else {
|
||||
if (this.challenge && !this._challengeToken) {
|
||||
this.emit("error", new Error("Not authenticated"));
|
||||
return;
|
||||
}
|
||||
let str = "rcon ";
|
||||
if (this._challengeToken) str += this._challengeToken + " ";
|
||||
if (this.password) str += this.password + " ";
|
||||
str += data + "\n";
|
||||
sendBuf = Buffer.alloc(4 + Buffer.byteLength(str));
|
||||
sendBuf.writeInt32LE(-1, 0);
|
||||
sendBuf.write(str, 4);
|
||||
}
|
||||
this._sendSocket(sendBuf);
|
||||
};
|
||||
|
||||
private _sendSocket = (buf: Buffer) => {
|
||||
if (this._tcpSocket) {
|
||||
this._tcpSocket.write(buf.toString("binary"), "binary");
|
||||
} else if (this._udpSocket) {
|
||||
this._udpSocket.send(buf, 0, buf.length, this.port, this.host);
|
||||
}
|
||||
};
|
||||
|
||||
public connect = (): void => {
|
||||
if (this.tcp) {
|
||||
this._tcpSocket = net.createConnection(this.port, this.host);
|
||||
this._tcpSocket.on("data", (data) => {
|
||||
this._tcpSocketOnData(data);
|
||||
});
|
||||
this._tcpSocket.on("connect", () => {
|
||||
this.socketOnConnect();
|
||||
});
|
||||
this._tcpSocket.on("error", (err) => {
|
||||
//this.emit("error", err);
|
||||
this.socketOnEnd()
|
||||
});
|
||||
this._tcpSocket.on("end", () => {
|
||||
this.socketOnEnd();
|
||||
});
|
||||
} else {
|
||||
this._udpSocket = dgram.createSocket("udp4");
|
||||
this._udpSocket
|
||||
.on("message", (data) => {
|
||||
this._udpSocketOnData(data);
|
||||
})
|
||||
.on("listening", () => {
|
||||
this.socketOnConnect();
|
||||
})
|
||||
.on("error", (err) => {
|
||||
this.emit("error", err);
|
||||
})
|
||||
.on("close", () => {
|
||||
this.socketOnEnd();
|
||||
});
|
||||
this._udpSocket.bind(0);
|
||||
}
|
||||
};
|
||||
|
||||
public disconnect = (): void => {
|
||||
if (this._tcpSocket) this._tcpSocket.end();
|
||||
if (this._udpSocket) this._udpSocket.close();
|
||||
};
|
||||
|
||||
public setTimeout = (timeout: number, callback: () => void): void => {
|
||||
if (!this._tcpSocket) return;
|
||||
this._tcpSocket.setTimeout(timeout, () => {
|
||||
this._tcpSocket.end();
|
||||
if (callback) callback();
|
||||
});
|
||||
};
|
||||
|
||||
private _udpSocketOnData = (data: Buffer) => {
|
||||
const a = data.readUInt32LE(0);
|
||||
if (a === 0xffffffff) {
|
||||
const str = data.toString("utf-8", 4);
|
||||
const tokens = str.split(" ");
|
||||
if (
|
||||
tokens.length === 3 &&
|
||||
tokens[0] === "challenge" &&
|
||||
tokens[1] === "rcon"
|
||||
) {
|
||||
this._challengeToken = tokens[2]
|
||||
.substring(0, tokens[2].length - 1)
|
||||
.trim();
|
||||
this.hasAuthed = true;
|
||||
this.emit("auth");
|
||||
} else {
|
||||
this.emit("response", str.substring(1, str.length - 2));
|
||||
}
|
||||
} else {
|
||||
this.emit("error", new Error("Received malformed packet"));
|
||||
}
|
||||
};
|
||||
|
||||
private _tcpSocketOnData = (data: Buffer) => {
|
||||
if (this.outstandingData != null) {
|
||||
data = Buffer.concat(
|
||||
[this.outstandingData, data],
|
||||
this.outstandingData.length + data.length
|
||||
);
|
||||
this.outstandingData = null;
|
||||
}
|
||||
|
||||
while (data.length) {
|
||||
const len = data.readInt32LE(0);
|
||||
if (!len) return;
|
||||
|
||||
const id = data.readInt32LE(4);
|
||||
const type = data.readInt32LE(8);
|
||||
|
||||
if (len >= 10 && data.length >= len + 4) {
|
||||
if (id === this.rconId) {
|
||||
if (!this.hasAuthed && type === PacketType.RESPONSE_AUTH) {
|
||||
this.hasAuthed = true;
|
||||
this.emit("auth");
|
||||
} else if (type === PacketType.RESPONSE_VALUE) {
|
||||
// Read just the body of the packet (truncate the last null byte)
|
||||
// See https://developer.valvesoftware.com/wiki/Source_RCON_Protocol for details
|
||||
let str = data.toString("utf8", 12, 12 + len - 10);
|
||||
|
||||
if (str.charAt(str.length - 1) === "\n") {
|
||||
// Emit the response without the newline.
|
||||
str = str.substring(0, str.length - 1);
|
||||
}
|
||||
|
||||
this.emit("response", str);
|
||||
}
|
||||
} else {
|
||||
this.emit("error", new Error("Authentication failed"));
|
||||
}
|
||||
|
||||
data = data.slice(12 + len - 8);
|
||||
} else {
|
||||
// Keep a reference to the chunk if it doesn't represent a full packet
|
||||
this.outstandingData = data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public socketOnConnect = (): void => {
|
||||
this.emit("connect");
|
||||
|
||||
if (this.tcp) {
|
||||
this.send(this.password, PacketType.AUTH);
|
||||
} else if (this.challenge) {
|
||||
const str = "challenge rcon\n";
|
||||
const sendBuf = Buffer.alloc(str.length + 4);
|
||||
sendBuf.writeInt32LE(-1, 0);
|
||||
sendBuf.write(str, 4);
|
||||
this._sendSocket(sendBuf);
|
||||
} else {
|
||||
const sendBuf = Buffer.alloc(5);
|
||||
sendBuf.writeInt32LE(-1, 0);
|
||||
sendBuf.writeUInt8(0, 4);
|
||||
this._sendSocket(sendBuf);
|
||||
|
||||
this.hasAuthed = true;
|
||||
this.emit("auth");
|
||||
}
|
||||
};
|
||||
|
||||
public socketOnEnd = (): void => {
|
||||
this.emit("end");
|
||||
this.hasAuthed = false;
|
||||
};
|
||||
}
|
||||
27
api/tsconfig.json
Normal file
27
api/tsconfig.json
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
// Enable latest features
|
||||
"lib": ["ESNext", "DOM"],
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"allowJs": true,
|
||||
|
||||
// Bundler mode
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue