forked from MunifTanjim/scripts.sh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync-cloudflare-dns-records-with-tailscale
executable file
·355 lines (273 loc) · 7.8 KB
/
sync-cloudflare-dns-records-with-tailscale
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/env zx
// vim: set filetype=javascript :
$.verbose = false;
const DOMAIN_NAME = 'muniftanjim.dev';
const DNS_RECORD_NAMESPACE = 'tailscale';
const DNS_RECORD_SUFFIX_PATTERN = new RegExp(
`\\.${DNS_RECORD_NAMESPACE}\\.${DOMAIN_NAME.replace('.', '\\.')}`
);
function exit(code) {
process.exit(code);
}
class CacheFile {
constructor(name) {
this.cachePath = `${os.homedir()}/.cache/@muniftanjim/${name}`;
this.content = null;
this.exists = false;
}
#ensure = async () => {
if (this.content && this.exists) {
return;
}
const cacheDir = String(await $`dirname ${this.cachePath}`).trim();
try {
await fs.access(cacheDir);
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
await fs.mkdir(cacheDir, { recursive: true });
}
try {
const content = await fs.readFile(this.cachePath, { encoding: 'utf8' });
this.content = JSON.parse(content);
} catch (err) {
this.content = {};
await fs.writeFile(this.cachePath, JSON.stringify(this.content), {
encoding: 'utf8',
});
}
this.exists = true;
};
read = async () => {
await this.#ensure();
return this;
};
write = async () => {
if (!this.content) {
this.content = {};
}
await this.#ensure();
fs.writeFile(this.cachePath, JSON.stringify(this.content), {
encoding: 'utf8',
});
return this;
};
}
class Logger {
#typeMap = {
'': ' ',
error: chalk.red('error'),
info: chalk.blue(' info'),
input: chalk.magenta('input'),
warn: chalk.yellow(' warn'),
};
constructor(service) {
this.service = service;
}
fmt = (type, message) => {
const string = [this.service, this.#typeMap[type], message]
.filter(Boolean)
.join(' ');
return string;
};
#log = (type, message) => {
console.log(this.fmt(type, message));
};
error = (message) => this.#log('error', message);
info = (message) => this.#log('info', message);
log = (message) => this.#log('', message);
warn = (message) => this.#log('warn', message);
}
class Cloudflare {
#baseUrl = 'https://api.cloudflare.com/client/v4';
#cache = new CacheFile(
'cloudflare/sync-cloudflare-dns-records-with-tailscale'
);
log = new Logger(chalk.bgYellowBright.black.bold.dim(' cloudflare '));
api = async (endpoint, options = {}) => {
const response = await fetch(`${this.#baseUrl}${endpoint}`, {
headers: {
authorization: `Bearer ${this.#cache.content.token}`,
'content-type': 'application/json',
},
...options,
});
const json = await response.json();
return json;
};
verifyToken = async () => {
this.log.info('Checking Token validity...');
const { success, errors, messages } = await this.api('/user/tokens/verify');
if (success) {
for (const { message } of messages) {
this.log.info(message);
}
} else {
for (const { message } of errors) {
this.log.error(message);
}
}
return success;
};
ensureToken = async () => {
const cache = await this.#cache.read();
if (cache.content.token) {
const valid = await this.verifyToken();
if (valid) {
return;
}
}
this.log.log('For createing API Token, visit:');
this.log.log(' https://dash.cloudflare.com/profile/api-tokens');
cache.content.token = await question(
this.log.fmt('input', 'Enter API Token: ')
);
const valid = await this.verifyToken();
if (valid) {
return await this.#cache.write();
}
cache.content.token = null;
return await this.ensureToken();
};
getZone = async () => {
this.log.info(`Finding zone for ${DOMAIN_NAME}...`);
const { result } = await this.api(
`/zones?name=${DOMAIN_NAME}&status=active`
);
const zone = result[0];
this.log.info('Found zone!');
return zone;
};
listDnsRecords = async ({ zoneId }) => {
this.log.info('Finding existing DNS Records...');
const { result } = await this.api(
`/zones/${zoneId}/dns_records?type=A&proxied=false`
);
const dnsRecords = result.filter((item) =>
DNS_RECORD_SUFFIX_PATTERN.test(item.name)
);
this.log.info(`Found ${dnsRecords.length} DNS Records!`);
return dnsRecords;
};
createDnsRecord = async ({ zoneId, dnsRecordName, dnsRecordContent }) => {
this.log.info(`${chalk.cyan(`Creating DNS Record:`)} ${dnsRecordName}`);
const { result } = await this.api(`/zones/${zoneId}/dns_records`, {
method: 'POST',
body: JSON.stringify({
type: 'A',
name: dnsRecordName,
content: dnsRecordContent,
ttl: 1,
}),
});
return result;
};
deleteDnsRecord = async ({ zoneId, dnsRecordId, dnsRecordName }) => {
this.log.info(`${chalk.red(`Deleting DNS Record:`)} ${dnsRecordName}`);
const { result } = await this.api(
`/zones/${zoneId}/dns_records/${dnsRecordId}`,
{
method: 'DELETE',
}
);
return result;
};
updateDnsRecord = async ({
zoneId,
dnsRecordId,
dnsRecordName,
dnsRecordContent,
}) => {
this.log.info(`${chalk.yellow(`Updating DNS Record:`)} ${dnsRecordName}`);
const { result } = await this.api(
`/zones/${zoneId}/dns_records/${dnsRecordId}`,
{
method: 'PATCH',
body: JSON.stringify({
content: dnsRecordContent,
}),
}
);
return result;
};
}
class Tailscale {
log = new Logger(chalk.bgBlackBright.bold.dim(' tailscale '));
getMachines = async () => {
this.log.info('Fetching Machines...');
const machines = [];
const { BackendState, Self, Peer, MagicDNSSuffix } = JSON.parse(
await $`tailscale status --json`
);
if (BackendState !== 'Running') {
this.log.error(`Backend is ${BackendState}!`);
this.log.log('Run `tailscale up` to continue.');
exit(1);
}
const patternToRemove = new RegExp(`\\.${MagicDNSSuffix}\\.?`);
machines.push({
name: Self.DNSName.replace(patternToRemove, ''),
ip: Self.TailAddr,
});
for (const { DNSName, TailAddr } of Object.values(Peer)) {
machines.push({
name: DNSName.replace(patternToRemove, ''),
ip: TailAddr,
});
}
this.log.info(`${machines.length} Machines found!`);
return machines;
};
}
const cloudflare = new Cloudflare();
const tailscale = new Tailscale();
const machines = await tailscale.getMachines();
await cloudflare.ensureToken();
const { id: zoneId } = await cloudflare.getZone();
const dnsRecords = await cloudflare.listDnsRecords({ zoneId });
const dnsRecordByMachineName = dnsRecords.reduce((byMachineName, dnsRecord) => {
const machineName = dnsRecord.name.replace(DNS_RECORD_SUFFIX_PATTERN, '');
byMachineName[machineName] = dnsRecord;
return byMachineName;
}, {});
const machineByName = machines.reduce((byName, machine) => {
byName[machine.name] = machine;
return byName;
}, {});
for (const [
machineName,
{ id: dnsRecordId, name: dnsRecordName, content: dnsRecordContent },
] of Object.entries(dnsRecordByMachineName)) {
const machine = machineByName[machineName];
if (!machine) {
await cloudflare.deleteDnsRecord({
zoneId,
dnsRecordId,
dnsRecordName,
});
continue;
}
const { ip } = machine;
if (ip !== dnsRecordContent) {
await cloudflare.updateDnsRecord({
zoneId,
dnsRecordId,
dnsRecordName,
dnsRecordContent: ip,
});
continue;
}
}
for (const [machineName, { ip }] of Object.entries(machineByName)) {
const dnsRecord = dnsRecordByMachineName[machineName];
if (!dnsRecord) {
const dnsRecordName = `${machineName}.${DNS_RECORD_NAMESPACE}.${DOMAIN_NAME}`;
await cloudflare.createDnsRecord({
zoneId,
dnsRecordName,
dnsRecordContent: ip,
});
continue;
}
}