Repository navigation
Expand file tree
/
Copy pathbuild.js
More file actions
210 lines (187 loc) · 7.74 KB
/
Copy pathbuild.js
File metadata and controls
210 lines (187 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import {readFileSync, writeFileSync} from "node:fs";
import {mergeCidr, excludeCidr, parseCidr, containsCidr} from "cidr-tools";
import JSON5 from "json5";
const POLICY_FILE = "policy.hujson";
const FETCH_TIMEOUT_MS = 30_000;
// IPverse RIR aggregated country ranges (source of truth for RU).
const IPVERSE_BASE =
"https://raw.githubusercontent.com/ipverse/rir-ip/master/country/ru";
const RU_IPV4_URL = `${IPVERSE_BASE}/ipv4-aggregated.txt`;
const RU_IPV6_URL = `${IPVERSE_BASE}/ipv6-aggregated.txt`;
// IPv4 base for EU = entire IPv4 internet.
const IPV4_BASE = "0.0.0.0/0";
// IPv6 base for EU = global unicast space; this naturally excludes
// private/ULA, link-local, multicast and other reserved IPv6 blocks.
const IPV6_BASE = "2000::/3";
// IPv4 special-use / technical ranges removed from EU before subtracting RU.
// Note: only 100.64.0.0/10 (CGNAT/Tailscale) is excluded, not the full 100.0.0.0/8.
const IPV4_TECHNICAL = [
"0.0.0.0/8", // "this network"
"10.0.0.0/8", // private LAN
"100.64.0.0/10", // CGNAT / Tailscale shared address space
"127.0.0.0/8", // loopback
"169.254.0.0/16", // IPv4 link-local
"172.16.0.0/12", // private LAN
"192.0.0.0/24", // IETF protocol assignments
"192.0.2.0/24", // documentation / TEST-NET-1
"192.88.99.0/24", // deprecated 6to4 relay anycast
"192.168.0.0/16", // private LAN
"198.18.0.0/15", // benchmark / testing
"198.51.100.0/24", // documentation / TEST-NET-2
"203.0.113.0/24", // documentation / TEST-NET-3
"224.0.0.0/4", // multicast
"240.0.0.0/4", // reserved / future use
];
async function downloadCIDRs(url) {
console.log(`Downloading: ${url}`);
const res = await fetch(url, {signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)});
if (!res.ok) throw new Error(`Failed to download ${url}: ${res.status}`);
const text = await res.text();
return text
.split("\n")
.map((l) => l.trim())
.filter((l) => l && !l.startsWith("#"));
}
function isV6(cidr) {
return cidr.includes(":");
}
function validateRoutes(routes, name) {
const seen = new Set();
for (const c of routes) {
try {
parseCidr(c);
} catch {
throw new Error(`${name}: invalid CIDR ${c}`);
}
if (seen.has(c)) throw new Error(`${name}: exact duplicate CIDR ${c}`);
seen.add(c);
}
}
// Returns [aCidr, bCidr] for the first overlapping pair (containment or
// equality) between two CIDR lists, or null. Runs per-IP-version in O(n+m)
// using a sorted-merge over parsed [start,end] ranges.
function findCidrOverlap(aList, bList) {
for (const v of [4, 6]) {
const a = aList
.filter((c) => (isV6(c) ? 6 : 4) === v)
.map((c) => {
const p = parseCidr(c);
return [p.start, p.end, c];
})
.sort((x, y) => (x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0));
const b = bList
.filter((c) => (isV6(c) ? 6 : 4) === v)
.map((c) => {
const p = parseCidr(c);
return [p.start, p.end, c];
})
.sort((x, y) => (x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0));
let i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i][1] < b[j][0]) { i++; continue; }
if (b[j][1] < a[i][0]) { j++; continue; }
return [a[i][2], b[j][2]];
}
}
return null;
}
async function main() {
const policy = JSON5.parse(readFileSync(POLICY_FILE, "utf-8"));
const connectors =
policy.nodeAttrs[0].app["tailscale.com/app-connectors"];
const ruConn = connectors.find((c) => c.name === "ru");
const euConn = connectors.find((c) => c.name === "eu");
if (!ruConn) throw new Error(`Connector "ru" not found in ${POLICY_FILE}`);
if (!euConn) throw new Error(`Connector "eu" not found in ${POLICY_FILE}`);
// ---- DERP node IPs must NOT be tunneled via app-connectors,
// otherwise Tailscale clients lose their DERP relay.
// Subtract them from both ru and eu as host routes.
const derpV4 = [];
const derpV6 = [];
const regions = policy.derpMap?.Regions ?? {};
for (const region of Object.values(regions)) {
for (const node of region?.Nodes ?? []) {
if (node?.IPv4) derpV4.push(`${node.IPv4}/32`);
if (node?.IPv6) derpV6.push(`${node.IPv6}/128`);
}
}
if (derpV4.length || derpV6.length) {
console.log(
`derp exclusions: ${derpV4.length} v4 + ${derpV6.length} v6 ` +
`(${[...derpV4, ...derpV6].join(", ")})`,
);
}
// ---- RU: IPverse Russia IPv4 + IPv6, minus DERP host IPs ----
const [ruV4Raw, ruV6Raw] = await Promise.all([
downloadCIDRs(RU_IPV4_URL),
downloadCIDRs(RU_IPV6_URL),
]);
if (ruV4Raw.length === 0) throw new Error("IPverse RU IPv4 list is empty");
if (ruV6Raw.length === 0) throw new Error("IPverse RU IPv6 list is empty");
const ruV4Full = mergeCidr(ruV4Raw);
const ruV6Full = mergeCidr(ruV6Raw);
const ruV4 = derpV4.length ? excludeCidr(ruV4Full, derpV4) : ruV4Full;
const ruV6 = derpV6.length ? excludeCidr(ruV6Full, derpV6) : ruV6Full;
const ruRoutes = mergeCidr([...ruV4, ...ruV6]);
console.log(`ru: ${ruRoutes.length} CIDRs (${ruV4.length} v4 + ${ruV6.length} v6)`);
// ---- EU: Public Internet - Technical Ranges - RU - DERP ----
const euV4 = excludeCidr(
[IPV4_BASE],
[...IPV4_TECHNICAL, ...ruV4Full, ...derpV4],
);
const euV6 = excludeCidr([IPV6_BASE], [...ruV6Full, ...derpV6]);
const euRoutes = mergeCidr([...euV4, ...euV6]);
console.log(`eu: ${euRoutes.length} CIDRs (${euV4.length} v4 + ${euV6.length} v6)`);
// ---- Validation ----
validateRoutes(ruRoutes, "ru");
validateRoutes(euRoutes, "eu");
// RU and EU must be fully disjoint, including containment overlaps
// (e.g. RU=1.2.0.0/16 and EU=1.2.3.0/24). Use a sorted-merge scan over
// parsed [start,end] ranges so this stays O(n+m) instead of O(n*m).
const overlap = findCidrOverlap(ruRoutes, euRoutes);
if (overlap) {
throw new Error(`eu and ru overlap: ${overlap[0]} <> ${overlap[1]}`);
}
// EU must not overlap any listed IPv4 technical/special-use range
// (either contained by or containing one of them).
for (const c of euRoutes) {
if (isV6(c)) continue;
const tech = IPV4_TECHNICAL.find(
(t) => containsCidr(t, c) || containsCidr(c, t),
);
if (tech) {
throw new Error(
`eu contains technical/special-use CIDR ${c} (overlaps ${tech})`,
);
}
}
// IPv6 part of EU must lie within 2000::/3.
for (const c of euRoutes) {
if (isV6(c) && !containsCidr(IPV6_BASE, c)) {
throw new Error(`eu IPv6 CIDR ${c} is outside ${IPV6_BASE}`);
}
}
// DERP node IPs must not be covered by any ru/eu route, so that
// traffic to relays continues over the regular Tailscale path.
for (const derp of [...derpV4, ...derpV6]) {
for (const [name, routes] of [["ru", ruRoutes], ["eu", euRoutes]]) {
const hit = routes.find(
(r) => isV6(r) === isV6(derp) && containsCidr(r, derp),
);
if (hit) {
throw new Error(
`${name} contains DERP IP ${derp} (covered by ${hit})`,
);
}
}
}
// ---- Update only the routes lists, preserve everything else ----
ruConn.routes = ruRoutes;
euConn.routes = euRoutes;
writeFileSync(POLICY_FILE, JSON.stringify(policy, null, 2) + "\n");
console.log(`${POLICY_FILE}: updated`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});