forked from willswire/unifi-ddns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
131 lines (109 loc) · 3.92 KB
/
index.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
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
import { ClientOptions, Cloudflare } from 'cloudflare';
import { AAAARecord, ARecord } from 'cloudflare/src/resources/dns/records.js';
type AddressableRecord = AAAARecord | ARecord;
class HttpError extends Error {
constructor(
public statusCode: number,
message: string,
) {
super(message);
this.name = 'HttpError';
}
}
function constructClientOptions(request: Request): ClientOptions {
const authorization = request.headers.get('Authorization');
if (!authorization) {
throw new HttpError(401, 'API token missing.');
}
const [, data] = authorization.split(' ');
const decoded = atob(data);
const index = decoded.indexOf(':');
if (index === -1 || /[\0-\x1F\x7F]/.test(decoded)) {
throw new HttpError(401, 'Invalid API key or token.');
}
return {
apiEmail: decoded.substring(0, index),
apiToken: decoded.substring(index + 1),
};
}
function constructDNSRecord(request: Request): AddressableRecord {
const url = new URL(request.url);
const params = url.searchParams;
const ip = params.get('ip');
const hostname = params.get('hostname');
if (ip === null || ip === undefined) {
throw new HttpError(422, 'The "ip" parameter is required and cannot be empty.');
}
if (hostname === null || hostname === undefined) {
throw new HttpError(422, 'The "hostname" parameter is required and cannot be empty.');
}
return {
content: ip,
name: hostname,
type: ip.includes('.') ? 'A' : 'AAAA',
ttl: 1,
};
}
async function update(clientOptions: ClientOptions, newRecord: AddressableRecord): Promise<Response> {
const cloudflare = new Cloudflare(clientOptions);
const tokenStatus = (await cloudflare.user.tokens.verify()).status;
if (tokenStatus !== 'active') {
throw new HttpError(401, 'This API Token is ' + tokenStatus);
}
const zones = (await cloudflare.zones.list()).result;
if (zones.length > 1) {
throw new HttpError(400, 'More than one zone was found! You must supply an API Token scoped to a single zone.');
} else if (zones.length === 0) {
throw new HttpError(400, 'No zones found! You must supply an API Token scoped to a single zone.');
}
const zone = zones[0];
const records = (
await cloudflare.dns.records.list({
zone_id: zone.id,
name: newRecord.name,
type: newRecord.type,
})
).result;
if (records.length > 1) {
throw new HttpError(400, 'More than one matching record found!');
} else if (records.length === 0 || records[0].id === undefined) {
throw new HttpError(400, 'No record found! You must first manually create the record.');
}
// Extract the current `proxied` status
const currentRecord = records[0] as AddressableRecord;
const proxied = currentRecord.proxied ?? false; // Default to `false` if `proxied` is undefined
await cloudflare.dns.records.update(records[0].id, {
content: newRecord.content,
zone_id: zone.id,
name: newRecord.name,
type: newRecord.type,
proxied, // Pass the existing "proxied" status
});
console.log('DNS record for ' + newRecord.name + '(' + newRecord.type +') updated successfully to ' + newRecord.content);
return new Response('OK', { status: 200 });
}
export default {
async fetch(request): Promise<Response> {
const url = new URL(request.url);
console.log('Requester IP: ' + request.headers.get('CF-Connecting-IP'));
console.log(request.method + ': ' + request.url);
if (request.body) {
console.log('Body: ' + await request.text());
}
try {
// Construct client options and DNS record
const clientOptions = constructClientOptions(request);
const record = constructDNSRecord(request);
// Run the update function
return await update(clientOptions, record);
} catch (error) {
if (error instanceof HttpError) {
console.log('Error updating DNS record: ' + error.message);
return new Response(error.message, { status: error.statusCode });
} else {
console.log('Error updating DNS record: ' + error);
return new Response('Internal Server Error', { status: 500 });
}
}
},
} satisfies ExportedHandler<Env>;