-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.ts
194 lines (161 loc) · 5.9 KB
/
app.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
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
import express, { Request, Response } from 'express';
import Dns, * as $Dns from '@alicloud/alidns20150109';
import Util from '@alicloud/tea-util';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Console from '@alicloud/tea-console';
import * as $tea from '@alicloud/tea-typescript';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const API_KEY = process.env.API_KEY
function initializeClient(regionId: string): Dns {
const config = new $OpenApi.Config({
accessKeyId: process.env.ACCESS_KEY_ID,
accessKeySecret: process.env.ACCESS_KEY_SECRET,
regionId: regionId
});
return new Dns(config);
}
async function getDomainRecords(client: Dns, domainName: string, RR: string, recordType: string) {
const req = new $Dns.DescribeDomainRecordsRequest({});
req.domainName = domainName;
req.RRKeyWord = RR;
req.type = recordType;
const response = await client.describeDomainRecords(req);
// Add exact match filter
if (response?.body?.domainRecords?.record) {
const exactMatch = response.body.domainRecords.record.find(
record => record.RR === RR
);
if (exactMatch) {
response.body.domainRecords.record = [exactMatch];
} else {
response.body.domainRecords.record = [];
}
}
return response;
}
app.get('/change-ip', async (req: Request, res: Response): Promise<any> => {
const startTime = new Date();
console.log(`[${startTime.toISOString()}] Received request:`, {
server: req.query.server,
ip: req.query.ip,
type: req.query.type
});
try {
// Validate API key
const key = req.query.key as string;
if (key !== API_KEY) {
console.warn(`[${new Date().toISOString()}] Invalid API key attempt`);
return res.status(401).json({ error: 'Invalid API key' });
}
// Get and validate required parameters
const server = req.query.server as string;
const ip = req.query.ip as string;
const type = (req.query.type as string) || 'AAAA';
if (!server || !ip) {
return res.status(400).json({ error: 'Missing required parameters' });
}
// Validate record type
if (type !== 'A' && type !== 'AAAA') {
return res.status(400).json({ error: 'Invalid record type' });
}
// Construct full domain name
const domain = process.env.DOMAIN || ''
// if domain is empty, return 400
if (!domain) {
return res.status(400).json({ error: 'DOMAIN is not set' });
}
const fullDomain = `${server}.${domain}`
// Set record type
const recordType = type;
console.log(`[${new Date().toISOString()}] Processing request for domain: ${fullDomain}, IP: ${ip}, Type: ${recordType}`);
// Initialize client and update DNS record
const regionId = 'cn-hangzhou';
const client = initializeClient(regionId);
// Get current DNS records
console.log(`[${new Date().toISOString()}] Fetching existing DNS records...`);
const records = await getDomainRecords(client, domain, server, recordType);
const existingRecord = records?.body?.domainRecords?.record?.[0];
if (existingRecord) {
console.log(`[${new Date().toISOString()}] Found existing record:`, {
recordId: existingRecord.recordId,
currentValue: existingRecord.value
});
// Check if the IP value has changed
if (existingRecord.value === ip) {
const endTime = new Date();
const duration = endTime.getTime() - startTime.getTime();
console.log(`[${endTime.toISOString()}] No update needed - IP hasn't changed`, {
duration: `${duration}ms`,
domain: fullDomain,
ip: ip,
type: recordType
});
return res.json({
success: true,
message: 'No update needed - IP hasn\'t changed',
details: {
domain: fullDomain,
ip: ip,
type: recordType,
operation: 'none'
}
});
}
// Update existing record only if IP has changed
const updateRequest = new $Dns.UpdateDomainRecordRequest({});
updateRequest.RR = server;
updateRequest.recordId = existingRecord.recordId;
updateRequest.value = ip;
updateRequest.type = recordType;
updateRequest.TTL = 60;
await client.updateDomainRecord(updateRequest);
} else {
console.log(`[${new Date().toISOString()}] No existing record found, creating new record`);
// Add new record
const addRequest = new $Dns.AddDomainRecordRequest({});
addRequest.domainName = domain;
addRequest.RR = server;
addRequest.type = recordType;
addRequest.value = ip;
addRequest.TTL = 60;
await client.addDomainRecord(addRequest);
}
const endTime = new Date();
const duration = endTime.getTime() - startTime.getTime();
console.log(`[${endTime.toISOString()}] Operation completed successfully`, {
duration: `${duration}ms`,
operation: existingRecord ? 'update' : 'add',
domain: fullDomain,
ip: ip,
type: recordType
});
res.json({
success: true,
message: existingRecord ? 'DNS record updated successfully' : 'DNS record added successfully',
details: {
domain: fullDomain,
ip: ip,
type: recordType,
operation: existingRecord ? 'update' : 'add'
}
});
} catch (error) {
const endTime = new Date();
const duration = endTime.getTime() - startTime.getTime();
console.error(`[${endTime.toISOString()}] Operation failed`, {
duration: `${duration}ms`,
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined
});
res.status(500).json({
error: 'Failed to update DNS record',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});