Repository: cmliu/CF-Workers-SUB Branch: main Commit: 42edd449f71f Files: 5 Total size: 52.1 KB Directory structure: gitextract_5rrimb93/ ├── .github/ │ └── workflows/ │ └── sync.yml ├── LICENSE ├── README.md ├── _worker.js └── wrangler.toml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/sync.yml ================================================ name: Upstream Sync permissions: contents: write on: schedule: - cron: "0 0 * * *" # every day workflow_dispatch: jobs: sync_latest_from_upstream: name: Sync latest commits from upstream repo runs-on: ubuntu-latest if: ${{ github.event.repository.fork }} steps: # Step 1: run a standard checkout action - name: Checkout target repo uses: actions/checkout@v3 # Step 2: run the sync action - name: Sync upstream changes id: sync uses: aormsby/Fork-Sync-With-Upstream-action@v3.4 with: upstream_sync_repo: cmliu/CF-Workers-SUB upstream_sync_branch: main target_sync_branch: main target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set # Set test_mode true to run tests instead of the true action!! test_mode: false - name: Sync check if: failure() run: | echo "[Error] 由于上游仓库的 workflow 文件变更,导致 GitHub 自动暂停了本次自动更新,你需要手动 Sync Fork 一次,详细教程请查看项目README.md " echo "[Error] Due to a change in the workflow file of the upstream repository, GitHub has automatically suspended the scheduled automatic update. You need to manually sync your fork. Please refer to the project README.md for instructions. " exit 1 ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # ⚙ 自建汇聚订阅 CF-Workers-SUB ![自建汇聚订阅 CF-Workers-SUB](./sub.png) 这是一个将多个节点和订阅合并为单一链接的工具,支持自动适配与自定义分流,简化了订阅管理。 > [!CAUTION] > **汇聚订阅非base64订阅时**,会自动生成一个**有效期为24小时的临时订阅**,并提交给**订阅转换后端**来完成订阅转换,可避免您的汇聚订阅地址泄露。 > [!WARNING] > **汇聚订阅非base64订阅时**,如果您的节点数量**十分庞大**,订阅转换后端将需要较长时间才能完成订阅转换,这会导致部分梯子客户端在订阅时提示超时而无法完成订阅(说直白一点就是**汇聚节点池的节点时容易导致Clash订阅超时**)! > > 可自行删减订阅节点数量,提高订阅转换效率! ## 🛠 功能特点 1. **节点链接自动转换成base64订阅链接:** 这是最基础的功能,可以将您的节点自动转换为base64格式的订阅链接; 2. **将多个base64订阅汇聚成一个订阅链接:** 可以将多个订阅(例如不同的机场)合并成一个订阅,只需使用一个订阅地址即可获取所有节点; 3. **自动适配不同梯子的格式订阅链接:** 依托[订阅转换](https://sub.cmliussss.com/)服务,自动将订阅转换为不同梯子所需的格式,实现一条订阅适配多种梯子; 4. **专属代理分流规则:** 自定义分流规则,实现个性化的分流模式; 5. **更多功能等待发掘...** ## 🎬 视频教程 - **[自建订阅!CF-Workers-SUB 教你如何将多节点多订阅汇聚合并为一个订阅!](https://youtu.be/w6rRY4FDd58)** ## 🤝 社区支持 - Telegram 交流群: [@CMLiussss](https://t.me/CMLiussss) - 感谢 [Alice Networks](https://alicenetworks.net/) 提供的云服务器维持 [CM订阅转换服务](https://sub.cmliussss.com/) ## 📦 Pages 部署方法
「 Pages GitHub 部署文字教程 」 ### 1. 部署 Cloudflare Pages: - 在 Github 上先 Fork 本项目,并点上 Star !!! - 在 Cloudflare Pages 控制台中选择 `连接到 Git`后,选中 `CF-Workers-SUB`项目后点击 `开始设置`。 ### 2. 给 Pages绑定 自定义域: - 在 Pages控制台的 `自定义域`选项卡,下方点击 `设置自定义域`。 - 填入你的自定义次级域名,注意不要使用你的根域名,例如: 您分配到的域名是 `fuck.cloudns.biz`,则添加自定义域填入 `sub.fuck.cloudns.biz`即可; - 按照 Cloudflare 的要求将返回你的域名DNS服务商,添加 该自定义域 `sub`的 CNAME记录 `CF-Workers-SUB.pages.dev` 后,点击 `激活域`即可。 ### 3. 修改 快速订阅入口 : 例如您的pages项目域名为:`sub.fuck.cloudns.biz`; - 添加 `TOKEN` 变量,快速订阅访问入口,默认值为: `auto` ,获取订阅器默认节点订阅地址即 `/auto` ,例如 `https://sub.fuck.cloudns.biz/auto` ### 4. 添加你的节点和订阅链接: 1. 绑定**变量名称**为`KV`的**KV命名空间**; 2. 访问 `https://sub.fuck.cloudns.biz/auto`,添加你的自建节点链接和机场订阅链接,确保每行一个链接,例如: ``` vless://b7a392e2-4ef0-4496-90bc-1c37bb234904@cf.090227.xyz:443?encryption=none&security=tls&sni=edgetunnel-2z2.pages.dev&fp=random&type=ws&host=edgetunnel-2z2.pages.dev&path=%2F%3Fed%3D2048#%E5%8A%A0%E5%85%A5%E6%88%91%E7%9A%84%E9%A2%91%E9%81%93t.me%2FCMLiussss%E8%A7%A3%E9%94%81%E6%9B%B4%E5%A4%9A%E4%BC%98%E9%80%89%E8%8A%82%E7%82%B9 vmess://ew0KICAidiI6ICIyIiwNCiAgInBzIjogIuWKoOWFpeaIkeeahOmikemBk3QubWUvQ01MaXVzc3Nz6Kej6ZSB5pu05aSa5LyY6YCJ6IqC54K5PuiLseWbvSDlgKvmlabph5Hono3ln44iLA0KICAiYWRkIjogImNmLjA5MDIyNy54eXoiLA0KICAicG9ydCI6ICI4NDQzIiwNCiAgImlkIjogIjAzZmNjNjE4LWI5M2QtNjc5Ni02YWVkLThhMzhjOTc1ZDU4MSIsDQogICJhaWQiOiAiMCIsDQogICJzY3kiOiAiYXV0byIsDQogICJuZXQiOiAid3MiLA0KICAidHlwZSI6ICJub25lIiwNCiAgImhvc3QiOiAicHBmdjJ0bDl2ZW9qZC1tYWlsbGF6eS5wYWdlcy5kZXYiLA0KICAicGF0aCI6ICIvamFkZXIuZnVuOjQ0My9saW5rdndzIiwNCiAgInRscyI6ICJ0bHMiLA0KICAic25pIjogInBwZnYydGw5dmVvamQtbWFpbGxhenkucGFnZXMuZGV2IiwNCiAgImFscG4iOiAiIiwNCiAgImZwIjogIiINCn0= https://sub.xf.free.hr/auto https://hy2sub.pages.dev ```
## 🛠️ Workers 部署方法
「 Workers 部署文字教程 」 ### 1. 部署 Cloudflare Worker: - 在 Cloudflare Worker 控制台中创建一个新的 Worker。 - 将 [_worker.js](https://github.com/cmliu/CF-Workers-SUB/blob/main/_worker.js) 的内容粘贴到 Worker 编辑器中。 ### 2. 修改 订阅入口 : 例如您的workers项目域名为:`sub.cmliussss.workers.dev`; - 通过修改 `mytoken` 赋值内容,达到修改你专属订阅的入口,避免订阅泄漏。 ``` let mytoken = 'auto'; ``` 如上所示,你的订阅地址则如下: ```url https://sub.cmliussss.workers.dev/auto 或 https://sub.cmliussss.workers.dev/?token=auto ``` ### 3. 添加你的节点或订阅链接: 1. 绑定**变量名称**为`KV`的**KV命名空间**; 2. 访问 `https://sub.cmliussss.workers.dev/auto`,添加你的自建节点链接和机场订阅链接,确保每行一个链接,例如: ``` vless://b7a392e2-4ef0-4496-90bc-1c37bb234904@cf.090227.xyz:443?encryption=none&security=tls&sni=edgetunnel-2z2.pages.dev&fp=random&type=ws&host=edgetunnel-2z2.pages.dev&path=%2F%3Fed%3D2048#%E5%8A%A0%E5%85%A5%E6%88%91%E7%9A%84%E9%A2%91%E9%81%93t.me%2FCMLiussss%E8%A7%A3%E9%94%81%E6%9B%B4%E5%A4%9A%E4%BC%98%E9%80%89%E8%8A%82%E7%82%B9 vmess://ew0KICAidiI6ICIyIiwNCiAgInBzIjogIuWKoOWFpeaIkeeahOmikemBk3QubWUvQ01MaXVzc3Nz6Kej6ZSB5pu05aSa5LyY6YCJ6IqC54K5PuiLseWbvSDlgKvmlabph5Hono3ln44iLA0KICAiYWRkIjogImNmLjA5MDIyNy54eXoiLA0KICAicG9ydCI6ICI4NDQzIiwNCiAgImlkIjogIjAzZmNjNjE4LWI5M2QtNjc5Ni02YWVkLThhMzhjOTc1ZDU4MSIsDQogICJhaWQiOiAiMCIsDQogICJzY3kiOiAiYXV0byIsDQogICJuZXQiOiAid3MiLA0KICAidHlwZSI6ICJub25lIiwNCiAgImhvc3QiOiAicHBmdjJ0bDl2ZW9qZC1tYWlsbGF6eS5wYWdlcy5kZXYiLA0KICAicGF0aCI6ICIvamFkZXIuZnVuOjQ0My9saW5rdndzIiwNCiAgInRscyI6ICJ0bHMiLA0KICAic25pIjogInBwZnYydGw5dmVvamQtbWFpbGxhenkucGFnZXMuZGV2IiwNCiAgImFscG4iOiAiIiwNCiAgImZwIjogIiINCn0= https://sub.xf.free.hr/auto https://hy2sub.pages.dev ```
## 📋 变量说明 | 变量名 | 示例 | 必填 | 备注 | |-|-|-|-| | TOKEN | `auto` | ✅ | 汇聚订阅的订阅配置路径地址,例如:`/auto` | | GUEST | `test` | ❌ | 汇聚订阅的访客订阅TOKEN,例如:`/sub?token=test` | | LINK | `vless://b7a39...`,`vmess://ew0K...`,`https://sub...` | ❌ | 可同时放入多个节点链接与多个订阅链接,链接之间用换行做间隔(添加**KV命名空间**后,变量将不会使用)| | TGTOKEN | `6894123456:XXXXXXXXXX0qExVsBPUhHDAbXXXXXqWXgBA` | ❌ | 发送TG通知的机器人token | | TGID | `6946912345` | ❌ | 接收TG通知的账户数字ID | | SUBNAME | `CF-Workers-SUB` | ❌ | 订阅名称 | | SUBAPI | `SUBAPI.cmliussss.net` | ❌ | clash、singbox等 订阅转换后端 | | SUBCONFIG | [https://raw.github.../ACL4SSR_Online_MultiCountry.ini](https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_MultiCountry.ini) | ❌ | clash、singbox等 订阅转换配置文件 | ## ⚠️ 注意事项 项目中,TGTOKEN和TGID在使用时需要先到Telegram注册并获取。其中,TGTOKEN是telegram bot的凭证,TGID是用来接收通知的telegram用户或者组的id。 ## ⭐ Star 星星走起 [![Stargazers over time](https://starchart.cc/cmliu/CF-Workers-SUB.svg?variant=adaptive)](https://starchart.cc/cmliu/CF-Workers-SUB) # 🙏 致谢 [Alice Networks LTD](https://alicenetworks.net/),[mianayang](https://github.com/mianayang/myself/blob/main/cf-workers/sub/sub.js)、[ACL4SSR](https://github.com/ACL4SSR/ACL4SSR/tree/master/Clash/config)、[肥羊](https://sub.v1.mk/) ================================================ FILE: _worker.js ================================================ // 部署完成后在网址后面加上这个,获取自建节点和机场聚合节点,/?token=auto或/auto或 let mytoken = 'auto'; let guestToken = ''; //可以随便取,或者uuid生成,https://1024tools.com/uuid let BotToken = ''; //可以为空,或者@BotFather中输入/start,/newbot,并关注机器人 let ChatID = ''; //可以为空,或者@userinfobot中获取,/start let TG = 0; //小白勿动, 开发者专用,1 为推送所有的访问信息,0 为不推送订阅转换后端的访问信息与异常访问 let FileName = 'CF-Workers-SUB'; let SUBUpdateTime = 6; //自定义订阅更新时间,单位小时 let total = 99;//TB let timestamp = 4102329600000;//2099-12-31 //节点链接 + 订阅链接 let MainData = ` https://cfxr.eu.org/getSub `; let urls = []; let subConverter = "SUBAPI.cmliussss.net"; //在线订阅转换后端,目前使用CM的订阅转换功能。支持自建psub 可自行搭建https://github.com/bulianglin/psub let subConfig = "https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_MultiCountry.ini"; //订阅配置文件 let subProtocol = 'https'; export default { async fetch(request, env) { const userAgentHeader = request.headers.get('User-Agent'); const userAgent = userAgentHeader ? userAgentHeader.toLowerCase() : "null"; const url = new URL(request.url); const token = url.searchParams.get('token'); mytoken = env.TOKEN || mytoken; BotToken = env.TGTOKEN || BotToken; ChatID = env.TGID || ChatID; TG = env.TG || TG; subConverter = env.SUBAPI || subConverter; if (subConverter.includes("http://")) { subConverter = subConverter.split("//")[1]; subProtocol = 'http'; } else { subConverter = subConverter.split("//")[1] || subConverter; } subConfig = env.SUBCONFIG || subConfig; FileName = env.SUBNAME || FileName; const currentDate = new Date(); currentDate.setHours(0, 0, 0, 0); const timeTemp = Math.ceil(currentDate.getTime() / 1000); const fakeToken = await MD5MD5(`${mytoken}${timeTemp}`); guestToken = env.GUESTTOKEN || env.GUEST || guestToken; if (!guestToken) guestToken = await MD5MD5(mytoken); const 访客订阅 = guestToken; //console.log(`${fakeUserID}\n${fakeHostName}`); // 打印fakeID let UD = Math.floor(((timestamp - Date.now()) / timestamp * total * 1099511627776) / 2); total = total * 1099511627776; let expire = Math.floor(timestamp / 1000); SUBUpdateTime = env.SUBUPTIME || SUBUpdateTime; if (!([mytoken, fakeToken, 访客订阅].includes(token) || url.pathname == ("/" + mytoken) || url.pathname.includes("/" + mytoken + "?"))) { if (TG == 1 && url.pathname !== "/" && url.pathname !== "/favicon.ico") await sendMessage(`#异常访问 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${userAgent}\n域名: ${url.hostname}\n入口: ${url.pathname + url.search}`); if (env.URL302) return Response.redirect(env.URL302, 302); else if (env.URL) return await proxyURL(env.URL, url); else return new Response(await nginx(), { status: 200, headers: { 'Content-Type': 'text/html; charset=UTF-8', }, }); } else { if (env.KV) { await 迁移地址列表(env, 'LINK.txt'); if (userAgent.includes('mozilla') && !url.search) { await sendMessage(`#编辑订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${userAgentHeader}\n域名: ${url.hostname}\n入口: ${url.pathname + url.search}`); return await KV(request, env, 'LINK.txt', 访客订阅); } else { MainData = await env.KV.get('LINK.txt') || MainData; } } else { MainData = env.LINK || MainData; if (env.LINKSUB) urls = await ADD(env.LINKSUB); } let 重新汇总所有链接 = await ADD(MainData + '\n' + urls.join('\n')); let 自建节点 = ""; let 订阅链接 = ""; for (let x of 重新汇总所有链接) { if (x.toLowerCase().startsWith('http')) { 订阅链接 += x + '\n'; } else { 自建节点 += x + '\n'; } } MainData = 自建节点; urls = await ADD(订阅链接); await sendMessage(`#获取订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${userAgentHeader}\n域名: ${url.hostname}\n入口: ${url.pathname + url.search}`); const isSubConverterRequest = request.headers.get('subconverter-request') || request.headers.get('subconverter-version') || userAgent.includes('subconverter'); let 订阅格式 = 'base64'; if (!(userAgent.includes('null') || isSubConverterRequest || userAgent.includes('nekobox') || userAgent.includes(('CF-Workers-SUB').toLowerCase()))) { if (userAgent.includes('sing-box') || userAgent.includes('singbox') || url.searchParams.has('sb') || url.searchParams.has('singbox')) { 订阅格式 = 'singbox'; } else if (userAgent.includes('surge') || url.searchParams.has('surge')) { 订阅格式 = 'surge'; } else if (userAgent.includes('quantumult') || url.searchParams.has('quanx')) { 订阅格式 = 'quanx'; } else if (userAgent.includes('loon') || url.searchParams.has('loon')) { 订阅格式 = 'loon'; } else if (userAgent.includes('clash') || userAgent.includes('meta') || userAgent.includes('mihomo') || url.searchParams.has('clash')) { 订阅格式 = 'clash'; } } let subConverterUrl; let 订阅转换URL = `${url.origin}/${await MD5MD5(fakeToken)}?token=${fakeToken}`; //console.log(订阅转换URL); let req_data = MainData; let 追加UA = 'v2rayn'; if (url.searchParams.has('b64') || url.searchParams.has('base64')) 订阅格式 = 'base64'; else if (url.searchParams.has('clash')) 追加UA = 'clash'; else if (url.searchParams.has('singbox')) 追加UA = 'singbox'; else if (url.searchParams.has('surge')) 追加UA = 'surge'; else if (url.searchParams.has('quanx')) 追加UA = 'Quantumult%20X'; else if (url.searchParams.has('loon')) 追加UA = 'Loon'; const 订阅链接数组 = [...new Set(urls)].filter(item => item?.trim?.()); // 去重 if (订阅链接数组.length > 0) { const 请求订阅响应内容 = await getSUB(订阅链接数组, request, 追加UA, userAgentHeader); console.log(请求订阅响应内容); req_data += 请求订阅响应内容[0].join('\n'); 订阅转换URL += "|" + 请求订阅响应内容[1]; if (订阅格式 == 'base64' && !isSubConverterRequest && 请求订阅响应内容[1].includes('://')) { subConverterUrl = `${subProtocol}://${subConverter}/sub?target=mixed&url=${encodeURIComponent(请求订阅响应内容[1])}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`; try { const subConverterResponse = await fetch(subConverterUrl, { headers: { 'User-Agent': 'v2rayN/CF-Workers-SUB (https://github.com/cmliu/CF-Workers-SUB)' } }); if (subConverterResponse.ok) { const subConverterContent = await subConverterResponse.text(); req_data += '\n' + atob(subConverterContent); } } catch (error) { console.log('订阅转换请回base64失败,检查订阅转换后端是否正常运行'); } } } if (env.WARP) 订阅转换URL += "|" + (await ADD(env.WARP)).join("|"); //修复中文错误 const utf8Encoder = new TextEncoder(); const encodedData = utf8Encoder.encode(req_data); //const text = String.fromCharCode.apply(null, encodedData); const utf8Decoder = new TextDecoder(); const text = utf8Decoder.decode(encodedData); //去重 const uniqueLines = new Set(text.split('\n')); const result = [...uniqueLines].join('\n'); //console.log(result); let base64Data; try { base64Data = btoa(result); } catch (e) { function encodeBase64(data) { const binary = new TextEncoder().encode(data); let base64 = ''; const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (let i = 0; i < binary.length; i += 3) { const byte1 = binary[i]; const byte2 = binary[i + 1] || 0; const byte3 = binary[i + 2] || 0; base64 += chars[byte1 >> 2]; base64 += chars[((byte1 & 3) << 4) | (byte2 >> 4)]; base64 += chars[((byte2 & 15) << 2) | (byte3 >> 6)]; base64 += chars[byte3 & 63]; } const padding = 3 - (binary.length % 3 || 3); return base64.slice(0, base64.length - padding) + '=='.slice(0, padding); } base64Data = encodeBase64(result) } // 构建响应头对象 const responseHeaders = { "content-type": "text/plain; charset=utf-8", "Profile-Update-Interval": `${SUBUpdateTime}`, "Profile-web-page-url": request.url.includes('?') ? request.url.split('?')[0] : request.url, //"Subscription-Userinfo": `upload=${UD}; download=${UD}; total=${total}; expire=${expire}`, }; if (订阅格式 == 'base64' || token == fakeToken) { return new Response(base64Data, { headers: responseHeaders }); } else if (订阅格式 == 'clash') { subConverterUrl = `${subProtocol}://${subConverter}/sub?target=clash&url=${encodeURIComponent(订阅转换URL)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`; } else if (订阅格式 == 'singbox') { subConverterUrl = `${subProtocol}://${subConverter}/sub?target=singbox&url=${encodeURIComponent(订阅转换URL)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`; } else if (订阅格式 == 'surge') { subConverterUrl = `${subProtocol}://${subConverter}/sub?target=surge&ver=4&url=${encodeURIComponent(订阅转换URL)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`; } else if (订阅格式 == 'quanx') { subConverterUrl = `${subProtocol}://${subConverter}/sub?target=quanx&url=${encodeURIComponent(订阅转换URL)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&udp=true`; } else if (订阅格式 == 'loon') { subConverterUrl = `${subProtocol}://${subConverter}/sub?target=loon&url=${encodeURIComponent(订阅转换URL)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false`; } //console.log(订阅转换URL); try { const subConverterResponse = await fetch(subConverterUrl, { headers: { 'User-Agent': userAgentHeader } });//订阅转换 if (!subConverterResponse.ok) return new Response(base64Data, { headers: responseHeaders }); let subConverterContent = await subConverterResponse.text(); if (订阅格式 == 'clash') subConverterContent = await clashFix(subConverterContent); // 只有非浏览器订阅才会返回SUBNAME if (!userAgent.includes('mozilla')) responseHeaders["Content-Disposition"] = `attachment; filename*=utf-8''${encodeURIComponent(FileName)}`; return new Response(subConverterContent, { headers: responseHeaders }); } catch (error) { return new Response(base64Data, { headers: responseHeaders }); } } } }; async function ADD(envadd) { var addtext = envadd.replace(/[ "'|\r\n]+/g, '\n').replace(/\n+/g, '\n'); // 替换为换行 //console.log(addtext); if (addtext.charAt(0) == '\n') addtext = addtext.slice(1); if (addtext.charAt(addtext.length - 1) == '\n') addtext = addtext.slice(0, addtext.length - 1); const add = addtext.split('\n'); //console.log(add); return add; } async function nginx() { const text = ` Welcome to nginx!

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

