-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudflare-sync-dns-cmd.js
executable file
·298 lines (250 loc) · 9.38 KB
/
cloudflare-sync-dns-cmd.js
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
#!/usr/bin/env node
import { DateTime } from 'luxon';
import {
readFileSync,
writeFileSync,
} from 'fs';
import {
hostname,
file_exists,
run_command_sync_to_console,
ping_google,
ping,
} from 'rad-scripts';
import {
getPublicIp,
callApi,
} from './csd.js';
// The path to the settings file must be provided as the first parameter.
// Get the settings loaded and validated.
// 0 = node, 1 = script path, so we ignore those.
// 2 = first parameter, the settings file.
const cloudflareSettingsFile = process.argv[ 2 ];
if ( !cloudflareSettingsFile ) {
console.log( 'Usage: cloudflare-sync-dns /path/to/settings.JSON' );
console.log( 'Details: https://gitlab.com/moodboom/cloudflare-sync-dns' );
process.exit( 1 );
}
const baseUrl = 'https://api.cloudflare.com/client/v4/zones';
const timestampShort = timestamp => timestamp.toLocaleString( DateTime.DATETIME_SHORT );
const timestampShortNow = () => timestampShort( DateTime.now());
// WE NEED A MASTER SYNC CHAIN FUNCTION.
// See Javascript scrap for the initial sync chain skeleton, fun!
// We will use a chain of promise functions that do the work and "resolve" when done.
// NOTE I was thinking we could do some fun async parallel scripting.
// But it turned out we need it all to be sync this time.
// NOTE that any errors should be generally reported, and will short-circuit the chain completion.
// If no update is needed, nothing is returned so that cron does not send an email.
const createDnsHistoryAsNeeded = async dnsHistoryFile => {
return new Promise(( resolve, reject ) => {
if ( !file_exists( dnsHistoryFile )) {
const initialHistory = [{ ip: '0.0.0.0', date: timestampShortNow() }];
writeFileSync( dnsHistoryFile, JSON.stringify( initialHistory ), 'utf-8' );
resolve( true );
}
resolve( false );
});
}
const loadDnsHistory = async dnsHistoryFile => {
return new Promise(( resolve, reject ) => {
try {
const historyFileString = readFileSync( dnsHistoryFile, 'utf8' );
const ha = JSON.parse( historyFileString );
const lastDnsIp = ha[ ha.length - 1 ].ip;
resolve( lastDnsIp );
}
catch( e ) {
console.log( 'loadDnsHistory error', e );
reject( e );
}
});
}
const loadCloudflareSettings = async () => {
return new Promise(( resolve, reject ) => {
try {
const cloudflareSettingsFileString = readFileSync( cloudflareSettingsFile, 'utf8' );
const s = JSON.parse( cloudflareSettingsFileString );
if (
!s
|| !( s.accountAPIKey )
|| !( s.accountEmail )
|| !( s.zoneIds?.length )
|| !( s.routerHostname )
) {
reject( 'Your cloudflareSettings.JSON file does not contain all required settings.' );
}
const { routerHostname } = s;
// If not on router, log and exit.
if ( hostname() !== routerHostname ) {
reject( `This script is only intended to run on ${routerHostname}, not ${hostname()}.` );
}
resolve( s );
}
catch( e ) {
console.log( `\nCould not load ${cloudflareSettingsFile}, make sure you have created and configured it.\n` );
reject( e );
}
});
}
const updateFirewall = async restartFirewallScript => {
return new Promise(( resolve, reject ) => {
// reset firewall with new IP
const bFWOK = run_command_sync_to_console( restartFirewallScript );
resolve( bFWOK );
});
}
// GET DNS RECORDS
// We GET DNS records first, so we can later use the dns_record_ids to update IP.
const getDnsRecords = async ({ headers, domain, zoneId }) => {
return new Promise(( resolve, reject ) => {
// We just want A records, which contain the IP address of the domain.
// Note that there are many filtering options available, KISS.
// const aFilter = 'type=A&match=any&order=type&direction=desc&per_page=100&page=1';
const aFilter = 'type=A&match=any&order=type&direction=desc';
const zoneGetUrl = `${baseUrl}/${zoneId}/dns_records?${aFilter}`;
// TOTHINK: Account (all domains) vs zone (one domain!)
// const accountGetUrl = `${baseUrl}/dns_records?account.id=${accountId}&${aFilter}`;
// Get existing Cloudflare DNS A records
const gotDnsRecords = data => {
const dnsData = data.result.map( d => ({
name: d.name,
id: d.id,
proxied: d.proxiable,
zoneId,
}));
if ( dnsData.find( d => d.name !== domain )) {
console.log( `Warning: domain ${ domain } returned name ${ d.name }` );
}
resolve( dnsData );
};
callApi({
headers,
method: 'GET',
url: zoneGetUrl,
successResponse: gotDnsRecords,
});
});
}
const updateDns = async ({ headers, currentExternalIp, dnsRecord }) => {
return new Promise(( resolve, reject ) => {
const baseUrl = 'https://api.cloudflare.com/client/v4/zones';
const patchedDnsRecord = data => {
if ( !data.success ) {
console.log( 'DNS record update failed:' );
console.log( JSON.stringify( data, null, 2 ) );
}
resolve( data.success );
};
const contents = {
'comment': `${timestampShortNow()} IP updated to ${currentExternalIp} by cloudflare-sync-dns npm command`,
'content': currentExternalIp,
};
const dnsPatchUrl = `${baseUrl}/${dnsRecord.zoneId}/dns_records/${dnsRecord.id}`;
callApi({
headers,
method: 'PATCH',
url: dnsPatchUrl,
contents,
successResponse: patchedDnsRecord,
});
});
}
const checkLan = async pingChecks => {
return new Promise(( resolve, reject ) => {
// verify we can ping both externally and internally
const bLanOk = ping_google() && pingChecks.every( p => ping( p ));
resolve( bLanOk );
});
}
const addCurrentIpToDnsHistory = async ( currentExternalIp, dnsHistoryFile ) => {
return new Promise(( resolve, reject ) => {
try {
const historyFileString = readFileSync( dnsHistoryFile, 'utf8' );
const h = JSON.parse( historyFileString );
h.push({
ip: currentExternalIp,
date: timestampShortNow(),
});
writeFileSync( dnsHistoryFile, JSON.stringify( h, null, 2 ), 'utf-8' );
resolve( true );
}
catch( e ) {
console.log( 'loadDnsHistory error', e );
resolve( false );
}
});
}
const syncDnsChainParent = async () => {
try {
const chainLog = [];
chainLog.push( `${timestampShortNow()} Chain running...` );
const settings = await loadCloudflareSettings();
const {
accountAPIKey,
accountEmail,
zoneIds,
restartFirewallScript,
pingChecks,
dnsHistoryFile,
} = settings;
chainLog.push( `${timestampShortNow()} Settings loaded` );
const currentExternalIp = await getPublicIp();
chainLog.push( `${timestampShortNow()} External IP: ${ currentExternalIp }` );
const bCreated = await createDnsHistoryAsNeeded( dnsHistoryFile );
chainLog.push( `${timestampShortNow()} Create history as needed: ${bCreated}` );
const lastDnsIp = await loadDnsHistory( dnsHistoryFile );
chainLog.push( `${timestampShortNow()} Load last: ${lastDnsIp}` );
if ( currentExternalIp !== lastDnsIp ) {
const headers = {
'X-Auth-Key': accountAPIKey,
'X-Auth-Email': accountEmail,
// 2024/11/13 I COULD NOT GET THIS GOING for v4 at this time.
// Even tho cloudflare recommends it, none of their docs are updated to use it.
// Also, it does not work and the "old" key+email way does. lol
// 'Authorization': `Bearer ${cloudflareAPIToken}`,
};
if ( restartFirewallScript ) {
const bFirewallOk = await updateFirewall( restartFirewallScript );
if ( !bFirewallOk ) {
throw new Error( `Failed to restart firewall` );
}
chainLog.push( `${timestampShortNow()} Restarted firewall` );
}
// NOTE LOOPS with await cannot use forEach.
// Simply use a normal for.
let dnsRecords = [];
for ( const z of zoneIds ) {
const dnsParams = { headers, ...z };
const dnsZoneRecords = await getDnsRecords( dnsParams );
dnsRecords = dnsRecords.concat( dnsZoneRecords );
};
chainLog.push( `${timestampShortNow()} Got ${dnsRecords.length} DNS records` );
let bUpdateOk = true;
for ( const dnsRecord of dnsRecords ) {
const bOk = await updateDns({ headers, currentExternalIp, dnsRecord });
if ( !bOk ) {
throw new Error( `Failed to update ${ dnsRecord.name } to IP ${currentExternalIp}` );
}
chainLog.push( `${timestampShortNow()} Updated ${ dnsRecord.name } to IP ${currentExternalIp}` );
bUpdateOk = bUpdateOk && bOk;
};
chainLog.push( `${timestampShortNow()} Update all DNS records: ${bUpdateOk}` );
const bLanOk = await checkLan( pingChecks );
chainLog.push( `${timestampShortNow()} Reset LAN: ${bLanOk}` );
if ( bLanOk ) {
// Update the local DNS history with the new IP.
const bUpdated = await addCurrentIpToDnsHistory( currentExternalIp, dnsHistoryFile );
chainLog.push( `${timestampShortNow()} Update local DNS history: ${bUpdated}` );
}
// Play out the sync chain log.
const firstLogging = chainLog.reduce(( accum, l ) => `${accum ? `${accum}\n` : ''}${l}`, '' );
console.log( firstLogging );
};
} catch( e ) {
console.log( `${timestampShortNow()} Chain error: ${e}` );
}
}
syncDnsChainParent().then(() => {
// DEBUG
// console.log( `${timestampShortNow()} Chain done.` );
});