Luigit
repositories / Unfugwart

Unfugwart

Discord caretaker for Abteilung Unfug

owned by admin

installer.js

Raw
import { mkdtemp, mkdir, readFile, rm, writeFile, copyFile, lstat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawn } from 'node:child_process';

export const ARCHIVE_URL = 'https://vcs.bugabinga.net/Unfugwart/archive/trunk.tar';
export const RUNTIME_FILES = ['bot.js', 'api.js', 'config.js', 'lifecycle.js', 'occupancy.js', 'readiness.js', 'telemetry.js', 'ui.js', 'discord-ui.js', 'package.json', 'package-lock.json'];
const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024;
const TIMEOUT_MS = 30_000;

function run(command, args, options = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, { stdio: 'inherit', ...options });
    child.once('error', reject);
    child.once('exit', code => code === 0 ? resolve() : reject(new Error(`${command} exited ${code}`)));
  });
}

export function validateListing(listing) {
  const entries = listing.trimEnd().split('\n');
  const first = entries[0]?.replace(/\/$/, '');
  const firstParts = first?.split('/');
  const prefix = firstParts?.[0];
  if (!prefix || !/^Unfugwart-[a-f0-9]+$/.test(prefix) || firstParts.length < 2) throw new Error('archive has invalid root prefix');
  const seen = new Set();
  const files = new Set();
  for (const entry of entries) {
    if (!entry || entry.includes('\\') || /[\x00-\x1f\x7f]/.test(entry) || entry.startsWith('/')) throw new Error('archive contains unsafe path');
    const isDirectory = entry.endsWith('/');
    const path = isDirectory ? entry.slice(0, -1) : entry;
    const parts = path.split('/');
    if (parts[0] !== prefix || parts.length < 2 || parts.some(part => !part || part === '.' || part === '..')) throw new Error('archive contains unsafe path');
    if (parts.includes('config.json')) throw new Error('archive contains forbidden config.json');
    if (seen.has(entry) || seen.has(path) || seen.has(`${path}/`)) throw new Error('archive contains duplicate paths');
    seen.add(entry);
    if (!isDirectory) files.add(path);
  }
  for (const file of RUNTIME_FILES) if (!files.has(`${prefix}/${file}`)) throw new Error(`archive misses ${file}`);
  return prefix;
}

export function validateVerboseListing(listing) {
  const types = listing.trimEnd().split('\n').map(line => line[0]);
  if (types.some(type => type !== '-' && type !== 'd')) throw new Error('archive contains non-regular files');
}

async function download(url, destination, fetchFn) {
  const response = await fetchFn(url, { redirect: 'error', signal: AbortSignal.timeout(TIMEOUT_MS) });
  if (!response.ok) throw new Error(`archive download failed: HTTP ${response.status}`);
  const length = Number(response.headers.get('content-length'));
  if (Number.isFinite(length) && length > MAX_ARCHIVE_BYTES) throw new Error('archive download exceeds size limit');
  if (!response.body) throw new Error('archive download has no body');
  let size = 0;
  const chunks = [];
  for await (const chunk of response.body) {
    size += chunk.length;
    if (size > MAX_ARCHIVE_BYTES) throw new Error('archive download exceeds size limit');
    chunks.push(chunk);
  }
  await writeFile(destination, Buffer.concat(chunks));
}

export async function install({ root = process.cwd(), archiveUrl = ARCHIVE_URL, fetchFn = fetch, runNpm = () => run('npm', ['ci', '--omit=dev'], { cwd: root }) } = {}) {
  const stage = await mkdtemp(join(tmpdir(), 'unfugwart-'));
  try {
    const archive = join(stage, 'archive.tar');
    await download(archiveUrl, archive, fetchFn);
    const list = await capture('tar', ['-tf', archive]);
    const prefix = validateListing(list);
    validateVerboseListing(await capture('tar', ['-tvf', archive]));
    const extracted = join(stage, 'extract');
    await mkdir(extracted);
    await run('tar', ['-xf', archive, '--no-same-owner', '--no-same-permissions', '-C', extracted, '--', ...RUNTIME_FILES.map(file => `${prefix}/${file}`)]);
    for (const file of RUNTIME_FILES) {
      const info = await lstat(join(extracted, prefix, file));
      if (!info.isFile() || info.isSymbolicLink()) throw new Error(`archive output ${file} is not a regular file`);
    }
    for (const file of RUNTIME_FILES) await copyFile(join(extracted, prefix, file), join(root, file));
    await runNpm();
  } finally {
    await rm(stage, { recursive: true, force: true });
  }
}

function capture(command, args) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'inherit'] });
    let output = '';
    child.stdout.setEncoding('utf8');
    child.stdout.on('data', chunk => { output += chunk; });
    child.once('error', reject);
    child.once('exit', code => code === 0 ? resolve(output) : reject(new Error(`${command} exited ${code}`)));
  });
}

if (import.meta.url.startsWith('data:')) await install();