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

这是一个将多个节点和订阅合并为单一链接的工具,支持自动适配与自定义分流,简化了订阅管理。
> [!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 部署方法
<details>
<summary><code><strong>「 Pages GitHub 部署文字教程 」</strong></code></summary>
### 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
```
</details>
## 🛠️ Workers 部署方法
<details>
<summary><code><strong>「 Workers 部署文字教程 」</strong></code></summary>
### 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
```
</details>
## 📋 变量说明
| 变量名 | 示例 | 必填 | 备注 |
|-|-|-|-|
| 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 星星走起
[](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}</tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
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}</tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
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}</tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
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 = `
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
`
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<tg-spoiler>城市: ${ipInfo.city}\n组织: ${ipInfo.org}\nASN: ${ipInfo.as}\n${add_data}`;
} else {
msg = `${type}\nIP: ${ip}\n<tg-spoiler>${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 = `
<!DOCTYPE html>
<html>
<head>
<title>${FileName} 订阅编辑</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
padding: 15px; /* 调整padding */
box-sizing: border-box;
font-size: 13px; /* 设置全局字体大小 */
}
.editor-container {
width: 100%;
max-width: 100%;
margin: 0 auto;
}
.editor {
width: 100%;
height: 300px; /* 调整高度 */
margin: 15px 0; /* 调整margin */
padding: 10px; /* 调整padding */
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 13px;
line-height: 1.5;
overflow-y: auto;
resize: none;
}
.save-container {
margin-top: 8px; /* 调整margin */
display: flex;
align-items: center;
gap: 10px; /* 调整gap */
}
.save-btn, .back-btn {
padding: 6px 15px; /* 调整padding */
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.save-btn {
background: #4CAF50;
}
.save-btn:hover {
background: #45a049;
}
.back-btn {
background: #666;
}
.back-btn:hover {
background: #555;
}
.save-status {
color: #666;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/@keeex/qrcodejs-kx@1.0.2/qrcode.min.js"></script>
</head>
<body>
################################################################<br>
Subscribe / sub 订阅地址, 点击链接自动 <strong>复制订阅链接</strong> 并 <strong>生成订阅二维码</strong> <br>
---------------------------------------------------------------<br>
自适应订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/${mytoken}?sub','qrcode_0')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/${mytoken}</a><br>
<div id="qrcode_0" style="margin: 10px 10px 10px 10px;"></div>
Base64订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/${mytoken}?b64','qrcode_1')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/${mytoken}?b64</a><br>
<div id="qrcode_1" style="margin: 10px 10px 10px 10px;"></div>
clash订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/${mytoken}?clash','qrcode_2')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/${mytoken}?clash</a><br>
<div id="qrcode_2" style="margin: 10px 10px 10px 10px;"></div>
singbox订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/${mytoken}?sb','qrcode_3')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/${mytoken}?sb</a><br>
<div id="qrcode_3" style="margin: 10px 10px 10px 10px;"></div>
surge订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/${mytoken}?surge','qrcode_4')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/${mytoken}?surge</a><br>
<div id="qrcode_4" style="margin: 10px 10px 10px 10px;"></div>
loon订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/${mytoken}?loon','qrcode_5')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/${mytoken}?loon</a><br>
<div id="qrcode_5" style="margin: 10px 10px 10px 10px;"></div>
<strong><a href="javascript:void(0);" id="noticeToggle" onclick="toggleNotice()">查看访客订阅∨</a></strong><br>
<div id="noticeContent" class="notice-content" style="display: none;">
---------------------------------------------------------------<br>
访客订阅只能使用订阅功能,无法查看配置页!<br>
GUEST(访客订阅TOKEN): <strong>${guest}</strong><br>
---------------------------------------------------------------<br>
自适应订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/sub?token=${guest}','guest_0')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/sub?token=${guest}</a><br>
<div id="guest_0" style="margin: 10px 10px 10px 10px;"></div>
Base64订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/sub?token=${guest}&b64','guest_1')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/sub?token=${guest}&b64</a><br>
<div id="guest_1" style="margin: 10px 10px 10px 10px;"></div>
clash订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/sub?token=${guest}&clash','guest_2')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/sub?token=${guest}&clash</a><br>
<div id="guest_2" style="margin: 10px 10px 10px 10px;"></div>
singbox订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/sub?token=${guest}&sb','guest_3')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/sub?token=${guest}&sb</a><br>
<div id="guest_3" style="margin: 10px 10px 10px 10px;"></div>
surge订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/sub?token=${guest}&surge','guest_4')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/sub?token=${guest}&surge</a><br>
<div id="guest_4" style="margin: 10px 10px 10px 10px;"></div>
loon订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${url.hostname}/sub?token=${guest}&loon','guest_5')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${url.hostname}/sub?token=${guest}&loon</a><br>
<div id="guest_5" style="margin: 10px 10px 10px 10px;"></div>
</div>
---------------------------------------------------------------<br>
################################################################<br>
订阅转换配置<br>
---------------------------------------------------------------<br>
SUBAPI(订阅转换后端): <strong>${subProtocol}://${subConverter}</strong><br>
SUBCONFIG(订阅转换配置文件): <strong>${subConfig}</strong><br>
---------------------------------------------------------------<br>
################################################################<br>
${FileName} 汇聚订阅编辑:
<div class="editor-container">
${hasKV ? `
<textarea class="editor"
placeholder="${decodeURIComponent(atob('TElOSyVFNyVBNCVCQSVFNCVCRSU4QiVFRiVCQyU4OCVFNCVCOCU4MCVFOCVBMSU4QyVFNCVCOCU4MCVFNCVCOCVBQSVFOCU4QSU4MiVFNyU4MiVCOSVFOSU5MyVCRSVFNiU4RSVBNSVFNSU4RCVCMyVFNSU4RiVBRiVFRiVCQyU4OSVFRiVCQyU5QQp2bGVzcyUzQSUyRiUyRjI0NmFhNzk1LTA2MzctNGY0Yy04ZjY0LTJjOGZiMjRjMWJhZCU0MDEyNy4wLjAuMSUzQTEyMzQlM0ZlbmNyeXB0aW9uJTNEbm9uZSUyNnNlY3VyaXR5JTNEdGxzJTI2c25pJTNEVEcuQ01MaXVzc3NzLmxvc2V5b3VyaXAuY29tJTI2YWxsb3dJbnNlY3VyZSUzRDElMjZ0eXBlJTNEd3MlMjZob3N0JTNEVEcuQ01MaXVzc3NzLmxvc2V5b3VyaXAuY29tJTI2cGF0aCUzRCUyNTJGJTI1M0ZlZCUyNTNEMjU2MCUyM0NGbmF0CnRyb2phbiUzQSUyRiUyRmFhNmRkZDJmLWQxY2YtNGE1Mi1iYTFiLTI2NDBjNDFhNzg1NiU0MDIxOC4xOTAuMjMwLjIwNyUzQTQxMjg4JTNGc2VjdXJpdHklM0R0bHMlMjZzbmklM0RoazEyLmJpbGliaWxpLmNvbSUyNmFsbG93SW5zZWN1cmUlM0QxJTI2dHlwZSUzRHRjcCUyNmhlYWRlclR5cGUlM0Rub25lJTIzSEsKc3MlM0ElMkYlMkZZMmhoWTJoaE1qQXRhV1YwWmkxd2IyeDVNVE13TlRveVJYUlFjVzQyU0ZscVZVNWpTRzlvVEdaVmNFWlJkMjVtYWtORFVUVnRhREZ0U21SRlRVTkNkV04xVjFvNVVERjFaR3RTUzBodVZuaDFielUxYXpGTFdIb3lSbTgyYW5KbmRERTRWelkyYjNCMGVURmxOR0p0TVdwNlprTm1RbUklMjUzRCU0MDg0LjE5LjMxLjYzJTNBNTA4NDElMjNERQoKCiVFOCVBRSVBMiVFOSU5OCU4NSVFOSU5MyVCRSVFNiU4RSVBNSVFNyVBNCVCQSVFNCVCRSU4QiVFRiVCQyU4OCVFNCVCOCU4MCVFOCVBMSU4QyVFNCVCOCU4MCVFNiU5RCVBMSVFOCVBRSVBMiVFOSU5OCU4NSVFOSU5MyVCRSVFNiU4RSVBNSVFNSU4RCVCMyVFNSU4RiVBRiVFRiVCQyU4OSVFRiVCQyU5QQpodHRwcyUzQSUyRiUyRnN1Yi54Zi5mcmVlLmhyJTJGYXV0bw=='))}"
id="content">${content}</textarea>
<div class="save-container">
<button class="save-btn" onclick="saveContent(this)">保存</button>
<span class="save-status" id="saveStatus"></span>
</div>
` : '<p>请绑定 <strong>变量名称</strong> 为 <strong>KV</strong> 的KV命名空间</p>'}
</div>
<br>
################################################################<br>
${decodeURIComponent(atob('dGVsZWdyYW0lMjAlRTQlQkElQTQlRTYlQjUlODElRTclQkUlQTQlMjAlRTYlOEElODAlRTYlOUMlQUYlRTUlQTQlQTclRTQlQkQlQUMlN0UlRTUlOUMlQTglRTclQkElQkYlRTUlOEYlOTElRTclODklOEMhJTNDYnIlM0UKJTNDYSUyMGhyZWYlM0QlMjdodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlMjclM0VodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlM0MlMkZhJTNFJTNDYnIlM0UKLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tJTNDYnIlM0UKZ2l0aHViJTIwJUU5JUExJUI5JUU3JTlCJUFFJUU1JTlDJUIwJUU1JTlEJTgwJTIwU3RhciFTdGFyIVN0YXIhISElM0NiciUzRQolM0NhJTIwaHJlZiUzRCUyN2h0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmNtbGl1JTJGQ0YtV29ya2Vycy1TVUIlMjclM0VodHRwcyUzQSUyRiUyRmdpdGh1Yi5jb20lMkZjbWxpdSUyRkNGLVdvcmtlcnMtU1VCJTNDJTJGYSUzRSUzQ2JyJTNFCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSUzQ2JyJTNFCiUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMw=='))}
<br><br>UA: <strong>${request.headers.get('User-Agent')}</strong>
<script>
function copyToClipboard(text, qrcode) {
navigator.clipboard.writeText(text).then(() => {
alert('已复制到剪贴板');
}).catch(err => {
console.error('复制失败:', err);
});
const qrcodeDiv = document.getElementById(qrcode);
qrcodeDiv.innerHTML = '';
new QRCode(qrcodeDiv, {
text: text,
width: 220, // 调整宽度
height: 220, // 调整高度
colorDark: "#000000", // 二维码颜色
colorLight: "#ffffff", // 背景颜色
correctLevel: QRCode.CorrectLevel.Q, // 设置纠错级别
scale: 1 // 调整像素颗粒度
});
}
if (document.querySelector('.editor')) {
let timer;
const textarea = document.getElementById('content');
const originalContent = textarea.value;
function goBack() {
const currentUrl = window.location.href;
const parentUrl = currentUrl.substring(0, currentUrl.lastIndexOf('/'));
window.location.href = parentUrl;
}
function replaceFullwidthColon() {
const text = textarea.value;
textarea.value = text.replace(/:/g, ':');
}
function saveContent(button) {
try {
const updateButtonText = (step) => {
button.textContent = \`保存中: \${step}\`;
};
// 检测是否为iOS设备
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
// 仅在非iOS设备上执行replaceFullwidthColon
if (!isIOS) {
replaceFullwidthColon();
}
updateButtonText('开始保存');
button.disabled = true;
// 获取textarea内容和原始内容
const textarea = document.getElementById('content');
if (!textarea) {
throw new Error('找不到文本编辑区域');
}
updateButtonText('获取内容');
let newContent;
let originalContent;
try {
newContent = textarea.value || '';
originalContent = textarea.defaultValue || '';
} catch (e) {
console.error('获取内容错误:', e);
throw new Error('无法获取编辑内容');
}
updateButtonText('准备状态更新函数');
const updateStatus = (message, isError = false) => {
const statusElem = document.getElementById('saveStatus');
if (statusElem) {
statusElem.textContent = message;
statusElem.style.color = isError ? 'red' : '#666';
}
};
updateButtonText('准备按钮重置函数');
const resetButton = () => {
button.textContent = '保存';
button.disabled = false;
};
if (newContent !== originalContent) {
updateButtonText('发送保存请求');
fetch(window.location.href, {
method: 'POST',
body: newContent,
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
},
cache: 'no-cache'
})
.then(response => {
updateButtonText('检查响应状态');
if (!response.ok) {
throw new Error(\`HTTP error! status: \${response.status}\`);
}
updateButtonText('更新保存状态');
const now = new Date().toLocaleString();
document.title = \`编辑已保存 \${now}\`;
updateStatus(\`已保存 \${now}\`);
})
.catch(error => {
updateButtonText('处理错误');
console.error('Save error:', error);
updateStatus(\`保存失败: \${error.message}\`, true);
})
.finally(() => {
resetButton();
});
} else {
updateButtonText('检查内容变化');
updateStatus('内容未变化');
resetButton();
}
} catch (error) {
console.error('保存过程出错:', error);
button.textContent = '保存';
button.disabled = false;
const statusElem = document.getElementById('saveStatus');
if (statusElem) {
statusElem.textContent = \`错误: \${error.message}\`;
statusElem.style.color = 'red';
}
}
}
textarea.addEventListener('blur', saveContent);
textarea.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(saveContent, 5000);
});
}
function toggleNotice() {
const noticeContent = document.getElementById('noticeContent');
const noticeToggle = document.getElementById('noticeToggle');
if (noticeContent.style.display === 'none' || noticeContent.style.display === '') {
noticeContent.style.display = 'block';
noticeToggle.textContent = '隐藏访客订阅∧';
} else {
noticeContent.style.display = 'none';
noticeToggle.textContent = '查看访客订阅∨';
}
}
// 初始化 noticeContent 的 display 属性
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('noticeContent').style.display = 'none';
});
</script>
</body>
</html>
`;
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
gitextract_5rrimb93/ ├── .github/ │ └── workflows/ │ └── sync.yml ├── LICENSE ├── README.md ├── _worker.js └── wrangler.toml
SYMBOL INDEX (13 symbols across 1 files)
FILE: _worker.js
method fetch (line 25) | async fetch(request, env) {
function ADD (line 220) | async function ADD(envadd) {
function nginx (line 230) | async function nginx() {
function sendMessage (line 261) | async function sendMessage(type, ip, add_data = "") {
function base64Decode (line 284) | function base64Decode(str) {
function MD5MD5 (line 290) | async function MD5MD5(text) {
function clashFix (line 304) | function clashFix(content) {
function proxyURL (line 329) | async function proxyURL(proxyURL, url) {
function getSUB (line 369) | async function getSUB(api, request, 追加UA, userAgentHeader) {
function getUrl (line 447) | async function getUrl(request, targetUrl, 追加UA, userAgentHeader) {
function isValidBase64 (line 478) | function isValidBase64(str) {
function 迁移地址列表 (line 485) | async function 迁移地址列表(env, txt = 'ADD.txt') {
function KV (line 499) | async function KV(request, env, txt = 'ADD.txt', guest) {
Condensed preview — 5 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (59K chars).
[
{
"path": ".github/workflows/sync.yml",
"chars": 1372,
"preview": "name: Upstream Sync\r\n\r\npermissions:\r\n contents: write\r\n\r\non:\r\n schedule:\r\n - cron: \"0 0 * * *\" # every day\r\n workf"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 5758,
"preview": "# ⚙ 自建汇聚订阅 CF-Workers-SUB\n\n\n\n这是一个将多个节点和订阅合并为单一链接的工具,支持自动适配与自定义分流,简化了订阅管理。\n\n> [!CAUTIO"
},
{
"path": "_worker.js",
"chars": 34640,
"preview": "\r\n// 部署完成后在网址后面加上这个,获取自建节点和机场聚合节点,/?token=auto或/auto或\r\n\r\nlet mytoken = 'auto';\r\nlet guestToken = ''; //可以随便取,或者uuid生成,ht"
},
{
"path": "wrangler.toml",
"chars": 201,
"preview": "name = \"sub-worker\"\r\nmain = \"_worker.js\"\r\ncompatibility_date = \"2025-07-23\"\r\nkeep_vars = true\r\n\r\n#[[kv_namespaces]]\r\n#bi"
}
]
About this extraction
This page contains the full source code of the cmliu/CF-Workers-SUB GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 5 files (52.1 KB), approximately 16.7k tokens, and a symbol index with 13 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.