├── .github
└── workflows
│ └── sync.yml
├── LICENSE
├── README.md
├── _worker.js
└── sub.png
/.github/workflows/sync.yml:
--------------------------------------------------------------------------------
1 | name: Upstream Sync
2 |
3 | permissions:
4 | contents: write
5 |
6 | on:
7 | schedule:
8 | - cron: "0 0 * * *" # every day
9 | workflow_dispatch:
10 |
11 | jobs:
12 | sync_latest_from_upstream:
13 | name: Sync latest commits from upstream repo
14 | runs-on: ubuntu-latest
15 | if: ${{ github.event.repository.fork }}
16 |
17 | steps:
18 | # Step 1: run a standard checkout action
19 | - name: Checkout target repo
20 | uses: actions/checkout@v3
21 |
22 | # Step 2: run the sync action
23 | - name: Sync upstream changes
24 | id: sync
25 | uses: aormsby/Fork-Sync-With-Upstream-action@v3.4
26 | with:
27 | upstream_sync_repo: cmliu/CF-Workers-SUB
28 | upstream_sync_branch: main
29 | target_sync_branch: main
30 | target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set
31 |
32 | # Set test_mode true to run tests instead of the true action!!
33 | test_mode: false
34 |
35 | - name: Sync check
36 | if: failure()
37 | run: |
38 | echo "[Error] 由于上游仓库的 workflow 文件变更,导致 GitHub 自动暂停了本次自动更新,你需要手动 Sync Fork 一次,详细教程请查看项目README.md "
39 | 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. "
40 | exit 1
--------------------------------------------------------------------------------
/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 | # ⚙ 自建汇聚订阅 CF-Workers-SUB
2 |
3 | 
4 |
5 | 这是一个将多个节点和订阅合并为单一链接的工具,支持自动适配与自定义分流,简化了订阅管理。
6 |
7 | > [!CAUTION]
8 | > **汇聚订阅非base64订阅时**,会自动生成一个**有效期为24小时的临时订阅**,并提交给**订阅转换后端**来完成订阅转换,可避免您的汇聚订阅地址泄露。
9 |
10 | > [!WARNING]
11 | > **汇聚订阅非base64订阅时**,如果您的节点数量**十分庞大**,订阅转换后端将需要较长时间才能完成订阅转换,这会导致部分梯子客户端在订阅时提示超时而无法完成订阅(说直白一点就是**汇聚节点池的节点时容易导致Clash订阅超时**)!
12 | >
13 | > 可自行删减订阅节点数量,提高订阅转换效率!
14 |
15 | ## 🛠 功能特点
16 | 1. **节点链接自动转换成base64订阅链接:** 这是最基础的功能,可以将您的节点自动转换为base64格式的订阅链接;
17 | 2. **将多个base64订阅汇聚成一个订阅链接:** 可以将多个订阅(例如不同的机场)合并成一个订阅,只需使用一个订阅地址即可获取所有节点;
18 | 3. **自动适配不同梯子的格式订阅链接:** 依托[订阅转换](https://sub.cmliussss.com/)服务,自动将订阅转换为不同梯子所需的格式,实现一条订阅适配多种梯子;
19 | 4. **专属代理分流规则:** 自定义分流规则,实现个性化的分流模式;
20 | 5. **更多功能等待发掘...**
21 |
22 | ## 🎬 视频教程
23 | - **[自建订阅!CF-Workers-SUB 教你如何将多节点多订阅汇聚合并为一个订阅!](https://youtu.be/w6rRY4FDd58)**
24 |
25 | ## 🤝 社区支持
26 | - Telegram 交流群: [@CMLiussss](https://t.me/CMLiussss)
27 | - 感谢 [Alice Networks](https://alicenetworks.net/) 提供的云服务器维持 [CM订阅转换服务](https://sub.cmliussss.com/)
28 |
29 | ## 📦 Pages 部署方法
30 |
31 |
32 | 「 Pages GitHub 部署文字教程 」
33 |
34 | ### 1. 部署 Cloudflare Pages:
35 | - 在 Github 上先 Fork 本项目,并点上 Star !!!
36 | - 在 Cloudflare Pages 控制台中选择 `连接到 Git`后,选中 `CF-Workers-SUB`项目后点击 `开始设置`。
37 |
38 | ### 2. 给 Pages绑定 自定义域:
39 | - 在 Pages控制台的 `自定义域`选项卡,下方点击 `设置自定义域`。
40 | - 填入你的自定义次级域名,注意不要使用你的根域名,例如:
41 | 您分配到的域名是 `fuck.cloudns.biz`,则添加自定义域填入 `sub.fuck.cloudns.biz`即可;
42 | - 按照 Cloudflare 的要求将返回你的域名DNS服务商,添加 该自定义域 `sub`的 CNAME记录 `CF-Workers-SUB.pages.dev` 后,点击 `激活域`即可。
43 |
44 | ### 3. 修改 快速订阅入口 :
45 |
46 | 例如您的pages项目域名为:`sub.fuck.cloudns.biz`;
47 | - 添加 `TOKEN` 变量,快速订阅访问入口,默认值为: `auto` ,获取订阅器默认节点订阅地址即 `/auto` ,例如 `https://sub.fuck.cloudns.biz/auto`
48 |
49 | ### 4. 添加你的节点和订阅链接:
50 | 1. 绑定**变量名称**为`KV`的**KV命名空间**;
51 | 2. 访问 `https://sub.fuck.cloudns.biz/auto`,添加你的自建节点链接和机场订阅链接,确保每行一个链接,例如:
52 | ```
53 | 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
54 | vmess://ew0KICAidiI6ICIyIiwNCiAgInBzIjogIuWKoOWFpeaIkeeahOmikemBk3QubWUvQ01MaXVzc3Nz6Kej6ZSB5pu05aSa5LyY6YCJ6IqC54K5PuiLseWbvSDlgKvmlabph5Hono3ln44iLA0KICAiYWRkIjogImNmLjA5MDIyNy54eXoiLA0KICAicG9ydCI6ICI4NDQzIiwNCiAgImlkIjogIjAzZmNjNjE4LWI5M2QtNjc5Ni02YWVkLThhMzhjOTc1ZDU4MSIsDQogICJhaWQiOiAiMCIsDQogICJzY3kiOiAiYXV0byIsDQogICJuZXQiOiAid3MiLA0KICAidHlwZSI6ICJub25lIiwNCiAgImhvc3QiOiAicHBmdjJ0bDl2ZW9qZC1tYWlsbGF6eS5wYWdlcy5kZXYiLA0KICAicGF0aCI6ICIvamFkZXIuZnVuOjQ0My9saW5rdndzIiwNCiAgInRscyI6ICJ0bHMiLA0KICAic25pIjogInBwZnYydGw5dmVvamQtbWFpbGxhenkucGFnZXMuZGV2IiwNCiAgImFscG4iOiAiIiwNCiAgImZwIjogIiINCn0=
55 | https://sub.xf.free.hr/auto
56 | https://hy2sub.pages.dev
57 | ```
58 |
59 |
60 |
61 | ## 🛠️ Workers 部署方法
62 |
63 |
64 | 「 Workers 部署文字教程 」
65 |
66 | ### 1. 部署 Cloudflare Worker:
67 |
68 | - 在 Cloudflare Worker 控制台中创建一个新的 Worker。
69 | - 将 [_worker.js](https://github.com/cmliu/CF-Workers-SUB/blob/main/_worker.js) 的内容粘贴到 Worker 编辑器中。
70 |
71 |
72 | ### 2. 修改 订阅入口 :
73 |
74 | 例如您的workers项目域名为:`sub.cmliussss.workers.dev`;
75 | - 通过修改 `mytoken` 赋值内容,达到修改你专属订阅的入口,避免订阅泄漏。
76 | ```
77 | let mytoken = 'auto';
78 | ```
79 | 如上所示,你的订阅地址则如下:
80 | ```url
81 | https://sub.cmliussss.workers.dev/auto
82 | 或
83 | https://sub.cmliussss.workers.dev/?token=auto
84 | ```
85 |
86 |
87 | ### 3. 添加你的节点或订阅链接:
88 | 1. 绑定**变量名称**为`KV`的**KV命名空间**;
89 | 2. 访问 `https://sub.cmliussss.workers.dev/auto`,添加你的自建节点链接和机场订阅链接,确保每行一个链接,例如:
90 | ```
91 | 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
92 | vmess://ew0KICAidiI6ICIyIiwNCiAgInBzIjogIuWKoOWFpeaIkeeahOmikemBk3QubWUvQ01MaXVzc3Nz6Kej6ZSB5pu05aSa5LyY6YCJ6IqC54K5PuiLseWbvSDlgKvmlabph5Hono3ln44iLA0KICAiYWRkIjogImNmLjA5MDIyNy54eXoiLA0KICAicG9ydCI6ICI4NDQzIiwNCiAgImlkIjogIjAzZmNjNjE4LWI5M2QtNjc5Ni02YWVkLThhMzhjOTc1ZDU4MSIsDQogICJhaWQiOiAiMCIsDQogICJzY3kiOiAiYXV0byIsDQogICJuZXQiOiAid3MiLA0KICAidHlwZSI6ICJub25lIiwNCiAgImhvc3QiOiAicHBmdjJ0bDl2ZW9qZC1tYWlsbGF6eS5wYWdlcy5kZXYiLA0KICAicGF0aCI6ICIvamFkZXIuZnVuOjQ0My9saW5rdndzIiwNCiAgInRscyI6ICJ0bHMiLA0KICAic25pIjogInBwZnYydGw5dmVvamQtbWFpbGxhenkucGFnZXMuZGV2IiwNCiAgImFscG4iOiAiIiwNCiAgImZwIjogIiINCn0=
93 | https://sub.xf.free.hr/auto
94 | https://hy2sub.pages.dev
95 | ```
96 |
97 |
98 |
99 | ## 📋 变量说明
100 | | 变量名 | 示例 | 必填 | 备注 |
101 | |-|-|-|-|
102 | | TOKEN | `auto` | ✅ | 汇聚订阅的订阅配置路径地址,例如:`/auto` |
103 | | GUEST | `test` | ❌ | 汇聚订阅的访客订阅TOKEN,例如:`/sub?token=test` |
104 | | LINK | `vless://b7a39...`,`vmess://ew0K...`,`https://sub...` | ❌ | 可同时放入多个节点链接与多个订阅链接,链接之间用换行做间隔(添加**KV命名空间**后,变量将不会使用)|
105 | | TGTOKEN | `6894123456:XXXXXXXXXX0qExVsBPUhHDAbXXXXXqWXgBA` | ❌ | 发送TG通知的机器人token |
106 | | TGID | `6946912345` | ❌ | 接收TG通知的账户数字ID |
107 | | SUBNAME | `CF-Workers-SUB` | ❌ | 订阅名称 |
108 | | SUBAPI | `SUBAPI.cmliussss.net` | ❌ | clash、singbox等 订阅转换后端 |
109 | | SUBCONFIG | [https://raw.github.../ACL4SSR_Online_MultiCountry.ini](https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_MultiCountry.ini) | ❌ | clash、singbox等 订阅转换配置文件 |
110 |
111 |
112 | ## ⚠️ 注意事项
113 | 项目中,TGTOKEN和TGID在使用时需要先到Telegram注册并获取。其中,TGTOKEN是telegram bot的凭证,TGID是用来接收通知的telegram用户或者组的id。
114 |
115 |
116 | ## ⭐ Star 星星走起
117 | [](https://starchart.cc/cmliu/CF-Workers-SUB)
118 |
119 |
120 | # 🙏 致谢
121 | [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/)
122 |
--------------------------------------------------------------------------------
/_worker.js:
--------------------------------------------------------------------------------
1 |
2 | // 部署完成后在网址后面加上这个,获取自建节点和机场聚合节点,/?token=auto或/auto或
3 |
4 | let mytoken = 'auto';
5 | let guestToken = ''; //可以随便取,或者uuid生成,https://1024tools.com/uuid
6 | let BotToken = ''; //可以为空,或者@BotFather中输入/start,/newbot,并关注机器人
7 | let ChatID = ''; //可以为空,或者@userinfobot中获取,/start
8 | let TG = 0; //小白勿动, 开发者专用,1 为推送所有的访问信息,0 为不推送订阅转换后端的访问信息与异常访问
9 | let FileName = 'CF-Workers-SUB';
10 | let SUBUpdateTime = 6; //自定义订阅更新时间,单位小时
11 | let total = 99;//TB
12 | let timestamp = 4102329600000;//2099-12-31
13 |
14 | //节点链接 + 订阅链接
15 | let MainData = `
16 | https://raw.githubusercontent.com/mfuu/v2ray/master/v2ray
17 | `;
18 |
19 | let urls = [];
20 | let subConverter = "SUBAPI.cmliussss.net"; //在线订阅转换后端,目前使用CM的订阅转换功能。支持自建psub 可自行搭建https://github.com/bulianglin/psub
21 | let subConfig = "https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_MultiCountry.ini"; //订阅配置文件
22 | let subProtocol = 'https';
23 |
24 | export default {
25 | async fetch(request, env) {
26 | const userAgentHeader = request.headers.get('User-Agent');
27 | const userAgent = userAgentHeader ? userAgentHeader.toLowerCase() : "null";
28 | const url = new URL(request.url);
29 | const token = url.searchParams.get('token');
30 | mytoken = env.TOKEN || mytoken;
31 | BotToken = env.TGTOKEN || BotToken;
32 | ChatID = env.TGID || ChatID;
33 | TG = env.TG || TG;
34 | subConverter = env.SUBAPI || subConverter;
35 | if (subConverter.includes("http://")) {
36 | subConverter = subConverter.split("//")[1];
37 | subProtocol = 'http';
38 | } else {
39 | subConverter = subConverter.split("//")[1] || subConverter;
40 | }
41 | subConfig = env.SUBCONFIG || subConfig;
42 | FileName = env.SUBNAME || FileName;
43 |
44 | const currentDate = new Date();
45 | currentDate.setHours(0, 0, 0, 0);
46 | const timeTemp = Math.ceil(currentDate.getTime() / 1000);
47 | const fakeToken = await MD5MD5(`${mytoken}${timeTemp}`);
48 | guestToken = env.GUESTTOKEN || env.GUEST || guestToken;
49 | if (!guestToken) guestToken = await MD5MD5(mytoken);
50 | const 访客订阅 = guestToken;
51 | //console.log(`${fakeUserID}\n${fakeHostName}`); // 打印fakeID
52 |
53 | let UD = Math.floor(((timestamp - Date.now()) / timestamp * total * 1099511627776) / 2);
54 | total = total * 1099511627776;
55 | let expire = Math.floor(timestamp / 1000);
56 | SUBUpdateTime = env.SUBUPTIME || SUBUpdateTime;
57 |
58 | if (!([mytoken, fakeToken, 访客订阅].includes(token) || url.pathname == ("/" + mytoken) || url.pathname.includes("/" + mytoken + "?"))) {
59 | 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}`);
60 | if (env.URL302) return Response.redirect(env.URL302, 302);
61 | else if (env.URL) return await proxyURL(env.URL, url);
62 | else return new Response(await nginx(), {
63 | status: 200,
64 | headers: {
65 | 'Content-Type': 'text/html; charset=UTF-8',
66 | },
67 | });
68 | } else {
69 | if (env.KV) {
70 | await 迁移地址列表(env, 'LINK.txt');
71 | if (userAgent.includes('mozilla') && !url.search) {
72 | await sendMessage(`#编辑订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${userAgentHeader}\n域名: ${url.hostname}\n入口: ${url.pathname + url.search}`);
73 | return await KV(request, env, 'LINK.txt', 访客订阅);
74 | } else {
75 | MainData = await env.KV.get('LINK.txt') || MainData;
76 | }
77 | } else {
78 | MainData = env.LINK || MainData;
79 | if (env.LINKSUB) urls = await ADD(env.LINKSUB);
80 | }
81 | let 重新汇总所有链接 = await ADD(MainData + '\n' + urls.join('\n'));
82 | let 自建节点 = "";
83 | let 订阅链接 = "";
84 | for (let x of 重新汇总所有链接) {
85 | if (x.toLowerCase().startsWith('http')) {
86 | 订阅链接 += x + '\n';
87 | } else {
88 | 自建节点 += x + '\n';
89 | }
90 | }
91 | MainData = 自建节点;
92 | urls = await ADD(订阅链接);
93 | await sendMessage(`#获取订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${userAgentHeader}\n域名: ${url.hostname}\n入口: ${url.pathname + url.search}`);
94 |
95 | let 订阅格式 = 'base64';
96 | if (userAgent.includes('null') || userAgent.includes('subconverter') || userAgent.includes('nekobox') || userAgent.includes(('CF-Workers-SUB').toLowerCase())) {
97 | 订阅格式 = 'base64';
98 | } else if (userAgent.includes('clash') || (url.searchParams.has('clash') && !userAgent.includes('subconverter'))) {
99 | 订阅格式 = 'clash';
100 | } else if (userAgent.includes('sing-box') || userAgent.includes('singbox') || ((url.searchParams.has('sb') || url.searchParams.has('singbox')) && !userAgent.includes('subconverter'))) {
101 | 订阅格式 = 'singbox';
102 | } else if (userAgent.includes('surge') || (url.searchParams.has('surge') && !userAgent.includes('subconverter'))) {
103 | 订阅格式 = 'surge';
104 | } else if (userAgent.includes('quantumult%20x') || (url.searchParams.has('quanx') && !userAgent.includes('subconverter'))) {
105 | 订阅格式 = 'quanx';
106 | } else if (userAgent.includes('loon') || (url.searchParams.has('loon') && !userAgent.includes('subconverter'))) {
107 | 订阅格式 = 'loon';
108 | }
109 |
110 | let subConverterUrl;
111 | let 订阅转换URL = `${url.origin}/${await MD5MD5(fakeToken)}?token=${fakeToken}`;
112 | //console.log(订阅转换URL);
113 | let req_data = MainData;
114 |
115 | let 追加UA = 'v2rayn';
116 | if (url.searchParams.has('b64') || url.searchParams.has('base64')) 订阅格式 = 'base64';
117 | else if (url.searchParams.has('clash')) 追加UA = 'clash';
118 | else if (url.searchParams.has('singbox')) 追加UA = 'singbox';
119 | else if (url.searchParams.has('surge')) 追加UA = 'surge';
120 | else if (url.searchParams.has('quanx')) 追加UA = 'Quantumult%20X';
121 | else if (url.searchParams.has('loon')) 追加UA = 'Loon';
122 |
123 | const 订阅链接数组 = [...new Set(urls)].filter(item => item?.trim?.()); // 去重
124 | if (订阅链接数组.length > 0) {
125 | const 请求订阅响应内容 = await getSUB(订阅链接数组, request, 追加UA, userAgentHeader);
126 | console.log(请求订阅响应内容);
127 | req_data += 请求订阅响应内容[0].join('\n');
128 | 订阅转换URL += "|" + 请求订阅响应内容[1];
129 | }
130 |
131 | if (env.WARP) 订阅转换URL += "|" + (await ADD(env.WARP)).join("|");
132 | //修复中文错误
133 | const utf8Encoder = new TextEncoder();
134 | const encodedData = utf8Encoder.encode(req_data);
135 | //const text = String.fromCharCode.apply(null, encodedData);
136 | const utf8Decoder = new TextDecoder();
137 | const text = utf8Decoder.decode(encodedData);
138 |
139 | //去重
140 | const uniqueLines = new Set(text.split('\n'));
141 | const result = [...uniqueLines].join('\n');
142 | //console.log(result);
143 |
144 | let base64Data;
145 | try {
146 | base64Data = btoa(result);
147 | } catch (e) {
148 | function encodeBase64(data) {
149 | const binary = new TextEncoder().encode(data);
150 | let base64 = '';
151 | const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
152 |
153 | for (let i = 0; i < binary.length; i += 3) {
154 | const byte1 = binary[i];
155 | const byte2 = binary[i + 1] || 0;
156 | const byte3 = binary[i + 2] || 0;
157 |
158 | base64 += chars[byte1 >> 2];
159 | base64 += chars[((byte1 & 3) << 4) | (byte2 >> 4)];
160 | base64 += chars[((byte2 & 15) << 2) | (byte3 >> 6)];
161 | base64 += chars[byte3 & 63];
162 | }
163 |
164 | const padding = 3 - (binary.length % 3 || 3);
165 | return base64.slice(0, base64.length - padding) + '=='.slice(0, padding);
166 | }
167 |
168 | base64Data = encodeBase64(result)
169 | }
170 |
171 | if (订阅格式 == 'base64' || token == fakeToken) {
172 | return new Response(base64Data, {
173 | headers: {
174 | "content-type": "text/plain; charset=utf-8",
175 | "Profile-Update-Interval": `${SUBUpdateTime}`,
176 | //"Subscription-Userinfo": `upload=${UD}; download=${UD}; total=${total}; expire=${expire}`,
177 | }
178 | });
179 | } else if (订阅格式 == 'clash') {
180 | 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`;
181 | } else if (订阅格式 == 'singbox') {
182 | 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`;
183 | } else if (订阅格式 == 'surge') {
184 | 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`;
185 | } else if (订阅格式 == 'quanx') {
186 | 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`;
187 | } else if (订阅格式 == 'loon') {
188 | 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`;
189 | }
190 | //console.log(订阅转换URL);
191 | try {
192 | const subConverterResponse = await fetch(subConverterUrl);
193 |
194 | if (!subConverterResponse.ok) {
195 | return new Response(base64Data, {
196 | headers: {
197 | "content-type": "text/plain; charset=utf-8",
198 | "Profile-Update-Interval": `${SUBUpdateTime}`,
199 | //"Subscription-Userinfo": `upload=${UD}; download=${UD}; total=${total}; expire=${expire}`,
200 | }
201 | });
202 | //throw new Error(`Error fetching subConverterUrl: ${subConverterResponse.status} ${subConverterResponse.statusText}`);
203 | }
204 | let subConverterContent = await subConverterResponse.text();
205 | if (订阅格式 == 'clash') subConverterContent = await clashFix(subConverterContent);
206 | return new Response(subConverterContent, {
207 | headers: {
208 | "Content-Disposition": `attachment; filename*=utf-8''${encodeURIComponent(FileName)}`,
209 | "content-type": "text/plain; charset=utf-8",
210 | "Profile-Update-Interval": `${SUBUpdateTime}`,
211 | //"Subscription-Userinfo": `upload=${UD}; download=${UD}; total=${total}; expire=${expire}`,
212 |
213 | },
214 | });
215 | } catch (error) {
216 | return new Response(base64Data, {
217 | headers: {
218 | "content-type": "text/plain; charset=utf-8",
219 | "Profile-Update-Interval": `${SUBUpdateTime}`,
220 | //"Subscription-Userinfo": `upload=${UD}; download=${UD}; total=${total}; expire=${expire}`,
221 | }
222 | });
223 | }
224 | }
225 | }
226 | };
227 |
228 | async function ADD(envadd) {
229 | var addtext = envadd.replace(/[ "'|\r\n]+/g, '\n').replace(/\n+/g, '\n'); // 替换为换行
230 | //console.log(addtext);
231 | if (addtext.charAt(0) == '\n') addtext = addtext.slice(1);
232 | if (addtext.charAt(addtext.length - 1) == '\n') addtext = addtext.slice(0, addtext.length - 1);
233 | const add = addtext.split('\n');
234 | //console.log(add);
235 | return add;
236 | }
237 |
238 | async function nginx() {
239 | const text = `
240 |
241 |
242 |
243 | Welcome to nginx!
244 |
251 |
252 |
253 |
Welcome to nginx!
254 |
If you see this page, the nginx web server is successfully installed and
255 | working. Further configuration is required.
256 |
257 |
For online documentation and support please refer to
258 | nginx.org.
259 | Commercial support is available at
260 | nginx.com.