[
  {
    "path": ".github/workflows/sync.yml",
    "content": "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  workflow_dispatch:\r\n\r\njobs:\r\n  sync_latest_from_upstream:\r\n    name: Sync latest commits from upstream repo\r\n    runs-on: ubuntu-latest\r\n    if: ${{ github.event.repository.fork }}\r\n\r\n    steps:\r\n      # Step 1: run a standard checkout action\r\n      - name: Checkout target repo\r\n        uses: actions/checkout@v3\r\n\r\n      # Step 2: run the sync action\r\n      - name: Sync upstream changes\r\n        id: sync\r\n        uses: aormsby/Fork-Sync-With-Upstream-action@v3.4\r\n        with:\r\n          upstream_sync_repo: cmliu/CF-Workers-SUB\r\n          upstream_sync_branch: main\r\n          target_sync_branch: main\r\n          target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set\r\n\r\n          # Set test_mode true to run tests instead of the true action!!\r\n          test_mode: false\r\n\r\n      - name: Sync check\r\n        if: failure()\r\n        run: |\r\n          echo \"[Error] 由于上游仓库的 workflow 文件变更，导致 GitHub 自动暂停了本次自动更新，你需要手动 Sync Fork 一次，详细教程请查看项目README.md \"\r\n          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. \"\r\n          exit 1"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# ⚙ 自建汇聚订阅 CF-Workers-SUB\n\n![自建汇聚订阅 CF-Workers-SUB](./sub.png)\n\n这是一个将多个节点和订阅合并为单一链接的工具，支持自动适配与自定义分流，简化了订阅管理。\n\n> [!CAUTION]\n> **汇聚订阅非base64订阅时**，会自动生成一个**有效期为24小时的临时订阅**，并提交给**订阅转换后端**来完成订阅转换，可避免您的汇聚订阅地址泄露。\n\n> [!WARNING]\n> **汇聚订阅非base64订阅时**，如果您的节点数量**十分庞大**，订阅转换后端将需要较长时间才能完成订阅转换，这会导致部分梯子客户端在订阅时提示超时而无法完成订阅（说直白一点就是**汇聚节点池的节点时容易导致Clash订阅超时**）！\n>\n> 可自行删减订阅节点数量，提高订阅转换效率！\n\n## 🛠 功能特点\n1. **节点链接自动转换成base64订阅链接：** 这是最基础的功能，可以将您的节点自动转换为base64格式的订阅链接；\n2. **将多个base64订阅汇聚成一个订阅链接：** 可以将多个订阅（例如不同的机场）合并成一个订阅，只需使用一个订阅地址即可获取所有节点；\n3. **自动适配不同梯子的格式订阅链接：** 依托[订阅转换](https://sub.cmliussss.com/)服务，自动将订阅转换为不同梯子所需的格式，实现一条订阅适配多种梯子；\n4. **专属代理分流规则：** 自定义分流规则，实现个性化的分流模式；\n5. **更多功能等待发掘...**\n\n## 🎬 视频教程\n- **[自建订阅！CF-Workers-SUB 教你如何将多节点多订阅汇聚合并为一个订阅！](https://youtu.be/w6rRY4FDd58)**\n\n## 🤝 社区支持\n- Telegram 交流群: [@CMLiussss](https://t.me/CMLiussss)\n- 感谢 [Alice Networks](https://alicenetworks.net/) 提供的云服务器维持 [CM订阅转换服务](https://sub.cmliussss.com/)\n\n## 📦 Pages 部署方法\n\n<details>\n<summary><code><strong>「 Pages GitHub 部署文字教程 」</strong></code></summary>\n\n### 1. 部署 Cloudflare Pages：\n   - 在 Github 上先 Fork 本项目，并点上 Star !!!\n   - 在 Cloudflare Pages 控制台中选择 `连接到 Git`后，选中 `CF-Workers-SUB`项目后点击 `开始设置`。\n\n### 2. 给 Pages绑定 自定义域：\n   - 在 Pages控制台的 `自定义域`选项卡，下方点击 `设置自定义域`。\n   - 填入你的自定义次级域名，注意不要使用你的根域名，例如：\n     您分配到的域名是 `fuck.cloudns.biz`，则添加自定义域填入 `sub.fuck.cloudns.biz`即可；\n   - 按照 Cloudflare 的要求将返回你的域名DNS服务商，添加 该自定义域 `sub`的 CNAME记录 `CF-Workers-SUB.pages.dev` 后，点击 `激活域`即可。\n\n### 3. 修改 快速订阅入口 ：\n\n  例如您的pages项目域名为：`sub.fuck.cloudns.biz`；\n   - 添加 `TOKEN` 变量，快速订阅访问入口，默认值为: `auto` ，获取订阅器默认节点订阅地址即 `/auto` ，例如 `https://sub.fuck.cloudns.biz/auto`\n\n### 4. 添加你的节点和订阅链接：\n   1. 绑定**变量名称**为`KV`的**KV命名空间**；\n   2. 访问 `https://sub.fuck.cloudns.biz/auto`，添加你的自建节点链接和机场订阅链接，确保每行一个链接，例如：\n      ```\n      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\n      vmess://ew0KICAidiI6ICIyIiwNCiAgInBzIjogIuWKoOWFpeaIkeeahOmikemBk3QubWUvQ01MaXVzc3Nz6Kej6ZSB5pu05aSa5LyY6YCJ6IqC54K5PuiLseWbvSDlgKvmlabph5Hono3ln44iLA0KICAiYWRkIjogImNmLjA5MDIyNy54eXoiLA0KICAicG9ydCI6ICI4NDQzIiwNCiAgImlkIjogIjAzZmNjNjE4LWI5M2QtNjc5Ni02YWVkLThhMzhjOTc1ZDU4MSIsDQogICJhaWQiOiAiMCIsDQogICJzY3kiOiAiYXV0byIsDQogICJuZXQiOiAid3MiLA0KICAidHlwZSI6ICJub25lIiwNCiAgImhvc3QiOiAicHBmdjJ0bDl2ZW9qZC1tYWlsbGF6eS5wYWdlcy5kZXYiLA0KICAicGF0aCI6ICIvamFkZXIuZnVuOjQ0My9saW5rdndzIiwNCiAgInRscyI6ICJ0bHMiLA0KICAic25pIjogInBwZnYydGw5dmVvamQtbWFpbGxhenkucGFnZXMuZGV2IiwNCiAgImFscG4iOiAiIiwNCiAgImZwIjogIiINCn0=\n      https://sub.xf.free.hr/auto\n      https://hy2sub.pages.dev\n      ```\n\n</details>\n\n## 🛠️ Workers 部署方法\n\n<details>\n<summary><code><strong>「 Workers 部署文字教程 」</strong></code></summary>\n\n### 1. 部署 Cloudflare Worker：\n\n   - 在 Cloudflare Worker 控制台中创建一个新的 Worker。\n   - 将 [_worker.js](https://github.com/cmliu/CF-Workers-SUB/blob/main/_worker.js)  的内容粘贴到 Worker 编辑器中。\n\n\n### 2. 修改 订阅入口 ：\n\n  例如您的workers项目域名为：`sub.cmliussss.workers.dev`；\n   - 通过修改 `mytoken` 赋值内容，达到修改你专属订阅的入口，避免订阅泄漏。\n     ```\n     let mytoken = 'auto';\n     ```\n     如上所示，你的订阅地址则如下：\n     ```url\n     https://sub.cmliussss.workers.dev/auto\n     或\n     https://sub.cmliussss.workers.dev/?token=auto\n     ```\n\n\n### 3. 添加你的节点或订阅链接：\n   1. 绑定**变量名称**为`KV`的**KV命名空间**；\n   2. 访问 `https://sub.cmliussss.workers.dev/auto`，添加你的自建节点链接和机场订阅链接，确保每行一个链接，例如：\n      ```\n      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\n      vmess://ew0KICAidiI6ICIyIiwNCiAgInBzIjogIuWKoOWFpeaIkeeahOmikemBk3QubWUvQ01MaXVzc3Nz6Kej6ZSB5pu05aSa5LyY6YCJ6IqC54K5PuiLseWbvSDlgKvmlabph5Hono3ln44iLA0KICAiYWRkIjogImNmLjA5MDIyNy54eXoiLA0KICAicG9ydCI6ICI4NDQzIiwNCiAgImlkIjogIjAzZmNjNjE4LWI5M2QtNjc5Ni02YWVkLThhMzhjOTc1ZDU4MSIsDQogICJhaWQiOiAiMCIsDQogICJzY3kiOiAiYXV0byIsDQogICJuZXQiOiAid3MiLA0KICAidHlwZSI6ICJub25lIiwNCiAgImhvc3QiOiAicHBmdjJ0bDl2ZW9qZC1tYWlsbGF6eS5wYWdlcy5kZXYiLA0KICAicGF0aCI6ICIvamFkZXIuZnVuOjQ0My9saW5rdndzIiwNCiAgInRscyI6ICJ0bHMiLA0KICAic25pIjogInBwZnYydGw5dmVvamQtbWFpbGxhenkucGFnZXMuZGV2IiwNCiAgImFscG4iOiAiIiwNCiAgImZwIjogIiINCn0=\n      https://sub.xf.free.hr/auto\n      https://hy2sub.pages.dev\n      ```\n\n</details>\n\n## 📋 变量说明\n| 变量名 | 示例 | 必填 | 备注 | \n|-|-|-|-|\n| TOKEN | `auto` | ✅ | 汇聚订阅的订阅配置路径地址，例如：`/auto` | \n| GUEST | `test` | ❌ | 汇聚订阅的访客订阅TOKEN，例如：`/sub?token=test` | \n| LINK | `vless://b7a39...`,`vmess://ew0K...`,`https://sub...` | ❌ | 可同时放入多个节点链接与多个订阅链接，链接之间用换行做间隔（添加**KV命名空间**后，变量将不会使用）|\n| TGTOKEN | `6894123456:XXXXXXXXXX0qExVsBPUhHDAbXXXXXqWXgBA` | ❌ | 发送TG通知的机器人token | \n| TGID | `6946912345` | ❌ | 接收TG通知的账户数字ID | \n| SUBNAME | `CF-Workers-SUB` | ❌ | 订阅名称 |\n| SUBAPI | `SUBAPI.cmliussss.net` | ❌ | clash、singbox等 订阅转换后端 | \n| SUBCONFIG | [https://raw.github.../ACL4SSR_Online_MultiCountry.ini](https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_MultiCountry.ini) | ❌ | clash、singbox等 订阅转换配置文件 | \n\n\n## ⚠️ 注意事项\n项目中，TGTOKEN和TGID在使用时需要先到Telegram注册并获取。其中，TGTOKEN是telegram bot的凭证，TGID是用来接收通知的telegram用户或者组的id。\n\n\n## ⭐ Star 星星走起\n[![Stargazers over time](https://starchart.cc/cmliu/CF-Workers-SUB.svg?variant=adaptive)](https://starchart.cc/cmliu/CF-Workers-SUB)\n\n\n# 🙏 致谢\n[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/)\n"
  },
  {
    "path": "_worker.js",
    "content": "\r\n// 部署完成后在网址后面加上这个，获取自建节点和机场聚合节点，/?token=auto或/auto或\r\n\r\nlet mytoken = 'auto';\r\nlet guestToken = ''; //可以随便取，或者uuid生成，https://1024tools.com/uuid\r\nlet BotToken = ''; //可以为空，或者@BotFather中输入/start，/newbot，并关注机器人\r\nlet ChatID = ''; //可以为空，或者@userinfobot中获取，/start\r\nlet TG = 0; //小白勿动， 开发者专用，1 为推送所有的访问信息，0 为不推送订阅转换后端的访问信息与异常访问\r\nlet FileName = 'CF-Workers-SUB';\r\nlet SUBUpdateTime = 6; //自定义订阅更新时间，单位小时\r\nlet total = 99;//TB\r\nlet timestamp = 4102329600000;//2099-12-31\r\n\r\n//节点链接 + 订阅链接\r\nlet MainData = `\r\nhttps://cfxr.eu.org/getSub\r\n`;\r\n\r\nlet urls = [];\r\nlet subConverter = \"SUBAPI.cmliussss.net\"; //在线订阅转换后端，目前使用CM的订阅转换功能。支持自建psub 可自行搭建https://github.com/bulianglin/psub\r\nlet subConfig = \"https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_MultiCountry.ini\"; //订阅配置文件\r\nlet subProtocol = 'https';\r\n\r\nexport default {\r\n\tasync fetch(request, env) {\r\n\t\tconst userAgentHeader = request.headers.get('User-Agent');\r\n\t\tconst userAgent = userAgentHeader ? userAgentHeader.toLowerCase() : \"null\";\r\n\t\tconst url = new URL(request.url);\r\n\t\tconst token = url.searchParams.get('token');\r\n\t\tmytoken = env.TOKEN || mytoken;\r\n\t\tBotToken = env.TGTOKEN || BotToken;\r\n\t\tChatID = env.TGID || ChatID;\r\n\t\tTG = env.TG || TG;\r\n\t\tsubConverter = env.SUBAPI || subConverter;\r\n\t\tif (subConverter.includes(\"http://\")) {\r\n\t\t\tsubConverter = subConverter.split(\"//\")[1];\r\n\t\t\tsubProtocol = 'http';\r\n\t\t} else {\r\n\t\t\tsubConverter = subConverter.split(\"//\")[1] || subConverter;\r\n\t\t}\r\n\t\tsubConfig = env.SUBCONFIG || subConfig;\r\n\t\tFileName = env.SUBNAME || FileName;\r\n\r\n\t\tconst currentDate = new Date();\r\n\t\tcurrentDate.setHours(0, 0, 0, 0);\r\n\t\tconst timeTemp = Math.ceil(currentDate.getTime() / 1000);\r\n\t\tconst fakeToken = await MD5MD5(`${mytoken}${timeTemp}`);\r\n\t\tguestToken = env.GUESTTOKEN || env.GUEST || guestToken;\r\n\t\tif (!guestToken) guestToken = await MD5MD5(mytoken);\r\n\t\tconst 访客订阅 = guestToken;\r\n\t\t//console.log(`${fakeUserID}\\n${fakeHostName}`); // 打印fakeID\r\n\r\n\t\tlet UD = Math.floor(((timestamp - Date.now()) / timestamp * total * 1099511627776) / 2);\r\n\t\ttotal = total * 1099511627776;\r\n\t\tlet expire = Math.floor(timestamp / 1000);\r\n\t\tSUBUpdateTime = env.SUBUPTIME || SUBUpdateTime;\r\n\r\n\t\tif (!([mytoken, fakeToken, 访客订阅].includes(token) || url.pathname == (\"/\" + mytoken) || url.pathname.includes(\"/\" + mytoken + \"?\"))) {\r\n\t\t\tif (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>`);\r\n\t\t\tif (env.URL302) return Response.redirect(env.URL302, 302);\r\n\t\t\telse if (env.URL) return await proxyURL(env.URL, url);\r\n\t\t\telse return new Response(await nginx(), {\r\n\t\t\t\tstatus: 200,\r\n\t\t\t\theaders: {\r\n\t\t\t\t\t'Content-Type': 'text/html; charset=UTF-8',\r\n\t\t\t\t},\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tif (env.KV) {\r\n\t\t\t\tawait 迁移地址列表(env, 'LINK.txt');\r\n\t\t\t\tif (userAgent.includes('mozilla') && !url.search) {\r\n\t\t\t\t\tawait sendMessage(`#编辑订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${userAgentHeader}</tg-spoiler>\\n域名: ${url.hostname}\\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);\r\n\t\t\t\t\treturn await KV(request, env, 'LINK.txt', 访客订阅);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tMainData = await env.KV.get('LINK.txt') || MainData;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tMainData = env.LINK || MainData;\r\n\t\t\t\tif (env.LINKSUB) urls = await ADD(env.LINKSUB);\r\n\t\t\t}\r\n\t\t\tlet 重新汇总所有链接 = await ADD(MainData + '\\n' + urls.join('\\n'));\r\n\t\t\tlet 自建节点 = \"\";\r\n\t\t\tlet 订阅链接 = \"\";\r\n\t\t\tfor (let x of 重新汇总所有链接) {\r\n\t\t\t\tif (x.toLowerCase().startsWith('http')) {\r\n\t\t\t\t\t订阅链接 += x + '\\n';\r\n\t\t\t\t} else {\r\n\t\t\t\t\t自建节点 += x + '\\n';\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tMainData = 自建节点;\r\n\t\t\turls = await ADD(订阅链接);\r\n\t\t\tawait sendMessage(`#获取订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${userAgentHeader}</tg-spoiler>\\n域名: ${url.hostname}\\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);\r\n\t\t\tconst isSubConverterRequest = request.headers.get('subconverter-request') || request.headers.get('subconverter-version') || userAgent.includes('subconverter');\r\n\t\t\tlet 订阅格式 = 'base64';\r\n\t\t\tif (!(userAgent.includes('null') || isSubConverterRequest || userAgent.includes('nekobox') || userAgent.includes(('CF-Workers-SUB').toLowerCase()))) {\r\n\t\t\t\tif (userAgent.includes('sing-box') || userAgent.includes('singbox') || url.searchParams.has('sb') || url.searchParams.has('singbox')) {\r\n\t\t\t\t\t订阅格式 = 'singbox';\r\n\t\t\t\t} else if (userAgent.includes('surge') || url.searchParams.has('surge')) {\r\n\t\t\t\t\t订阅格式 = 'surge';\r\n\t\t\t\t} else if (userAgent.includes('quantumult') || url.searchParams.has('quanx')) {\r\n\t\t\t\t\t订阅格式 = 'quanx';\r\n\t\t\t\t} else if (userAgent.includes('loon') || url.searchParams.has('loon')) {\r\n\t\t\t\t\t订阅格式 = 'loon';\r\n\t\t\t\t} else if (userAgent.includes('clash') || userAgent.includes('meta') || userAgent.includes('mihomo') || url.searchParams.has('clash')) {\r\n\t\t\t\t\t订阅格式 = 'clash';\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tlet subConverterUrl;\r\n\t\t\tlet 订阅转换URL = `${url.origin}/${await MD5MD5(fakeToken)}?token=${fakeToken}`;\r\n\t\t\t//console.log(订阅转换URL);\r\n\t\t\tlet req_data = MainData;\r\n\r\n\t\t\tlet 追加UA = 'v2rayn';\r\n\t\t\tif (url.searchParams.has('b64') || url.searchParams.has('base64')) 订阅格式 = 'base64';\r\n\t\t\telse if (url.searchParams.has('clash')) 追加UA = 'clash';\r\n\t\t\telse if (url.searchParams.has('singbox')) 追加UA = 'singbox';\r\n\t\t\telse if (url.searchParams.has('surge')) 追加UA = 'surge';\r\n\t\t\telse if (url.searchParams.has('quanx')) 追加UA = 'Quantumult%20X';\r\n\t\t\telse if (url.searchParams.has('loon')) 追加UA = 'Loon';\r\n\r\n\t\t\tconst 订阅链接数组 = [...new Set(urls)].filter(item => item?.trim?.()); // 去重\r\n\t\t\tif (订阅链接数组.length > 0) {\r\n\t\t\t\tconst 请求订阅响应内容 = await getSUB(订阅链接数组, request, 追加UA, userAgentHeader);\r\n\t\t\t\tconsole.log(请求订阅响应内容);\r\n\t\t\t\treq_data += 请求订阅响应内容[0].join('\\n');\r\n\t\t\t\t订阅转换URL += \"|\" + 请求订阅响应内容[1];\r\n\t\t\t\tif (订阅格式 == 'base64' && !isSubConverterRequest && 请求订阅响应内容[1].includes('://')) {\r\n\t\t\t\t\tsubConverterUrl = `${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`;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tconst subConverterResponse = await fetch(subConverterUrl, { headers: { 'User-Agent': 'v2rayN/CF-Workers-SUB  (https://github.com/cmliu/CF-Workers-SUB)' } });\r\n\t\t\t\t\t\tif (subConverterResponse.ok) {\r\n\t\t\t\t\t\t\tconst subConverterContent = await subConverterResponse.text();\r\n\t\t\t\t\t\t\treq_data += '\\n' + atob(subConverterContent);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\tconsole.log('订阅转换请回base64失败，检查订阅转换后端是否正常运行');\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (env.WARP) 订阅转换URL += \"|\" + (await ADD(env.WARP)).join(\"|\");\r\n\t\t\t//修复中文错误\r\n\t\t\tconst utf8Encoder = new TextEncoder();\r\n\t\t\tconst encodedData = utf8Encoder.encode(req_data);\r\n\t\t\t//const text = String.fromCharCode.apply(null, encodedData);\r\n\t\t\tconst utf8Decoder = new TextDecoder();\r\n\t\t\tconst text = utf8Decoder.decode(encodedData);\r\n\r\n\t\t\t//去重\r\n\t\t\tconst uniqueLines = new Set(text.split('\\n'));\r\n\t\t\tconst result = [...uniqueLines].join('\\n');\r\n\t\t\t//console.log(result);\r\n\r\n\t\t\tlet base64Data;\r\n\t\t\ttry {\r\n\t\t\t\tbase64Data = btoa(result);\r\n\t\t\t} catch (e) {\r\n\t\t\t\tfunction encodeBase64(data) {\r\n\t\t\t\t\tconst binary = new TextEncoder().encode(data);\r\n\t\t\t\t\tlet base64 = '';\r\n\t\t\t\t\tconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\r\n\r\n\t\t\t\t\tfor (let i = 0; i < binary.length; i += 3) {\r\n\t\t\t\t\t\tconst byte1 = binary[i];\r\n\t\t\t\t\t\tconst byte2 = binary[i + 1] || 0;\r\n\t\t\t\t\t\tconst byte3 = binary[i + 2] || 0;\r\n\r\n\t\t\t\t\t\tbase64 += chars[byte1 >> 2];\r\n\t\t\t\t\t\tbase64 += chars[((byte1 & 3) << 4) | (byte2 >> 4)];\r\n\t\t\t\t\t\tbase64 += chars[((byte2 & 15) << 2) | (byte3 >> 6)];\r\n\t\t\t\t\t\tbase64 += chars[byte3 & 63];\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tconst padding = 3 - (binary.length % 3 || 3);\r\n\t\t\t\t\treturn base64.slice(0, base64.length - padding) + '=='.slice(0, padding);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbase64Data = encodeBase64(result)\r\n\t\t\t}\r\n\r\n\t\t\t// 构建响应头对象\r\n\t\t\tconst responseHeaders = {\r\n\t\t\t\t\"content-type\": \"text/plain; charset=utf-8\",\r\n\t\t\t\t\"Profile-Update-Interval\": `${SUBUpdateTime}`,\r\n\t\t\t\t\"Profile-web-page-url\": request.url.includes('?') ? request.url.split('?')[0] : request.url,\r\n\t\t\t\t//\"Subscription-Userinfo\": `upload=${UD}; download=${UD}; total=${total}; expire=${expire}`,\r\n\t\t\t};\r\n\r\n\t\t\tif (订阅格式 == 'base64' || token == fakeToken) {\r\n\t\t\t\treturn new Response(base64Data, { headers: responseHeaders });\r\n\t\t\t} else if (订阅格式 == 'clash') {\r\n\t\t\t\tsubConverterUrl = `${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`;\r\n\t\t\t} else if (订阅格式 == 'singbox') {\r\n\t\t\t\tsubConverterUrl = `${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`;\r\n\t\t\t} else if (订阅格式 == 'surge') {\r\n\t\t\t\tsubConverterUrl = `${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`;\r\n\t\t\t} else if (订阅格式 == 'quanx') {\r\n\t\t\t\tsubConverterUrl = `${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`;\r\n\t\t\t} else if (订阅格式 == 'loon') {\r\n\t\t\t\tsubConverterUrl = `${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`;\r\n\t\t\t}\r\n\t\t\t//console.log(订阅转换URL);\r\n\t\t\ttry {\r\n\t\t\t\tconst subConverterResponse = await fetch(subConverterUrl, { headers: { 'User-Agent': userAgentHeader } });//订阅转换\r\n\t\t\t\tif (!subConverterResponse.ok) return new Response(base64Data, { headers: responseHeaders });\r\n\t\t\t\tlet subConverterContent = await subConverterResponse.text();\r\n\t\t\t\tif (订阅格式 == 'clash') subConverterContent = await clashFix(subConverterContent);\r\n\t\t\t\t// 只有非浏览器订阅才会返回SUBNAME\r\n\t\t\t\tif (!userAgent.includes('mozilla')) responseHeaders[\"Content-Disposition\"] = `attachment; filename*=utf-8''${encodeURIComponent(FileName)}`;\r\n\t\t\t\treturn new Response(subConverterContent, { headers: responseHeaders });\r\n\t\t\t} catch (error) {\r\n\t\t\t\treturn new Response(base64Data, { headers: responseHeaders });\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nasync function ADD(envadd) {\r\n\tvar addtext = envadd.replace(/[\t\"'|\\r\\n]+/g, '\\n').replace(/\\n+/g, '\\n');\t// 替换为换行\r\n\t//console.log(addtext);\r\n\tif (addtext.charAt(0) == '\\n') addtext = addtext.slice(1);\r\n\tif (addtext.charAt(addtext.length - 1) == '\\n') addtext = addtext.slice(0, addtext.length - 1);\r\n\tconst add = addtext.split('\\n');\r\n\t//console.log(add);\r\n\treturn add;\r\n}\r\n\r\nasync function nginx() {\r\n\tconst text = `\r\n\t<!DOCTYPE html>\r\n\t<html>\r\n\t<head>\r\n\t<title>Welcome to nginx!</title>\r\n\t<style>\r\n\t\tbody {\r\n\t\t\twidth: 35em;\r\n\t\t\tmargin: 0 auto;\r\n\t\t\tfont-family: Tahoma, Verdana, Arial, sans-serif;\r\n\t\t}\r\n\t</style>\r\n\t</head>\r\n\t<body>\r\n\t<h1>Welcome to nginx!</h1>\r\n\t<p>If you see this page, the nginx web server is successfully installed and\r\n\tworking. Further configuration is required.</p>\r\n\t\r\n\t<p>For online documentation and support please refer to\r\n\t<a href=\"http://nginx.org/\">nginx.org</a>.<br/>\r\n\tCommercial support is available at\r\n\t<a href=\"http://nginx.com/\">nginx.com</a>.</p>\r\n\t\r\n\t<p><em>Thank you for using nginx.</em></p>\r\n\t</body>\r\n\t</html>\r\n\t`\r\n\treturn text;\r\n}\r\n\r\nasync function sendMessage(type, ip, add_data = \"\") {\r\n\tif (BotToken !== '' && ChatID !== '') {\r\n\t\tlet msg = \"\";\r\n\t\tconst response = await fetch(`http://ip-api.com/json/${ip}?lang=zh-CN`);\r\n\t\tif (response.status == 200) {\r\n\t\t\tconst ipInfo = await response.json();\r\n\t\t\tmsg = `${type}\\nIP: ${ip}\\n国家: ${ipInfo.country}\\n<tg-spoiler>城市: ${ipInfo.city}\\n组织: ${ipInfo.org}\\nASN: ${ipInfo.as}\\n${add_data}`;\r\n\t\t} else {\r\n\t\t\tmsg = `${type}\\nIP: ${ip}\\n<tg-spoiler>${add_data}`;\r\n\t\t}\r\n\r\n\t\tlet url = \"https://api.telegram.org/bot\" + BotToken + \"/sendMessage?chat_id=\" + ChatID + \"&parse_mode=HTML&text=\" + encodeURIComponent(msg);\r\n\t\treturn fetch(url, {\r\n\t\t\tmethod: 'get',\r\n\t\t\theaders: {\r\n\t\t\t\t'Accept': 'text/html,application/xhtml+xml,application/xml;',\r\n\t\t\t\t'Accept-Encoding': 'gzip, deflate, br',\r\n\t\t\t\t'User-Agent': 'Mozilla/5.0 Chrome/90.0.4430.72'\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n}\r\n\r\nfunction base64Decode(str) {\r\n\tconst bytes = new Uint8Array(atob(str).split('').map(c => c.charCodeAt(0)));\r\n\tconst decoder = new TextDecoder('utf-8');\r\n\treturn decoder.decode(bytes);\r\n}\r\n\r\nasync function MD5MD5(text) {\r\n\tconst encoder = new TextEncoder();\r\n\r\n\tconst firstPass = await crypto.subtle.digest('MD5', encoder.encode(text));\r\n\tconst firstPassArray = Array.from(new Uint8Array(firstPass));\r\n\tconst firstHex = firstPassArray.map(b => b.toString(16).padStart(2, '0')).join('');\r\n\r\n\tconst secondPass = await crypto.subtle.digest('MD5', encoder.encode(firstHex.slice(7, 27)));\r\n\tconst secondPassArray = Array.from(new Uint8Array(secondPass));\r\n\tconst secondHex = secondPassArray.map(b => b.toString(16).padStart(2, '0')).join('');\r\n\r\n\treturn secondHex.toLowerCase();\r\n}\r\n\r\nfunction clashFix(content) {\r\n\tif (content.includes('wireguard') && !content.includes('remote-dns-resolve')) {\r\n\t\tlet lines;\r\n\t\tif (content.includes('\\r\\n')) {\r\n\t\t\tlines = content.split('\\r\\n');\r\n\t\t} else {\r\n\t\t\tlines = content.split('\\n');\r\n\t\t}\r\n\r\n\t\tlet result = \"\";\r\n\t\tfor (let line of lines) {\r\n\t\t\tif (line.includes('type: wireguard')) {\r\n\t\t\t\tconst 备改内容 = `, mtu: 1280, udp: true`;\r\n\t\t\t\tconst 正确内容 = `, mtu: 1280, remote-dns-resolve: true, udp: true`;\r\n\t\t\t\tresult += line.replace(new RegExp(备改内容, 'g'), 正确内容) + '\\n';\r\n\t\t\t} else {\r\n\t\t\t\tresult += line + '\\n';\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcontent = result;\r\n\t}\r\n\treturn content;\r\n}\r\n\r\nasync function proxyURL(proxyURL, url) {\r\n\tconst URLs = await ADD(proxyURL);\r\n\tconst fullURL = URLs[Math.floor(Math.random() * URLs.length)];\r\n\r\n\t// 解析目标 URL\r\n\tlet parsedURL = new URL(fullURL);\r\n\tconsole.log(parsedURL);\r\n\t// 提取并可能修改 URL 组件\r\n\tlet URLProtocol = parsedURL.protocol.slice(0, -1) || 'https';\r\n\tlet URLHostname = parsedURL.hostname;\r\n\tlet URLPathname = parsedURL.pathname;\r\n\tlet URLSearch = parsedURL.search;\r\n\r\n\t// 处理 pathname\r\n\tif (URLPathname.charAt(URLPathname.length - 1) == '/') {\r\n\t\tURLPathname = URLPathname.slice(0, -1);\r\n\t}\r\n\tURLPathname += url.pathname;\r\n\r\n\t// 构建新的 URL\r\n\tlet newURL = `${URLProtocol}://${URLHostname}${URLPathname}${URLSearch}`;\r\n\r\n\t// 反向代理请求\r\n\tlet response = await fetch(newURL);\r\n\r\n\t// 创建新的响应\r\n\tlet newResponse = new Response(response.body, {\r\n\t\tstatus: response.status,\r\n\t\tstatusText: response.statusText,\r\n\t\theaders: response.headers\r\n\t});\r\n\r\n\t// 添加自定义头部，包含 URL 信息\r\n\t//newResponse.headers.set('X-Proxied-By', 'Cloudflare Worker');\r\n\t//newResponse.headers.set('X-Original-URL', fullURL);\r\n\tnewResponse.headers.set('X-New-URL', newURL);\r\n\r\n\treturn newResponse;\r\n}\r\n\r\nasync function getSUB(api, request, 追加UA, userAgentHeader) {\r\n\tif (!api || api.length === 0) {\r\n\t\treturn [];\r\n\t} else api = [...new Set(api)]; // 去重\r\n\tlet newapi = \"\";\r\n\tlet 订阅转换URLs = \"\";\r\n\tlet 异常订阅 = \"\";\r\n\tconst controller = new AbortController(); // 创建一个AbortController实例，用于取消请求\r\n\tconst timeout = setTimeout(() => {\r\n\t\tcontroller.abort(); // 2秒后取消所有请求\r\n\t}, 2000);\r\n\r\n\ttry {\r\n\t\t// 使用Promise.allSettled等待所有API请求完成，无论成功或失败\r\n\t\tconst responses = await Promise.allSettled(api.map(apiUrl => getUrl(request, apiUrl, 追加UA, userAgentHeader).then(response => response.ok ? response.text() : Promise.reject(response))));\r\n\r\n\t\t// 遍历所有响应\r\n\t\tconst modifiedResponses = responses.map((response, index) => {\r\n\t\t\t// 检查是否请求成功\r\n\t\t\tif (response.status === 'rejected') {\r\n\t\t\t\tconst reason = response.reason;\r\n\t\t\t\tif (reason && reason.name === 'AbortError') {\r\n\t\t\t\t\treturn {\r\n\t\t\t\t\t\tstatus: '超时',\r\n\t\t\t\t\t\tvalue: null,\r\n\t\t\t\t\t\tapiUrl: api[index] // 将原始的apiUrl添加到返回对象中\r\n\t\t\t\t\t};\r\n\t\t\t\t}\r\n\t\t\t\tconsole.error(`请求失败: ${api[index]}, 错误信息: ${reason.status} ${reason.statusText}`);\r\n\t\t\t\treturn {\r\n\t\t\t\t\tstatus: '请求失败',\r\n\t\t\t\t\tvalue: null,\r\n\t\t\t\t\tapiUrl: api[index] // 将原始的apiUrl添加到返回对象中\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\treturn {\r\n\t\t\t\tstatus: response.status,\r\n\t\t\t\tvalue: response.value,\r\n\t\t\t\tapiUrl: api[index] // 将原始的apiUrl添加到返回对象中\r\n\t\t\t};\r\n\t\t});\r\n\r\n\t\tconsole.log(modifiedResponses); // 输出修改后的响应数组\r\n\r\n\t\tfor (const response of modifiedResponses) {\r\n\t\t\t// 检查响应状态是否为'fulfilled'\r\n\t\t\tif (response.status === 'fulfilled') {\r\n\t\t\t\tconst content = await response.value || 'null'; // 获取响应的内容\r\n\t\t\t\tif (content.includes('proxies:')) {\r\n\t\t\t\t\t//console.log('Clash订阅: ' + response.apiUrl);\r\n\t\t\t\t\t订阅转换URLs += \"|\" + response.apiUrl; // Clash 配置\r\n\t\t\t\t} else if (content.includes('outbounds\"') && content.includes('inbounds\"')) {\r\n\t\t\t\t\t//console.log('Singbox订阅: ' + response.apiUrl);\r\n\t\t\t\t\t订阅转换URLs += \"|\" + response.apiUrl; // Singbox 配置\r\n\t\t\t\t} else if (content.includes('://')) {\r\n\t\t\t\t\t//console.log('明文订阅: ' + response.apiUrl);\r\n\t\t\t\t\tnewapi += content + '\\n'; // 追加内容\r\n\t\t\t\t} else if (isValidBase64(content)) {\r\n\t\t\t\t\t//console.log('Base64订阅: ' + response.apiUrl);\r\n\t\t\t\t\tnewapi += base64Decode(content) + '\\n'; // 解码并追加内容\r\n\t\t\t\t} else {\r\n\t\t\t\t\tconst 异常订阅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]}`;\r\n\t\t\t\t\tconsole.log('异常订阅: ' + 异常订阅LINK);\r\n\t\t\t\t\t异常订阅 += `${异常订阅LINK}\\n`;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} catch (error) {\r\n\t\tconsole.error(error); // 捕获并输出错误信息\r\n\t} finally {\r\n\t\tclearTimeout(timeout); // 清除定时器\r\n\t}\r\n\r\n\tconst 订阅内容 = await ADD(newapi + 异常订阅); // 将处理后的内容转换为数组\r\n\t// 返回处理后的结果\r\n\treturn [订阅内容, 订阅转换URLs];\r\n}\r\n\r\nasync function getUrl(request, targetUrl, 追加UA, userAgentHeader) {\r\n\t// 设置自定义 User-Agent\r\n\tconst newHeaders = new Headers(request.headers);\r\n\tnewHeaders.set(\"User-Agent\", `${atob('djJyYXlOLzYuNDU=')} cmliu/CF-Workers-SUB ${追加UA}(${userAgentHeader})`);\r\n\r\n\t// 构建新的请求对象\r\n\tconst modifiedRequest = new Request(targetUrl, {\r\n\t\tmethod: request.method,\r\n\t\theaders: newHeaders,\r\n\t\tbody: request.method === \"GET\" ? null : request.body,\r\n\t\tredirect: \"follow\",\r\n\t\tcf: {\r\n\t\t\t// 忽略SSL证书验证\r\n\t\t\tinsecureSkipVerify: true,\r\n\t\t\t// 允许自签名证书\r\n\t\t\tallowUntrusted: true,\r\n\t\t\t// 禁用证书验证\r\n\t\t\tvalidateCertificate: false\r\n\t\t}\r\n\t});\r\n\r\n\t// 输出请求的详细信息\r\n\tconsole.log(`请求URL: ${targetUrl}`);\r\n\tconsole.log(`请求头: ${JSON.stringify([...newHeaders])}`);\r\n\tconsole.log(`请求方法: ${request.method}`);\r\n\tconsole.log(`请求体: ${request.method === \"GET\" ? null : request.body}`);\r\n\r\n\t// 发送请求并返回响应\r\n\treturn fetch(modifiedRequest);\r\n}\r\n\r\nfunction isValidBase64(str) {\r\n\t// 先移除所有空白字符(空格、换行、回车等)\r\n\tconst cleanStr = str.replace(/\\s/g, '');\r\n\tconst base64Regex = /^[A-Za-z0-9+/=]+$/;\r\n\treturn base64Regex.test(cleanStr);\r\n}\r\n\r\nasync function 迁移地址列表(env, txt = 'ADD.txt') {\r\n\tconst 旧数据 = await env.KV.get(`/${txt}`);\r\n\tconst 新数据 = await env.KV.get(txt);\r\n\r\n\tif (旧数据 && !新数据) {\r\n\t\t// 写入新位置\r\n\t\tawait env.KV.put(txt, 旧数据);\r\n\t\t// 删除旧数据\r\n\t\tawait env.KV.delete(`/${txt}`);\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nasync function KV(request, env, txt = 'ADD.txt', guest) {\r\n\tconst url = new URL(request.url);\r\n\ttry {\r\n\t\t// POST请求处理\r\n\t\tif (request.method === \"POST\") {\r\n\t\t\tif (!env.KV) return new Response(\"未绑定KV空间\", { status: 400 });\r\n\t\t\ttry {\r\n\t\t\t\tconst content = await request.text();\r\n\t\t\t\tawait env.KV.put(txt, content);\r\n\t\t\t\treturn new Response(\"保存成功\");\r\n\t\t\t} catch (error) {\r\n\t\t\t\tconsole.error('保存KV时发生错误:', error);\r\n\t\t\t\treturn new Response(\"保存失败: \" + error.message, { status: 500 });\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// GET请求部分\r\n\t\tlet content = '';\r\n\t\tlet hasKV = !!env.KV;\r\n\r\n\t\tif (hasKV) {\r\n\t\t\ttry {\r\n\t\t\t\tcontent = await env.KV.get(txt) || '';\r\n\t\t\t} catch (error) {\r\n\t\t\t\tconsole.error('读取KV时发生错误:', error);\r\n\t\t\t\tcontent = '读取数据时发生错误: ' + error.message;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst html = `\r\n\t\t\t<!DOCTYPE html>\r\n\t\t\t<html>\r\n\t\t\t\t<head>\r\n\t\t\t\t\t<title>${FileName} 订阅编辑</title>\r\n\t\t\t\t\t<meta charset=\"utf-8\">\r\n\t\t\t\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n\t\t\t\t\t<style>\r\n\t\t\t\t\t\tbody {\r\n\t\t\t\t\t\t\tmargin: 0;\r\n\t\t\t\t\t\t\tpadding: 15px; /* 调整padding */\r\n\t\t\t\t\t\t\tbox-sizing: border-box;\r\n\t\t\t\t\t\t\tfont-size: 13px; /* 设置全局字体大小 */\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.editor-container {\r\n\t\t\t\t\t\t\twidth: 100%;\r\n\t\t\t\t\t\t\tmax-width: 100%;\r\n\t\t\t\t\t\t\tmargin: 0 auto;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.editor {\r\n\t\t\t\t\t\t\twidth: 100%;\r\n\t\t\t\t\t\t\theight: 300px; /* 调整高度 */\r\n\t\t\t\t\t\t\tmargin: 15px 0; /* 调整margin */\r\n\t\t\t\t\t\t\tpadding: 10px; /* 调整padding */\r\n\t\t\t\t\t\t\tbox-sizing: border-box;\r\n\t\t\t\t\t\t\tborder: 1px solid #ccc;\r\n\t\t\t\t\t\t\tborder-radius: 4px;\r\n\t\t\t\t\t\t\tfont-size: 13px;\r\n\t\t\t\t\t\t\tline-height: 1.5;\r\n\t\t\t\t\t\t\toverflow-y: auto;\r\n\t\t\t\t\t\t\tresize: none;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.save-container {\r\n\t\t\t\t\t\t\tmargin-top: 8px; /* 调整margin */\r\n\t\t\t\t\t\t\tdisplay: flex;\r\n\t\t\t\t\t\t\talign-items: center;\r\n\t\t\t\t\t\t\tgap: 10px; /* 调整gap */\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.save-btn, .back-btn {\r\n\t\t\t\t\t\t\tpadding: 6px 15px; /* 调整padding */\r\n\t\t\t\t\t\t\tcolor: white;\r\n\t\t\t\t\t\t\tborder: none;\r\n\t\t\t\t\t\t\tborder-radius: 4px;\r\n\t\t\t\t\t\t\tcursor: pointer;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.save-btn {\r\n\t\t\t\t\t\t\tbackground: #4CAF50;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.save-btn:hover {\r\n\t\t\t\t\t\t\tbackground: #45a049;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.back-btn {\r\n\t\t\t\t\t\t\tbackground: #666;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.back-btn:hover {\r\n\t\t\t\t\t\t\tbackground: #555;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t.save-status {\r\n\t\t\t\t\t\t\tcolor: #666;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t</style>\r\n\t\t\t\t\t<script src=\"https://cdn.jsdelivr.net/npm/@keeex/qrcodejs-kx@1.0.2/qrcode.min.js\"></script>\r\n\t\t\t\t</head>\r\n\t\t\t\t<body>\r\n\t\t\t\t\t################################################################<br>\r\n\t\t\t\t\tSubscribe / sub 订阅地址, 点击链接自动 <strong>复制订阅链接</strong> 并 <strong>生成订阅二维码</strong> <br>\r\n\t\t\t\t\t---------------------------------------------------------------<br>\r\n\t\t\t\t\t自适应订阅地址:<br>\r\n\t\t\t\t\t<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>\r\n\t\t\t\t\t<div id=\"qrcode_0\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\tBase64订阅地址:<br>\r\n\t\t\t\t\t<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>\r\n\t\t\t\t\t<div id=\"qrcode_1\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\tclash订阅地址:<br>\r\n\t\t\t\t\t<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>\r\n\t\t\t\t\t<div id=\"qrcode_2\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\tsingbox订阅地址:<br>\r\n\t\t\t\t\t<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>\r\n\t\t\t\t\t<div id=\"qrcode_3\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\tsurge订阅地址:<br>\r\n\t\t\t\t\t<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>\r\n\t\t\t\t\t<div id=\"qrcode_4\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\tloon订阅地址:<br>\r\n\t\t\t\t\t<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>\r\n\t\t\t\t\t<div id=\"qrcode_5\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\t&nbsp;&nbsp;<strong><a href=\"javascript:void(0);\" id=\"noticeToggle\" onclick=\"toggleNotice()\">查看访客订阅∨</a></strong><br>\r\n\t\t\t\t\t<div id=\"noticeContent\" class=\"notice-content\" style=\"display: none;\">\r\n\t\t\t\t\t\t---------------------------------------------------------------<br>\r\n\t\t\t\t\t\t访客订阅只能使用订阅功能，无法查看配置页！<br>\r\n\t\t\t\t\t\tGUEST（访客订阅TOKEN）: <strong>${guest}</strong><br>\r\n\t\t\t\t\t\t---------------------------------------------------------------<br>\r\n\t\t\t\t\t\t自适应订阅地址:<br>\r\n\t\t\t\t\t\t<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>\r\n\t\t\t\t\t\t<div id=\"guest_0\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\t\tBase64订阅地址:<br>\r\n\t\t\t\t\t\t<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>\r\n\t\t\t\t\t\t<div id=\"guest_1\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\t\tclash订阅地址:<br>\r\n\t\t\t\t\t\t<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>\r\n\t\t\t\t\t\t<div id=\"guest_2\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\t\tsingbox订阅地址:<br>\r\n\t\t\t\t\t\t<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>\r\n\t\t\t\t\t\t<div id=\"guest_3\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\t\tsurge订阅地址:<br>\r\n\t\t\t\t\t\t<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>\r\n\t\t\t\t\t\t<div id=\"guest_4\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\t\tloon订阅地址:<br>\r\n\t\t\t\t\t\t<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>\r\n\t\t\t\t\t\t<div id=\"guest_5\" style=\"margin: 10px 10px 10px 10px;\"></div>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t---------------------------------------------------------------<br>\r\n\t\t\t\t\t################################################################<br>\r\n\t\t\t\t\t订阅转换配置<br>\r\n\t\t\t\t\t---------------------------------------------------------------<br>\r\n\t\t\t\t\tSUBAPI（订阅转换后端）: <strong>${subProtocol}://${subConverter}</strong><br>\r\n\t\t\t\t\tSUBCONFIG（订阅转换配置文件）: <strong>${subConfig}</strong><br>\r\n\t\t\t\t\t---------------------------------------------------------------<br>\r\n\t\t\t\t\t################################################################<br>\r\n\t\t\t\t\t${FileName} 汇聚订阅编辑: \r\n\t\t\t\t\t<div class=\"editor-container\">\r\n\t\t\t\t\t\t${hasKV ? `\r\n\t\t\t\t\t\t<textarea class=\"editor\" \r\n\t\t\t\t\t\t\tplaceholder=\"${decodeURIComponent(atob('TElOSyVFNyVBNCVCQSVFNCVCRSU4QiVFRiVCQyU4OCVFNCVCOCU4MCVFOCVBMSU4QyVFNCVCOCU4MCVFNCVCOCVBQSVFOCU4QSU4MiVFNyU4MiVCOSVFOSU5MyVCRSVFNiU4RSVBNSVFNSU4RCVCMyVFNSU4RiVBRiVFRiVCQyU4OSVFRiVCQyU5QQp2bGVzcyUzQSUyRiUyRjI0NmFhNzk1LTA2MzctNGY0Yy04ZjY0LTJjOGZiMjRjMWJhZCU0MDEyNy4wLjAuMSUzQTEyMzQlM0ZlbmNyeXB0aW9uJTNEbm9uZSUyNnNlY3VyaXR5JTNEdGxzJTI2c25pJTNEVEcuQ01MaXVzc3NzLmxvc2V5b3VyaXAuY29tJTI2YWxsb3dJbnNlY3VyZSUzRDElMjZ0eXBlJTNEd3MlMjZob3N0JTNEVEcuQ01MaXVzc3NzLmxvc2V5b3VyaXAuY29tJTI2cGF0aCUzRCUyNTJGJTI1M0ZlZCUyNTNEMjU2MCUyM0NGbmF0CnRyb2phbiUzQSUyRiUyRmFhNmRkZDJmLWQxY2YtNGE1Mi1iYTFiLTI2NDBjNDFhNzg1NiU0MDIxOC4xOTAuMjMwLjIwNyUzQTQxMjg4JTNGc2VjdXJpdHklM0R0bHMlMjZzbmklM0RoazEyLmJpbGliaWxpLmNvbSUyNmFsbG93SW5zZWN1cmUlM0QxJTI2dHlwZSUzRHRjcCUyNmhlYWRlclR5cGUlM0Rub25lJTIzSEsKc3MlM0ElMkYlMkZZMmhoWTJoaE1qQXRhV1YwWmkxd2IyeDVNVE13TlRveVJYUlFjVzQyU0ZscVZVNWpTRzlvVEdaVmNFWlJkMjVtYWtORFVUVnRhREZ0U21SRlRVTkNkV04xVjFvNVVERjFaR3RTUzBodVZuaDFielUxYXpGTFdIb3lSbTgyYW5KbmRERTRWelkyYjNCMGVURmxOR0p0TVdwNlprTm1RbUklMjUzRCU0MDg0LjE5LjMxLjYzJTNBNTA4NDElMjNERQoKCiVFOCVBRSVBMiVFOSU5OCU4NSVFOSU5MyVCRSVFNiU4RSVBNSVFNyVBNCVCQSVFNCVCRSU4QiVFRiVCQyU4OCVFNCVCOCU4MCVFOCVBMSU4QyVFNCVCOCU4MCVFNiU5RCVBMSVFOCVBRSVBMiVFOSU5OCU4NSVFOSU5MyVCRSVFNiU4RSVBNSVFNSU4RCVCMyVFNSU4RiVBRiVFRiVCQyU4OSVFRiVCQyU5QQpodHRwcyUzQSUyRiUyRnN1Yi54Zi5mcmVlLmhyJTJGYXV0bw=='))}\"\r\n\t\t\t\t\t\t\tid=\"content\">${content}</textarea>\r\n\t\t\t\t\t\t<div class=\"save-container\">\r\n\t\t\t\t\t\t\t<button class=\"save-btn\" onclick=\"saveContent(this)\">保存</button>\r\n\t\t\t\t\t\t\t<span class=\"save-status\" id=\"saveStatus\"></span>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t` : '<p>请绑定 <strong>变量名称</strong> 为 <strong>KV</strong> 的KV命名空间</p>'}\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t<br>\r\n\t\t\t\t\t################################################################<br>\r\n\t\t\t\t\t${decodeURIComponent(atob('dGVsZWdyYW0lMjAlRTQlQkElQTQlRTYlQjUlODElRTclQkUlQTQlMjAlRTYlOEElODAlRTYlOUMlQUYlRTUlQTQlQTclRTQlQkQlQUMlN0UlRTUlOUMlQTglRTclQkElQkYlRTUlOEYlOTElRTclODklOEMhJTNDYnIlM0UKJTNDYSUyMGhyZWYlM0QlMjdodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlMjclM0VodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlM0MlMkZhJTNFJTNDYnIlM0UKLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tJTNDYnIlM0UKZ2l0aHViJTIwJUU5JUExJUI5JUU3JTlCJUFFJUU1JTlDJUIwJUU1JTlEJTgwJTIwU3RhciFTdGFyIVN0YXIhISElM0NiciUzRQolM0NhJTIwaHJlZiUzRCUyN2h0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmNtbGl1JTJGQ0YtV29ya2Vycy1TVUIlMjclM0VodHRwcyUzQSUyRiUyRmdpdGh1Yi5jb20lMkZjbWxpdSUyRkNGLVdvcmtlcnMtU1VCJTNDJTJGYSUzRSUzQ2JyJTNFCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSUzQ2JyJTNFCiUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMyUyMw=='))}\r\n\t\t\t\t\t<br><br>UA: <strong>${request.headers.get('User-Agent')}</strong>\r\n\t\t\t\t\t<script>\r\n\t\t\t\t\tfunction copyToClipboard(text, qrcode) {\r\n\t\t\t\t\t\tnavigator.clipboard.writeText(text).then(() => {\r\n\t\t\t\t\t\t\talert('已复制到剪贴板');\r\n\t\t\t\t\t\t}).catch(err => {\r\n\t\t\t\t\t\t\tconsole.error('复制失败:', err);\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\tconst qrcodeDiv = document.getElementById(qrcode);\r\n\t\t\t\t\t\tqrcodeDiv.innerHTML = '';\r\n\t\t\t\t\t\tnew QRCode(qrcodeDiv, {\r\n\t\t\t\t\t\t\ttext: text,\r\n\t\t\t\t\t\t\twidth: 220, // 调整宽度\r\n\t\t\t\t\t\t\theight: 220, // 调整高度\r\n\t\t\t\t\t\t\tcolorDark: \"#000000\", // 二维码颜色\r\n\t\t\t\t\t\t\tcolorLight: \"#ffffff\", // 背景颜色\r\n\t\t\t\t\t\t\tcorrectLevel: QRCode.CorrectLevel.Q, // 设置纠错级别\r\n\t\t\t\t\t\t\tscale: 1 // 调整像素颗粒度\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\tif (document.querySelector('.editor')) {\r\n\t\t\t\t\t\tlet timer;\r\n\t\t\t\t\t\tconst textarea = document.getElementById('content');\r\n\t\t\t\t\t\tconst originalContent = textarea.value;\r\n\t\t\r\n\t\t\t\t\t\tfunction goBack() {\r\n\t\t\t\t\t\t\tconst currentUrl = window.location.href;\r\n\t\t\t\t\t\t\tconst parentUrl = currentUrl.substring(0, currentUrl.lastIndexOf('/'));\r\n\t\t\t\t\t\t\twindow.location.href = parentUrl;\r\n\t\t\t\t\t\t}\r\n\t\t\r\n\t\t\t\t\t\tfunction replaceFullwidthColon() {\r\n\t\t\t\t\t\t\tconst text = textarea.value;\r\n\t\t\t\t\t\t\ttextarea.value = text.replace(/：/g, ':');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tfunction saveContent(button) {\r\n\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\tconst updateButtonText = (step) => {\r\n\t\t\t\t\t\t\t\t\tbutton.textContent = \\`保存中: \\${step}\\`;\r\n\t\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t\t\t// 检测是否为iOS设备\r\n\t\t\t\t\t\t\t\tconst isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t// 仅在非iOS设备上执行replaceFullwidthColon\r\n\t\t\t\t\t\t\t\tif (!isIOS) {\r\n\t\t\t\t\t\t\t\t\treplaceFullwidthColon();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tupdateButtonText('开始保存');\r\n\t\t\t\t\t\t\t\tbutton.disabled = true;\r\n\r\n\t\t\t\t\t\t\t\t// 获取textarea内容和原始内容\r\n\t\t\t\t\t\t\t\tconst textarea = document.getElementById('content');\r\n\t\t\t\t\t\t\t\tif (!textarea) {\r\n\t\t\t\t\t\t\t\t\tthrow new Error('找不到文本编辑区域');\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tupdateButtonText('获取内容');\r\n\t\t\t\t\t\t\t\tlet newContent;\r\n\t\t\t\t\t\t\t\tlet originalContent;\r\n\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\tnewContent = textarea.value || '';\r\n\t\t\t\t\t\t\t\t\toriginalContent = textarea.defaultValue || '';\r\n\t\t\t\t\t\t\t\t} catch (e) {\r\n\t\t\t\t\t\t\t\t\tconsole.error('获取内容错误:', e);\r\n\t\t\t\t\t\t\t\t\tthrow new Error('无法获取编辑内容');\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\tupdateButtonText('准备状态更新函数');\r\n\t\t\t\t\t\t\t\tconst updateStatus = (message, isError = false) => {\r\n\t\t\t\t\t\t\t\t\tconst statusElem = document.getElementById('saveStatus');\r\n\t\t\t\t\t\t\t\t\tif (statusElem) {\r\n\t\t\t\t\t\t\t\t\t\tstatusElem.textContent = message;\r\n\t\t\t\t\t\t\t\t\t\tstatusElem.style.color = isError ? 'red' : '#666';\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\tupdateButtonText('准备按钮重置函数');\r\n\t\t\t\t\t\t\t\tconst resetButton = () => {\r\n\t\t\t\t\t\t\t\t\tbutton.textContent = '保存';\r\n\t\t\t\t\t\t\t\t\tbutton.disabled = false;\r\n\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\tif (newContent !== originalContent) {\r\n\t\t\t\t\t\t\t\t\tupdateButtonText('发送保存请求');\r\n\t\t\t\t\t\t\t\t\tfetch(window.location.href, {\r\n\t\t\t\t\t\t\t\t\t\tmethod: 'POST',\r\n\t\t\t\t\t\t\t\t\t\tbody: newContent,\r\n\t\t\t\t\t\t\t\t\t\theaders: {\r\n\t\t\t\t\t\t\t\t\t\t\t'Content-Type': 'text/plain;charset=UTF-8'\r\n\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\tcache: 'no-cache'\r\n\t\t\t\t\t\t\t\t\t})\r\n\t\t\t\t\t\t\t\t\t.then(response => {\r\n\t\t\t\t\t\t\t\t\t\tupdateButtonText('检查响应状态');\r\n\t\t\t\t\t\t\t\t\t\tif (!response.ok) {\r\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\\`HTTP error! status: \\${response.status}\\`);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tupdateButtonText('更新保存状态');\r\n\t\t\t\t\t\t\t\t\t\tconst now = new Date().toLocaleString();\r\n\t\t\t\t\t\t\t\t\t\tdocument.title = \\`编辑已保存 \\${now}\\`;\r\n\t\t\t\t\t\t\t\t\t\tupdateStatus(\\`已保存 \\${now}\\`);\r\n\t\t\t\t\t\t\t\t\t})\r\n\t\t\t\t\t\t\t\t\t.catch(error => {\r\n\t\t\t\t\t\t\t\t\t\tupdateButtonText('处理错误');\r\n\t\t\t\t\t\t\t\t\t\tconsole.error('Save error:', error);\r\n\t\t\t\t\t\t\t\t\t\tupdateStatus(\\`保存失败: \\${error.message}\\`, true);\r\n\t\t\t\t\t\t\t\t\t})\r\n\t\t\t\t\t\t\t\t\t.finally(() => {\r\n\t\t\t\t\t\t\t\t\t\tresetButton();\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tupdateButtonText('检查内容变化');\r\n\t\t\t\t\t\t\t\t\tupdateStatus('内容未变化');\r\n\t\t\t\t\t\t\t\t\tresetButton();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\t\t\tconsole.error('保存过程出错:', error);\r\n\t\t\t\t\t\t\t\tbutton.textContent = '保存';\r\n\t\t\t\t\t\t\t\tbutton.disabled = false;\r\n\t\t\t\t\t\t\t\tconst statusElem = document.getElementById('saveStatus');\r\n\t\t\t\t\t\t\t\tif (statusElem) {\r\n\t\t\t\t\t\t\t\t\tstatusElem.textContent = \\`错误: \\${error.message}\\`;\r\n\t\t\t\t\t\t\t\t\tstatusElem.style.color = 'red';\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\r\n\t\t\t\t\t\ttextarea.addEventListener('blur', saveContent);\r\n\t\t\t\t\t\ttextarea.addEventListener('input', () => {\r\n\t\t\t\t\t\t\tclearTimeout(timer);\r\n\t\t\t\t\t\t\ttimer = setTimeout(saveContent, 5000);\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfunction toggleNotice() {\r\n\t\t\t\t\t\tconst noticeContent = document.getElementById('noticeContent');\r\n\t\t\t\t\t\tconst noticeToggle = document.getElementById('noticeToggle');\r\n\t\t\t\t\t\tif (noticeContent.style.display === 'none' || noticeContent.style.display === '') {\r\n\t\t\t\t\t\t\tnoticeContent.style.display = 'block';\r\n\t\t\t\t\t\t\tnoticeToggle.textContent = '隐藏访客订阅∧';\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tnoticeContent.style.display = 'none';\r\n\t\t\t\t\t\t\tnoticeToggle.textContent = '查看访客订阅∨';\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\t\t// 初始化 noticeContent 的 display 属性\r\n\t\t\t\t\tdocument.addEventListener('DOMContentLoaded', () => {\r\n\t\t\t\t\t\tdocument.getElementById('noticeContent').style.display = 'none';\r\n\t\t\t\t\t});\r\n\t\t\t\t\t</script>\r\n\t\t\t\t</body>\r\n\t\t\t</html>\r\n\t\t`;\r\n\r\n\t\treturn new Response(html, {\r\n\t\t\theaders: { \"Content-Type\": \"text/html;charset=utf-8\" }\r\n\t\t});\r\n\t} catch (error) {\r\n\t\tconsole.error('处理请求时发生错误:', error);\r\n\t\treturn new Response(\"服务器错误: \" + error.message, {\r\n\t\t\tstatus: 500,\r\n\t\t\theaders: { \"Content-Type\": \"text/plain;charset=utf-8\" }\r\n\t\t});\r\n\t}\r\n}"
  },
  {
    "path": "wrangler.toml",
    "content": "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#binding = \"KV\"\t\t\t#KV绑定名默认不可修改\r\n#id = \"7dbef248fcc547d39689967f91f5f46f\"\t\t\t\t\t#KV据库id"
  }
]