Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

2.2 KB
Raw Blame
import fs from 'node:fs';
import path, { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Upstream list of ASNs belonging to datacenters / hosting providers. Traffic
// from them is almost never a real end user, so an IP's ASN (MaxMind GeoLite2-ASN)
// is checked for membership in this set. The list is regenerated, never
// hand-edited, so upstream additions flow in on every `bun run codegen`.
const SOURCE_URL =
  'https://raw.githubusercontent.com/X4BNet/lists_vpn/main/input/datacenter/ASN.txt';

// Each line looks like: `AS14061 # DIGITALOCEAN-ASN - DigitalOcean, LLC, US`.
// Blank lines and anything that is not an `AS<number>` entry are ignored.
const AS_LINE_REGEX = /^AS(\d+)\b/;

export function parseAsnList(raw: string): number[] {
  const asns = new Set<number>();
  for (const line of raw.split('\n')) {
    const match = line.trim().match(AS_LINE_REGEX);
    if (match) {
      asns.add(Number(match[1]));
    }
  }
  return [...asns].sort((a, b) => a - b);
}

async function main(): Promise<void> {
  const raw = await fetch(SOURCE_URL).then((res) => res.text());
  const asns = parseAsnList(raw);

  if (asns.length === 0) {
    throw new Error('Parsed 0 datacenter ASNs — refusing to write empty list');
  }

  fs.writeFileSync(
    path.resolve(__dirname, '../src/clients/datacenter-asns.ts'),
    [
      '// This file is generated by the script get-datacenter-asns.ts',
      '',
      `// Source: ${SOURCE_URL}`,
      '',
      '// Autonomous System Numbers belonging to datacenters / hosting providers.',
      '// Used to flag (not block) traffic that is unlikely to be a real end user.',
      `const datacenterAsns: readonly number[] = ${JSON.stringify(asns)};`,
      'export default datacenterAsns;',
      '',
    ].join('\n'),
    'utf-8'
  );

  console.log(`✅ Generated datacenter-asns.ts with ${asns.length} ASNs`);
}

// Only fetch when run directly, so `parseAsnList` can be unit-tested without a network call.
if (process.argv[1] === __filename) {
  main().catch((error) => {
    console.error('Error generating datacenter ASN list:', error);
    process.exit(1);
  });
}