Repository: kobe-koto/EdgeSub Branch: main Commit: f4c00115a68b Files: 87 Total size: 435.9 KB Directory structure: gitextract_a6ww6u21/ ├── .gitattributes ├── .gitignore ├── LICENSE ├── astro.config.ts ├── bun.lockb ├── functions/ │ ├── _middleware.js │ ├── internal/ │ │ ├── Converter/ │ │ │ ├── getClashMetaConfig.js │ │ │ └── getSingBoxConfig.ts │ │ ├── Dumpers/ │ │ │ ├── clash-meta.ts │ │ │ ├── share-link.js │ │ │ └── sing-box.js │ │ ├── Parsers/ │ │ │ ├── clash-meta.js │ │ │ ├── share-link.js │ │ │ └── sing-box.js │ │ ├── RuleProviderReader/ │ │ │ ├── Readers/ │ │ │ │ └── ini.js │ │ │ └── main.js │ │ ├── configs.ts │ │ ├── data/ │ │ │ ├── rule/ │ │ │ │ ├── MetaToSingLogicalRule.ts │ │ │ │ └── MetaToSingMapping.ts │ │ │ └── ruleset/ │ │ │ └── transformGeoRef.ts │ │ ├── getParsedSubData.ts │ │ ├── types/ │ │ │ └── ClashMetaConfig.ts │ │ └── utils/ │ │ ├── TrulyAssign.js │ │ ├── fetchCached.ts │ │ ├── parseContentDisposition.ts │ │ └── removeUndefinedFields.ts │ ├── ruleset/ │ │ ├── preprocessor/ │ │ │ └── sing-box.ts │ │ └── proxy.ts │ ├── short/ │ │ ├── admin-password/ │ │ │ ├── set.ts │ │ │ └── status.ts │ │ ├── delete/ │ │ │ └── [id].ts │ │ ├── get/ │ │ │ └── [id].ts │ │ ├── list.ts │ │ ├── put.ts │ │ ├── token-reset/ │ │ │ └── [id].ts │ │ └── utils/ │ │ └── defaultHeader.ts │ └── sub/ │ ├── base64.js │ ├── clash-meta.js │ ├── debug.js │ ├── share-link.js │ └── sing-box.js ├── package.json ├── public/ │ ├── basic-config/ │ │ ├── mihomo.yaml │ │ └── sing-box.jsonc │ └── minimal_remote_rules.ini ├── readme.md ├── src/ │ ├── components/ │ │ ├── NavBar.astro │ │ ├── backendIndicator.astro │ │ ├── data-input.astro │ │ ├── index/ │ │ │ └── SubURLGenerator.astro │ │ ├── k-dropdown.astro │ │ ├── layouts/ │ │ │ └── SEOComponent.astro │ │ └── shorter/ │ │ ├── k-shorter.astro │ │ ├── short-destroyer.astro │ │ ├── short-editor.astro │ │ ├── short-token-reset.astro │ │ ├── shorter-list.astro │ │ └── shorter-password.astro │ ├── config/ │ │ ├── AvalibleOptoutFormat.ts │ │ └── RuleProviders.ts │ ├── env.d.ts │ ├── layouts/ │ │ └── base.astro │ ├── pages/ │ │ ├── index.astro │ │ └── shorter/ │ │ ├── admin.astro │ │ ├── create.astro │ │ ├── destory.astro │ │ ├── edit.astro │ │ ├── list.astro │ │ └── reset-token.astro │ ├── scripts/ │ │ ├── components/ │ │ │ ├── data-input.ts │ │ │ ├── k-dropdown.ts │ │ │ ├── k-suburl-generator.ts │ │ │ └── shorter/ │ │ │ ├── k-shorter.ts │ │ │ ├── short-destroyer.ts │ │ │ ├── short-editor.ts │ │ │ ├── short-token-reset.ts │ │ │ ├── shorter-list.ts │ │ │ └── shorter-password.ts │ │ └── utils/ │ │ ├── copy.ts │ │ ├── filterObject.ts │ │ └── getDefaultBackend.ts │ └── styles/ │ ├── app.scss │ ├── import.css │ ├── index.scss │ └── main.scss ├── tsconfig.json └── types/ └── worker-configuration.d.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto ================================================ FILE: .gitignore ================================================ # build output dist/ _worker.bundle # generated types .astro/ .wrangler/ # dependencies node_modules/ # logs npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* # IDE files .idea/ .vscode/ # environment variables .env .env.production # macOS-specific files .DS_Store # others *.bak *.kate-swap wrangler.toml ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: astro.config.ts ================================================ import { defineConfig } from "astro/config"; // astro integrations import compress from "astro-compress"; import icon from "astro-icon"; // vite plugins import tailwindcss from "@tailwindcss/vite"; export default defineConfig({ prefetch: true, integrations: [ compress(), icon(), ], vite: { css: { preprocessorOptions: { scss: { api: "modern-compiler" } } }, plugins: [ tailwindcss(), ], // log dropping not enabled by default cuz this project will never be production ready lol // esbuild: { // drop: ["console", "debugger"], // }, }, }); ================================================ FILE: functions/_middleware.js ================================================ async function RequestInfo (context) { const Path = (new URL(context.request.url)).pathname; console.info("[Main] Processing request...") console.info(`[Main] Request type: ${Path}`) return await context.next(); } async function PerformanceCounting (context) { const __startTime = performance.now(); const response = await context.next(); console.info(`[PerformanceCounting] we've done this glory, totally wasting ${performance.now() - __startTime}ms.`) return response; } export const onRequest = [RequestInfo, PerformanceCounting]; ================================================ FILE: functions/internal/Converter/getClashMetaConfig.js ================================================ import { TrulyAssign } from "../utils/TrulyAssign"; import { parseYAML } from "confbox"; import ClashMetaDumper from "../Dumpers/clash-meta.js"; const BasicConfig = { isUDP: true, isSSUoT: false, isInsecure: true, RuleProvider: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini", RuleProvidersProxy: false, BaseConfig: "http://localhost:4321/basic-config/mihomo.yaml", // BaseConfig: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/basic-config/mihomo.yaml", isForcedRefresh: false } import { RuleProviderReader } from "../RuleProviderReader/main.js"; export async function getClashMetaConfig ( Proxies, EdgeSubDB, PassedConfig = {}, ) { const Config = TrulyAssign(BasicConfig, PassedConfig); console.log(`[getClashMetaConfig] fetching base config from remote (${Config.BaseConfig})`) const ClashConfig = parseYAML(await fetch(Config.BaseConfig).then(res => res.text())); console.log("[getClashMetaConfig] fetched base config", ClashConfig) let RuleProvider = await (new RuleProviderReader(Config.RuleProvider)).Process(EdgeSubDB, Config.isForcedRefresh) let Dumper = new ClashMetaDumper(Config.isUDP, Config.isSSUoT, Config.isInsecure) // validate proxies Proxies = Proxies.map(i => { if (Dumper.__validate(i)) { i.Hostname = i.Hostname.replace(/(^\[|\]$)/g, ""); return i; } }).filter(i => !!i); // append proxies ClashConfig.proxies = Proxies.map(i => Dumper[i.__Type](i)); // Append proxy groups. ClashConfig["proxy-groups"] = [] for (let i of RuleProvider.ProxyGroup) { // get Matched Proxies let MatchedProxies = []; for (let t of i.RegExps) { MatchedProxies = [ ...MatchedProxies, ...Proxies.filter( loc => loc.__Remark.match(new RegExp(t)) ) ] } // unique proxy MatchedProxies = Array.from(new Set(MatchedProxies)); // generate proxies list let GroupProxies = []; for (let t of i.GroupSelectors) { GroupProxies.push(t.replace(/^\[\]/, "")) } for (let t of MatchedProxies) { GroupProxies.push(t.__Remark) } if (MatchedProxies.length + i.GroupSelectors.length === 0) { // add fallback selector if no selector can be added GroupProxies.push("DIRECT") GroupProxies.push("REJECT") } //generate proxy group let ProxyGroup = {} ProxyGroup.name = i.name; ProxyGroup.type = i.type; if (i.type === "url-test" || i.type === "load-balance" || i.type === "fallback") { ProxyGroup.url = i.TestConfig.TestURL; ProxyGroup.interval = i.TestConfig.Interval; } if (i.type === "url-test") { ProxyGroup.tolerance = i.TestConfig.Tolerance; } ProxyGroup.proxies = GroupProxies; // append proxy group to config ClashConfig["proxy-groups"].push(ProxyGroup) } // append rule providers ClashConfig["rule-providers"] = {}; let RuleProvidersMapping = {}; // { URL: ID }[] for (let i in RuleProvider.RuleProviders) { for (let t in RuleProvider.RuleProviders[i]) { const RuleProviderPayload = RuleProvider.RuleProviders[i][t]; const RuleProviderID = `${i}__${t}`; RuleProvidersMapping[RuleProviderPayload] = RuleProviderID; let RuleProviderURL; if (Config.RuleProvidersProxy) { let RuleProviderURLObject = new URL(Config.RuleProvidersProxy); RuleProviderURLObject.pathname = "/ruleset/proxy" RuleProviderURLObject.search = "" RuleProviderURLObject.searchParams.append("target", RuleProviderPayload) RuleProviderURL = RuleProviderURLObject.toString() } else { RuleProviderURL = RuleProviderPayload; } ClashConfig["rule-providers"][RuleProviderID] = { type: "http", behavior: "classical", url: RuleProviderURL, format: (RuleProviderPayload.endsWith(".yaml") || RuleProviderPayload.endsWith(".yml")) ? "yaml" : "text", interval: 21600 } } } // Append rule sets; ClashConfig.rules = [] for (let i of RuleProvider.Rules) { const rulesetBreakdown = i.split(",") const id = rulesetBreakdown[0]; let payload = rulesetBreakdown.slice(1).join(","); if (payload.startsWith("http://") || payload.startsWith("https://")) { payload = `RULE-SET,${RuleProvidersMapping[payload]}`; } ClashConfig.rules.push(`${payload},${id}`) } return ClashConfig; } ================================================ FILE: functions/internal/Converter/getSingBoxConfig.ts ================================================ import { TrulyAssign } from "../utils/TrulyAssign"; import SingBoxDumper from "../Dumpers/sing-box.js"; import { MetaToSingRuleMapping } from "../data/rule/MetaToSingMapping.ts"; import { MetaToSingLogicalRule } from "../data/rule/MetaToSingLogicalRule.ts"; import { transformGeoRef } from "../data/ruleset/transformGeoRef.ts"; import { parseJSON5 } from "confbox"; const BasicConfig = { isUDP: true, isSSUoT: true, isInsecure: true, RuleProvider: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini", RuleProvidersProxy: true, // this is required BaseConfig: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/basic-config/sing-box.jsonc", isForcedRefresh: false } import { RuleProviderReader } from "../RuleProviderReader/main.js"; import mod from "astro/zod"; export async function getSingBoxConfig ( Proxies, EdgeSubDB, PassedConfig = {}, ) { const Config = TrulyAssign(BasicConfig, PassedConfig); if (!Config.RuleProvidersProxy) { throw new Error("RuleProvidersProxy is required for SingBox config generation."); } console.log(`[getSingBoxConfig] fetching base config from remote (${Config.BaseConfig})`) const SingBoxConfig = parseJSON5(await fetch(Config.BaseConfig).then(res => res.text())) as any; console.log("[getSingBoxConfig] fetched base config", SingBoxConfig) // Process OutBounds let Dumper = new SingBoxDumper(Config.isUDP, Config.isSSUoT, Config.isInsecure); // validate proxies Proxies = Proxies.map(i => { if (Dumper.__validate(i)) { return i; } }).filter(i => !!i); // append proxies SingBoxConfig.outbounds = SingBoxConfig.outbounds || []; SingBoxConfig.outbounds = [ ...SingBoxConfig.outbounds, ...Proxies.map(i => Dumper[i.__Type](i)) ] // check for essential outbounds if (!SingBoxConfig.outbounds.find(i => i.tag === "DIRECT")) { SingBoxConfig.outbounds.push({ type: "direct", tag: "DIRECT" }) } if (!SingBoxConfig.outbounds.find(i => i.tag === "REJECT")) { SingBoxConfig.outbounds.push({ type: "block", tag: "REJECT" }) } // proxy clash external ui archive if (SingBoxConfig.experimental.clash_api.external_ui_download_url) { let ClashWebUIURLObject = new URL(Config.RuleProvidersProxy); ClashWebUIURLObject.pathname = "/ruleset/proxy"; ClashWebUIURLObject.search = ""; ClashWebUIURLObject.searchParams.append("target", SingBoxConfig.experimental.clash_api.external_ui_download_url); SingBoxConfig.experimental.clash_api.external_ui_download_url = ClashWebUIURLObject.toString(); } // RULES!; let RuleProvider = await (new RuleProviderReader(Config.RuleProvider)).Process(EdgeSubDB, Config.isForcedRefresh) console.log(RuleProvider) // Append proxy groups. // SingBoxConfig.outbounds = [] // GLOBAL selector SingBoxConfig.outbounds.push({ tag: "GLOBAL", type: "selector", outbounds: [ "DIRECT", "REJECT", ...Proxies.map(i => i.__Remark)] }) // Respect RuleProvider for (let i of RuleProvider.ProxyGroup) { // get Matched Proxies let MatchedProxies = []; for (let t of i.RegExps) { MatchedProxies = [ ...MatchedProxies, ...Proxies.filter( loc => loc.__Remark.match(new RegExp(t)) ) ] } // unique proxy MatchedProxies = Array.from(new Set(MatchedProxies)); // generate proxies list let GroupProxies = []; for (let t of i.GroupSelectors) { GroupProxies.push(t.replace(/^\[\]/, "")) } for (let t of MatchedProxies) { GroupProxies.push(t.__Remark) } if (MatchedProxies.length + i.GroupSelectors.length === 0) { // add fallback selector if no selector can be added GroupProxies.push("DIRECT") GroupProxies.push("REJECT") } //generate proxy group let ProxyGroup: { type: string, tag: string, outbounds: string[], url?: string | URL, // for url-test onlly interval?: string, // for url-test onlly tolerance?: string, // for url-test onlly } = { tag: i.name, type: "", // placeholder... change it later outbounds: GroupProxies } if (i.type === "select") { ProxyGroup.type = "selector" } else if (i.type === "url-test" || i.type === "load-balance" || i.type === "fallback") { ProxyGroup.type = "urltest" ProxyGroup.url = i.TestConfig.TestURL; ProxyGroup.interval = `${i.TestConfig.Interval}s`; if (i.type === "url-test") { ProxyGroup.tolerance = i.TestConfig.Tolerance; } if (i.type === "load-balance" || i.type === "fallback") { console.log(`[getSingBoxConfig] ${i.name} fallback to urltest`) } } // append proxy group to config SingBoxConfig.outbounds.push(ProxyGroup) } // Append rule-sets // SingBoxConfig.route.rule_set = []; let RuleProvidersMapping = {}; // { URL: ID }[] for (let i in RuleProvider.RuleProviders) { for (let t in RuleProvider.RuleProviders[i]) { const RuleProviderPayload = RuleProvider.RuleProviders[i][t]; const RuleProviderID = `${i}__${t}`; RuleProvidersMapping[RuleProviderPayload] = RuleProviderID; // construct RuleProviderURL let RuleProviderURLObject = new URL(Config.RuleProvidersProxy); RuleProviderURLObject.pathname = "/ruleset/preprocessor/sing-box" RuleProviderURLObject.search = "" RuleProviderURLObject.searchParams.append("target", RuleProviderPayload) const RuleProviderURL = RuleProviderURLObject.toString() SingBoxConfig.route.rule_set.push({ type: "remote", tag: RuleProviderID, format: "source", url: RuleProviderURL, download_detour: "DIRECT" }) } } // Append rules // SingBoxConfig.route.rules = [] let FinalOutboundID; for (let i of RuleProvider.Rules) { const rulesetBreakdown = i.split(",").map(i => i.trim()) const outboundID = rulesetBreakdown[0]; // parse in simple rules ,, const type = MetaToSingRuleMapping[rulesetBreakdown[1]] as string; const payload = rulesetBreakdown.slice(2).join(",") as string; // parse in rule-set route rules const RuleSetPayload = rulesetBreakdown.slice(1).join(","); if (RuleSetPayload.startsWith("http://") || RuleSetPayload.startsWith("https://")) { SingBoxConfig.route.rules.push({ rule_set: RuleProvidersMapping[RuleSetPayload], action: "route", outbound: outboundID }); continue; } // handle Match Type Rule (Final Ooutbound) if (rulesetBreakdown[1] === "MATCH") { FinalOutboundID = outboundID; continue } // handle GEOIP and GEOSITE if (type === "geoip" || type === "geosite") { const { headlessRule, headlessRuleSet } = transformGeoRef(type, payload, Config.RuleProvidersProxy); SingBoxConfig.route.rules.push({ ...headlessRule, action: "route", outbound: outboundID }); // if we cant find rule set with same tag (ie append before), if (headlessRuleSet && !(SingBoxConfig.route.rule_set.find(i => i.tag === headlessRuleSet.tag))) { // append rule-set SingBoxConfig.route.rule_set.push({ ...headlessRuleSet, download_detour: "DIRECT" }) } continue; } // handle the types that payload need to be number if (type === "source_port" || type === "port") { let numPayload = Number(payload); if (isNaN(numPayload)) { console.warn(`[getSingBoxConfig] invalid port number: ${payload}, skiping rule ${i}`); continue; } SingBoxConfig.route.rules.push({ [type]: numPayload, action: "route", outbound: outboundID }); continue; } // handle AND | OR Logic rules if (type === "and" || type === "or") { let { headlessRule, headlessRuleSet } = MetaToSingLogicalRule(type, payload, Config.RuleProvidersProxy); headlessRuleSet = headlessRuleSet.filter(i => !!i && !SingBoxConfig.route.rule_set.find(t => t.tag === i.tag)); SingBoxConfig.route.rule_set.push(...headlessRuleSet); SingBoxConfig.route.rules.push({ ...headlessRule, action: "route", outbound: outboundID }); continue; } // any other route rules else should works... not sure SingBoxConfig.route.rules.push({ [type]: payload, action: "route", outbound: outboundID }); } // Append Final Outbound SingBoxConfig.route.final = FinalOutboundID; return SingBoxConfig; } ================================================ FILE: functions/internal/Dumpers/clash-meta.ts ================================================ import type { RealityConfig, TransportGRPC, TransportH2, TransportHTTP, TransportWS } from "../types/ClashMetaConfig"; export default class Dumper { config = { UDP: true, SSUoT: true, SkipCertVerify: true, ClientFingerprint: "chrome" } constructor ( UDP = true, SSUoT = true, SkipCertVerify = true, ClientFingerprint = "chrome" ) { this.config.UDP = UDP; this.config.SSUoT = SSUoT; this.config.SkipCertVerify = SkipCertVerify; this.config.ClientFingerprint = ClientFingerprint; return this; } // __appendCommonField () {} __validate (ProxyObject) { if (!(ProxyObject.__Type in this)) { console.warn(`[Dumper: Clash Meta] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`) return false; } return true; } http (HTTP) { return { name: HTTP.__Remark, type: HTTP.__Type, server: HTTP.Hostname, port: HTTP.Port, username: HTTP.Auth.username, password: HTTP.Auth.password, "skip-cert-verify": this.config.SkipCertVerify } } socks5 (SOCKS5) { return { name: SOCKS5.__Remark, type: SOCKS5.__Type, server: SOCKS5.Hostname, port: SOCKS5.Port, username: SOCKS5.Auth.username, password: SOCKS5.Auth.password, "skip-cert-verify": this.config.SkipCertVerify, udp: this.config.UDP } } hysteria (hyObject) { return { name: hyObject.__Remark, type: hyObject.__Type, server: hyObject.Hostname, port: hyObject.Port, ports: hyObject.Query.mport, "auth_str": hyObject.Query.auth, "auth-str": hyObject.Query.auth, alpn: hyObject.Query.alpn ? [ hyObject.Query.alpn ] : undefined, up: hyObject.Query.upmbps, down: hyObject.Query.downmbps, sni: hyObject.Query.peer, "skip-cert-verify": this.config.SkipCertVerify, protocol: this.config.UDP ? "UDP" : "wechat-video", } } hysteria2 (hy2Object) { return { name: hy2Object.__Remark, type: hy2Object.__Type, server: hy2Object.Hostname, port: hy2Object.Port, ports: hy2Object.Query.mport, password: hy2Object.Auth, sni: hy2Object.Query.sni, obfs: hy2Object.Query.obfs, "obfs-password": hy2Object.Query["obfs-password"], "client-fingerprint": this.config.ClientFingerprint, "skip-cert-verify": this.config.SkipCertVerify, udp: this.config.UDP, } } hy2 = this.hysteria2; tuic (TUIC) { return { name: TUIC.__Remark, type: TUIC.__Type, server: TUIC.Hostname, port: TUIC.Port, uuid: TUIC.Auth.uuid, password: TUIC.Auth.password, alpn: TUIC.Query.alpn ? [ TUIC.Query.alpn ] : undefined, "disable-sni": !!parseInt(TUIC.Query.disable_sni), "udp-relay-mode": TUIC.Query.udp_relay_mode, "congestion-controller": TUIC.Query.congestion_control, "skip-cert-verify": this.config.SkipCertVerify, sni: TUIC.Query.sni, // max-udp-relay-packet-size: 1500, // fast-open: true, // max-open-streams: 20, } } vless (VLESS) { return { name: VLESS.__Remark, type: VLESS.__Type, server: VLESS.Hostname, port: VLESS.Port, uuid: VLESS.Auth, flow: VLESS.Query.flow, "packet-encoding": VLESS.Query.packetEncoding, tls: !!VLESS.Query.sni, servername: VLESS.Query.sni, alpn: VLESS.Query.alpn ? [ VLESS.Query.alpn ] : undefined, "client-fingerprint": VLESS.Query.fp, network: VLESS.Query.type, "reality-opts": __genRealityConfig(VLESS), // transport layer config "ws-opts": __genTransportWS(VLESS), "grpc-opts": __genTransportGRPC(VLESS), "h2-opts": __genTransportH2(VLESS), "http-opts": __genTransportHTTP(VLESS), udp: this.config.UDP, "skip-cert-verify": this.config.SkipCertVerify, } } vmess (VMESS) { return { name: VMESS.__Remark, type: VMESS.__Type, server: VMESS.Hostname, port: VMESS.Port, uuid: VMESS.Auth, alterId: VMESS.Query.aid, cipher: VMESS.Query.scy ? VMESS.Query.scy : "auto", network: VMESS.Query.net, protocol: VMESS.Query.type, "client-fingerprint": VMESS.Query.fp, alpn: ["h2", "http/1.1"], // tls tls: VMESS.Query.tls === "tls", servername: VMESS.Query.sni, // "reality-opts": { // "public-key": "xxxx", // "short-id": "xxxx", // }, // transport layer config "ws-opts": __genTransportWS(VMESS), "grpc-opts": __genTransportGRPC(VMESS), "h2-opts": __genTransportH2(VMESS), "http-opts": __genTransportHTTP(VMESS), "skip-cert-verify": this.config.SkipCertVerify, udp: this.config.UDP, // packet-encoding // global-padding // authenticated-length } } vmess__shadowsocks_type (VMESS) { return { name: VMESS.__Remark, type: "vmess", server: VMESS.Hostname, port: VMESS.Port, uuid: VMESS.Auth, alterId: parseInt(VMESS.Query.alterId), cipher: "auto", network: VMESS.Query.obfs, // tls tls: VMESS.Query.tls === "1", servername: VMESS.Query.peer, // transport layer config "ws-opts": __genTransportWS(VMESS), "grpc-opts": __genTransportGRPC(VMESS), "http-opts": __genTransportHTTP(VMESS), "h2-opts": __genTransportH2(VMESS), "skip-cert-verify": this.config.SkipCertVerify, udp: this.config.UDP, // packet-encoding // global-padding // authenticated-length } } ss (SS) { return { name: SS.__Remark, type: "ss", server: SS.Hostname, port: SS.Port, cipher: SS.Auth.cipher, password: SS.Auth.password, udp: this.config.UDP, "udp-over-tcp": this.config.SSUoT, "udp-over-tcp-version": this.config.SSUoT ? 2 : undefined, } } trojan (TROJAN) { return { name: TROJAN.__Remark, type: "trojan", server: TROJAN.Hostname, port: TROJAN.Port, password: TROJAN.Auth, network: TROJAN.Query.type ? TROJAN.Query.type : "tcp", sni: TROJAN.Query.sni, alpn: ["h2", "http/1.1"], "reality-opts": __genRealityConfig(TROJAN), // transport layer config "ws-opts": __genTransportWS(TROJAN), "grpc-opts": __genTransportGRPC(TROJAN), "http-opts": __genTransportHTTP(TROJAN), "client-fingerprint": TROJAN.Query.fp, udp: this.config.UDP, "skip-cert-verify": this.config.SkipCertVerify, } } } function __genRealityConfig (Obj) : RealityConfig | undefined { return Obj.Query.security === "reality" ? { "public-key": Obj.Query.pbk ? Obj.Query.pbk : undefined, "short-id": Obj.Query.sid ? Obj.Query.sid : undefined } : undefined } function __genTransportWS (Obj) : TransportWS | undefined { const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type; if (PassedTransportType !== "ws") { return undefined; } const host = Obj.Query.host || Obj.Query.obfsParam; const PathObj = new URL(`path:${Obj.Query.path}`) const ParsedMaxEarlyData = parseInt(Obj.Query.ed || PathObj.searchParams.get("ed")); const MaxEarlyData = isNaN(ParsedMaxEarlyData) ? undefined : ParsedMaxEarlyData; const EarlyDataHeaderName = Obj.Query.eh || (MaxEarlyData ? "Sec-WebSocket-Protocol" : undefined) return { path: PathObj.pathname, headers: host ? { host } : undefined, "max-early-data": MaxEarlyData, "early-data-header-name": EarlyDataHeaderName, //"v2ray-http-upgrade"?: unknown, //"v2ray-http-upgrade-fast-open"?: unknown, } } function __genTransportGRPC (Obj) : TransportGRPC | undefined { const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type; return PassedTransportType === "grpc" ? { "grpc-service-name": Obj.Query.serviceName || Obj.Query.path } : undefined; } function __genTransportHTTP (Obj) : TransportHTTP | undefined { const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type; const host = Obj.Query.host || Obj.Query.obfsParam; return PassedTransportType === "http" ? { method: Obj.Query.method, path: Obj.Query.path ? [ Obj.Query.path ] : undefined, headers: host ? { host } : undefined, } : undefined; } function __genTransportH2 (Obj) : TransportH2 | undefined { const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type; return PassedTransportType === "h2" ? { method: Obj.Query.method, path: Obj.Query.path, } : undefined; } ================================================ FILE: functions/internal/Dumpers/share-link.js ================================================ export class ShareLinkDumper { constructor () { return true; } __validate (ProxyObject) { if (!(ProxyObject.__Type in this)) { console.warn(`[Dumper: Share Link] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`) return false } return true; } http (HTTP) { return `http://${HTTP.Auth.username}:${HTTP.Auth.password}@${HTTP.Hostname}:${HTTP.Port}/#${encodeURIComponent(HTTP.__Remark)}`; } socks5 (SOCKS5) { return `socks5://${SOCKS5.Auth.username}:${SOCKS5.Auth.password}@${SOCKS5.Hostname}:${SOCKS5.Port}/#${encodeURIComponent(SOCKS5.__Remark)}`; } hysteria (Obj) { return `hysteria://${Obj.Hostname}:${Obj.Port}/${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}` } hysteria2 (Obj) { return `hysteria2://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}` } hy2 = this.hysteria2; tuic (Obj) { return `tuic://${Obj.Auth.uuid}:${Obj.Auth.password}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}` } vless (Obj) { return `vless://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}` } vmess (Obj) { let VMESSObj = { ps: unescape(encodeURIComponent(Obj.__Remark)) , add: Obj.Hostname, port: Obj.Port, id: Obj.Auth, ...Obj.Query, } return `vmess://${btoa(JSON.stringify(VMESSObj))}` } vmess__shadowsocks_type (Obj) { let VMESSObj = { ps: unescape(encodeURIComponent(Obj.__Remark)) , add: Obj.Hostname, port: Obj.Port, id: Obj.Auth, //...Obj.Query, aid: Obj.Query.alterId, scy: "auto", net: Obj.Query.obfs, tls: Obj.Query.tls === "1" ? "tls" : undefined, sni: Obj.Query.peer, host: Obj.Query.obfsParam, path: Obj.Query.path } return `vmess://${btoa(JSON.stringify(VMESSObj))}` } ss (Obj) { return `ss://${encodeURIComponent(btoa(`${Obj.Auth.cipher}:${Obj.Auth.password}`))}@${Obj.Hostname}:${Obj.Port}/#${encodeURIComponent(Obj.__Remark)}` } trojan (Obj) { return `trojan://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}` } } function URLQueryWrapper (Obj) { let Childs = []; for (let i in Obj) { let value = Obj[i]; if (value) { Childs.push(`${i}=${encodeURIComponent(Obj[i])}`) } } return Childs.join("&"); } ================================================ FILE: functions/internal/Dumpers/sing-box.js ================================================ export default class Dumper { config = {} constructor ( UDP = true, SSUoT = false, SkipCertVerify = true ) { this.config.UDP = UDP; this.config.SSUoT = SSUoT; this.config.SkipCertVerify = SkipCertVerify; return true; } // __appendCommonField () {} __validate (ProxyObject) { if (!(ProxyObject.__Type in this)) { console.warn(`[Dumper: Sing Box] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`) return false; } if (ProxyObject.__Type === "vmess__shadowsocks_type" && ProxyObject.Query.obfs === "none") { console.warn(`[Dumper: Sing Box] [WARN] ${ProxyObject.__Type} TCP-Transport is not supported by sing-box, ignoring...`) return false; } return true; } http (HTTP) { return { tag: HTTP.__Remark, type: "http", server: HTTP.Hostname, server_port: HTTP.Port, username: HTTP.Auth.username, password: HTTP.Auth.password, path: "/", headers: {}, tls: { insecure: this.config.SkipCertVerify }, } } socks5 (SOCKS5) { return { tag: SOCKS5.__Remark, type: "socks", server: SOCKS5.Hostname, server_port: SOCKS5.Port, version: "5", username: SOCKS5.Auth.username, password: SOCKS5.Auth.password, //udp_over_tcp: this.config.UDP ? "udp" : "tcp" } } hysteria (hyObject) { return { type: "hysteria", tag: hyObject.__Remark, server: hyObject.Hostname, server_port: hyObject.Port, server_ports: hyObject.Query.mport ? hyObject.Query.mport.replace(/\-/g, ":").split(",") : undefined, up_mbps: parseInt(hyObject.Query.upmbps) || 250, down_mbps: parseInt(hyObject.Query.downmbps) || 500, obfs: hyObject.Query.obfsParam, auth_str: hyObject.Query.auth, tls: { enabled: true, server_name: hyObject.Query.peer, insecure: this.config.SkipCertVerify }, } } hysteria2 (hy2Object) { return { type: "hysteria2", tag: hy2Object.__Remark, server: hy2Object.Hostname, server_port: hy2Object.Port, server_ports: hy2Object.Query.mport ? hy2Object.Query.mport.replace(/\-/g, ":").split(",") : undefined, up_mbps: parseInt(hy2Object.Query.upmbps) || 250, down_mbps: parseInt(hy2Object.Query.downmbps) || 500, obfs: (hy2Object.Query.obfs && hy2Object.Query["obfs-password"] ) ? { type: hy2Object.Query.obfs, password: hy2Object.Query["obfs-password"], } : undefined, password: hy2Object.Auth, tls: { enabled: true, server_name: hy2Object.Query.sni, insecure: this.config.SkipCertVerify, alpn: [ "h3" ] }, } } hy2 = this.hysteria2; tuic (TUIC) { return { type: "tuic", tag: TUIC.__Remark, server: TUIC.Hostname, server_port: TUIC.Port, uuid: TUIC.Auth.uuid, password: TUIC.Auth.password, udp_relay_mode: TUIC.Query.udp_relay_mode, congestion_control: TUIC.Query.congestion_control, heartbeat: "10s", tls: { enabled: true, disable_sni: !!parseInt(TUIC.Query.disable_sni), alpn: TUIC.Query.alpn ? [ TUIC.Query.alpn ] : undefined, insecure: this.config.SkipCertVerify, server_name: TUIC.Query.sni, } } } vless (VLESS) { return { type: "vless", tag: VLESS.__Remark, server: VLESS.Hostname, server_port: VLESS.Port, uuid: VLESS.Auth, flow: VLESS.Query.flow, packet_encoding: VLESS.Query.packetEncoding, tls: !!VLESS.Query.sni ? { enabled: true, server_name: VLESS.Query.sni, insecure: this.config.SkipCertVerify, alpn: VLESS.Query.alpn ? [ VLESS.Query.alpn ] : undefined, utls: { enabled: !!VLESS.Query.fp, fingerprint: VLESS.Query.fp }, reality: __genRealityConfig(VLESS), } : undefined, //"multiplex: {}, transport: __genTransportConfig(VLESS) } } vmess__shadowsocks_type (VMess) { let URITransportType = URIObject.Query.obfs; const PathObject = new URL(`path:${URIObject.Query.path}`); return { type: "vmess", tag: VMess.__Remark, server: VMess.Hostname, server_port: VMess.Port, uuid: VMess.Auth, security: "auto", alter_id: parseInt(VMess.Query.alterId), tls: VMess.Query.sni === "1" ? { enabled: true, server_name: VMess.Query.peer, insecure: this.config.SkipCertVerify, } : undefined, //"multiplex: {}, transport: { type: URITransportType, // http headers: { Host: (URITransportType !== "quic" && URITransportType !== "grpc") ? URIObject.Query.obfsParam : undefined, }, path: URITransportType !== "grpc" ? PathObject.path : undefined, // max early data early_data_header_name: PathObject.searchParams.has("ed") ? "Sec-WebSocket-Protocol" : undefined, max_early_data: PathObject.searchParams.has("ed") ? parseInt(PathObject.searchParams.get("ed")) : undefined, // grpc service_name: URITransportType === "grpc" ? ( URIObject.Query.path ) : undefined, } } } vmess (VMESS) { return { type: "vmess", tag: VMESS.__Remark, server: VMESS.Hostname, server_port: VMESS.Port, uuid: VMESS.Auth, security: VMESS.Query.scy ? VMESS.Query.scy : "auto", alter_id: VMESS.Query.aid, // global_padding: false, //?? // authenticated_length: true, //?? tls: (VMESS.Query.tls === "tls") ? { enabled: true, server_name: VMESS.Query.sni, insecure: this.config.SkipCertVerify, alpn: ["h2", "http/1.1"], utls: { enabled: !!VMESS.Query.fp, fingerprint: VMESS.Query.fp }, reality: __genRealityConfig(VMESS), } : undefined, transport: __genTransportConfig(VMESS) } } ss (SS) { return { type: "shadowsocks", tag: SS.__Remark, server: SS.Hostname, server_port: SS.Port, method: SS.Auth.cipher, password: SS.Auth.password, udp_over_tcp: this.config.SSUoT ? { enabled: true, version: 2 } : false, } } trojan (TROJAN) { return { type: "trojan", tag: TROJAN.__Remark, server: TROJAN.Hostname, server_port: TROJAN.Port, password: TROJAN.Auth, network: TROJAN.Query.type ? TROJAN.Query.type : "tcp", tls: !!TROJAN.Query.sni ? { enabled: true, server_name: TROJAN.Query.sni, alpn: ["h2", "http/1.1"], insecure: this.config.SkipCertVerify, utls: { enabled: !!TROJAN.Query.fp, fingerprint: TROJAN.Query.fp }, reality: __genRealityConfig(TROJAN), } : undefined, transport: __genTransportConfig(TROJAN) } } } function __genRealityConfig (URIObject) { return (URIObject.Query.security === "reality") ? { enabled: true, public_key: URIObject.Query.pbk || undefined, short_id: URIObject.Query.sid || undefined } : undefined; } function __genTransportConfig (URIObject) { const URITransportType = URIObject.Query.net || URIObject.Query.type; const PathObject = new URL(`path:${URIObject.Query.path}`); return ( URITransportType === "http" || URITransportType === "ws" || URITransportType === "grpc" || URITransportType === "quic" || URITransportType === "httpupgrade" ) ? { type: URITransportType, // http headers: { Host: (URITransportType !== "quic") ? URIObject.Query.host : undefined, }, path: PathObject.pathname || "", method: URIObject.Query.method, // max early data early_data_header_name: PathObject.searchParams.has("ed") ? "Sec-WebSocket-Protocol" : undefined, max_early_data: PathObject.searchParams.has("ed") ? parseInt(PathObject.searchParams.get("ed")) : undefined, // grpc service_name: URITransportType === "grpc" ? ( URIObject.Query.serviceName || URIObject.Query.path ) : undefined, } : undefined; } ================================================ FILE: functions/internal/Parsers/clash-meta.js ================================================ export class ClashMetaParser { constructor () {} __validate (ProxyObject) { if (!(ProxyObject.type in this)) { console.warn(`[Parser: Clash Meta] [WARN] ${ProxyObject.__Type} is not supported to parse, ignoring...`) return false; } return true; } http (Obj) { return { __Type: "http", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: { username: Obj.username, password: Obj.password } } } socks5 (Obj) { return { __Type: "socks5", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: { username: Obj.username, password: Obj.password } } } hysteria (Obj) { return { __Type: "hysteria", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Query: { auth: (Obj["auth_str"] || Obj["auth-str"]), alpn: Obj.alpn ? Obj.alpn.join(",") : undefined, upmbps: Obj.up, downmbps: Obj.down, peer: Obj.sni, mport: Obj.ports, } } } hysteria2 (Obj) { return { __Type: "hysteria2", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: Obj.auth || Obj.password, Query: { objs: Obj.obfs, "obfs-password": Obj["obfs-password"], insecure: Obj["skip-cert-verify"] ? 1 : 0, mport: Obj.ports, } } } hy2 = this.hysteria2; tuic (Obj) { return { __Type: "tuic", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: { uuid: Obj.uuid, password: Obj.password }, Query: { alpn: Obj.alpn ? Obj.alpn.join(",") : undefined, disable_sni: Obj["disable-sni"], udp_relay_mode: Obj["udp-relay-mode"], congestion_control: Obj["congestion-controller"], sni: Obj.sni, } } } vless (Obj) { return { __Type: "vless", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: Obj.uuid, Query: { flow: Obj.flow, packetEncoding: Obj["packet-encoding"], sni: Obj.servername, alpn: Obj.alpn ? Obj.alpn.join(",") : undefined, fp: Obj["client-fingerprint"], type: Obj.network, // reality security: !!Obj["reality-opts"] ? "reality": undefined, pbk: (Obj["reality-opts"] || {})["public-key"], sid: (Obj["reality-opts"] || {})["short-id"], // transport layer config // - ws ed: Obj["max-early-data"], eh: Obj["early-data-header-name"], // - grpc serviceName: Obj["grpc-service-name"], // - http method: Obj.method, // - http & ws & h2 path: Obj["ws-path"] || Obj.path, host: Obj.host || (Obj["ws-headers"] || Obj.headers || {}).Host, } } } vmess (Obj) { return { __Type: "vmess", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: Obj.uuid, Query: { aid: Obj.alterId, cipher: Obj.cipher, net: Obj.network, type: Obj.protocol, fp: Obj["client-fingerprint"], alpn: Obj.alpn ? Obj.alpn.join(",") : undefined, tls: Obj.tls ? "tls" : undefined, sni: Obj.servername, // transport layer config // - http & ws & h2 host: (Obj["ws-headers"] || Obj.headers || {}).Host, // - http & ws & h2 & grpc path: Obj["ws-path"] || ( Obj["ws-opts"] || Obj["h2-opts"] || {} ).path || ( (Obj["http-opts"] || {}).path || [] )[0] || Obj["grpc-service-name"] || undefined, } } } ss (Obj) { return { __Type: "ss", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: { cipher: Obj.cipher, password: Obj.password }, } } trojan (Obj) { return { __Type: "trojan", __Remark: Obj.name, Hostname: Obj.server, Port: Obj.port, Auth: Obj.password, Query: { type: Obj.network, sni: Obj.sni, // reality security: !!Obj["reality-opts"] ? "reality" : undefined, pbk: Obj["public-key"], sid: Obj["short-id"], // transport layer config // - ws ed: Obj["max-early-data"], eh: Obj["early-data-header-name"], // - grpc serviceName: Obj["grpc-service-name"], // - http method: Obj.method, // - http & ws path: Obj["ws-path"] || Obj.path, host: (Obj["ws-headers"] || Obj.headers || {}).Host, } } } } function __searchParamsMapper (searchParams) { let Query = {} for (const [key, value] of searchParams) { Query[key] = value } return Query; } ================================================ FILE: functions/internal/Parsers/share-link.js ================================================ export class ShareLinkParser { constructor () {} __validate (URI) { if (!(URI.split(":")[0] in this)) { console.warn(`[Parser: Share Link] [WARN] ${URI.__Type} is not supported to parse, ignoring...`) return false; } return true; } http (URI) { let URIObject = new URL (URI); return { __Type: "http", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Hostname: URIObject.hostname, Port: parseInt(URIObject.port), Auth: { username: URIObject.username, password: URIObject.password } } } socks5 (URI) { let URIObject = new URL (URI); return { __Type: "socks5", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Hostname: URIObject.hostname, Port: parseInt(URIObject.port), Auth: { username: URIObject.username, password: URIObject.password } } } hysteria (HYURL) { const URIObject = new URL (HYURL); const HY = { __Type: "hysteria", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Hostname: URIObject.hostname, Port: parseInt(URIObject.port), Query: __searchParamsMapper(URIObject.searchParams) } return HY; } hysteria2 (HY2URL) { const URIObject = new URL (HY2URL); const HY2 = { __Type: "hysteria2", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Auth: decodeURIComponent(URIObject.password || URIObject.username), Hostname: URIObject.hostname, Port: parseInt(URIObject.port), Query: __searchParamsMapper(URIObject.searchParams) } return HY2; } hy2 = this.hysteria2; tuic (TUICURI) { let URIObject = new URL(TUICURI); const TUIC = { __Type: "tuic", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Auth: { uuid: URIObject.username, password: URIObject.password}, Hostname: URIObject.hostname, Port: parseInt(URIObject.port), Query: __searchParamsMapper(URIObject.searchParams) } return TUIC; } vless (URI) { let URIObject = new URL (URI); let VLESS = { __Type: "vless", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Hostname: URIObject.hostname, Port: parseInt(URIObject.port), Auth: URIObject.username, Query: __searchParamsMapper(URIObject.searchParams) } return VLESS; } vmess (URI) { let URIObject = new URL(URI); let VMessRawData = atob(URIObject.host); try { let VMessRawObject = JSON.parse(VMessRawData); let Remark; try { Remark = decodeURIComponent(escape(VMessRawObject.ps)) } catch (e) { Remark = VMessRawObject.ps } let VMess = { __Type: "vmess", __Remark: Remark || `${VMessRawObject.add}:${VMessRawObject.port}`, Hostname: VMessRawObject.add, Port: parseInt(VMessRawObject.port), Auth: VMessRawObject.id, } delete VMessRawObject.ps delete VMessRawObject.add delete VMessRawObject.port delete VMessRawObject.id // am i doing right... delete VMessRawObject.v // assume its version 2 // delete all the empty fields for (let i in VMessRawObject) { if ( VMessRawObject[i] === "" || VMessRawObject[i] === null || VMessRawObject[i] === undefined ) { delete VMessRawObject[i] } } VMessRawObject.aid = parseInt(VMessRawObject.aid) VMess.Query = VMessRawObject; return VMess; } catch (err) { let StandardURIObj = new URL(`vmess://${VMessRawData}${URIObject.pathname}${URIObject.search}`) let VMess = { //__Type: "vmess", __Type: "vmess__shadowsocks_type", __Remark: StandardURIObj.searchParams.get("remarks") || StandardURIObj.host, Hostname: StandardURIObj.hostname, Port: parseInt(StandardURIObj.port), Auth: StandardURIObj.password, Query: __searchParamsMapper(URIObject.searchParams) } delete VMess.Query.remarks if (VMess.Query.obfs === "websocket") { VMess.Query.obfs = "ws" } return VMess } } ss (URI) { let StandardURI = (URI => { let URIObject = new URL(URI); try { // base64-encoded cipher:uuid@host:port return `ss://${encodeURIComponent(atob(decodeURIComponent(URIObject.host))).replace(/\%3A/gi,":").replace(/\%40/gi,"@")}${URIObject.search}${URIObject.hash}`; } catch (e) {} try { // base64-encoded cipher:uuid return `ss://${encodeURIComponent(atob(decodeURIComponent(URIObject.username))).replace(/\%3A/i,":")}@${URIObject.host}${URIObject.search}${URIObject.hash}`; } catch (e) {} // plain return URI; })(URI) let URIObject = new URL(StandardURI); return { __Type: "ss", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Auth: { cipher: decodeURIComponent(URIObject.username), password: decodeURIComponent(URIObject.password) }, Hostname: URIObject.hostname, Port: parseInt(URIObject.port) } } trojan (URI) { let URIObject = new URL(URI); const TROJAN = { __Type: "trojan", __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host, Auth: URIObject.username, Hostname: URIObject.hostname, Port: parseInt(URIObject.port), Query: __searchParamsMapper(URIObject.searchParams) } return TROJAN; } } function __searchParamsMapper (searchParams) { let Query = {} for (const [key, value] of searchParams) { Query[key] = value } return Query; } ================================================ FILE: functions/internal/Parsers/sing-box.js ================================================ export class SingBoxParser { constructor () {} __validate (ProxyObject) { if (!(ProxyObject.type in this)) { console.warn(`[Parser: Sing-Box] [WARN] ${ProxyObject.__Type} is not supported to parse, ignoring...`) return false; } if (ProxyObject.type === "socks" && ProxyObject.version != 5) { console.warn(`[Parser: Sing-Box] [WARN] Only Socks version 5 is supported to parse, ignoring...`) return false; } return true; } http (Obj) { return { __Type: "http", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: { username: Obj.username, password: Obj.password } } } socks (Obj) { return { __Type: "socks5", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: { username: Obj.username, password: Obj.password } } } hysteria (Obj) { return { __Type: "hysteria", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Query: { auth: (Obj["auth_str"] || Obj["auth"]), alpn: Obj.tls && Obj.tls.alpn ? Obj.tls.alpn.join(",") : undefined, upmbps: Obj.up || Obj.up_mbps, downmbps: Obj.down || Obj.down_mbps, peer: Obj.tls && Obj.tls.server_name, mport: Obj.server_ports ? Obj.server_ports.map(i=>i.replace(/\:/gi, "-")).join(",") : undefined, } } } hysteria2 (Obj) { return { __Type: "hysteria2", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: Obj.password, Query: { upmbps: Obj.up_mbps, downmbps: Obj.down_mbps, objs: Obj.obfs ? Obj.obfs.type : undefined, "obfs-password": Obj.obfs ? Obj.obfs.password : undefined, insecure: Obj.tls && Obj.tls.insecure ? 1 : 0, mport: Obj.server_ports ? Obj.server_ports.map(i=>i.replace(/\:/gi, "-")).join(",") : undefined, } } } tuic (Obj) { return { __Type: "tuic", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: { uuid: Obj.uuid, password: Obj.password }, Query: { alpn: Obj.alpn ? Obj.alpn.join(",") : undefined, disable_sni: Obj.tls.disable_sni, udp_relay_mode: Obj.udp_relay_mode, congestion_control: Obj.congestion_control, sni: Obj.tls && Obj.tls.server_name, } } } vless (Obj) { return { __Type: "vless", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: Obj.uuid, Query: { flow: Obj.flow, packetEncoding: Obj.packet_encoding, sni: Obj.tls && Obj.tls.server_name, alpn: Obj.tls && Obj.tls.alpn ? Obj.tls.alpn.join(",") : undefined, fp: Obj.tls && Obj.tls.utls && Obj.tls.utls.enabled === true ? Obj.tls.utls.fingerprint: undefined, type: Obj.network, // reality security: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? "reality" : undefined, pbk: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["public_key"] : undefined, sid: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["short_id"] : undefined, // transport layer config // - ws ed: Obj.transport && Obj.transport["max_early_data"], eh: Obj.transport && Obj.transport["early_data_header_name"], // - grpc serviceName: Obj.transport && Obj.transport["service_name"], // - http method: Obj.method, // - http & ws path: Obj.transport && Obj.transport.path, host: (Obj.transport && Obj.transport.headers || {}).Host, } } } vmess (Obj) { return { __Type: "vmess", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: Obj.uuid, Query: { aid: Obj.alter_id, cipher: Obj.security, net: Obj.network, type: Obj.protocol, fp: Obj.tls && Obj.tls.utls ? Obj.tls.utls.fingerprint : undefined, alpn: Obj.alpn ? Obj.alpn.join(",") : undefined, tls: Obj.tls && Obj.tls.enabled ? "tls" : undefined, sni: Obj.server_name, // transport layer config // - http & ws & h2 host: (Obj.headers || {}).Host, // - http & ws & h2 & grpc path: Obj.path || undefined } } } shadowsocks (Obj) { return { __Type: "ss", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: { cipher: Obj.method, password: Obj.password }, } } trojan (Obj) { return { __Type: "trojan", __Remark: Obj.tag, Hostname: Obj.server, Port: Obj.server_port, Auth: Obj.password, Query: { type: Obj.network, sni: Obj.tls && Obj.tls.server_name, // reality security: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? "reality" : undefined, pbk: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["public_key"] : undefined, sid: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["short_id"] : undefined, // transport layer config // - ws ed: Obj.transport && Obj.transport["max_early_data"], eh: Obj.transport && Obj.transport["early_data_header_name"], // - grpc serviceName: Obj.transport && Obj.transport["service_name"], // - http method: Obj.method, // - http & ws path: Obj.transport && Obj.transport["path"] || Obj.path, host: (Obj.transport && Obj.transport["headers"] || Obj.headers || {}).Host, } } } } ================================================ FILE: functions/internal/RuleProviderReader/Readers/ini.js ================================================ import { parseINI } from "confbox"; import { fetchCached } from "../../utils/fetchCached.js"; export async function ini (RuleProviderURL, CacheDB, isForcedRefresh) { let Config = { RuleProviders: [], Rules: [], ProxyGroup: [] }; // get raw remote config. let RuleProvider = await fetchCached(RuleProviderURL, "RuleProvider", CacheDB, isForcedRefresh) .then( res => res.replaceAll("ruleset=", "ruleset[]=") .replaceAll("custom_proxy_group=", "custom_proxy_group[]=") ) .then(res => parseINI(res)); // process rules for (let i of RuleProvider.custom.ruleset) { const rulesetBreakdown = i.split(",").map(i=>i.trim()) const id = rulesetBreakdown[0]; const payload = rulesetBreakdown.slice(1).join(","); // append rule providers if (payload.startsWith("https://") || payload.startsWith("http://")) { if (!Config.RuleProviders[id]) { Config.RuleProviders[id] = []; } Config.RuleProviders[id].push(payload) } // append route rules const postProcessedContent = `${id},${payload .replace(/^\[\]FINAL/i, "MATCH") .replace(/^\[\]/g, "") }` Config.Rules.push(postProcessedContent) } // process proxy groups for (let i of RuleProvider.custom.custom_proxy_group) { // "特殊筛选条件" (starts with "!!") are not supported. #todo const ConfigArr = i.split("`").map(i => i.trim()).filter(t => !t.startsWith("!!")); const Args = ConfigArr.slice(2).filter(t => !t.startsWith("[]")); const type = ConfigArr[1]; let ProxyGroupConfig = { name: ConfigArr[0], type: type, RegExps: Args, GroupSelectors: ConfigArr.slice(2).filter(t => t.startsWith("[]")), } if (type === "url-test" || type === "fallback" || type === "load-balance") { let TestURLIndex = Args.findIndex(loc => (loc.startsWith("https://") || loc.startsWith("http://"))) let TestArgs = [Args.slice(TestURLIndex)[0], ...Args.slice(TestURLIndex)[1].split(",").map(i => i.trim())]; ProxyGroupConfig.TestConfig = { TestURL: TestArgs[0], Interval: parseInt(TestArgs[1]), Timeout: parseInt(TestArgs[2]), Tolerance: parseInt(TestArgs[3]), } } Config.ProxyGroup.push(ProxyGroupConfig) } return Config; } ================================================ FILE: functions/internal/RuleProviderReader/main.js ================================================ import { ini } from "./Readers/ini.js" export class RuleProviderReader { RuleProvider = {}; Reader = { ini, } constructor (RuleProviderURL) { this.RuleProvider.URL = RuleProviderURL; const pathname = new URL(RuleProviderURL).pathname; this.RuleProvider.Type = pathname.split(".").slice(-1)[0].toLowerCase(); console.info(`[Remote Config Reader] Inputed remote config type: ${this.RuleProvider.Type}`); if (this.RuleProvider.Type in this.Reader) { return true; } else { console.warn("[Remote Config Reader] [WARN] Inputed remote config type cannot be detected, assume as .ini."); this.RuleProvider.Type = "ini" return true; } } Process = async function (EdgeSubDB, isForcedRefresh) { let __startTime = performance.now(); console.info(`[Remote Config Reader] started`); const response = this.Reader[this.RuleProvider.Type](this.RuleProvider.URL, EdgeSubDB, isForcedRefresh); //let RawConfig = await fetchRuleProvider(RuleProviderURL, isForcedRefresh); console.info(`[Remote Config Reader] done, wasting ${performance.now() - __startTime}ms`); return response } } ================================================ FILE: functions/internal/configs.ts ================================================ export const DefaultRequestHeaders = { "Accept": "*/*", "User-Agent": "EdgeSub-git/0.0.0 (Prefer ClashMeta / Mihomo Format)", } ================================================ FILE: functions/internal/data/rule/MetaToSingLogicalRule.ts ================================================ import { MetaToSingRuleMapping } from "./MetaToSingMapping"; import { transformGeoRef } from "../ruleset/transformGeoRef"; import type { headlessRuleSet } from "../ruleset/transformGeoRef"; /** * Parse Mihomo Logical rules, AND | OR * example: * - AND, ((DOMAIN,baidu.com),(NETWORK,UDP)) * - OR, ((NETWORK,UDP),(DOMAIN,baidu.com)) * Nesting supported! * example: * - AND, ( (DOMAIN,baidu.com), (OR, ( (NETWORK,UDP), (PORT,443) ) ) ) * @param type Sing rule type * @returns Sing Headless rule */ export function MetaToSingLogicalRule (type: string, payload: string, EdgeSubInstanceBaseURL): { headlessRule: any, headlessRuleSet: headlessRuleSet[] } { // console.log(payload) const payloads = payload.replace(/(^\(|\)$)/g, ""); // console.log(payloads) const ruleSets: headlessRuleSet[] = []; const rules = parseParenthesizedItems(payloads).map(i => { const itemBreakdown = i.split(","); const itemType = MetaToSingRuleMapping[itemBreakdown[0]]; const itemPayload = itemBreakdown[1]; // handle GEOIP and GEOSITE if (itemType === "geoip" || itemType === "geosite") { const { headlessRule, headlessRuleSet } = transformGeoRef(itemType, itemPayload, EdgeSubInstanceBaseURL); // if we cant find rule set with same tag (ie append before), if (headlessRuleSet && !(ruleSets.find(i => i.tag === headlessRuleSet.tag))) { ruleSets.push(headlessRuleSet); } return headlessRule; } if (itemType === "and" || itemType === "or") { let { headlessRule: RecrusivlyHeadlessRule, headlessRuleSet: RecrusivlyHeadlessRuleSet } = MetaToSingLogicalRule(itemType, itemBreakdown.slice(1).join(","), EdgeSubInstanceBaseURL); RecrusivlyHeadlessRuleSet = RecrusivlyHeadlessRuleSet.filter(i => !!i && !ruleSets.find(t => t.tag === i.tag)); ruleSets.push(...RecrusivlyHeadlessRuleSet); return RecrusivlyHeadlessRule; } return { [itemType]: itemPayload, } }); return { headlessRule: { type: "logical", mode: type, rules: rules }, headlessRuleSet: ruleSets } } /** * Parses a string containing comma-separated, parenthesized items into an array of strings. * This version correctly handles nested parentheses by manually balancing them, * which is a task simple regular expressions cannot reliably perform. * * @param inputString The string to parse, e.g., "(A,(B)),(C)". * @returns An array containing the inner content of each top-level parenthesized item. * For example, ["A,(B)", "C"]. * Returns an empty array if there are no matches. */ function parseParenthesizedItems(inputString: string): string[] { const result: string[] = []; let parenCount = 0; let itemStart = -1; for (let i = 0; i < inputString.length; i++) { const char = inputString[i]; if (char === '(') { if (parenCount === 0) { // This is the start of a top-level item. // Mark the position right after the opening parenthesis. itemStart = i + 1; } parenCount++; } else if (char === ')') { parenCount--; if (parenCount === 0 && itemStart !== -1) { // We've found the closing parenthesis of a top-level item. // Extract the content from itemStart to the current position. result.push(inputString.substring(itemStart, i)); itemStart = -1; // Reset for the next item. } } } // A final check: if parenCount is not 0, the input string had mismatched parentheses. // You might want to throw an error here, but for now we'll return what we found. if (parenCount !== 0) { console.error("Warning: Mismatched parentheses in input string."); } return result; } ================================================ FILE: functions/internal/data/rule/MetaToSingMapping.ts ================================================ // mihomo src rule syntax // , , , // note: headless rule doesnt need to care bout outbound // additional parameters is not handled by sing-box/route/rule: // - "no-resolve"'s sing-box/dns/rule's work. // - "src" is a crazy thing i don't even know why it exists ( export const MetaToSingRuleMapping = { "DOMAIN": "domain", "DOMAIN-SUFFIX": "domain_suffix", "DOMAIN-KEYWORD": "domain_keyword", "DOMAIN-REGEX": "domain_regex", "GEOSITE": "geosite", "GEOIP": "geoip", "IP-CIDR": "ip_cidr", "IP-CIDR6": "ip_cidr", // IP-CIDR6 is a alias for IP-CIDR in mihomo route rule "SRC-IP-CIDR": "source_ip_cidr", "SRC-PORT": "source_port", "DST-PORT": "port", "PROCESS-PATH": "process_path", "PROCESS-PATH-REGEX": "process_path_regex", "PROCESS-NAME": "process_name", "NETWORK": "network", "UID": "user_id", "IN_NAME": "inbound", "Sing_PROTOCOL": "protocol", "AND": "and", "OR": "or", // "NOT": "invert", // #TBD: invert rules } // mihomo source route rule w/o matching or no need to convert // IP-SUFFIX IP-ASN // destination IP rules // SRC-GEOIP SRC-IP-ASN SRC-IP-SUFFIX // source IP rules // IN-PORT IN-TYPE IN-USER IN-NAME // inbound rules // PROCESS-NAME-REGEX // UID // DSCP // RULE-SET // SUB-RULE // MATCH ================================================ FILE: functions/internal/data/ruleset/transformGeoRef.ts ================================================ export type headlessRuleSet = { type: "remote", tag: string, url: string, format: "binary" | "source", } export function transformGeoRef ( type: string, payload: string, EdgeSubInstanceBaseURL ): { headlessRule: any, headlessRuleSet: headlessRuleSet | null } { const RuleSetTag = `${type}-${payload.toLowerCase()}`; if (RuleSetTag === "geoip-lan") { return { headlessRule: { ip_is_private: true, }, headlessRuleSet: null } } // let edge-sub preprocess the rule-set // construct url let RuleSetURLObject = new URL(EdgeSubInstanceBaseURL); RuleSetURLObject.pathname = "/ruleset/proxy"; RuleSetURLObject.search = ""; RuleSetURLObject.searchParams.append("target", `https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/${RuleSetTag}.srs`); const RuleSetURL = RuleSetURLObject.toString(); return { headlessRule: { rule_set: RuleSetTag, }, headlessRuleSet: { type: "remote", tag: RuleSetTag, format: "binary", url: RuleSetURL, } } } ================================================ FILE: functions/internal/getParsedSubData.ts ================================================ import type { ClashMetaConfig } from "./types/ClashMetaConfig"; import { DefaultRequestHeaders } from "./configs"; import { ShareLinkParser } from "./Parsers/share-link"; import { ClashMetaParser } from "./Parsers/clash-meta"; import { SingBoxParser } from "./Parsers/sing-box"; import { parseYAML } from "confbox"; import { TrulyAssign } from "./utils/TrulyAssign"; import { parseContentDisposition } from "./utils/parseContentDisposition"; type SubURL = string; // start with `short:`, `http(s)://`, or sth like `[proxy protocol]://` type SubURLs = string; // contains SubURL a lot type SubURLArr = SubURL[]; // usually it is some SubURLs squeeze into a Array. type ParsedSubscription = { data: any[]; SubscriptionUserInfo?: SubscriptionUserInfo; }; type SubscriptionUserInfo = { traffic?: string; // e.g. 'upload=; download=; total=; expire=', from `subscription-userinfo` header name?: string; // e.g. 'Nexitally', from `content-disposition` header filename field. } /** * * @returns {Array} */ export default async function getParsedSubData ( SubURLs: SubURLs, EdgeSubDB, isShowHost = false as boolean, CustomHTTPHeaders = {} as Headers, ExcludeRegExpPattern = "" ) { let __startTime = performance.now(); console.info("[Fetch Sub Data] Job started") console.info(`[Fetch Sub Data] isShowHost: ${isShowHost.toString()}`) const RequestHeaders = TrulyAssign(DefaultRequestHeaders, CustomHTTPHeaders); let SubURLArr = SubURLs.replaceAll("\r", "\n").split("\n").filter((i) => !!i).map(i => encodeURIComponent(i.trim())).map(i => decodeURIComponent(i)) as SubURLArr; let Proxies = [], SubscriptionUserInfos: SubscriptionUserInfo[] = []; for (let i in SubURLArr) { console.info(`[Fetch Sub Data] Fetching ${parseInt(i) + 1}/${SubURLArr.length}`) const ParsedSubscription = await ParseSubData(SubURLArr[i], EdgeSubDB, RequestHeaders); Proxies = [...Proxies, ...ParsedSubscription.data]; if (ParsedSubscription.SubscriptionUserInfo) { SubscriptionUserInfos.push(ParsedSubscription.SubscriptionUserInfo); } } if (isShowHost === true) { Proxies = Proxies.map(i => { i.__Remark = `${i.__Remark} - ${i.Hostname}:${i.Port}` return i; }) } if (!!ExcludeRegExpPattern) { const ExcludeRegExp = new RegExp(ExcludeRegExpPattern, "g") console.log("[Fetch Sub Data] filtering out outbounds matched with", ExcludeRegExp) Proxies = Proxies.filter(i => !i.__Remark.match(ExcludeRegExp)) } console.info(`[Fetch Sub Data] Job done, wasting ${performance.now() - __startTime}ms.`) return {Proxies, SubscriptionUserInfos}; } async function ParseSubData (SubURL: SubURL, EdgeSubDB, RequestHeaders) : Promise { // pre define SubscriptionUserInfo let SubscriptionUserInfo: SubscriptionUserInfo; // handle `short` here if (SubURL.match(/^short:/i)) { let ShortData: SubURLs = await EdgeSubDB.get(SubURL).then(res => JSON.parse(res).subdata); console.info(`[Fetch Sub Data] starting sub task for ${SubURL}`) let ParsedShortData = (await getParsedSubData(ShortData, EdgeSubDB, RequestHeaders)).Proxies; console.info(`[Fetch Sub Data] sub task for ${SubURL} done`) return { data: ParsedShortData }; } let SubData; // handle bundle share link (not starts with `http(s|)://` ) if (!SubURL.match(/^http(s|):\/\//i)) { SubData = { type: "share-link", data: SubURL } } else { SubData = await fetch(SubURL, { headers: RequestHeaders }) .then(async res => { console.info(`[Fetch Sub Data] Response status code ${res.status}`); return { data: await res.text(), headers: res.headers } }) .then(res => { // fill out SubscriptionUserInfo SubscriptionUserInfo = { traffic: res.headers.has("Subscription-UserInfo") ? res.headers.get("Subscription-UserInfo") : null, name: res.headers.has("Content-Disposition") ? parseContentDisposition(res.headers.get("Content-Disposition")) : null }; // try decode as yaml, for clash-meta config try { let YAMLData = parseYAML(res.data) as ClashMetaConfig; if (YAMLData.proxies) { return { type: "clash-meta", data: YAMLData } } } catch (e) { console.warn(`[Fetch Sub Data] Err when try parse as yaml: ${e}, skipping...`) } // try decode as json, for sing-box config try { let SingBoxConfig = JSON.parse(res.data); if (SingBoxConfig.outbounds) { return { type: "sing-box", data: SingBoxConfig } } } catch (e) { console.warn(`[Fetch Sub Data] Err when try parse as JSON (sing-box): ${e}, skipping...`) } // try decode as base64 endoded share-links try { let decodedData = atob(res.data.trim()); if (!decodedData.match(/\:\/\//gi)) { throw "seems like base64 decoded data malformed" } return { type: "share-link", data: decodedData } } catch (e) { console.warn(`[Fetch Sub Data] try parse as base64: ${e}, skipping...`) } // final return as share-link return { type: "share-link", data: res.data } }) } let ParsedSubData = []; if (SubData.type === "share-link") { let links = SubData.data.replaceAll("\r", "\n").split("\n").filter(loc => !!loc); let Parser = new ShareLinkParser(); for (let i of links) { let protocol = i.split(":")[0]; try { if (Parser.__validate(i)) { ParsedSubData.push(Parser[protocol](i)) } } catch (e) { console.warn(`[Fetch Sub Data] this share-url doesn't seem right, ignoring... ('${i}')`) console.warn(e) } } } else if (SubData.type === "clash-meta") { let { proxies } = SubData.data; let Parser = new ClashMetaParser(); for (let i of proxies) { if (Parser.__validate(i)) { ParsedSubData.push(Parser[i.type](i)) } } } else if (SubData.type === "sing-box") { let { outbounds } = SubData.data; let Parser = new SingBoxParser(); for (let i of outbounds) { if (Parser.__validate(i)) { ParsedSubData.push(Parser[i.type](i)) } } } return { data: ParsedSubData, SubscriptionUserInfo, }; } ================================================ FILE: functions/internal/types/ClashMetaConfig.ts ================================================ // reference: https://wiki.metacubex.one/ type ClashMetaProxyGroup = { name: string; type: string; // head to https://wiki.metacubex.one/config/proxy-groups/ url?: string | URL; interval?: number; tolerance?: number; proxies: string[] } export type ClashMetaConfig = { port: number; "socks-port": number; "allow-lan": boolean; mode: "Rule" | "Global" | "Direct"; "log-level": "silent" | "error" | "warning" | "info" | "debug"; "external-controller": string; // start with ":" ipv6: boolean; // default true dns: { enabled: boolean; // default true nameserver: string[]; fallback: string[]; }; proxies: [] "proxy-groups": ClashMetaProxyGroup[]; rules: string[] // head to https://wiki.metacubex.one/config/rules/ } // for transport layers export type TransportHTTP = { method: string; path: string[]; headers?: { host?: string }; } export type TransportH2 = { method: string; path: string; } export type TransportGRPC = { "grpc-service-name": string; } export type TransportWS = { path?: string; headers?: { host?: string }; "max-early-data"?: number; "early-data-header-name"?: "Sec-WebSocket-Protocol" | string; "v2ray-http-upgrade"?: unknown; "v2ray-http-upgrade-fast-open"?: unknown; } // for reality export type RealityConfig = { "public-key"?: string; "short-id"?: string; } ================================================ FILE: functions/internal/utils/TrulyAssign.js ================================================ /** * Assign source to target, note that its only for the first frame. * You will not get the target modified, instead, the target you need is in the returns. * @param {Object} target * @param {Object} source * @returns {Object} Assigned Target */ export function TrulyAssign (target, source) { let DeepCopiedTarget = JSON.parse(JSON.stringify(target)) for (let key in source) { if (key in source && source[key] !== "__DEFAULT") { DeepCopiedTarget[key] = source[key]; } } return DeepCopiedTarget; } ================================================ FILE: functions/internal/utils/fetchCached.ts ================================================ export async function fetchCached (URL: URL, Prefix = "Cached", CacheDB: KVNamespace, isForcedRefresh = false) { // const CacheKey = `RuleProvider_${URL}`; const CacheKey = `${Prefix}_${URL}`; const CacheTTL = 6 * 60 * 60; // 6hrs for default // check if data was cached let CachedData: string | null; if (!CacheDB) { CachedData = null; console.info(`[fetchCached] - CacheDB is not configured, fetching.`) } else { if (isForcedRefresh) { CachedData = null; } else { CachedData = await CacheDB.get(CacheKey) } } // return cached data when it exist if (CachedData) { return CachedData; } console.info(`[fetchCached] - "${CacheKey}" is not cached, fetching.`) // only when CachedData == falsy let data = await fetch (URL) .then(res => { if (res.status === 200 || res.status === 304) { return res } else { throw "Failed to fetch." } }) .then(res => res.text()) .catch(() => null); // save it into CacheDB when success, and, whatever, when CacheDB exist. if (data !== null && CacheDB) { await CacheDB.put(CacheKey, data.toString(), { expirationTtl: CacheTTL }) } // just return return data; } ================================================ FILE: functions/internal/utils/parseContentDisposition.ts ================================================ export function parseContentDisposition(RawContentDispositionHeader: string): string { if (!RawContentDispositionHeader || !RawContentDispositionHeader.toLowerCase().startsWith('attachment')) { console.warn('Invalid Content-Disposition header'); return null; } // Match filename*= (RFC 5987) const filenameStarMatch = RawContentDispositionHeader.match(/filename\*\s*=\s*([^'"]*)''([^;]+)/i); if (filenameStarMatch) { try { const encoding = filenameStarMatch[1].toLowerCase(); const filenameEncoded = filenameStarMatch[2]; return decodeURIComponent(filenameEncoded); } catch (err) { return null; } } // Match filename= (quoted or unquoted) const filenameMatch = RawContentDispositionHeader.match(/filename\s*=\s*("?)([^";]+)\1/i); if (filenameMatch) { return filenameMatch[2]; } return null; // No fucking filename found } ================================================ FILE: functions/internal/utils/removeUndefinedFields.ts ================================================ export function removeUndefinedFields (obj: object) : object { for (const key in obj) { if (typeof obj[key] === 'object' && obj[key] !== null) { removeUndefinedFields(obj[key]); } if (obj[key] === undefined) { delete obj[key]; } } return obj; } ================================================ FILE: functions/ruleset/preprocessor/sing-box.ts ================================================ import { fetchCached } from "../../internal/utils/fetchCached.js"; import { MetaToSingRuleMapping } from "functions/internal/data/rule/MetaToSingMapping.js"; export async function onRequest (context) { const { request } = context; const URLObject = new URL(request.url); const targetURL = URLObject.searchParams.get("target") as unknown as URL; const isForcedRefresh = URLObject.searchParams.get("forced_refresh") === "true" ? true : false; if (!targetURL) { return new Response("400 Bad Request. 'targetURL' required.", { status: 200, headers: { "Content-Type": "text/plain; charset=utf-8" } }) } let RawData = await fetchCached(targetURL, "RuleSet", context.env.EdgeSubDB, isForcedRefresh); let RulesList = RawData.split("\n").map(i => i.trim()).filter(i => i.length > 0 && !i.startsWith("#")).map(i => i.split(",").map(j => j.trim())); // merge up rules let rules = {}; // ref: https://sing-box.sagernet.org/configuration/rule-set/headless-rule/ for (let i of RulesList) { const type = MetaToSingRuleMapping[i[0]], payload = i[1]; if (!type) { continue } if (!(type in rules)) { rules[type] = []; } rules[type].push(payload); } return new Response(JSON.stringify({ "version": 1, rules: [ rules ] }), { status: 200, headers: { "Content-Type": "application/json; charset=utf-8", "Content-Length": RawData.length } }) } ================================================ FILE: functions/ruleset/proxy.ts ================================================ import { fetchCached } from "../internal/utils/fetchCached.js"; export async function onRequest (context) { const { request } = context; const URLObject = new URL(request.url); const targetURL = URLObject.searchParams.get("target") as unknown as URL; if (!targetURL) { return new Response("400 Bad Request. 'targetURL' required.", { status: 200, headers: { "Content-Type": "text/plain; charset=utf-8" } }) } let RawData = await fetch(targetURL); return new Response(RawData.body, { status: 200, headers: RawData.headers }) } ================================================ FILE: functions/short/admin-password/set.ts ================================================ import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader"; import { sha256 } from "js-sha256"; export async function onRequestPost (context) { const { request } = context; const url = new URL(request.url); const defaultHeader = getDefaultHeader(url); const EdgeSubDB = context.env.EdgeSubDB; const { oldPassword, // will be false is client thinks the password is not set newPassword // new password, not hashed } = await request.json() const hashedOldPassword = sha256(oldPassword) const hashedNewPassword = sha256(newPassword) // security check? if (url.hostname === "localhost") { console.info("[setPassword - security check] in development, ignoring...") } else { if (url.protocol === "http:") { console.warn("[setPassword - security check] requested via http, upgrading to https") if (url.protocol === "http:") { url.protocol = "https:" return Response.redirect(url.toString(), 301) } } } if (!newPassword) { return new Response ( JSON.stringify({ msg: "new password cant be empty", passwordUpdated: false }), { status: 400, headers: defaultHeader } ) } let oldPasswordInDB = await EdgeSubDB.get("admin-password"); if ( !oldPasswordInDB || // should be true when there isn't any old password hashedOldPassword == oldPasswordInDB // should be true when there is an password in db and matched ) { await EdgeSubDB.put("admin-password", hashedNewPassword); } else { return new Response ( JSON.stringify({ msg: "the provided old password does not match with the old password in database.", passwordUpdated: false }), { status: 422, headers: defaultHeader } ) } return new Response ( JSON.stringify({ msg: "OK", passwordUpdated: true }), { status: 200, headers: defaultHeader } ) } export async function onRequestOptions (context) { const url = new URL(context.request.url); return new Response("OK", { status: 200, headers: getOptionsHeader(url) }); } ================================================ FILE: functions/short/admin-password/status.ts ================================================ import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader"; export async function onRequest (context) { const { request } = context; const defaultHeader = getDefaultHeader(new URL(request.url)); const EdgeSubDB = context.env.EdgeSubDB; let hashedPassword = await EdgeSubDB.get("admin-password"); return new Response ( JSON.stringify({ msg: "OK", isPasswordSet: !!hashedPassword }), { status: 200, headers: defaultHeader } ) } ================================================ FILE: functions/short/delete/[id].ts ================================================ import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader"; export async function onRequestDelete (context) { const { id } = context.params; const EdgeSubDB = context.env.EdgeSubDB; const defaultHeader = getDefaultHeader(new URL(context.request.url)); let { token } = await context.request.json(); if (!token) { return new Response( JSON.stringify({ msg: "400 Bad Request. token missing or empty." }), { status: 400, headers: defaultHeader } ) } let storedData = await EdgeSubDB.get(`short:${id}`); if (storedData) { // when data exists let storedJSON = JSON.parse(storedData); let storedToken = storedJSON.token ?? storedJSON.password; if (storedToken !== token) { // when token doesnt matchs return new Response( JSON.stringify({ msg: "401 Unauthorized. Incorrect short token." }), { status: 401, headers: defaultHeader } ) } } else { return new Response( JSON.stringify({ msg: "404 Not Found. requested short not exist.", }), { status: 404, headers: defaultHeader } ) } // when all the things seems right, eg: data not exist or token matches. await EdgeSubDB.delete(`short:${id}`) return new Response( JSON.stringify({ msg: `200 OK. short:${id} has been deleted.`, }), { status: 200, headers: defaultHeader } ) } export async function onRequestOptions (context) { return new Response("OK", { status: 200, headers: getOptionsHeader(new URL(context.request.url), [ "DELETE" ]) }); } ================================================ FILE: functions/short/get/[id].ts ================================================ import { getDefaultHeader } from "../utils/defaultHeader"; export async function onRequest (context) { const { id } = context.params; const EdgeSubDB = context.env.EdgeSubDB; const defaultHeader = getDefaultHeader(new URL(context.request.url)); let storedData = await EdgeSubDB.get(`short:${id}`); if (storedData) { let { subdata } = JSON.parse(storedData); return new Response( JSON.stringify({ msg: "OK", subdata, }), { status: 200, headers: defaultHeader } ) } else { return new Response( JSON.stringify({ msg: "Not Found" }), { status: 404, headers: defaultHeader } ) } } ================================================ FILE: functions/short/list.ts ================================================ import { getDefaultHeader, getOptionsHeader } from "./utils/defaultHeader"; import { sha256 } from "js-sha256"; export async function onRequestPost (context) { const { request } = context; const defaultHeader = getDefaultHeader(new URL(request.url)); const EdgeSubDB = context.env.EdgeSubDB; const { password } = await request.json() const hashedPassword = sha256(password) const hashedPasswordInDB = await EdgeSubDB.get("admin-password"); // check for password if (hashedPassword !== hashedPasswordInDB) { return new Response ( JSON.stringify({ msg: "the provided old password does not match with the old password in database", success: false, shortIDs: [] }), { status: 401, headers: defaultHeader } ) } // const shortIDs = // ((await EdgeSubDB.list({ prefix: "short:" })).keys || []) // .map(i => { // return { // name: i.name, // timestamp: EdgeSubDB.get(i.name).then(res => JSON.parse(res).timestamp) // its needed to be // } // }); const shortIDs = await EdgeSubDB.list({ prefix: "short:" }) .then(async listResult => { const keys = listResult.keys || []; const shortIDs = []; for (let i of keys) { let ShortItem = await EdgeSubDB.get(i.name) .then(res => JSON.parse(res).timestamp) .then(timestamp => ({ name: i.name, timestamp })); shortIDs.push(ShortItem) } return shortIDs }) .catch(error => { throw "Error fetching short IDs:" + error }); return new Response ( JSON.stringify({ msg: "OK", success: true, shortIDs }), { status: 200, headers: defaultHeader } ) } export async function onRequestOptions (context) { const url = new URL(context.request.url); return new Response("OK", { status: 200, headers: getOptionsHeader(url) }); } ================================================ FILE: functions/short/put.ts ================================================ import { getDefaultHeader, getOptionsHeader } from "./utils/defaultHeader"; export async function onRequestPost (context) { const { request } = context; const defaultHeader = getDefaultHeader(new URL(request.url)); const timestamp = Date.now(); const EdgeSubDB = context.env.EdgeSubDB; let { slug, token, subdata } = await request.json(); if (!slug && !token) { slug = await generateToken(8, EdgeSubDB); token = await generateToken(16); } let storedData = await EdgeSubDB.get(`short:${slug}`); if (storedData) { // when data exists let storedJSON = JSON.parse(storedData); let storedToken = storedJSON.token ?? storedJSON.password; if (storedToken !== token) { // when token doesnt matchs return new Response( JSON.stringify({ msg: "401 Unauthorized. Incorrect short token.", slug, }), { status: 401, headers: defaultHeader } ) } } // when all the things seems right, eg: data not exist or token matches. await EdgeSubDB.put(`short:${slug}`, JSON.stringify({ token, subdata, timestamp })) return new Response( JSON.stringify({ msg: "OK", slug, token }), { status: 200, headers: defaultHeader } ) } export async function onRequestOptions (context) { return new Response("OK", { status: 200, headers: getOptionsHeader(new URL(context.request.url)) }); } async function generateToken (length, EdgeSubDB = undefined) { const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let strArr = []; for (let i = 0, n = chars.length; i < length; i++) { strArr.push(chars[Math.floor(Math.random() * n)]) } let str = strArr.join(""); if ( EdgeSubDB && !!(await EdgeSubDB.get(`short:${str}`)) ) { return generateToken(length, EdgeSubDB); } return str; } ================================================ FILE: functions/short/token-reset/[id].ts ================================================ import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader"; export async function onRequestPatch (context) { const { id } = context.params; const EdgeSubDB = context.env.EdgeSubDB; const defaultHeader = getDefaultHeader(new URL(context.request.url)); let { oldToken, newToken } = await context.request.json(); if (!oldToken || !newToken) { return new Response( JSON.stringify({ msg: "400 Bad Request. oldToken or newToken missing or empty." }), { status: 400, headers: defaultHeader } ) } let storedData = await EdgeSubDB.get(`short:${id}`); let storedJSON = JSON.parse(storedData); if (storedData) { // when data exists let storedToken = storedJSON.token ?? storedJSON.password; if (storedToken !== oldToken) { // when oldToken doesnt matchs return new Response( JSON.stringify({ msg: "401 Unauthorized. Incorrect short oldToken." }), { status: 401, headers: defaultHeader } ) } } else { return new Response( JSON.stringify({ msg: "404 Not Found. requested short not exist.", }), { status: 404, headers: defaultHeader } ) } // when all the things seems right, eg: data not exist or token matches. storedJSON.token = newToken; await EdgeSubDB.put(`short:${id}`, JSON.stringify(storedJSON)) return new Response( JSON.stringify({ msg: `200 OK. short:${id}'s token has been changed.`, }), { status: 200, headers: defaultHeader } ) } export async function onRequestOptions (context) { return new Response("OK", { status: 200, headers: getOptionsHeader(new URL(context.request.url), [ "PATCH" ]) }); } ================================================ FILE: functions/short/utils/defaultHeader.ts ================================================ export const getDefaultHeader = (url: URL) => { return { "Access-Control-Allow-Origin": getAllowedOriginHeader(url), "content-type": "application/json, charset=utf-8", "Access-Control-Allow-Credentials": "true", } as unknown as Headers; } export const getOptionsHeader = (url: URL, Methods = [ "POST" ]) => { Methods.push("OPTIONS") return { //"Access-Control-Allow-Origin": "localhost:4321") "Access-Control-Allow-Origin": getAllowedOriginHeader(url), "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": Methods.join(", "), } as unknown as Headers; } const getAllowedOriginHeader = (url: URL) => url.hostname === "localhost" ? "*" : `${url.protocol}//${url.host}`; ================================================ FILE: functions/sub/base64.js ================================================ import { onRequest as ShareLinkOnRequest } from "./share-link.js"; export async function onRequest (context) { return await ShareLinkOnRequest(context, true) } ================================================ FILE: functions/sub/clash-meta.js ================================================ import { getClashMetaConfig } from "../internal/Converter/getClashMetaConfig.js"; import getParsedSubData from "../internal/getParsedSubData.ts"; import { stringifyYAML } from "confbox"; export async function onRequest (context) { const { request } = context; const URLObject = new URL(request.url); let { Proxies, SubscriptionUserInfos } = await getParsedSubData( URLObject.searchParams.get("url"), context.env.EdgeSubDB, URLObject.searchParams.get("show_host") === "true", JSON.parse(URLObject.searchParams.get("http_headers")), URLObject.searchParams.get("ExcludeRegExpPattern"), ); // a javascript object !!! not YAML !!! let ClashMetaConfigObject = await getClashMetaConfig ( Proxies, context.env.EdgeSubDB, { isUDP: URLObject.searchParams.get("udp") === "true", isSSUoT: URLObject.searchParams.get("ss_uot") === "true", isInsecure: true, RuleProvider: URLObject.searchParams.get("remote_config") || "__DEFAULT", RuleProvidersProxy: URLObject.searchParams.get("rule_providers_proxy"), BaseConfig: URLObject.searchParams.get("BaseConfig"), isForcedRefresh: URLObject.searchParams.get("forced_refresh") === "true", } ) // handle forced ws 0-rtt if (URLObject.searchParams.get("forced_ws0rtt") === "true") { console.info("[Main] ForcedWS0RTT enabled.") for (let i of ClashMetaConfigObject.proxies) { if (!("ws-opts" in i)) { continue; } i["ws-opts"]["max-early-data"] = 2560 i["ws-opts"]["early-data-header-name"] = "Sec-WebSocket-Protocol" } } const ResponseBody = stringifyYAML(ClashMetaConfigObject); const response = new Response( ResponseBody, { status: 200, headers: { "Content-Type": "text/plain; charset=utf-8", "Content-Length": ResponseBody.length, "Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0", } } ) if (SubscriptionUserInfos.length > 0) { let Names = SubscriptionUserInfos.map(i => i.name).filter(i => !!i); // two name, then eclipse... let NamesLimit = Names.length > 2 ? 2 : Names.length; let Filename = `${Names.slice(0, NamesLimit).join(", ")}, and ${SubscriptionUserInfos.length - NamesLimit} more`; response.headers.set("Content-Disposition", `attachment; filename*=UTF-8''${encodeURIComponent(Filename)}.yaml`); let Traffic = SubscriptionUserInfos.map(i => i.traffic).filter(i => !!i)[0]; // first element of SubscriptionUserInfos // if Names.length > 1, then we shouldn't use such per-profile specific traffic values. if (Names.length === 1) { response.headers.set("Subscription-UserInfo", Traffic); } } return response; } ================================================ FILE: functions/sub/debug.js ================================================ import getParsedSubData from "../internal/getParsedSubData.ts"; export async function onRequest (context) { const { request } = context; const URLObject = new URL(request.url); const { Proxies } = await getParsedSubData( URLObject.searchParams.get("url"), context.env.EdgeSubDB, URLObject.searchParams.get("show_host") === "true", JSON.parse(URLObject.searchParams.get("http_headers")), URLObject.searchParams.get("ExcludeRegExpPattern"), ); const ResponseBody = JSON.stringify(Proxies) return new Response(ResponseBody, { status: 200, headers: { "Content-Type": "application/json, charset=utf-8", "Content-Length": ResponseBody.length, } }) } ================================================ FILE: functions/sub/share-link.js ================================================ import getParsedSubData from "../internal/getParsedSubData.ts"; import { ShareLinkDumper } from "../internal/Dumpers/share-link.js"; export async function onRequest (context, isBase64 = false) { const { request } = context; const URLObject = new URL(request.url); // do convert const { Proxies } = await getParsedSubData( URLObject.searchParams.get("url"), context.env.EdgeSubDB, URLObject.searchParams.get("show_host") === "true", JSON.parse(URLObject.searchParams.get("http_headers")), URLObject.searchParams.get("ExcludeRegExpPattern"), ); let Dumper = new ShareLinkDumper(); let ShareLinkArray = []; for (let i of Proxies) { if (Dumper[i.__Type]) { ShareLinkArray.push(Dumper[i.__Type](i)) } } // generate final response let ShareLinkResponse = ShareLinkArray.join("\n"); if (isBase64 === true) { ShareLinkResponse = btoa(ShareLinkResponse); } return new Response(ShareLinkResponse, { status: 200, headers: { "Content-Type": "text/plain, charset=utf-8", "Content-Length": ShareLinkResponse.length } }) } ================================================ FILE: functions/sub/sing-box.js ================================================ import { getSingBoxConfig } from "../internal/Converter/getSingBoxConfig.ts"; import getParsedSubData from "../internal/getParsedSubData.ts"; export async function onRequest (context) { const { request } = context; const URLObject = new URL(request.url); let { Proxies } = await getParsedSubData( URLObject.searchParams.get("url"), context.env.EdgeSubDB, URLObject.searchParams.get("show_host") === "true", JSON.parse(URLObject.searchParams.get("http_headers")), URLObject.searchParams.get("ExcludeRegExpPattern"), ); // a javascript object !!! not YAML !!! let SingBoxConfigObject = await getSingBoxConfig ( Proxies, context.env.EdgeSubDB, { isUDP: URLObject.searchParams.get("udp") === "true", isSSUoT: URLObject.searchParams.get("ss_uot") === "true", isInsecure: true, RuleProvider: URLObject.searchParams.get("remote_config") || "__DEFAULT", RuleProvidersProxy: URLObject.searchParams.get("rule_providers_proxy"), BaseConfig: URLObject.searchParams.get("BaseConfig"), isForcedRefresh: URLObject.searchParams.get("forced_refresh") === "true" ? true : false } ) // handle forced ws 0-rtt if (URLObject.searchParams.get("forced_ws0rtt") === "true") { console.info("[Main] ForcedWS0RTT enabled.") for (let i of SingBoxConfigObject.outbounds) { if (!("transport" in i)) { continue; } if (i.transport.type !== "ws") { continue; } i.transport.max_early_data = 2560 i.transport.early_data_header_name = "Sec-WebSocket-Protocol" } } const ResponseBody = JSON.stringify(SingBoxConfigObject) return new Response(ResponseBody, { status: 200, headers: { "Content-Type": "application/json; charset=utf-8", "Content-Length": ResponseBody.length, } }) } ================================================ FILE: package.json ================================================ { "name": "edge-sub", "type": "module", "version": "1.0.0", "license": "AGPL-3", "author": "kobe-koto", "homepage": "https://github.com/kobe-koto/EdgeSub", "scripts": { "build:frontend": "astro build", "dev": "concurrently 'wrangler pages dev ./' 'astro dev'", "dev:frontend": "astro dev", "dev:backend": "wrangler pages dev ./", "generate-types": "wrangler types ./types/worker-configuration.d.ts", "type-check": "generate-types && tsc" }, "dependencies": { "@iconify-json/iconoir": "^1.2.7", "@tailwindcss/vite": "^4.1.10", "astro": "5.4.1", "astro-compress": "^2.3.6", "astro-icon": "^1.1.5", "astro-seo": "^0.8.4", "confbox": "^0.2.2", "daisyui": "^5.0.43", "generate-password": "^1.7.1", "js-sha256": "^0.11.0", "sass": "^1.85.1", "tailwindcss": "^4.1.10" }, "devDependencies": { "concurrently": "^9.2.0" }, "trustedDependencies": [ "@parcel/watcher", "@tailwindcss/oxide", "esbuild", "sharp" ] } ================================================ FILE: public/basic-config/mihomo.yaml ================================================ auto-detect-interface: true log-level: "info" port: 7890 mixed-port: 7891 mode: "Rule" external-controller: ":9090" dns: enable: true ipv6: true listen: 0.0.0.0:1053 cache-algorithm: arc respect-rules: false enhanced-mode: fake-ip fake-ip-range: 198.18.0.1/16 fake-ip-filter-mode: blacklist fake-ip-filter: - '*' - '.lan' - lancache.steamcontent.com default-nameserver: - 119.29.29.29 - 223.5.5.5 nameserver: - https://doh.pub/dns-query - https://dns.alidns.com/dns-query direct-nameserver: - https://doh.pub/dns-query - https://dns.alidns.com/dns-query fallback: - https://dns.google/dns-query - https://cloudflare-dns.com/dns-query fallback-filter: geoip: true geoip-code: CN ipcidr: - 240.0.0.0/4 - 0.0.0.0/24 - 127.0.0.1/24 ================================================ FILE: public/basic-config/sing-box.jsonc ================================================ { "log": { "disabled": false, "level": "info" }, "dns": { "servers": [ { "tag": "hosts", "type": "hosts" }, { "tag": "google", "type": "tls", "server": "8.8.8.8" }, { "tag": "local", "type": "udp", "server": "223.5.5.5" }, { "tag": "remote", "type": "fakeip", "inet4_range": "198.18.0.0/15", "inet6_range": "fc00::/18" } ], "rules": [ { "ip_accept_any": true, "action": "route", "server": "hosts" }, { "query_type": [ "A", "AAAA" ], "server": "remote" } ], "independent_cache": true }, "inbounds": [ { "type": "mixed", "tag": "mixed-in", "listen": "127.0.0.1", "listen_port": 7890 }, { "type": "tun", "tag": "tun-in", "address": [ "172.19.0.1/30", "fdfe:dcba:9876::1/126" ], "auto_route": true } ], "experimental": { "clash_api": { "external_controller": "127.0.0.1:9090", "external_ui": "ui", "secret": "", "external_ui_download_url": "https://github.com/MetaCubeX/metacubexd/archive/refs/heads/gh-pages.zip", "external_ui_download_detour": "DIRECT", "default_mode": "rule" }, "cache_file": { "enabled": true, "store_fakeip": false } }, "outbounds": [ { "type": "direct", "tag": "DIRECT" }, { "type": "block", "tag": "REJECT" } ], "route": { "rules": [ { "action": "sniff" }, { "protocol": "dns", "action": "hijack-dns" }, { "ip_is_private": true, "outbound": "direct" }, { "clash_mode": "direct", "outbound": "DIRECT" }, { "clash_mode": "global", "outbound": "GLOBAL" } ], "rule_set": [], "geosite": { "download_detour": "DIRECT" }, "geoip": { "download_detour": "DIRECT" }, "default_domain_resolver": "local", "auto_detect_interface": true } } ================================================ FILE: public/minimal_remote_rules.ini ================================================ ;https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini [custom] ruleset=Proxies,[]DOMAIN-SUFFIX,googleapis.cn ruleset=CN-Directed,[]GEOIP,CN ruleset=CN-Directed,[]GEOSITE,CN ruleset=Proxies,[]MATCH custom_proxy_group=Proxies`select`[]DIRECT`[]REJECT`.* custom_proxy_group=CN-Directed`select`[]DIRECT`[]REJECT`[]Proxies ================================================ FILE: readme.md ================================================ # Edge Sub 在 CloudFlare 的全球網絡上轉換您的代理訂閱. 請為我點一個 ⭐ Star! ## 使用方式 - ### UI 在 Cloudflare Pages 部署後打開,並按提示操作。 - ### Debug > **⚠️ Warning** > > 該格式隨時可能發生變更, 僅供測試用途 Endpoint: `/sub/debug` 需要以下參數: - `url`: 輸入的訂閱的遠程位址 ## 部署 - ### 在 Cloudflare Pages 上部署 0. Fork 本項目 1. 打開 dash.cloudflare.com 2. 轉到側邊欄上的 **Workers & Pages** (Overview) 部分 3. 按下 **Create** 按鈕 4. 切換到 **Pages** 欄 5. 按 **Connect to Git** 6. 選擇你剛 Fork 下來的 EdgeSub 項目 7. 在 **Build settings > Framework preset** 中選擇 Astro 8. 編輯 **Build settings > Build command** 為 `pnpm build:frontend` 9. 按下 **Save and Deploy** 10. 部署完成後,你可能需要添加自訂網域,請前往 **項目 > Custom domains** 添加 #### ✡️ 可選 - 為遠端規則添加緩存以加快處理速度: **需要注意的是,開發時會以假設緩存 KV 存在來開發,無緩存 KV 環境將作為低優先級來開發。** **因此,不添加緩存 KV 是不被推薦的行為。** 1. 轉到 **Workers & Pages > KV** 2. 按 **Create a namespacce**,**輸入任意名字**,然後按 **Add** 3. 回到項目 4. 轉到 **Settings > Functions > KV namespace bindings** 5. 按 **Add binding** 6. 在 **Variable name** 填寫 `EdgeSubDB`,**KV namespace** 選擇你剛建立的 KV 空間 7. 點按 **Save** 8. 轉到**項目 > Deployments** 9. 在 **All deployments** 中找到最近的一個 Deployment,然後點**右側三個點 > Retry Deployment** 10. 完成 ## 相容性表格 - 節點類型 | 類型 | 支援 | 已經測試 | Notes | | ------------ | ---- | -------- | ------------------------------------- | | HTTP | 🗿 | 🚫 | 由於與 **遠端訂閱** 不相容, 請勿直接傳入 HTTP Proxy | | Socks 5 | ✅ | 🚫 | | | Hysteria 1 | ✅ | ✅ | | | Hysteria 2 | ✅ | ✅ | | | TUIC v5 | ✅ | ✅ | | | Vmess | ✅ | ☑️ | 未經完全測試 | | Vless | ✅ | ☑️ | 未經完全測試 | | Shadowsocks | ✅ | ✅ | | | Trojan | ✅ | ✅ | | | WireGuard | 🚫 | - | 似乎沒有通用的 ShareLink 格式 | | ShadowsocksR | 🚫 | - | 暫無計劃實現 | | SSH | 🚫 | - | 暫無計劃實現 | - 訂閱類型 | 類型 | 輸入 | 輸出 | 輸出 Endpoint | | ----------------------- | ---- | ---- | ----------------- | | 內部除錯用格式 | 🚫 | ✅ | `/sub/debug` | | ShareLink 集合 | ✅ | ✅ | `/sub/share-link` | | ShareLink 集合 (Base64) | ✅ | ✅ | `/sub/base64` | | Clash Meta 配置 | ✅ | ✅ | `/sub/clash-meta` | | Sing-Box 配置 | ✅ | ✅ | `/sub/sing-box` | Notes: - Legacy Clash config support has been dropped at `Commit 13df326` - **內部除錯用格式**: 僅供除錯, 將會在未來的任意某個時間點做出破壞性改動或刪除. ## Remote Rules Parsing **ONLY** support .ini with `ruleset=` `custom_proxy_group=` and comments. ### Special Remote Rules - `Sing_PROTOCOL` see https://sing-box.sagernet.org/configuration/route/sniff/ ## Handling Traffic and Name Information **Note: This section's behavior description applies specifically to Clash Meta Config.** This section describes how `traffic` and `name` information is processed from incoming data. 1. **Data Parsing:** The `decodeURIComponent`-decoded URL (or "subdata") is parsed line by line. Each non-empty and valid line is treated as either a `Subscription` or a `Proxy`. * A `Subscription` object may contain a `SubscriptionUserInfo` attribute. * A `Proxy` object does not contain `SubscriptionUserInfo`. * The `SubscriptionUserInfo` attribute, if present, contains `traffic` and `name` fields. Both `traffic` and `name` can be empty or absent within `SubscriptionUserInfo`. 2. **Name Processing and Display:** Names that are extracted and considered "visible" (i.e., non-empty) are aggregated for display. If multiple visible names exist, they will be presented in a summarized format, for example: `Name1, Name2, and more` (where `` represents the count of additional subscriptions and proxies with visible names). *Note: A `name` might not be explicitly present or might be empty within a `SubscriptionUserInfo` object, even if `SubscriptionUserInfo` itself exists.* 3. **Traffic Data Handling:** Traffic data is processed based on the number of unique "visible" names found: * If only **one** visible `name` is identified across all parsed Subscriptions and Proxies, the first available `traffic` value will be displayed or passed through. The **order in which the lines are parsed** determines which `traffic` value is considered "first." * If **more than one** visible `name` is identified, traffic data will be ignored. ## Subscription Requesting When requesting subscriptions based on user-provided data, the following HTTP headers are used: 1. **Default HTTP Headers:** The application sends a set of default HTTP headers, as defined in `/functions/internal/configs.ts`. These include: ```json { "Accept": "*/*", "User-Agent": "EdgeSub-git/0.0.0 (Prefer ClashMeta / Mihomo Format)" } ``` 2. **User-Provided HTTP Headers:** Users can provide additional HTTP headers. The processing of these headers is as follows: * Any non-empty and valid user-provided header that shares a key with a default HTTP header will **overwrite** the corresponding default header. * Any non-conflicting user-provided headers (i.e., those with unique keys not present in the default set) will be **appended** to the request. ## Shorter Feature Security Overview Shorts data is **stored remotely** is **unencrypted**. * Each short is uniquely identified by a **Short ID**. * **Short IDs** provide **read-only access** to a specific short. * A corresponding **Short Token** grants **write access** to a specific short. These tokens are for access control only and are **not encryption keys**. The **Shorter Admin Password** allows viewing all Short IDs. If this password is forgotten, you will need to delete the "admin-password" key in the KV database and then setting a new one. ================================================ FILE: src/components/NavBar.astro ================================================ --- import { Icon } from "astro-icon/components"; --- ================================================ FILE: src/components/backendIndicator.astro ================================================ --- import { Icon } from "astro-icon/components"; --- ================================================ FILE: src/components/data-input.astro ================================================ --- import type { DropdownItemPrototype } from "@components/k-dropdown.astro"; import KDropdown from "@components/k-dropdown.astro"; interface Props { slug: string; desc: string; detail?: string; optional?: boolean; type: "input" | "textarea" | "k-dropdown" | "toggle"; DropdownDefault?: DropdownItemPrototype; DropdownItems?: DropdownItemPrototype[]; SwitchDefault?: boolean; } const { slug, desc, detail = "<暂未设定 detail 属性>", type, optional = false, DropdownDefault, DropdownItems, SwitchDefault = false, } = Astro.props; --- { type === "input" && (
{desc} { optional && 可选 }
) } { type === "textarea" && (