Skip to content

Instantly share code, notes, and snippets.

@soruly
Created June 16, 2024 10:36
Show Gist options
  • Save soruly/12de925be00f94db58e1d5a94f6e0e2c to your computer and use it in GitHub Desktop.
Save soruly/12de925be00f94db58e1d5a94f6e0e2c to your computer and use it in GitHub Desktop.
Update Cloudflare IP address (IPv4 and IPv6)
#!/usr/bin/env node
import * as http2 from "node:http2";
import * as os from "node:os";
const CF_API = "https://api.cloudflare.com/client/v4";
const headers = {
"X-Auth-Email": "email@add.ress",
"X-Auth-Key": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"Content-Type": "application/json",
};
const getIpAddress = (family) =>
new Promise((resolve) => {
const client = http2.connect("https://to-the-cloudflare-worker-below", { family });
client.on("error", (err) => console.error(err));
const req = client.request({ ":path": "/" });
req.setEncoding("utf8");
let data = "";
req.on("data", (chunk) => (data += chunk));
req.on("end", () => (client.close(), resolve(data)));
req.setTimeout(5000, () => (req.close(http2.constants.NGHTTP2_CANCEL), resolve()));
req.end();
});
const IPv6Address = await getIpAddress(6);
console.log(`IPv6: ${IPv6Address}`);
for (const domain of [
"your.domain",
"another.domain",
]) {
console.log(`updating ${domain}`);
const zoneId = (
await fetch(`${CF_API}/zones?name=${domain}`, {
headers,
}).then((e) => e.json())
).result[0].id;
const nameRecordList = (
await fetch(`${CF_API}/zones/${zoneId}/dns_records?name=${os.hostname()}.${domain}`, {
headers,
}).then((e) => e.json())
).result;
const AAAARecord = nameRecordList.find((e) => e.type === "AAAA");
if (IPv6Address && (!AAAARecord || AAAARecord.content !== IPv6Address)) {
await fetch(
AAAARecord
? `${CF_API}/zones/${zoneId}/dns_records/${AAAARecord.id}`
: `${CF_API}/zones/${zoneId}/dns_records`,
{
headers,
method: AAAARecord ? "PATCH" : "POST",
body: JSON.stringify({
name: `${os.hostname()}.${domain}`,
content: IPv6Address,
type: "AAAA",
}),
}
).then((e) => e.json());
}
console.log(`updated ${domain}`);
}
process.exit();
export default {
async fetch(request) {
return new Response(
request.headers.get('X-Forwarded-For') || request.headers.get("Cf-Connecting-Ip")
);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment