Luigit
repositories / Unfugwart

Unfugwart

Discord caretaker for Abteilung Unfug

owned by admin

config.js

Raw
import { readFile } from 'node:fs/promises';
import { GAME_TYPES } from './telemetry.js';

const SELF_SERVER_ID = '61b39066';
const id = (value, name) => {
  if (typeof value !== 'string' || !/^\d+$/.test(value)) throw new Error(`${name} must be a numeric Discord ID`);
  return value;
};
const text = (value, name) => {
  if (typeof value !== 'string' || value.trim() === '') throw new Error(`${name} is required`);
  return value;
};

export function validateConfig(value) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('config must be an object');
  const panel = new URL(text(value.panelUrl, 'panelUrl'));
  if (panel.protocol !== 'https:' || panel.username || panel.password || (panel.pathname !== '/' && panel.pathname !== '')) throw new Error('panelUrl must be an HTTPS origin without credentials or path');
  if (!Array.isArray(value.mappings) || value.mappings.length === 0) throw new Error('mappings must be a non-empty array');
  const seen = new Set();
  const servers = new Set();
  const mappings = value.mappings.map((mapping, index) => {
    if (!mapping || typeof mapping !== 'object') throw new Error(`mappings[${index}] must be an object`);
    const result = {
      guildId: id(mapping.guildId, `mappings[${index}].guildId`),
      voiceChannelId: id(mapping.voiceChannelId, `mappings[${index}].voiceChannelId`),
      serverId: text(mapping.serverId, `mappings[${index}].serverId`),
      oauthClientId: text(mapping.oauthClientId, `mappings[${index}].oauthClientId`),
      oauthClientSecret: text(mapping.oauthClientSecret, `mappings[${index}].oauthClientSecret`),
      game: mapping.game === undefined ? 'generic' : text(mapping.game, `mappings[${index}].game`),
      gameEmojiName: mapping.gameEmojiName,
      displayName: mapping.displayName === undefined ? mapping.serverId : text(mapping.displayName, `mappings[${index}].displayName`),
      statusChannelId: mapping.statusChannelId === undefined ? undefined : id(mapping.statusChannelId, `mappings[${index}].statusChannelId`),
      controlRoleName: mapping.controlRoleName === undefined ? 'Unfugwart' : text(mapping.controlRoleName, `mappings[${index}].controlRoleName`),
      connectAddress: mapping.connectAddress,
    };
    if (!GAME_TYPES.includes(result.game)) throw new Error(`mappings[${index}].game must be ${GAME_TYPES.join(' or ')}`);
    if (result.gameEmojiName !== undefined && (typeof result.gameEmojiName !== 'string' || !/^[A-Za-z0-9_]{2,32}$/.test(result.gameEmojiName))) throw new Error(`mappings[${index}].gameEmojiName must be a Discord emoji name`);
    if (result.connectAddress !== undefined) {
      if (typeof result.connectAddress !== 'string' || result.connectAddress.length > 120 || !/^(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9a-fA-F:]+\])(?::\d{1,5})?$/.test(result.connectAddress)) throw new Error(`mappings[${index}].connectAddress must be a hostname or IP with optional port`);
      const address = new URL(`tcp://${result.connectAddress}`);
      if (address.port && (Number(address.port) < 1 || Number(address.port) > 65535)) throw new Error(`mappings[${index}].connectAddress has an invalid port`);
    }
    if (result.displayName.length > 80 || result.controlRoleName.length > 100) throw new Error(`mappings[${index}] display or role name is too long`);
    if (!/^[A-Za-z0-9_-]{1,64}$/.test(result.serverId)) throw new Error(`mappings[${index}].serverId must be a safe identifier`);
    if (result.serverId === SELF_SERVER_ID) throw new Error('PufferPanel server 61b39066 is forbidden');
    const key = `${result.guildId}/${result.voiceChannelId}`;
    if (seen.has(key)) throw new Error(`duplicate voice mapping: ${key}`);
    if (servers.has(result.serverId)) throw new Error(`duplicate PufferPanel server mapping: ${result.serverId}`);
    seen.add(key);
    servers.add(result.serverId);
    return result;
  });
  const emojiNames = value.emojiNames === undefined ? {} : value.emojiNames;
  if (!emojiNames || typeof emojiNames !== 'object' || Array.isArray(emojiNames) || Object.entries(emojiNames).some(([slot, name]) => !['sleeping', 'starting', 'ready', 'saving', 'stopping', 'adventurer'].includes(slot) || typeof name !== 'string' || !/^[A-Za-z0-9_]{2,32}$/.test(name))) throw new Error('emojiNames must map semantic names to valid Discord emoji names');
  return { discordToken: text(value.discordToken, 'discordToken'), panelUrl: panel.origin, mappings, emojiNames };
}

export async function loadConfig(path = new URL('./config.json', import.meta.url)) {
  return validateConfig(JSON.parse(await readFile(path, 'utf8')));
}