Add RCON client + SendCurrency service (AtomCMS-faithful)

- rcon.ts: Node net.Socket transport speaking AtomCMS's exact protocol (raw
  JSON {"key","data"} over rcon_ip:rcon_port, fire-and-forget) with a bounded
  timeout + backoff retry; typed commands matching RconService EXACTLY
  (sendgift `itemid`, disconnect `username`, no-data => data:null, givepoints
  numeric `type`, forwarduser, setmotto/setrank/alertuser, give*). Injectable
  transport keeps command shapes unit-testable.
- send-currency.ts: mirrors the SendCurrency action — RCON deliver, else DB
  fallback (credits -> users.credits; duckets/diamonds/points -> users_currency
  by type 0/5/101).
- env: RCON_HOST/PORT/TIMEOUT/RETRIES. vitest: SKIP_ENV_VALIDATION for unit tests.

Verified: tsc exit 0, vitest 39/39, next build exit 0. Live TCP test deferred
(needs a running emulator).
This commit is contained in:
Simo committed 2026-06-27 16:37:42 +02:00
1 parent 443d908909
commit 8fca407f0f
6 files changed
+350

No files matched your search

+127
View File
@@ -0,0 +1,127 @@
import net from "node:net";
import { CurrencyType } from "@/lib/services/currency";
import { env } from "@/env";
export interface RconPayload {
key: string;
data: Record<string, unknown> | null;
}
export type RconTransport = (payload: RconPayload) => Promise<boolean>;
/**
* TCP transport faithful to AtomCMS's RconService: writes the raw JSON
* `{"key":...,"data":...}` to rcon_ip:rcon_port with no terminator, fire-and-
* forget. The PHP original silently drops on a dead socket; we add a bounded
* connect timeout + exponential-backoff retry so delivery is best-effort.
*/
export function tcpTransport(opts: {
host: string;
port: number;
timeoutMs: number;
maxRetries: number;
}): RconTransport {
const sendOnce = (payload: RconPayload): Promise<boolean> =>
new Promise((resolve) => {
const socket = new net.Socket();
const json = JSON.stringify(payload);
let settled = false;
const finish = (ok: boolean) => {
if (settled) return;
settled = true;
clearTimeout(timer);
socket.destroy();
resolve(ok);
};
const timer = setTimeout(() => finish(false), opts.timeoutMs);
socket.once("error", () => finish(false));
socket.connect(opts.port, opts.host, () => {
socket.write(json, () => finish(true));
});
});
return async (payload) => {
for (let attempt = 0; attempt < opts.maxRetries; attempt++) {
if (await sendOnce(payload)) return true;
if (attempt < opts.maxRetries - 1) {
await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));
}
}
console.error("[RCON] delivery failed after retries:", payload.key);
return false;
};
}
/**
* Typed RCON commands. Payload shapes mirror AtomCMS's RconService EXACTLY
* (e.g. sendgift uses `itemid`, disconnect carries `username`, no-data commands
* send `data: null`, givepoints `type` is the numeric CurrencyType value).
*/
export class RconClient {
constructor(private readonly transport: RconTransport) {}
send(key: string, data: Record<string, unknown> | null = null): Promise<boolean> {
return this.transport({ key, data });
}
giveCredits(userId: number, credits: number) {
return this.send("givecredits", { user_id: userId, credits });
}
givePoints(userId: number, amount: number, type: CurrencyType) {
return this.send("givepoints", { user_id: userId, points: amount, type });
}
giveDuckets(userId: number, amount: number) {
return this.givePoints(userId, amount, CurrencyType.Duckets);
}
giveDiamonds(userId: number, amount: number) {
return this.givePoints(userId, amount, CurrencyType.Diamonds);
}
givePointsGotw(userId: number, amount: number) {
return this.givePoints(userId, amount, CurrencyType.Points);
}
giveBadge(userId: number, badge: string) {
return this.send("givebadge", { user_id: userId, badge });
}
setMotto(userId: number, motto: string) {
return this.send("setmotto", { user_id: userId, motto });
}
setRank(userId: number, rank: number) {
return this.send("setrank", { user_id: userId, rank });
}
sendGift(userId: number, itemId: number, message = "Here is a gift.") {
return this.send("sendgift", { user_id: userId, itemid: itemId, message });
}
disconnectUser(userId: number, username: string) {
return this.send("disconnect", { user_id: userId, username });
}
alertUser(userId: number, message: string) {
return this.send("alertuser", { user_id: userId, message });
}
forwardUser(userId: number, roomId: number) {
return this.send("forwarduser", { user_id: userId, room_id: roomId });
}
executeCommand(userId: number, command: string) {
return this.send("executecommand", { user_id: userId, command });
}
updateWordFilter() {
return this.send("updatewordfilter");
}
updateCatalog() {
return this.send("updatecatalog");
}
}
const globalForRcon = globalThis as unknown as { rcon?: RconClient };
export const rcon =
globalForRcon.rcon ??
new RconClient(
tcpTransport({
host: env.RCON_HOST,
port: env.RCON_PORT,
timeoutMs: env.RCON_TIMEOUT_MS,
maxRetries: env.RCON_MAX_RETRIES,
}),
);
if (env.NODE_ENV !== "production") globalForRcon.rcon = rcon;