forked from willswire/unifi-ddns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
236 lines (205 loc) · 6.73 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
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
/**
* Receives a HTTP request and replies with a response.
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const { protocol, pathname } = new URL(request.url);
// Require HTTPS (TLS) connection to be secure.
if (
"https:" !== protocol ||
"https" !== request.headers.get("x-forwarded-proto")
) {
throw new BadRequestException("Please use a HTTPS connection.");
}
switch (pathname) {
case "/nic/update":
case "/update":
if (request.headers.has("Authorization")) {
const { username, password } = basicAuthentication(request);
// Throws exception when query parameters aren't formatted correctly
const url = new URL(request.url);
verifyParameters(url);
// Only returns this response when no exception is thrown.
const response = await informAPI(url, username, password);
return response;
}
throw new BadRequestException("Please provide valid credentials.");
case "/favicon.ico":
case "/robots.txt":
return new Response(null, { status: 204 });
}
return new Response("Not Found.", { status: 404 });
}
/**
* Pass the request info to the Cloudflare API Handler
* @param {URL} url
* @param {String} name
* @param {String} token
* @returns {Promise<Response>}
*/
async function informAPI(url, name, token) {
// Parse Url
const hostname = url.searchParams.get("hostname");
// Get the IP address. This can accept two query parameters, this will
// use the "ip" query parameter if it is set, otherwise falling back to "myip".
const ip = url.searchParams.get("ip") || url.searchParams.get("myip");
// Initialize API Handler
const cloudflare = new Cloudflare({
token: token,
});
const zone = await cloudflare.findZone(name);
const record = await cloudflare.findRecord(zone, hostname);
const result = await cloudflare.updateRecord(record, ip);
// Only returns this response when no exception is thrown.
return new Response(`good`, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=UTF-8",
"Cache-Control": "no-store"
},
});
}
/**
* Throws exception on verification failure.
* @param {string} url
* @throws {UnauthorizedException}
*/
function verifyParameters(url) {
if (!url.searchParams) {
throw new BadRequestException("You must include proper query parameters");
}
if (!url.searchParams.get("hostname")) {
throw new BadRequestException("You must specify a hostname");
}
if (!(url.searchParams.get("ip") || url.searchParams.get("myip"))) {
throw new BadRequestException("You must specify an ip address");
}
}
/**
* Parse HTTP Basic Authorization value.
* @param {Request} request
* @throws {BadRequestException}
* @returns {{ user: string, pass: string }}
*/
function basicAuthentication(request) {
const Authorization = request.headers.get("Authorization");
const [scheme, encoded] = Authorization.split(" ");
// Decodes the base64 value and performs unicode normalization.
// @see https://dev.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
const buffer = Uint8Array.from(atob(encoded), (character) =>
character.charCodeAt(0)
);
const decoded = new TextDecoder().decode(buffer).normalize();
// The username & password are split by the first colon.
//=> example: "username:password"
const index = decoded.indexOf(":");
// The user & password are split by the first colon and MUST NOT contain control characters.
// @see https://tools.ietf.org/html/rfc5234#appendix-B.1 (=> "CTL = %x00-1F / %x7F")
if (index === -1 || /[\0-\x1F\x7F]/.test(decoded)) {
throw new BadRequestException("Invalid authorization value.");
}
return {
username: decoded.substring(0, index),
password: decoded.substring(index + 1),
};
}
class UnauthorizedException {
constructor(reason) {
this.status = 401;
this.statusText = "Unauthorized";
this.reason = reason;
}
}
class BadRequestException {
constructor(reason) {
this.status = 400;
this.statusText = "Bad Request";
this.reason = reason;
}
}
class CloudflareApiException {
constructor(reason) {
this.status = 500;
this.statusText = "Internal Server Error";
this.reason = reason;
}
}
class Cloudflare {
constructor(options) {
this.cloudflare_url = "https://api.cloudflare.com/client/v4";
if (options.token) {
this.token = options.token;
}
this.findZone = async (name) => {
var response = await fetch(
`https://api.cloudflare.com/client/v4/zones?name=${name}`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
},
}
);
var body = await response.json();
if(body.success !== true || body.result.length === 0) {
throw new CloudflareApiException("Failed to find zone '" + name + "'");
}
return body.result[0];
};
this.findRecord = async (zone, name) => {
var response = await fetch(
`https://api.cloudflare.com/client/v4/zones/${zone.id}/dns_records?name=${name}`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
},
}
);
var body = await response.json();
if(body.success !== true || body.result.length === 0) {
throw new CloudflareApiException("Failed to find dns record '" + name + "'");
}
return body.result[0];
};
this.updateRecord = async (record, value) => {
record.content = value;
var response = await fetch(
`https://api.cloudflare.com/client/v4/zones/${record.zone_id}/dns_records/${record.id}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
},
body: JSON.stringify(record),
}
);
var body = await response.json();
if(body.success !== true) {
throw new CloudflareApiException("Failed to update dns record");
}
return body.result[0];
};
}
}
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch((err) => {
console.error(err.constructor.name, err);
const message = err.reason || err.stack || "Unknown Error";
return new Response(message, {
status: err.status || 500,
statusText: err.statusText || null,
headers: {
"Content-Type": "text/plain;charset=UTF-8",
// Disables caching by default.
"Cache-Control": "no-store",
// Returns the "Content-Length" header for HTTP HEAD requests.
"Content-Length": message.length,
},
});
})
);
});