-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (74 loc) · 2.03 KB
/
index.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
// module dependencies
const path = require('path')
// dotenv file support
require('dotenv').config({ path: path.join(__dirname, '.env') })
// rest of dependencies
const axios = require('axios')
// initialize cloudflare
const cf = require('cloudflare')({
token: process.env.CLOUDFLARE_TOKEN
})
// cache object
const cache = {}
// get public ip address of current network
async function getPublicIP () {
const res = await axios.get('https://ipv4.icanhazip.com')
// return res.data
return res.data.replace('\n', '')
}
// get ip address of cloudflare dns record
async function getCloudflareIP () {
// check cache
const now = new Date()
if (cache.cloudflareIP && cache.cloudflareIP.expiresAt > now) {
console.info('retrieved cloudflare dns record ip from cache')
return cache.cloudflareIP.value
}
// get dns record
const { result } = await cf.dnsRecords.read(
process.env.CLOUDFLARE_ZONE,
process.env.CLOUDFLARE_RECORD
)
// validate dns record
if (result.type !== 'A') {
const err = new Error('Must be an A record')
throw err
}
const value = result.content
// cache result
const expiresAt = new Date()
expiresAt.setTime(expiresAt.getTime() + (60 * 60 * 1000))
cache.cloudflareIP = { value, expiresAt }
return value
}
async function updateCloudflareIP (ip) {
// update dns record
return cf.dnsRecords.edit(
process.env.CLOUDFLARE_ZONE,
process.env.CLOUDFLARE_RECORD,
{ ...result, content: ip }
)
}
const interval = 1 * 60 * 1000
async function loop () {
return Promise.all([
getPublicIP(),
getCloudflareIP()
]).then(([ ip, cloudflareIP ]) => {
// check if dns record needs an update
if (ip === cloudflareIP) {
console.info('no need for dns update')
} else {
// update dns record
return updateCloudflareIP(ip).then(() => {
console.info('dns record now points to %s', ip)
})
}
}).catch(err => {
console.error('an error occured')
console.error(err)
}).finally(() => {
setTimeout(loop, interval)
})
}
loop()