Files
Homelab-manager/server/src/integrations/fragnet/adapter.ts
T
bobbanandClaude Sonnet 5.5 9a3d5c466a Fragnet game servers: games, addresses, backups, power actions
New integration kind "fragnet" reading Fragnet's Pterodactyl-based panel through the
client API (account key). Game servers page under Infrastructure with game, IP:port,
state, memory/disk, backups, schedules and databases; alerts for late backups and
nearly full disk/memory; operators can start/stop/restart/kill (audited). Metrics,
docs and tests included; migration 0071 adds fragnet_state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 19:01:36 +01:00

360 lines
16 KiB
TypeScript

/**
* Fragnet game server adapter. Fragnet's game panel (https://panel.fragnet.net) is a fork of Pterodactyl, so this speaks Pterodactyl's *client* API
* (https://dashflo.net/docs/api/pterodactyl/v1/#req_…, base `/api/client`). Config: token (the account's API key — the panel's profile menu → API Credentials; it starts with **ptlc_**, an
* Application key, ptla_, does not work), optionally url (the panel; https://panel.fragnet.net when left out) and the three that the alerts use (see services/fragnetSync.ts): backupDays,
* fullPercent, ignoreBackups.
*
* Reading: the servers of the account (`GET /api/client`, paged, with the game — the egg — and the addresses) and, for each, `…/resources` (running or not, memory, CPU, disk, uptime), `…/backups`,
* `…/schedules` and `…/databases`. A part that cannot be read (a sub-user without that permission gets a 403) is null for that server, which is not the same as none. The only thing ever
* written is a **power signal** (`POST …/power`: start, stop, restart or kill), and only when someone asks for it on the page.
*
* Endpoints and field names are from Pterodactyl's source (ServerTransformer, StatsTransformer, BackupTransformer, ScheduleTransformer) and the panel's own documentation (docs.fragnet.net),
* not from a live account: Fragnet's fork may differ, so every field is read defensively. The panel allows a limited number of requests a minute (429); a pass makes four per server.
*/
import { requestJson } from "../httpJson.js";
import { withDiagLogging } from "../../services/diagLog.js";
export const DEFAULT_URL = "https://panel.fragnet.net";
export interface FragnetConfig {
token: string;
url?: string;
}
export interface FragnetAllocation {
ip: string;
/** A name the host gave the address (ip_alias), when there is one. */
alias: string | null;
port: number;
/** The server's main address. */
isDefault: boolean;
notes: string | null;
}
export interface FragnetBackup {
uuid: string;
name: string | null;
bytes: number;
createdAt: string | null;
/** Null while it is still being made. */
completedAt: string | null;
successful: boolean;
locked: boolean;
}
export interface FragnetSchedule {
id: number;
name: string;
/** The cron fields as one text: "minute hour day-of-month month day-of-week". */
cron: string;
active: boolean;
processing: boolean;
onlyWhenOnline: boolean;
lastRunAt: string | null;
nextRunAt: string | null;
}
export interface FragnetUsage {
memoryBytes: number;
/** Percent of one core (200 = two cores busy). */
cpu: number;
diskBytes: number;
rxBytes: number;
txBytes: number;
/** Milliseconds since it was started; 0 when it is not running. */
uptimeMs: number;
}
export interface FragnetServer {
/** The short id (8 characters) the panel uses in its addresses and API. */
id: string;
uuid: string;
name: string;
description: string | null;
node: string | null;
/** The game, as the panel names its egg ("Minecraft: Paper", "Rust"); null when the panel did not say. */
game: string | null;
dockerImage: string | null;
/** The panel's own status: installing, install_failed, reinstall_failed, suspended, restoring_backup; null when it is none of them. */
panelStatus: string | null;
suspended: boolean;
installing: boolean;
transferring: boolean;
/** Whether the account owns it (false: it was shared with the account as a sub-user). */
owner: boolean;
/** running, starting, stopping, offline — or unknown when the resources could not be read. */
state: string;
allocations: FragnetAllocation[];
/** Where SFTP is, as "host:port"; null when not said. */
sftp: string | null;
/** MB; 0 means no limit. */
memoryLimitMb: number | null;
diskLimitMb: number | null;
/** Percent of one core; 0 means no limit. */
cpuLimit: number | null;
databaseLimit: number | null;
backupLimit: number | null;
allocationLimit: number | null;
/** Null when the resources could not be read. */
usage: FragnetUsage | null;
/** Newest first; null when they could not be listed. */
backups: FragnetBackup[] | null;
schedules: FragnetSchedule[] | null;
databases: number | null;
}
export type PowerSignal = "start" | "stop" | "restart" | "kill";
export const POWER_SIGNALS: PowerSignal[] = ["start", "stop", "restart", "kill"];
export interface FragnetRead {
servers: FragnetServer[];
}
export interface FragnetAdapter {
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
read(): Promise<FragnetRead>;
power(serverId: string, signal: PowerSignal): Promise<void>;
}
const PER_PAGE = 50;
export const MAX_PAGES = 10;
/** The newest backups are what matters; a server rarely has more than a few. */
const BACKUP_PAGES = 3;
export const SERVER_ID = /^[A-Za-z0-9]{8}$/;
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
const num = (v: unknown): number | null => {
const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
return typeof n === "number" && Number.isFinite(n) ? n : null;
};
const iso = (v: unknown): string | null => {
const s = str(v);
return s !== null && Number.isFinite(Date.parse(s)) ? new Date(s).toISOString() : null;
};
/** What a Pterodactyl list wraps each item in: `{ object, attributes }`. */
const attrs = (item: unknown): Record<string, unknown> => obj(obj(item).attributes);
/** Pure: the page after this one, or null when this is the last. */
export function nextPage(raw: unknown): number | null {
const p = obj(obj(obj(raw).meta).pagination);
const current = num(p.current_page);
const total = num(p.total_pages);
return current !== null && total !== null && current < total ? current + 1 : null;
}
/** Pure: the addresses of a server (its `relationships.allocations`). */
export function parseAllocations(relationships: unknown): FragnetAllocation[] {
const out: FragnetAllocation[] = [];
for (const item of arr(obj(obj(relationships).allocations).data)) {
const a = attrs(item);
const ip = str(a.ip);
const port = num(a.port);
if (!ip || port === null) continue;
out.push({ ip, alias: str(a.ip_alias), port, isDefault: a.is_default === true, notes: str(a.notes) });
}
// The main address first, then by port.
return out.sort((x, y) => Number(y.isDefault) - Number(x.isDefault) || x.port - y.port);
}
/** Pure: the servers of one page of `GET /api/client` — what the list says of each, before its resources, backups and so on are asked for. */
export function parseServers(raw: unknown): FragnetServer[] {
const out: FragnetServer[] = [];
for (const item of arr(obj(raw).data)) {
const s = attrs(item);
const id = str(s.identifier);
const name = str(s.name);
if (!id || !SERVER_ID.test(id) || !name) continue;
const limits = obj(s.limits);
const feature = obj(s.feature_limits);
const sftp = obj(s.sftp_details);
const sftpHost = str(sftp.ip);
const rel = obj(s.relationships);
const egg = attrs(obj(rel.egg));
const panelStatus = str(s.status);
out.push({
id,
uuid: str(s.uuid) ?? id,
name,
description: str(s.description),
node: str(s.node),
game: str(egg.name),
dockerImage: str(s.docker_image),
panelStatus,
suspended: s.is_suspended === true || panelStatus === "suspended",
installing: s.is_installing === true || panelStatus === "installing",
transferring: s.is_transferring === true,
owner: s.server_owner !== false,
state: "unknown",
allocations: parseAllocations(rel),
sftp: sftpHost ? `${sftpHost}${num(sftp.port) !== null ? `:${num(sftp.port)}` : ""}` : null,
memoryLimitMb: num(limits.memory),
diskLimitMb: num(limits.disk),
cpuLimit: num(limits.cpu),
databaseLimit: num(feature.databases),
backupLimit: num(feature.backups),
allocationLimit: num(feature.allocations),
usage: null,
backups: null,
schedules: null,
databases: null,
});
}
return out;
}
/** Pure: `…/resources` — whether it runs and what it uses. Null when the answer is not that. */
export function parseResources(raw: unknown): { state: string; suspended: boolean; usage: FragnetUsage } | null {
const a = obj(obj(raw).attributes);
const state = str(a.current_state);
if (!state) return null;
const r = obj(a.resources);
return {
state: state.toLowerCase(),
suspended: a.is_suspended === true,
usage: { memoryBytes: num(r.memory_bytes) ?? 0, cpu: num(r.cpu_absolute) ?? 0, diskBytes: num(r.disk_bytes) ?? 0, rxBytes: num(r.network_rx_bytes) ?? 0, txBytes: num(r.network_tx_bytes) ?? 0, uptimeMs: num(r.uptime) ?? 0 },
};
}
/** Pure: the backups of one page of `…/backups`, newest first. */
export function parseBackups(raw: unknown): FragnetBackup[] {
const out: FragnetBackup[] = [];
for (const item of arr(obj(raw).data)) {
const b = attrs(item);
const uuid = str(b.uuid);
if (!uuid) continue;
out.push({ uuid, name: str(b.name), bytes: num(b.bytes) ?? 0, createdAt: iso(b.created_at), completedAt: iso(b.completed_at), successful: b.is_successful === true, locked: b.is_locked === true });
}
return out.sort((x, y) => (y.createdAt ?? "").localeCompare(x.createdAt ?? ""));
}
/** Pure: `…/schedules` — the tasks that run on their own (a restart every night, a backup every Sunday). */
export function parseSchedules(raw: unknown): FragnetSchedule[] {
const out: FragnetSchedule[] = [];
for (const item of arr(obj(raw).data)) {
const s = attrs(item);
const id = num(s.id);
const name = str(s.name);
if (id === null || !name) continue;
const c = obj(s.cron);
const cron = [c.minute, c.hour, c.day_of_month, c.month, c.day_of_week].map((x) => (typeof x === "string" || typeof x === "number" ? String(x) : "*")).join(" ");
out.push({ id, name, cron, active: s.is_active !== false, processing: s.is_processing === true, onlyWhenOnline: s.only_when_online === true, lastRunAt: iso(s.last_run_at), nextRunAt: iso(s.next_run_at) });
}
return out;
}
export function createFragnetAdapter(config: FragnetConfig): FragnetAdapter {
const base = `${String(config.url ?? "").trim().replace(/\/+$/, "") || DEFAULT_URL}/api/client`;
const token = String(config.token ?? "").trim();
const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
/** `forbiddenIsFine`: a 403 on one part of one server is that part's permission (a sub-user), not a key the panel refuses. */
function refusal(status: number, forbiddenIsFine = false): Error | null {
if (status === 401 || (status === 403 && !forbiddenIsFine)) {
return new Error(
token.startsWith("ptla_")
? `The panel did not accept the key (HTTP ${status}) — that is an Application key (ptla_); this needs the account's own API key, which starts with ptlc_`
: `The panel did not accept the key (HTTP ${status}) — make a new one under the profile menu → API Credentials (it starts with ptlc_), and check it has not been deleted or limited to other addresses`,
);
}
if (status === 429) return new Error("The panel says too many requests (HTTP 429) — it will be tried again at the next read");
return null;
}
async function get(path: string, forbiddenIsFine = false): Promise<{ status: number; json: unknown }> {
const res = await requestJson(`${base}${path}`, { headers });
const refused = refusal(res.status, forbiddenIsFine);
if (refused) throw refused;
return { status: res.status, json: res.json };
}
/** A part of a server that may be missing for it: null if it could not be read (a 403 for a sub-user without that permission, a 404, a server that is being installed). */
async function part<T>(path: string, parse: (json: unknown) => T): Promise<T | null> {
try {
const res = await get(path, true);
if (res.status < 200 || res.status >= 300 || res.json === null) return null;
return parse(res.json);
} catch (err) {
// A key the panel has stopped accepting, or a panel that is rate-limiting, is not "this part is missing": the whole read has failed.
if (err instanceof Error && /^(The panel did not accept|The panel says too many)/.test(err.message)) throw err;
return null;
}
}
async function listServers(): Promise<FragnetServer[]> {
const all: FragnetServer[] = [];
let page: number | null = 1;
for (let i = 0; i < MAX_PAGES && page !== null; i++) {
let res = await get(`?include=egg,allocations&per_page=${PER_PAGE}&page=${page}`);
// A panel that refuses what it does not know of the request is asked again plainly (the addresses come with a server anyway).
if (res.status >= 400 && res.status < 500) res = await get(`?per_page=${PER_PAGE}&page=${page}`);
if (res.status < 200 || res.status >= 300) throw new Error(`The panel answered with an error: HTTP ${res.status}`);
if (res.json === null) throw new Error("The panel answered with something that isn't JSON — is the address its own?");
all.push(...parseServers(res.json));
page = nextPage(res.json);
}
return all;
}
async function backupsOf(id: string): Promise<FragnetBackup[] | null> {
const all: FragnetBackup[] = [];
let page: number | null = 1;
for (let i = 0; i < BACKUP_PAGES && page !== null; i++) {
const res: { backups: FragnetBackup[]; next: number | null } | null = await part(`/servers/${id}/backups?per_page=50&page=${page}`, (json) => ({ backups: parseBackups(json), next: nextPage(json) }));
if (res === null) return i === 0 ? null : all;
all.push(...res.backups);
page = res.next;
}
return all.sort((x, y) => (y.createdAt ?? "").localeCompare(x.createdAt ?? ""));
}
async function read(): Promise<FragnetRead> {
const servers = await listServers();
const out: FragnetServer[] = [];
for (const s of servers) {
const [resources, backups, schedules, databases] = await Promise.all([
part(`/servers/${s.id}/resources`, parseResources),
backupsOf(s.id),
part(`/servers/${s.id}/schedules`, parseSchedules),
part(`/servers/${s.id}/databases`, (json) => arr(obj(json).data).length),
]);
out.push({
...s,
state: resources?.state ?? "unknown",
suspended: s.suspended || resources?.suspended === true,
usage: resources?.usage ?? null,
backups,
schedules,
databases,
});
}
return { servers: out };
}
async function power(serverId: string, signal: PowerSignal): Promise<void> {
if (!SERVER_ID.test(serverId)) throw new Error("That isn't a server id of the panel");
if (!POWER_SIGNALS.includes(signal)) throw new Error("That isn't a power signal");
const res = await requestJson(`${base}/servers/${serverId}/power`, { method: "POST", headers, body: { signal } });
const refused = refusal(res.status);
if (refused) throw refused;
if (res.status === 409) throw new Error("The panel says the server is busy (HTTP 409) — it is being installed, transferred or restored, or is suspended");
if (res.status === 404) throw new Error("The panel does not know that server (HTTP 404)");
if (res.status < 200 || res.status >= 300) throw new Error(`The panel answered with an error: HTTP ${res.status}`);
}
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
const start = Date.now();
try {
const res = await get("?per_page=1");
if (res.status < 200 || res.status >= 300) throw new Error(`The panel answered with an error: HTTP ${res.status} — check the address`);
if (res.json === null) throw new Error("The panel answered with something that isn't JSON — is the address its own?");
return { ok: true, latencyMs: Date.now() - start };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
return withDiagLogging("fragnet", { ping, read, power });
}