| 1 | #!/usr/bin/env node |
| 2 | import { createHash } from "node:crypto"; |
| 3 | import { mkdir, writeFile } from "node:fs/promises"; |
| 4 | import { isIPv4 } from "node:net"; |
| 5 | import { resolve } from "node:path"; |
| 6 | |
| 7 | |
| 8 | |
| 9 | const commit = process.argv[2]; |
| 10 | if (!/^[a-f0-9]{40}$/.test(commit || "")) { |
| 11 | throw new Error("Usage: node scripts/update-exit-country-list.mjs <upstream-commit-sha>"); |
| 12 | } |
| 13 | const upstream = "gaoyifan/china-operator-ip"; |
| 14 | const source = `https://raw.githubusercontent.com/${upstream}/${commit}`; |
| 15 | async function download(name) { |
| 16 | const response = await fetch(`${source}/${name}`, { signal: AbortSignal.timeout(30000) }); |
| 17 | if (!response.ok) throw new Error(`${name}: HTTP ${response.status}`); |
| 18 | return response.text(); |
| 19 | } |
| 20 | const [data, license] = await Promise.all([download("china.txt"), download("LICENSE")]); |
| 21 | const prefixes = data.trim().split(/\r?\n/); |
| 22 | if (prefixes.length < 1000 || prefixes.length > 50000) throw new Error("Unexpected mainland prefix count"); |
| 23 | for (const prefix of prefixes) { |
| 24 | const [address, bits, extra] = prefix.split("/"); |
| 25 | if (!isIPv4(address) || !/^[0-9]+$/.test(bits || "") || +bits < 8 || +bits > 32 || extra !== undefined) { |
| 26 | throw new Error(`Invalid IPv4 prefix: ${prefix}`); |
| 27 | } |
| 28 | } |
| 29 | if (!license.includes("MIT License") || !license.includes("Yifan Gao")) throw new Error("Review upstream license before updating"); |
| 30 | const target = resolve(import.meta.dirname, "../internal/exitpolicy/data"); |
| 31 | await mkdir(target, { recursive: true }); |
| 32 | await writeFile(`${target}/mainland-ipv4.txt`, data); |
| 33 | await writeFile(`${target}/LICENSE`, license); |
| 34 | await writeFile(`${target}/source.json`, JSON.stringify({ |
| 35 | sha256: createHash("sha256").update(data).digest("hex"), |
| 36 | ipv4_prefixes: prefixes.length, license: "MIT", |
| 37 | }, null, 2) + "\n"); |
| 38 | console.log(`Updated ${prefixes.length} mainland IPv4 prefixes from ${commit}`); |