Luigit
repositories / Unfugwart

Unfugwart

Discord caretaker for Abteilung Unfug

owned by admin

api.js

Raw
const timeoutFetch = async (fetchImpl, url, options, timeoutMs) => {
  const signal = AbortSignal.timeout(timeoutMs);
  return fetchImpl(url, { ...options, signal, redirect: 'error' });
};

export class PufferApi {
  constructor({ baseUrl, clientId, clientSecret, fetchImpl = fetch, timeoutMs = 10_000, retries = 2, maxConsoleBytes = 256 * 1024 }) {
    this.baseUrl = baseUrl;
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.fetch = fetchImpl;
    this.timeoutMs = timeoutMs;
    this.retries = retries;
    this.maxConsoleBytes = maxConsoleBytes;
    this.token = null;
    this.tokenExpiresAt = 0;
  }

  async requestToken() {
    const body = new URLSearchParams({ grant_type: 'client_credentials', client_id: this.clientId, client_secret: this.clientSecret });
    const response = await timeoutFetch(this.fetch, `${this.baseUrl}/oauth2/token`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body }, this.timeoutMs);
    if (!response.ok) throw new Error(`PufferPanel token request failed: HTTP ${response.status}`);
    const token = await response.json();
    if (typeof token.access_token !== 'string' || token.access_token === '') throw new Error('PufferPanel token response missing access_token');
    this.token = token.access_token;
    this.tokenExpiresAt = Date.now() + Math.max(1, Number(token.expires_in) || 3600) * 1000 - 30_000;
  }

  async bearer() {
    if (!this.token || Date.now() >= this.tokenExpiresAt) await this.requestToken();
    return this.token;
  }

  async request(path, method, valid = () => true) {
    let lastError;
    for (let attempt = 0; attempt <= this.retries; attempt += 1) {
      try {
        const token = await this.bearer();
        if (!valid()) return null;
        const response = await timeoutFetch(this.fetch, `${this.baseUrl}${path}`, { method, headers: { authorization: `Bearer ${token}` } }, this.timeoutMs);
        if ((response.status === 401 || response.status === 403) && attempt < this.retries) {
          this.token = null;
          this.tokenExpiresAt = 0;
          continue;
        }
        if (!response.ok) throw new Error(`PufferPanel request failed: HTTP ${response.status}`);
        return response;
      } catch (error) {
        lastError = error;
        if (attempt < this.retries) continue;
      }
    }
    throw lastError;
  }

  async status(serverId) {
    const response = await this.request(`/api/servers/${encodeURIComponent(serverId)}/status`, 'GET');
    const body = await response.json();
    if (typeof body.running !== 'boolean') throw new Error('PufferPanel status response missing running');
    return body.running;
  }

  async console(serverId, epoch = 0) {
    if (!Number.isSafeInteger(epoch) || epoch < 0) throw new Error('PufferPanel console epoch must be a non-negative integer');
    const response = await this.request(`/api/servers/${encodeURIComponent(serverId)}/console?time=${epoch}`, 'GET');
    const body = await response.json();
    if (!Number.isSafeInteger(body.epoch) || body.epoch < 0 || typeof body.logs !== 'string' || body.logs.length > Math.ceil(this.maxConsoleBytes / 3) * 4) throw new Error('PufferPanel console response is invalid');
    const logs = Buffer.from(body.logs, 'base64');
    if (logs.length > this.maxConsoleBytes) throw new Error('PufferPanel console response is invalid');
    return { epoch: body.epoch, logs };
  }

  start(serverId, valid = () => true) { return this.request(`/api/servers/${encodeURIComponent(serverId)}/start`, 'POST', valid); }
  // A validity change after fetch begins cannot retract that dispatched HTTP request.
  stop(serverId, valid) { return this.request(`/api/servers/${encodeURIComponent(serverId)}/stop`, 'POST', valid); }
}