├── LICENSE ├── README.md └── _worker.js /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Domains DDNS to Domain 2 | 将多个域名IP解析至指定域名的worker.js脚本 3 | 4 | ## 部署方式 5 | 6 | - **Workers** 部署:复制 [_worker.js](https://github.com/cmliu/CF-Workers-DD2D/blob/main/_worker.js) 代码,`保存并部署`即可 7 | 8 | ## 如何使用? 9 | 例如 您的Workers项目域名为:`dd2d.fxxk.workers.dev`; 10 | 11 | 1. 如你想将`cdn.xn--b6gac.eu.org`和`my-telegram-is-herocore.onecf.eu.org`内的IP解析到你的`ddns.google.com`下,你可以设置如下变量 12 | - 变量名`DOMAIN`,值为`cdn.xn--b6gac.eu.org,my-telegram-is-herocore.onecf.eu.org`,支持多元素之间使用`,`或**换行**作间隔; 13 | 14 | 2. 如你想将`https://ipdb.030101.xyz/api/bestproxy.txt`列表内的IP解析到你的`ddns.google.com`下,你可以设置如下变量 15 | - 变量名`IPAPI`,值为`https://ipdb.030101.xyz/api/bestproxy.txt`,支持多元素之间使用`,`或**换行**作间隔; 16 | 17 | ### 手动执行 18 | - 访问`https://dd2d.fxxk.workers.dev`即可**查看DD2D配置信息**; 19 | - 访问`https://dd2d.fxxk.workers.dev/go`即可**手动执行**DD2D域名解析任务; 20 | - *如果你设置了`TOKEN`变量则需要访问`https://dd2d.fxxk.workers.dev/go?token=admin`才会手动执行DD2D域名解析任务。* 21 | 22 | ### 定时任务 23 | - 设置添加`Cron 触发器`即可; 24 | - 例如`0 */8 * * *`为**每8小时执行一次**,更多定时任务Cron写法请自行GPT。 25 | 26 | ## 变量说明 27 | | 变量名 | 示例 | 必填 | 备注 | 28 | |--------|---------|-|-----| 29 | | CFMAIL | `admin@gmail.com` |√| Cloudflare 登录邮箱 | 30 | | CFDOMAIN | `ddns.google.com` |√| Cloudflare 待解析域名 | 31 | | CFZONEID | `6f0b34f36efb4bdaf5e22d68ac8e5c96` |√| Cloudflare 区域ID | 32 | | CFKEY | `tGb4_4f5e23efb4d68ac28exRnJTfbdaC6-IWocs` |√| Cloudflare API令牌 | 33 | | TOKEN | `admin` |×| **手动执行**时验证token,token不正确将不会执行DD2D | 34 | | DOH | `https://cloudflare-dns.com/dns-query` |×| DoH(DNS over HTTPS)URL | 35 | | DOMAIN | `cdn.xn--b6gac.eu.org` |×| 获取待解析至`待解析域名`IP的域名(支持多元素之间`,`或 换行 作间隔) | 36 | | IPV4 | `8.8.8.8` |×| 待解析至`待解析域名`IPv4(支持多元素之间`,`或 换行 作间隔) | 37 | | IPV6 | `2406:8dc0:6004:7019:ca7a:65a0:d3d7:1467` |×| 待解析至`待解析域名`IPv6(支持多元素之间`,`或 换行 作间隔) | 38 | | BANIP | `1.1.1.1,2406:8dc0:6004:7019:ca7a:65a0:d3d7:1467` |×| 拉黑IP将不会解析至`待解析域名`(支持多元素之间`,`或 换行 作间隔) | 39 | | IPAPI | `https://ipdb.030101.xyz/api/bestproxy.txt` |×| 通过API获取待解析至`待解析域名`IP的接口(支持多元素之间`,`或 换行 作间隔) | 40 | | TGTOKEN | `6894123456:XXXXXXXXXX0qExVsBPUhHDAbXXX` |×| 发送TG通知的机器人token | 41 | | TGID | `6946912345` |×| 接收TG通知的账户数字ID | 42 | 43 | -------------------------------------------------------------------------------- /_worker.js: -------------------------------------------------------------------------------- 1 | // 定义域名数组 2 | let domains = []; 3 | // 定义IPv4和IPv6数组,用于存储解析后的IP地址 4 | let IPv4 = []; 5 | let IPv6 = []; 6 | let banIP = []; 7 | // 定义API列表 8 | let ipAPI = [];//'https://ipdb.030101.xyz/api/bestproxy.txt' 9 | // 定义DoH(DNS over HTTPS)URL 10 | let dohURL = 'https://cloudflare-dns.com/dns-query'; 11 | 12 | //Cloudflare DDNS 13 | let CF邮箱 = '';//admin@gmail.com 14 | let CF域名 = '';//ddns.google.com 15 | let CF区域ID = '';//6f0b34f36efb4bdaf5e22d68ac8e5c96 16 | let CFAPI令牌 = '';//tGb4_4f3efb4bdaf5e22d68ac8exRnJTC6-IWocs 17 | 18 | let 执行日志 = ''; 19 | 20 | let BotToken =''; 21 | let ChatID =''; 22 | let tgmsg = ''; 23 | 24 | let 解析成功次数 = 0; 25 | let 解析失败次数 = 0; 26 | 27 | export default { 28 | async fetch(request, env, ctx) { 29 | 执行日志 = ''; 30 | let result = ''; 31 | try { 32 | if (env.DOMAIN) domains = await ADD(env.DOMAIN); 33 | if (env.IPV4) IPv4 = await ADD(env.IPV4); 34 | if (env.IPV6) IPv6 = await ADD(env.IPV6); 35 | if (env.BANIP) banIP = await ADD(env.BANIP); 36 | if (env.IPAPI) ipAPI = await ADD(env.IPAPI); 37 | dohURL = env.DOH || dohURL; 38 | 39 | CF邮箱 = env.CFMAIL || CF邮箱; 40 | CF域名 = env.CFDOMAIN || CF域名; 41 | CF区域ID = env.CFZONEID || CF区域ID; 42 | CFAPI令牌 = env.CFKEY || CFAPI令牌; 43 | 44 | BotToken = env.TGTOKEN || BotToken; 45 | ChatID = env.TGID || ChatID; 46 | 47 | log('变量加载完成'); 48 | if ((domains.length + IPv4.length + IPv6.length + ipAPI.length) == 0) { 49 | domains = ['cdn.xn--b6gac.eu.org']; 50 | log('DOMAIN、IPV4、IPV6、IPAPI变量值均为空,添加 演示解析域名 cdn.xn--b6gac.eu.org') 51 | } 52 | // 更新IPv4和IPv6数组 53 | const d2ip = await updateIPArrays(domains); 54 | IPv4 = IPv4.concat(d2ip[0]); 55 | IPv6 = IPv6.concat(d2ip[1]); 56 | log('域名解析完成'); 57 | 58 | const api2ip = await API2ip(ipAPI); 59 | IPv4 = IPv4.concat(api2ip[0]); 60 | IPv6 = IPv6.concat(api2ip[1]); 61 | log('API调用完成'); 62 | 63 | // 对数组进行去重 64 | IPv4 = [...new Set(IPv4)]; 65 | IPv6 = [...new Set(IPv6)]; 66 | log('IP去重完成'); 67 | 68 | // 处理被banIP 69 | IPv4 = IPv4.filter(ip => !banIP.includes(ip)); 70 | IPv6 = IPv6.filter(ip => !banIP.includes(ip)); 71 | log('BAN_IP清理完成'); 72 | 73 | const url = new URL(request.url); 74 | console.log(url.pathname); 75 | if (url.pathname == '/go') { 76 | const token = url.searchParams.get('token'); 77 | if (env.TOKEN && env.TOKEN != token) { 78 | if (!token) log('token不能为空'); 79 | else log('token不正确'); 80 | result = await 输出结果(0); 81 | } else { 82 | log('手动执行'); 83 | result = await 输出结果(1); 84 | } 85 | } else { 86 | result = await 输出结果(0); 87 | } 88 | } catch (error) { 89 | log(`发生错误: ${error.message}`); 90 | console.error(error); 91 | // 即使发生错误,也确保调用输出结果 92 | result = await 输出结果(0); 93 | } 94 | 95 | // 返回输出结果作为响应 96 | return new Response(result); 97 | }, 98 | 99 | // 添加对scheduled事件的处理 100 | async scheduled(event, env, ctx) { 101 | // 在这里执行定期任务的逻辑 102 | console.log("Cron job started at " + new Date().toUTCString()); 103 | 104 | // 复用fetch方法中的逻辑 105 | if (env.DOMAIN) domains = await ADD(env.DOMAIN); 106 | if (env.IPV4) IPv4 = await ADD(env.IPV4); 107 | if (env.IPV6) IPv6 = await ADD(env.IPV6); 108 | if (env.BANIP) banIP = await ADD(env.BANIP); 109 | if (env.IPAPI) ipAPI = await ADD(env.IPAPI); 110 | dohURL = env.DOH || dohURL; 111 | 112 | CF邮箱 = env.CFMAIL || CF邮箱; 113 | CF域名 = env.CFDOMAIN || CF域名; 114 | CF区域ID = env.CFZONEID || CF区域ID; 115 | CFAPI令牌 = env.CFKEY || CFAPI令牌; 116 | 117 | BotToken = env.TGTOKEN || BotToken; 118 | ChatID = env.TGID || ChatID; 119 | 120 | log('Cron: 变量加载完成'); 121 | if( (domains.length + IPv4.length + IPv6.length + ipAPI.length) == 0){ 122 | domains = ['cdn.xn--b6gac.eu.org']; 123 | log('DOMAIN、IPV4、IPV6、IPAPI变量值均为空,添加 演示解析域名 cdn.xn--b6gac.eu.org') 124 | } 125 | // 更新IPv4和IPv6数组 126 | const d2ip = await updateIPArrays(domains); 127 | IPv4 = IPv4.concat(d2ip[0]); 128 | IPv6 = IPv6.concat(d2ip[1]); 129 | log('Cron: 域名解析完成'); 130 | 131 | const api2ip = await API2ip(ipAPI); 132 | IPv4 = IPv4.concat(api2ip[0]); 133 | IPv6 = IPv6.concat(api2ip[1]); 134 | log('Cron: API调用完成'); 135 | 136 | // 对数组进行去重 137 | IPv4 = [...new Set(IPv4)]; 138 | IPv6 = [...new Set(IPv6)]; 139 | log('Cron: IP去重完成'); 140 | 141 | // 处理被banIP 142 | IPv4 = IPv4.filter(ip => !banIP.includes(ip)); 143 | IPv6 = IPv6.filter(ip => !banIP.includes(ip)); 144 | log('Cron: BAN_IP清理完成'); 145 | 146 | // 执行输出结果,但不需要返回Response对象 147 | await 输出结果(1); 148 | 149 | console.log("Cron job completed at " + new Date().toUTCString()); 150 | } 151 | }; 152 | 153 | async function sendMessage(msg) { 154 | if ( BotToken !== '' && ChatID !== ''){ 155 | let url = "https://api.telegram.org/bot"+ BotToken +"/sendMessage?chat_id=" + ChatID + "&parse_mode=HTML&text=" + encodeURIComponent(msg); 156 | console.log(msg); 157 | log(`TG推送完成`); 158 | 159 | return fetch(url, { 160 | method: 'get', 161 | headers: { 162 | 'Accept': 'text/html,application/xhtml+xml,application/xml;', 163 | 'Accept-Encoding': 'gzip, deflate, br', 164 | 'User-Agent': 'Mozilla/5.0 Chrome/90.0.4430.72' 165 | } 166 | }); 167 | } else { 168 | log(`TG推送关闭`); 169 | } 170 | } 171 | 172 | // 更新IP数组的函数 173 | async function API2ip(APIs) { 174 | let IP4 = []; 175 | let IP6 = []; 176 | if (!APIs || APIs.length === 0) { 177 | return [IP4, IP6]; 178 | } 179 | 180 | let newIP = ""; 181 | 182 | // 创建一个AbortController对象,用于控制fetch请求的取消 183 | const controller = new AbortController(); 184 | 185 | const timeout = setTimeout(() => { 186 | controller.abort(); // 取消所有请求 187 | }, 2000); // 2秒后触发 188 | 189 | try { 190 | // 使用Promise.allSettled等待所有API请求完成,无论成功或失败 191 | // 对api数组进行遍历,对每个API地址发起fetch请求 192 | const responses = await Promise.allSettled(APIs.map(apiUrl => fetch(apiUrl, { 193 | method: 'get', 194 | headers: { 195 | 'Accept': 'text/html,application/xhtml+xml,application/xml;', 196 | 'User-Agent': 'cmliu/CF-Workers-DD2D' 197 | }, 198 | signal: controller.signal // 将AbortController的信号量添加到fetch请求中,以便于需要时可以取消请求 199 | }).then(response => response.ok ? response.text() : Promise.reject()))); 200 | 201 | // 遍历所有响应 202 | for (const response of responses) { 203 | // 检查响应状态是否为'fulfilled',即请求成功完成 204 | if (response.status === 'fulfilled') { 205 | // 获取响应的内容 206 | const content = await response.value; 207 | newIP += content + '\n'; 208 | } 209 | } 210 | } catch (error) { 211 | console.error(error); 212 | } finally { 213 | // 无论成功或失败,最后都清除设置的超时定时器 214 | clearTimeout(timeout); 215 | } 216 | 217 | const newIPs = await ADD(newIP); 218 | // 正则表达式匹配IPv4地址 219 | const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; 220 | 221 | // 正则表达式匹配IPv6地址 222 | const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9])?[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9])?[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9])?[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9])?[0-9]))$/; 223 | 224 | newIPs.forEach(ip => { 225 | if (ipv4Regex.test(ip)) { 226 | IP4.push(ip); 227 | log(`API获取 A记录${ip}`); 228 | } else if (ipv6Regex.test(ip)) { 229 | IP6.push(ip); 230 | log(`API获取 AAAA记录${ip}`); 231 | } 232 | }); 233 | 234 | return [IP4, IP6]; 235 | } 236 | 237 | // 使用DoH解析域名的函数 238 | async function fetchDNSRecords(domain, type) { 239 | // 构建查询参数 240 | const query = new URLSearchParams({ 241 | name: domain, 242 | type: type 243 | }); 244 | const url = `${dohURL}?${query.toString()}`; 245 | 246 | // 发送HTTP GET请求 247 | const response = await fetch(url, { 248 | method: 'GET', 249 | headers: { 250 | 'Accept': 'application/dns-json' // 接受DNS JSON格式的响应 251 | } 252 | }); 253 | 254 | // 检查响应是否成功 255 | if (!response.ok) { 256 | throw new Error(`获取DNS记录失败: ${response.statusText}`); 257 | } 258 | 259 | // 解析响应数据 260 | const data = await response.json(); 261 | return data.Answer || []; 262 | } 263 | 264 | // 更新IP数组的函数 265 | async function updateIPArrays(domains) { 266 | let IP4 = []; 267 | let IP6 = []; 268 | for (const domain of domains) { 269 | try { 270 | // 获取域名的A记录 271 | const aRecords = await fetchDNSRecords(domain, 'A'); 272 | for (const record of aRecords) { 273 | if (record.type === 1) { // A记录 274 | IP4.push(record.data); 275 | log(`解析域名 ${domain} A记录${record.data}`); 276 | } 277 | } 278 | 279 | // 获取域名的AAAA记录 280 | const aaaaRecords = await fetchDNSRecords(domain, 'AAAA'); 281 | for (const record of aaaaRecords) { 282 | if (record.type === 28) { // AAAA记录 283 | IP6.push(record.data); 284 | log(`解析域名 ${domain} AAAA记录${record.data}`); 285 | } 286 | } 287 | } catch (error) { 288 | console.error(`解析域名 ${domain} 时出错:`, error); 289 | } 290 | } 291 | 292 | return [IP4, IP6]; 293 | } 294 | 295 | // 输出结果的函数 296 | async function 输出结果(on) { 297 | 解析成功次数 = 0; 298 | 解析失败次数 = 0; 299 | 300 | // 构建IPv6输出字符串 301 | let IPv6Text = '' 302 | if (IPv6.length != 0){ 303 | IPv6Text = `\nIPv6:\n${IPv6.join('\n')}\n`; 304 | } 305 | 306 | let APIText = '' 307 | if (ipAPI.length != 0){ 308 | APIText = `\nIP_API:\n${ipAPI.join('\n')}\n`; 309 | } 310 | 311 | let banIPTest = '' 312 | if (banIP.length != 0){ 313 | banIPTest = `\nBAN_IP:\n${banIP.join('\n')}\n`; 314 | } 315 | 316 | let domainsTest = ''; 317 | if (domains.length != 0){ 318 | domainsTest = `\n解析域名:\n${domains.join('\n')}\n`; 319 | } 320 | 321 | // 构建解析记录列表 322 | const 解析记录列表 = [...IPv4.map(ip => ({ type: 'A', content: ip })), ...IPv6.map(ip => ({ type: 'AAAA', content: ip }))]; 323 | 324 | const CF配置检查 = CF域名 + CF区域ID + CFAPI令牌 + CF邮箱; 325 | let CF配置信息 326 | if (CF配置检查 && CF配置检查 != '' && on == 1){ 327 | CF配置信息 = `域名:${CF域名} 328 | 邮箱:${CF邮箱.substring(0, 1)}****** 329 | 区域ID:${CF区域ID.substring(0, 3)}*************************${CF区域ID.substring(CF区域ID.length - 4)} 330 | API令牌:${CFAPI令牌.substring(0, 3)}*************************${CFAPI令牌.substring(CFAPI令牌.length - 4)}`; 331 | const 域名现有解析ID_URL = `https://api.cloudflare.com/client/v4/zones/${CF区域ID}/dns_records?name=${CF域名}`; 332 | const response = await fetch(域名现有解析ID_URL, { 333 | method: 'GET', 334 | headers: { 335 | 'X-Auth-Email': CF邮箱, 336 | 'Authorization': `Bearer ${CFAPI令牌}`, 337 | 'Content-Type': 'application/json' 338 | } 339 | }); 340 | const data = await response.json(); 341 | console.log(JSON.stringify(data, null, 2)); 342 | let 域名现有解析ID = []; 343 | if (!data.success || data.result.length === 0){ 344 | log(`${CF域名} 域名解析为空,跳过删除域名流程`) 345 | } else { 346 | for (let record of data.result) { 347 | 域名现有解析ID.push(record.id); 348 | } 349 | log(`现有域名ID\n${域名现有解析ID.join('\n')}`); 350 | } 351 | 352 | // 并发删除域名 353 | await 批量删除域名(域名现有解析ID); 354 | 355 | await new Promise(resolve => setTimeout(resolve, 8000)); 356 | 357 | // 调用批量添加解析 358 | await 批量添加解析(解析记录列表); 359 | 360 | } else { 361 | if(on == 0){ 362 | CF配置信息 = `域名:${CF域名} 363 | 邮箱:${CF邮箱.substring(0, 1)}****** 364 | 区域ID:${CF区域ID.substring(0, 3)}*************************${CF区域ID.substring(CF区域ID.length - 4)} 365 | API令牌:${CFAPI令牌.substring(0, 3)}*************************${CFAPI令牌.substring(CFAPI令牌.length - 4)}`; 366 | } else { 367 | CF配置信息 = 'Cloudflare配置信息错误!' 368 | } 369 | 370 | } 371 | // 构建最终的输出文本 372 | const text = `Domains DDNS to Domain 373 | ################################################################ 374 | Cloudflare域名配置信息 375 | --------------------------------------------------------------- 376 | ${CF配置信息} 377 | 378 | --------------------------------------------------------------- 379 | ################################################################ 380 | 配置信息 381 | --------------------------------------------------------------- 382 | DoH: 383 | ${dohURL} 384 | ${domainsTest}${APIText} 385 | --------------------------------------------------------------- 386 | ################################################################ 387 | 整理结果 388 | --------------------------------------------------------------- 389 | IPv4: 390 | ${IPv4.join('\n')} 391 | ${IPv6Text}${banIPTest} 392 | --------------------------------------------------------------- 393 | ################################################################ 394 | 执行日志 395 | --------------------------------------------------------------- 396 | ${执行日志} 397 | 398 | --------------------------------------------------------------- 399 | ################################################################ 400 | telegram 交流群 技术大佬~在线发牌! 401 | https://t.me/CMLiussss 402 | --------------------------------------------------------------- 403 | github 项目地址 Star!Star!Star!!! 404 | https://github.com/cmliu/CF-Workers-DD2D 405 | --------------------------------------------------------------- 406 | ################################################################`; 407 | if(on == 1) await sendMessage(`Domains DDNS to Domain:\n${CF域名} 解析完成! 成功: ${解析成功次数} 失败: ${解析失败次数}${tgmsg}`); 408 | return text; 409 | } 410 | 411 | async function log(text) { 412 | // 获取当前的 UTC 时间 413 | const now = new Date(); 414 | 415 | // 将 UTC 时间转换为中国时间 (CST, UTC+8) 416 | const offset = 8 * 60 * 60 * 1000; // 8 小时的毫秒数 417 | const chinaTime = new Date(now.getTime() + offset); 418 | 419 | // 格式化为 yyyy-MM-dd HH:mm:ss 420 | const formattedTime = formatDate(chinaTime); 421 | 执行日志 += formattedTime + ' ' + text + '\n' ; 422 | console.log(text); 423 | } 424 | 425 | function formatDate(date) { 426 | const year = date.getFullYear(); 427 | const month = String(date.getMonth() + 1).padStart(2, '0'); 428 | const day = String(date.getDate()).padStart(2, '0'); 429 | const hours = String(date.getHours()).padStart(2, '0'); 430 | const minutes = String(date.getMinutes()).padStart(2, '0'); 431 | const seconds = String(date.getSeconds()).padStart(2, '0'); 432 | 433 | return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; 434 | } 435 | 436 | async function ADD(envadd) { 437 | var addtext = envadd.replace(/[ |"'\r\n]+/g, ',').replace(/,+/g, ','); // 将空格、双引号、单引号和换行符替换为逗号 438 | if (addtext.charAt(0) == ',') addtext = addtext.slice(1); 439 | if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, addtext.length - 1); 440 | const add = addtext.split(','); 441 | return add; 442 | } 443 | 444 | async function 批量删除域名(域名ID数组) { 445 | const 批次大小 = 4; // 每批并发请求的数量 446 | const 批次间隔 = 2000; // 批次之间的间隔时间(毫秒) 447 | 448 | for (let i = 0; i < 域名ID数组.length; i += 批次大小) { 449 | const 当前批次 = 域名ID数组.slice(i, i + 批次大小); 450 | 451 | // 并发删除当前批次的域名 452 | const 删除promises = 当前批次.map(域名ID => 删除域名(域名ID)); 453 | const results = await Promise.allSettled(删除promises); 454 | 455 | results.forEach((result, index) => { 456 | if (result.status === 'fulfilled') { 457 | log(`${CF域名}:${当前批次[index]} 删除成功`); 458 | } else { 459 | log(`${CF域名}:${当前批次[index]} 删除失败: ${result.reason}`); 460 | } 461 | }); 462 | 463 | // 如果还有下一批,则等待指定的间隔时间 464 | if (i + 批次大小 < 域名ID数组.length) { 465 | await new Promise(resolve => setTimeout(resolve, 批次间隔)); 466 | } 467 | } 468 | } 469 | 470 | // 删除单个域名的函数保持不变 471 | async function 删除域名(域名ID) { 472 | const 删除域名_URL = `https://api.cloudflare.com/client/v4/zones/${CF区域ID}/dns_records/${域名ID}`; 473 | const response = await fetch(删除域名_URL, { 474 | method: 'DELETE', 475 | headers: { 476 | 'X-Auth-Email': CF邮箱, 477 | 'Authorization': `Bearer ${CFAPI令牌}`, 478 | 'Content-Type': 'application/json' 479 | } 480 | }); 481 | const data = await response.json(); 482 | console.log(JSON.stringify(data, null, 2)); 483 | if (!data.success) { 484 | throw new Error(`删除失败: ${JSON.stringify(data.errors)}`); 485 | } 486 | } 487 | 488 | async function 批量添加解析(解析记录列表) { 489 | const 批次大小 = 4; // 每批并发请求的数量 490 | const 批次间隔 =2000; // 批次之间的间隔时间(毫秒) 491 | 492 | for (let i = 0; i < 解析记录列表.length; i += 批次大小) { 493 | const 当前批次 = 解析记录列表.slice(i, i + 批次大小); 494 | 495 | // 并发发送当前批次的请求 496 | await Promise.all(当前批次.map(记录 => 添加解析(记录.type, 记录.content))); 497 | 498 | // 如果还有下一批,则等待指定的间隔时间 499 | if (i + 批次大小 < 解析记录列表.length) { 500 | await new Promise(resolve => setTimeout(resolve, 批次间隔)); 501 | } 502 | } 503 | } 504 | 505 | // 修改添加解析函数,返回一个 Promise 506 | async function 添加解析(A, IP) { 507 | const 添加解析_URL = `https://api.cloudflare.com/client/v4/zones/${CF区域ID}/dns_records`; 508 | try { 509 | const response = await fetch(添加解析_URL, { 510 | method: 'POST', 511 | headers: { 512 | 'X-Auth-Email': CF邮箱, 513 | 'Authorization': `Bearer ${CFAPI令牌}`, 514 | 'Content-Type': 'application/json', 515 | }, 516 | body: JSON.stringify({ 517 | type: A, 518 | name: CF域名, 519 | content: IP, 520 | ttl: 60, 521 | proxied: false 522 | }) 523 | }); 524 | const data = await response.json(); 525 | console.log(JSON.stringify(data, null, 2)); 526 | if (data.success) { 527 | 解析成功次数 += 1; 528 | tgmsg += `\n${A}记录: ${IP}` 529 | log(`${CF域名} 成功 ${A}记录: ${IP}`); 530 | } else { 531 | 解析失败次数 += 1; 532 | tgmsg += `\n失败: ${IP}` 533 | log(`${CF域名} 失败 ${A}记录: ${IP}`); 534 | } 535 | } catch (error) { 536 | 解析失败次数 += 1; 537 | tgmsg += `\n失败: ${IP}` 538 | log(`${CF域名} 失败 ${A}记录: ${IP}`); 539 | } 540 | } 541 | --------------------------------------------------------------------------------