Files
ddns-agent/agent/ddns/cloudflare/index.ts
2025-11-18 14:39:32 +08:00

88 lines
2.9 KiB
TypeScript

interface DnsUpdate {
zone_id: string;
record_id: string;
domain: string;
new_ip: string;
api_token: string;
type?: string; // 'A' or 'AAAA'
}
export class CloudflareDDNS {
makeHeader(api_token: string) {
return {
'Authorization': `Bearer ${api_token}`,
'Content-Type': 'application/json',
};
}
async updateRecord(data: DnsUpdate) {
const { zone_id, record_id, domain, type, new_ip, api_token } = data;
const url = `https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${record_id}`;
const body = {
"type": type || 'A',
"name": domain,
"content": new_ip,
"ttl": 0,
"proxied": false,
}
const response = await fetch(url, {
method: 'PUT',
headers: this.makeHeader(api_token),
body: JSON.stringify(body),
});
const result = await response.json();
if (!result.success) {
throw new Error(`更新失败: ${JSON.stringify(result.errors)}`);
}
return result;
}
async getList(zone_id: string, api_token: string, opts?: { per_page?: number; page?: number, search?: string }) {
const per_page = opts?.per_page || 100;
const page = opts?.page || 1;
const search = opts?.search ? `&search=${encodeURIComponent(opts.search)}` : '';
const url = `https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?per_page=${per_page}&page=${page}${search}`;
return fetch(url, {
method: 'GET',
headers: this.makeHeader(api_token),
}).then(res => res.json());
}
async getRecord(zone_id: string, record_id: string, api_token: string) {
const url = `https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${record_id}`;
return fetch(url, {
method: 'GET',
headers: this.makeHeader(api_token),
}).then(res => res.json());
}
async createRecord(data: Partial<DnsUpdate>) {
const { zone_id, domain, type = 'A', new_ip: content, api_token } = data;
const url = `https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records`;
const body = {
"type": type,
"name": domain,
"content": content,
"ttl": 0,
"proxied": false,
}
const response = await fetch(url, {
method: 'POST',
headers: this.makeHeader(api_token),
body: JSON.stringify(body),
});
const result = await response.json();
if (!result.success) {
throw new Error(`创建失败: ${JSON.stringify(result.errors)}`);
}
return result;
}
async deleteRecord(zone_id: string, record_id: string, api_token: string) {
const url = `https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${record_id}`;
const response = await fetch(url, {
method: 'DELETE',
headers: this.makeHeader(api_token),
});
const result = await response.json();
if (!result.success) {
throw new Error(`删除失败: ${JSON.stringify(result.errors)}`);
}
console.log(`删除成功: Record ID ${record_id}`);
return result;
}
}