` return text; } async function sendMessage(type, ip, add_data = "") { if (BotToken !== '' && ChatID !== '') { let msg = ""; const response = await fetch(`http://ip-api.com/json/${ip}?lang=zh-CN`); if (response.status == 200) { const ipInfo = await response.json(); msg = `${type}\nIP: ${ip}\n国家: ${ipInfo.country}\n城市: ${ipInfo.city}\n组织: ${ipInfo.org}\nASN: ${ipInfo.as}\n${add_data}`; } else { msg = `${type}\nIP: ${ip}\n${add_data}`; } let url = "https://api.telegram.org/bot" + BotToken + "/sendMessage?chat_id=" + ChatID + "&parse_mode=HTML&text=" + encodeURIComponent(msg); return fetch(url, { method: 'get', headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;', 'Accept-Encoding': 'gzip, deflate, br', 'User-Agent': 'Mozilla/5.0 Chrome/90.0.4430.72' } }); } } function base64Decode(str) { const bytes = new Uint8Array(atob(str).split('').map(c => c.charCodeAt(0))); const decoder = new TextDecoder('utf-8'); return decoder.decode(bytes); } async function MD5MD5(text) { const encoder = new TextEncoder(); const firstPass = await crypto.subtle.digest('MD5', encoder.encode(text)); const firstPassArray = Array.from(new Uint8Array(firstPass)); const firstHex = firstPassArray.map(b => b.toString(16).padStart(2, '0')).join(''); const secondPass = await crypto.subtle.digest('MD5', encoder.encode(firstHex.slice(7, 27))); const secondPassArray = Array.from(new Uint8Array(secondPass)); const secondHex = secondPassArray.map(b => b.toString(16).padStart(2, '0')).join(''); return secondHex.toLowerCase(); } function clashFix(content) { if (content.includes('wireguard') && !content.includes('remote-dns-resolve')) { let lines; if (content.includes('\r\n')) { lines = content.split('\r\n'); } else { lines = content.split('\n'); } let result = ""; for (let line of lines) { if (line.includes('type: wireguard')) { const 备改内容 = `, mtu: 1280, udp: true`; const 正确内容 = `, mtu: 1280, remote-dns-resolve: true, udp: true`; result += line.replace(new RegExp(备改内容, 'g'), 正确内容) + '\n'; } else { result += line + '\n'; } } content = result; } return content; } async function proxyURL(proxyURL, url) { const URLs = await ADD(proxyURL); const fullURL = URLs[Math.floor(Math.random() * URLs.length)]; // 解析目标 URL let parsedURL = new URL(fullURL); console.log(parsedURL); // 提取并可能修改 URL 组件 let URLProtocol = parsedURL.protocol.slice(0, -1) || 'https'; let URLHostname = parsedURL.hostname; let URLPathname = parsedURL.pathname; let URLSearch = parsedURL.search; // 处理 pathname if (URLPathname.charAt(URLPathname.length - 1) == '/') { URLPathname = URLPathname.slice(0, -1); } URLPathname += url.pathname; // 构建新的 URL let newURL = `${URLProtocol}://${URLHostname}${URLPathname}${URLSearch}`; // 反向代理请求 let response = await fetch(newURL); // 创建新的响应 let newResponse = new Response(response.body, { status: response.status, statusText: response.statusText, headers: response.headers }); // 添加自定义头部,包含 URL 信息 //newResponse.headers.set('X-Proxied-By', 'Cloudflare Worker'); //newResponse.headers.set('X-Original-URL', fullURL); newResponse.headers.set('X-New-URL', newURL); return newResponse; } async function getSUB(api, request, 追加UA, userAgentHeader) { if (!api || api.length === 0) { return []; } else api = [...new Set(api)]; // 去重 let newapi = ""; let 订阅转换URLs = ""; let 异常订阅 = ""; const controller = new AbortController(); // 创建一个AbortController实例,用于取消请求 const timeout = setTimeout(() => { controller.abort(); // 2秒后取消所有请求 }, 2000); try { // 使用Promise.allSettled等待所有API请求完成,无论成功或失败 const responses = await Promise.allSettled(api.map(apiUrl => getUrl(request, apiUrl, 追加UA, userAgentHeader).then(response => response.ok ? response.text() : Promise.reject(response)))); // 遍历所有响应 const modifiedResponses = responses.map((response, index) => { // 检查是否请求成功 if (response.status === 'rejected') { const reason = response.reason; if (reason && reason.name === 'AbortError') { return { status: '超时', value: null, apiUrl: api[index] // 将原始的apiUrl添加到返回对象中 }; } console.error(`请求失败: ${api[index]}, 错误信息: ${reason.status} ${reason.statusText}`); return { status: '请求失败', value: null, apiUrl: api[index] // 将原始的apiUrl添加到返回对象中 }; } return { status: response.status, value: response.value, apiUrl: api[index] // 将原始的apiUrl添加到返回对象中 }; }); console.log(modifiedResponses); // 输出修改后的响应数组 for (const response of modifiedResponses) { // 检查响应状态是否为'fulfilled' if (response.status === 'fulfilled') { const content = await response.value || 'null'; // 获取响应的内容 if (content.includes('proxies:')) { //console.log('Clash订阅: ' + response.apiUrl); 订阅转换URLs += "|" + response.apiUrl; // Clash 配置 } else if (content.includes('outbounds"') && content.includes('inbounds"')) { //console.log('Singbox订阅: ' + response.apiUrl); 订阅转换URLs += "|" + response.apiUrl; // Singbox 配置 } else if (content.includes('://')) { //console.log('明文订阅: ' + response.apiUrl); newapi += content + '\n'; // 追加内容 } else if (isValidBase64(content)) { //console.log('Base64订阅: ' + response.apiUrl); newapi += base64Decode(content) + '\n'; // 解码并追加内容 } else { const 异常订阅LINK = `trojan://CMLiussss@127.0.0.1:8888?security=tls&allowInsecure=1&type=tcp&headerType=none#%E5%BC%82%E5%B8%B8%E8%AE%A2%E9%98%85%20${response.apiUrl.split('://')[1].split('/')[0]}`; console.log('异常订阅: ' + 异常订阅LINK); 异常订阅 += `${异常订阅LINK}\n`; } } } } catch (error) { console.error(error); // 捕获并输出错误信息 } finally { clearTimeout(timeout); // 清除定时器 } const 订阅内容 = await ADD(newapi + 异常订阅); // 将处理后的内容转换为数组 // 返回处理后的结果 return [订阅内容, 订阅转换URLs]; } async function getUrl(request, targetUrl, 追加UA, userAgentHeader) { // 设置自定义 User-Agent const newHeaders = new Headers(request.headers); newHeaders.set("User-Agent", `${atob('djJyYXlOLzYuNDU=')} cmliu/CF-Workers-SUB ${追加UA}(${userAgentHeader})`); // 构建新的请求对象 const modifiedRequest = new Request(targetUrl, { method: request.method, headers: newHeaders, body: request.method === "GET" ? null : request.body, redirect: "follow", cf: { // 忽略SSL证书验证 insecureSkipVerify: true, // 允许自签名证书 allowUntrusted: true, // 禁用证书验证 validateCertificate: false } }); // 输出请求的详细信息 console.log(`请求URL: ${targetUrl}`); console.log(`请求头: ${JSON.stringify([...newHeaders])}`); console.log(`请求方法: ${request.method}`); console.log(`请求体: ${request.method === "GET" ? null : request.body}`); // 发送请求并返回响应 return fetch(modifiedRequest); } function isValidBase64(str) { // 先移除所有空白字符(空格、换行、回车等) const cleanStr = str.replace(/\s/g, ''); const base64Regex = /^[A-Za-z0-9+/=]+$/; return base64Regex.test(cleanStr); } async function 迁移地址列表(env, txt = 'ADD.txt') { const 旧数据 = await env.KV.get(`/${txt}`); const 新数据 = await env.KV.get(txt); if (旧数据 && !新数据) { // 写入新位置 await env.KV.put(txt, 旧数据); // 删除旧数据 await env.KV.delete(`/${txt}`); return true; } return false; } async function KV(request, env, txt = 'ADD.txt', guest) { const url = new URL(request.url); try { // POST请求处理 if (request.method === "POST") { if (!env.KV) return new Response("未绑定KV空间", { status: 400 }); try { const content = await request.text(); await env.KV.put(txt, content); return new Response("保存成功"); } catch (error) { console.error('保存KV时发生错误:', error); return new Response("保存失败: " + error.message, { status: 500 }); } } // GET请求部分 let content = ''; let hasKV = !!env.KV; if (hasKV) { try { content = await env.KV.get(txt) || ''; } catch (error) { console.error('读取KV时发生错误:', error); content = '读取数据时发生错误: ' + error.message; } } const html = ` ${FileName} 订阅编辑 ################################################################
Subscribe / sub 订阅地址, 点击链接自动 复制订阅链接生成订阅二维码
---------------------------------------------------------------
自适应订阅地址:
https://${url.hostname}/${mytoken}
Base64订阅地址:
https://${url.hostname}/${mytoken}?b64
clash订阅地址:
https://${url.hostname}/${mytoken}?clash
singbox订阅地址:
https://${url.hostname}/${mytoken}?sb
surge订阅地址:
https://${url.hostname}/${mytoken}?surge
loon订阅地址:
https://${url.hostname}/${mytoken}?loon
  查看访客订阅∨
