-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
101 lines (89 loc) · 2.32 KB
/
main.ts
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
import Cloudflare from "npm:cloudflare@4.0.0";
import yn from "npm:yn@5.0.0";
async function getOwnIp() {
const url = "https://checkip.amazonaws.com";
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch IP from ${url}`);
}
const text = await response.text();
return text.trim();
}
function requireEnvVar(name: string): string {
const value = Deno.env.get(name);
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
function getComment() {
const now = new Date().toISOString();
return `Automatically updated by cf-dyn-dns at ${now}`;
}
async function createARecord(
client: Cloudflare,
zoneId: string,
name: string,
ip: string,
proxied: boolean
) {
return await client.dns.records.create({
zone_id: zoneId,
type: "A",
proxied,
name,
content: ip,
comment: getComment(),
});
}
async function updateARecord(
client: Cloudflare,
zoneId: string,
recordId: string,
ip: string
) {
return await client.dns.records.update(recordId, {
zone_id: zoneId,
content: ip,
comment: getComment(),
});
}
if (import.meta.main) {
const apiToken = requireEnvVar("CF_API_TOKEN");
const zoneId = requireEnvVar("CF_ZONE_ID");
const aRecordNames = requireEnvVar("CF_A_RECORDS")
.split(",")
.map((s) => s.trim());
const createWithProxying = yn(requireEnvVar("CF_CREATE_WITH_PROXYING"), {
default: false,
});
if (!aRecordNames.length) {
throw new Error("No records specified");
}
const client = new Cloudflare({
apiToken,
});
const recordsResponse = await client.dns.records.list({
zone_id: zoneId,
});
const foundRecords = new Map(
aRecordNames.map((name) => [
name,
recordsResponse.result.find(
(record) => record.name === name && record.type === "A"
),
])
);
const ownIp = await getOwnIp();
for (const [name, record] of foundRecords) {
if (!record) {
console.log(`Creating record for ${name}`);
await createARecord(client, zoneId, name, ownIp, createWithProxying);
} else if (record.content !== ownIp) {
console.log(`Updating record for ${name}`);
await updateARecord(client, zoneId, record.id, ownIp);
} else {
console.log(`Record for ${name} is already up to date`);
}
}
}