---------------------------------------------------------------
################################################################
订阅转换配置
---------------------------------------------------------------
SUBAPI(订阅转换后端): ${subProtocol}://${subConverter}
SUBCONFIG(订阅转换配置文件): ${subConfig}
---------------------------------------------------------------
################################################################
${FileName} 汇聚订阅编辑:
${hasKV ? `
` : '

请绑定 变量名称KV 的KV命名空间

'}

################################################################
${decodeURIComponent(atob('dGVsZWdyYW0lMjAlRTQlQkElQTQlRTYlQjUlODElRTclQkUlQTQlMjAlRTYlOEElODAlRTYlOUMlQUYlRTUlQTQlQTclRTQlQkQlQUMlN0UlRTUlOUMlQTglRTclQkElQkYlRTUlOEYlOTElRTclODklOEMhJTNDYnIlM0UKJTNDYSUyMGhyZWYlM0QlMjdodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlMjclM0VodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlM0MlMkZhJTNFJTNDYnIlM0UKLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tJTNDYnIlM0UKZ2l0aHViJTIwJUU5JUExJUI5JUU3JTlCJUFFJUU1JTlDJUIwJUU1JTlEJTgwJTIwU3RhciFTdGFyIVN0YXIhISElM0NiciUzRQolM0NhJTIwaHJlZiUzRCUyN2h0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmNtbGl1JTJGQ0YtV29ya2Vycy1TVUIlMjclM0VodHRwcyUzQSUyRiUyRmdpdGh1Yi5jb20lMkZjbWxpdSUyRkNGLVdvcmtlcnMtU1VCJTNDJTJGYSUzRSUzQ2JyJTNFCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSUzQ2JyJTNFCiUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMw=='))}

UA: ${request.headers.get('User-Agent')} `; return new Response(html, { headers: { "Content-Type": "text/html;charset=utf-8" } }); } catch (error) { console.error('处理请求时发生错误:', error); return new Response("服务器错误: " + error.message, { status: 500, headers: { "Content-Type": "text/plain;charset=utf-8" } }); } } ================================================ FILE: wrangler.toml ================================================ name = "sub-worker" main = "_worker.js" compatibility_date = "2025-07-23" keep_vars = true #[[kv_namespaces]] #binding = "KV" #KV绑定名默认不可修改 #id = "7dbef248fcc547d39689967f91f5f46f" #KV据库id