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/pages/index.astro
================================================
---
import Base from "@layouts/base.astro";
import SubURLGenerator from "@components/index/SubURLGenerator.astro";
//import KShorter from "@components/index/k-shorter.astro";
---
================================================
FILE: src/pages/shorter/admin.astro
================================================
---
import Base from "@layouts/base.astro";
import { Icon } from "astro-icon/components";
import BackendIndicator from "@components/backendIndicator.astro";
import ShorterPassword from "@components/shorter/shorter-password.astro";
---
Administration
Please ensure that you
have binded a KV correctly to the project.
Warning: The following content is intended only for instance
owners.
Admin password status
Admin password defined
Admin password undefined
Check failed, open console to get more information.
Checking....
If you forget your admin password, you have to delete the key
"admin-password" in the KV database and set a new one.
Set / Change Admin Password
================================================
FILE: src/pages/shorter/create.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";
import KShorter from "@components/shorter/k-shorter.astro";
---
Create a new Short
================================================
FILE: src/pages/shorter/destory.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";
import ShortDestroyer from "@components/shorter/short-destroyer.astro";
---
Destory a existing Short
================================================
FILE: src/pages/shorter/edit.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";
import ShortEditor from "@components/shorter/short-editor.astro"
---
Short Editior
================================================
FILE: src/pages/shorter/list.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";
import ShorterList from "@components/shorter/shorter-list.astro"
---
List all the Shorts
================================================
FILE: src/pages/shorter/reset-token.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";
import ShortTokenReset from "@components/shorter/short-token-reset.astro";
---
Reset Access Token for a existing Short
================================================
FILE: src/scripts/components/data-input.ts
================================================
import type { Dropdown } from "@scripts/components/k-dropdown";
export class DataInput extends HTMLElement {
type = this.dataset.type;
constructor () {
super ();
}
get () { // boolean if toggle, string if any otherwise
if (this.type === "textarea") {
return this.querySelector("textarea").value.trim();
} else if (this.type === "input") {
return this.querySelector("input").value.trim();
} else if (this.type === "k-dropdown") {
const DropdownElement = this.querySelector("k-dropdown") as Dropdown;
return DropdownElement.dataset.selectedValue;
} else if (this.type === "toggle") {
const ToggleElement = this.querySelector("input.toggle") as HTMLInputElement;
return ToggleElement.checked;
}
}
set (value: string) {
if (this.type === "textarea") {
this.querySelector("textarea").value = value.trim();
} else if (this.type === "input") {
this.querySelector("input").value = value.trim();
} else if (this.type === "k-dropdown") {
const DropdownElement = this.querySelector("k-dropdown") as Dropdown;
DropdownElement.select(value);
} else if (this.type === "toggle") {
const SwitchElement = this.querySelector("toggle") as HTMLInputElement;
SwitchElement.checked = value == "true"; // "true" or true or whatever.... it should be boolean
}
}
setDetail(value: string) {
if (this.type === "textarea") {
this.querySelector("textarea").placeholder = value;
return true;
} else if (this.type === "input") {
this.querySelector("input").placeholder = value;
return true;
}
return false;
}
getDetail() {
if (this.type === "textarea") {
return this.querySelector("textarea").placeholder;
} else if (this.type === "input") {
return this.querySelector("input").placeholder;
}
}
}
function maybeWaitFor(tag) {
return customElements.get(tag) || document.querySelector(tag)
? customElements.whenDefined(tag)
: Promise.resolve(); // No need to wait
}
Promise.all([
maybeWaitFor("toggle"),
maybeWaitFor("k-dropdown")
]).then(() => {
console.log("[data-input] dependency elements toggle and k-dropdown registered, initializing");
customElements.define("data-input", DataInput);
console.info("[data-input] registered")
});
// Promise.all([
// customElements.whenDefined("toggle"),
// customElements.whenDefined("k-dropdown")
// ]).then(() => {
// console.log("[data-input] dependency toggle and k-dropdown registration detected, initializing");
// customElements.define("data-input", DataInput);
// console.info("[data-input] registered")
// });
================================================
FILE: src/scripts/components/k-dropdown.ts
================================================
export class Dropdown extends HTMLElement {
constructor () {
super();
this.initializeElements();
this.setupEventListeners();
}
private initializeElements() {
this.Elements = {
DropdownBotton: this.querySelector("div.btn") as HTMLElement,
DropdownBottonText: this.querySelector("div.btn > span") as HTMLElement,
Items: this.querySelectorAll(".dropdown-content > li > a") as NodeListOf
};
}
private setupEventListeners() {
this.Elements.Items.forEach(item => {
item.addEventListener("click", (event) => {
const targetElement = event.target as HTMLElement;
this.select(targetElement.dataset.value);
});
});
}
public select(value: string) {
if (!value) {
console.error("[k-dropdown.select] value is required")
return false;
};
this.dataset.selectedValue = value;
// mark the selected
this.Elements.Items.forEach(item => {
if (item.dataset.value === value) {
item.classList.add("menu-active")
this.Elements.DropdownBottonText.innerText = item.innerText;
} else {
// cancel non-targets out
item.classList.remove("menu-active")
}
});
// dispatch custom event to notify
this.dispatchEvent(new CustomEvent("dropdown-select", {
bubbles: true,
composed: true,
detail: {
value,
}
}));
}
Elements: {
DropdownBotton: HTMLElement;
DropdownBottonText: HTMLElement;
Items: NodeListOf;
}
}
customElements.define("k-dropdown", Dropdown);
console.info("[k-dropdown] registered")
================================================
FILE: src/scripts/components/k-suburl-generator.ts
================================================
import type { DataInput } from "@scripts/components/data-input";
import type { EndpointExtendConfigPrototype, EndpointPrototype } from "@config/AvalibleOptoutFormat";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
import { copyToClipboard } from "@scripts/utils/copy";
import filterObject from "@scripts/utils/filterObject";
class SubURLGenerator extends HTMLElement {
Endpoints: EndpointPrototype[] = JSON.parse(this.dataset.endpoints);
defaultBackend = getDefaultBackend();
constructor () {
super()
this.setupEventListeners();
customElements.whenDefined("data-input").then(() => {
this.Elements.Config.Basic.Backend.setDetail(`${this.Elements.Config.Basic.Backend.getDetail()} (${this.defaultBackend})`);
console.info("[k-sub-url-generator] data-input registration detected, default backend modified")
})
}
private setupEventListeners () {
this.Elements.Action.Generate.addEventListener("click", () => {this.CheckAndGenerate()});
this.Elements.Action.Copy.addEventListener("click", () => {
copyToClipboard(this.Elements.Action.MsgBlock.innerText)
.then(() => {
alert("已将连接复制到剪贴板");
})
.catch((err) => {
console.error("[k-suburl-generator] copy failed", err);
alert("复制失败, 请检查浏览器权限设置, 版本, 或尝试手动复制.");
});
});
this.Elements.Config.Basic.Endpoint.addEventListener("dropdown-select", (event: CustomEvent) => {
const SelectedEndpointPath: string = event.detail.selectedValue;
let Endpoint: EndpointPrototype = this.GetEndpoint(SelectedEndpointPath);
let NeededExtendConfig = Endpoint.ExtendConfig || [];
for (let i in this.Elements.Config.Extended) {
if (NeededExtendConfig.includes(i as EndpointExtendConfigPrototype)) {
this.Elements.Config.Extended[i].style.removeProperty("display")
} else {
this.Elements.Config.Extended[i].style.setProperty("display", "none")
}
}
});
}
private Elements = {
Action: {
Generate: this.querySelector("button#generate") as HTMLButtonElement,
Copy: this.querySelector("button#copy") as HTMLButtonElement,
MsgBlock: this.querySelector("code") as HTMLElement,
},
Config: {
Basic: {
SubURL: this.querySelector("data-input#SubURL") as DataInput,
Backend: this.querySelector("data-input#Backend") as DataInput,
Endpoint: this.querySelector("data-input#Endpoint") as DataInput,
},
UniversalExtended: {
isShowHost: this.querySelector("data-input#isShowHost") as DataInput,
HTTPHeaders: this.querySelector("data-input#HTTPHeaders") as DataInput,
ExcludeRegExpPattern: this.querySelector("data-input#ExcludeRegExpPattern") as DataInput,
},
Extended: {
RuleProviderUserspec: this.querySelector("data-input#RuleProviderUserspec") as DataInput,
RuleProvider: this.querySelector("data-input#RuleProvider") as DataInput,
RuleProvidersProxy: this.querySelector("data-input#RuleProvidersProxy") as DataInput,
BaseConfig: this.querySelector("data-input#BaseConfig") as DataInput,
isUDP: this.querySelector("data-input#isUDP") as DataInput,
isSSUoT: this.querySelector("data-input#isSSUoT") as DataInput,
ForcedWS0RTT: this.querySelector("data-input#ForcedWS0RTT") as DataInput,
}
}
}
private GetEndpoint (EndpointPath: string = String(this.Elements.Config.Basic.Endpoint.get())) {
for (let i of this.Endpoints) {
if (i.value === EndpointPath) {
return i as EndpointPrototype;
}
}
throw `no targeted endpoint found, expected value ${EndpointPath}`
}
private getConfig () {
const Backend = new URL(String(this.Elements.Config.Basic.Backend.get() || this.defaultBackend));
return {
Basic: {
SubURL: this.Elements.Config.Basic.SubURL.get() as string,
Backend: Backend.toString() as string,
Endpoint: this.Elements.Config.Basic.Endpoint.get() as string,
},
UniversalExtended: {
isShowHost: this.Elements.Config.UniversalExtended.isShowHost.get() as boolean,
ExcludeRegExpPattern: this.Elements.Config.UniversalExtended.ExcludeRegExpPattern.get() as string,
HTTPHeaders: JSON.stringify(JSON.parse(String(this.Elements.Config.UniversalExtended.HTTPHeaders.get()) || "{}")) as string,
},
Extended: {
RuleProvider: (this.Elements.Config.Extended.RuleProviderUserspec.get() || this.Elements.Config.Extended.RuleProvider.get()) as string,
RuleProvidersProxy: (this.Elements.Config.Extended.RuleProvidersProxy.get() && this.Elements.Config.Basic.Backend.get() || this.defaultBackend) as string,
BaseConfig: this.Elements.Config.Extended.BaseConfig.get() || "__DEFAULT" as String,
isUDP: this.Elements.Config.Extended.isUDP.get() as boolean,
isSSUoT: this.Elements.Config.Extended.isSSUoT.get() as boolean,
ForcedWS0RTT: this.Elements.Config.Extended.ForcedWS0RTT.get() as boolean,
}
}
}
CheckAndGenerate () {
// Get config
const Config = this.getConfig();
// non-empty check for basic configs
let ErrorOccurred = false;
for (let [key, value] of Object.entries(Config.Basic)) {
if (typeof value === "string" && value.length === 0) {
alert(`${key} can't be empty`);
ErrorOccurred = true;
continue;
}
}
if (ErrorOccurred === true) {
return;
}
// now we do some real works! con---gra---tu---la--tion---s---!
// grab the backend
let URLObj = new URL(Config.Basic.Backend);
URLObj.pathname = Config.Basic.Endpoint;
URLObj.search = "";
URLObj.hash = "";
// append inputed data (subdata)
URLObj.searchParams.append("url", Config.Basic.SubURL)
// append extended config
// - currently we do this mapping on client side,
// but in the future we may want to do this on server side,
// just to keep the URL clean and uniform.
let Mapping = {
"RuleProvider": "remote_config",
"RuleProvidersProxy": "rule_providers_proxy",
"isUDP": "udp",
"isSSUoT": "ss_uot",
"ForcedWS0RTT": "forced_ws0rtt",
"isShowHost": "show_host",
"HTTPHeaders": "http_headers"
}
for (let [key, value] of Object.entries({
...filterObject(Config.Extended, (key) => (this.GetEndpoint().ExtendConfig || []).includes(key)),
...Config.UniversalExtended,
})) {
if (!String(value)) {
continue;
}
URLObj.searchParams.append(Mapping[key] || key, String(value));
}
this.Elements.Action.MsgBlock.innerText = URLObj.toString();
}
}
customElements.define("k-suburl-generator", SubURLGenerator)
console.info("[k-suburl-generator] registered")
================================================
FILE: src/scripts/components/shorter/k-shorter.ts
================================================
import type { DataInput } from "../data-input";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
export class Shorter extends HTMLElement {
defaultBackend = getDefaultBackend();
constructor () {
super();
this.setupEventListeners()
}
private setupEventListeners () {
this.Elements.SubmitButton.addEventListener("click", () => {this.Submit()});
this.Elements.CopyButton.addEventListener("click", () => {this.Copy()});
}
private Copy () {
// copy slug and token to clipboard
let slug = `short:${String(this.Elements.slug.get())}`;
navigator.clipboard.writeText(slug).then(() => {
alert(`已复制: ${slug}`);
}).catch(err => {
alert(`复制失败: ${err}`);
});
}
private async Submit () {
this.Elements.SubmitButton.disabled = true;
this.Elements.Msg.innerText = "正在提交...";
this.Elements.SubmitButton.querySelector(".swap").classList.add("swap-active");
// build request body
let requestBody = {
subdata: this.Elements.subdata.get(),
slug: this.Elements.slug.get(),
token: this.Elements.token.get(),
}
// build api Endpoint
let requestURL = new URL(this.defaultBackend);
requestURL.pathname = "/short/put";
await fetch(requestURL, {
body: JSON.stringify(requestBody),
method: "POST"
}).then(async res => {
// handle non-success request
if (res.status !== 200) throw await res.text();
// parse returned data as json
return res.json()
}).then(res => {
this.Elements.Msg.innerText = `short:${res.slug}`;
// sync slug and token with reponse
this.Elements.slug.set(res.slug);
this.Elements.token.set(res.token);
this.Elements.SubmitButton.disabled = false;
this.Elements.SubmitButton.querySelector(".swap").classList.remove("swap-active");
}).catch((err) => {
this.Elements.Msg.innerText = `提交失败: ${err}`;
this.Elements.SubmitButton.disabled = false;
this.Elements.SubmitButton.querySelector(".swap").classList.remove("swap-active");
})
}
Elements = {
subdata: this.querySelector("data-input#SubURL") as DataInput,
slug: this.querySelector("data-input#short-slug") as DataInput,
token: this.querySelector("data-input#short-token") as DataInput,
Msg: this.querySelector("code"),
SubmitButton: this.querySelector("button#shorter") as HTMLButtonElement,
CopyButton: this.querySelector("button#copy") as HTMLButtonElement,
}
}
customElements.define("k-shorter", Shorter);
console.info("[k-shorter] registered")
================================================
FILE: src/scripts/components/shorter/short-destroyer.ts
================================================
import type { DataInput } from "../data-input";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
export class Shorter extends HTMLElement {
defaultBackend = getDefaultBackend();
constructor () {
super();
this.Elements.SubmitButton.addEventListener("click", () => {this.Submit()})
}
async Submit () {
this.Elements.SubmitButton.disabled = true;
this.Elements.SubmitButton.querySelector(".swap").classList.add("swap-active");
// build api Endpoint
let requestURL = new URL(this.defaultBackend);
requestURL.pathname = `/short/delete/${this.Elements.slug.get()}`;
await fetch(requestURL, {
body: JSON.stringify({
token: this.Elements.token.get()
}),
method: "DELETE"
}).then(async res => {
// handle non-success request
if (res.status !== 200) throw await res.text();
// parse returned data as json
return res.json()
}).then(res => {
this.Elements.Msg.innerText = res.msg;
}).catch((err) => {
this.Elements.Msg.innerText = `提交失败: ${err}`;
}).finally(() => {
this.Elements.SubmitButton.disabled = false;
this.Elements.SubmitButton.querySelector(".swap").classList.remove("swap-active");
})
}
Elements = {
slug: this.querySelector("data-input#slug") as DataInput,
token: this.querySelector("data-input#token") as DataInput,
Msg: this.querySelector("code"),
SubmitButton: this.querySelector("#submit") as HTMLButtonElement,
}
}
customElements.define("short-destroyer", Shorter);
console.info("[short-destroyer] registered")
================================================
FILE: src/scripts/components/shorter/short-editor.ts
================================================
import type { DataInput } from "../data-input";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
export class ShortEditor extends HTMLElement {
defaultBackend = getDefaultBackend()
constructor () {
super();
this.Elements.SubmitButton.addEventListener("click", () => {this.Submit()})
this.Elements.FetchButton.addEventListener("click", () => {this.Fetch()})
let PassedID = new URL(location.href).searchParams.get("id");
if (PassedID) {
this.Elements.ShortID.set(PassedID)
this.Fetch()
}
}
Fetch () {
this.Elements.FetchButton.disabled = true;
this.Elements.FetchButton.querySelector(".swap").classList.add("swap-active");
this.Elements.ShortData.set("fetching...")
let requestURL = new URL(this.defaultBackend);
requestURL.pathname = `/short/get/${this.Elements.ShortID.get()}`;
fetch(requestURL)
.then(res => res.json())
.then(res => {
this.Elements.ShortData.set(res.subdata)
}).catch((err) => {
alert(`Error: ${err}`);
}).finally(() => {
this.Elements.FetchButton.disabled = false;
this.Elements.FetchButton.querySelector(".swap").classList.remove("swap-active");
})
}
Submit () {
this.Elements.SubmitButton.disabled = true;
this.Elements.SubmitButton.querySelector(".swap").classList.add("swap-active");
// build request body
let requestBody = {
subdata: this.Elements.ShortData.get(),
slug: this.Elements.ShortID.get(),
token: this.Elements.ShortPassword.get(),
}
// build api Endpoint
let requestURL = new URL(this.defaultBackend);
requestURL.pathname = "/short/put";
fetch(requestURL, {
body: JSON.stringify(requestBody),
method: "POST"
}).then(async res => {
// handle non-success request
if (res.status !== 200) throw await res.text();
// parse returned data as json
return res.json()
}).then(res => {
this.Elements.Msg.innerText = `short:${res.slug}`;
}).catch((err) => {
this.Elements.Msg.innerText = `提交失败: ${err}`;
}).finally(() => {
this.Elements.SubmitButton.disabled = false;
this.Elements.SubmitButton.querySelector(".swap").classList.remove("swap-active");
})
}
Elements = {
ShortID: this.querySelector("#short-id") as DataInput,
ShortPassword: this.querySelector("#short-password") as DataInput,
ShortData: this.querySelector("#short-data") as DataInput,
Msg: this.querySelector("code") as HTMLElement,
FetchButton: this.querySelector("#editor-fetch") as HTMLButtonElement,
SubmitButton: this.querySelector("#editor-submit") as HTMLButtonElement,
}
}
customElements.define("short-editor", ShortEditor);
console.info("[short-editor] registered")
================================================
FILE: src/scripts/components/shorter/short-token-reset.ts
================================================
import type { DataInput } from "../data-input";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
export class ShortTokenResetter extends HTMLElement {
defaultBackend = getDefaultBackend();
constructor () {
super();
this.Elements.SubmitButton.addEventListener("click", () => {this.Submit()})
}
async Submit () {
this.Elements.SubmitButton.disabled = true;
this.Elements.SubmitButton.querySelector(".swap").classList.add("swap-active");
// build api Endpoint
let requestURL = new URL(this.defaultBackend);
requestURL.pathname = `/short/token-reset/${this.Elements.slug.get()}`;
await fetch(requestURL, {
body: JSON.stringify({
oldToken: this.Elements.oldToken.get(),
newToken: this.Elements.newToken.get()
}),
method: "PATCH"
}).then(async res => {
// handle non-success request
if (res.status !== 200) throw await res.text();
// parse returned data as json
return res.json()
}).then(res => {
this.Elements.Msg.innerText = res.msg;
}).catch((err) => {
this.Elements.Msg.innerText = `提交失败: ${err}`;
}).finally(() => {
this.Elements.SubmitButton.disabled = false;
this.Elements.SubmitButton.querySelector(".swap").classList.remove("swap-active");
})
}
Elements = {
slug: this.querySelector("data-input#slug") as DataInput,
oldToken: this.querySelector("data-input#old-token") as DataInput,
newToken: this.querySelector("data-input#new-token") as DataInput,
Msg: this.querySelector("code"),
SubmitButton: this.querySelector("#submit") as HTMLButtonElement,
}
}
customElements.define("short-token-reset", ShortTokenResetter);
console.info("[short-token-reset] registered")
================================================
FILE: src/scripts/components/shorter/shorter-list.ts
================================================
import type { DataInput } from "../data-input";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
export class ShorterList extends HTMLElement {
defaultBackend = getDefaultBackend()
constructor () {
super();
this.Elements.SubmitButton.addEventListener("click", () => {this.Submit()})
}
async Submit () {
this.Elements.SubmitButton.disabled = true;
this.Elements.SubmitButton.querySelector(".swap").classList.add("swap-active");
// build request body
let requestBody = {
password: this.Elements.password.get()
}
// build api Endpoint
let requestURL = new URL(this.defaultBackend);
requestURL.pathname = "/short/list";
await fetch(requestURL, {
body: JSON.stringify(requestBody),
method: "POST"
}).then(async res => {
const resText = await res.text();
try {
return JSON.parse(resText)
} catch (e) {
throw resText
}
}).then(res => {
if (res.success) {
if (res.shortIDs.length === 0) {
alert("no shorts to see, add some and try again :)");
}
Array.from(this.Elements.ListItems.querySelectorAll("list-item:not(.hidden)")).map(i=>i.remove())
for (let i of res.shortIDs) {
let t = this.Elements.ListItemPrototype.cloneNode(true) as ListItem;
t.update(i.name.replace(/^short\:/, ""), i.timestamp || 0)
t.classList.remove("hidden")
this.Elements.ListItems.appendChild(t)
}
} else {
alert(`Error due to: ${res.msg}`);
}
}).catch((err) => {
alert(`Error: ${err}`);
}).finally(() => {
this.Elements.SubmitButton.disabled = false;
this.Elements.SubmitButton.querySelector(".swap").classList.remove("swap-active");
})
}
Elements = {
password: this.querySelector("#password") as DataInput,
SubmitButton: this.querySelector("#list-submit") as HTMLButtonElement,
ListItemPrototype: this.querySelector("list-item.hidden") as ListItem,
ListItems: this.querySelector("#list-items") as HTMLElement,
}
}
customElements.define("shorter-list", ShorterList);
console.info("[shorter-list] registered")
export class ListItem extends HTMLElement {
defaultBackend = getDefaultBackend()
constructor () {
super();
this.Elements.CopyButton.addEventListener("click", () => {this.CopyID()})
this.Elements.EditButton.addEventListener("click", () => {this.JumpToEdit()})
}
CopyID () {
if (!navigator.clipboard) {
alert("navigator.clipboard API not found on your drowser")
return;
}
navigator.clipboard.writeText(`short:${this.Elements.IDInfo.innerText}`).then( () => {
alert("已将 Short ID 复制到剪贴板");
}).catch(function(err) {
alert(`err: ${err}`);
});
}
JumpToEdit () {
location.assign(`/shorter/edit/?id=${this.Elements.IDInfo.innerText}`)
}
update (ShortID, EditTimestamp) {
this.Elements.IDInfo.innerText = ShortID;
let EditDate = new Date(EditTimestamp);
this.Elements.DateInfo.innerText = `${EditDate.toLocaleDateString()} ${EditDate.toLocaleTimeString()}`;
}
Elements = {
EditButton: this.querySelector(".item-edit") as HTMLButtonElement,
CopyButton: this.querySelector(".item-copy") as HTMLButtonElement,
IDInfo: this.querySelector(".item-id") as HTMLElement,
DateInfo: this.querySelector(".item-date") as HTMLSpanElement,
}
}
customElements.define("list-item", ListItem);
console.info("[shorter-list: list-item] registered")
================================================
FILE: src/scripts/components/shorter/shorter-password.ts
================================================
import type { DataInput } from "../data-input";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
export class ShorterPassword extends HTMLElement {
defaultBackend = getDefaultBackend()
constructor () {
super();
this.Elements.SubmitButton.addEventListener("click", () => {this.Submit()})
}
async Submit () {
this.Elements.SubmitButton.disabled = true;
this.Elements.SubmitButton.querySelector(".swap").classList.add("swap-active");
this.Elements.Msg.innerText = "submitting..";
// build request body
let requestBody = {
newPassword: this.Elements.newPassword.get(),
oldPassword: this.Elements.oldPassword.get()
}
// build api Endpoint
let requestURL = new URL(this.defaultBackend);
requestURL.pathname = "/short/admin-password/set";
await fetch(requestURL, {
body: JSON.stringify(requestBody),
method: "POST"
}).then(async res => {
const resText = await res.text();
try {
return JSON.parse(resText)
} catch (e) {
throw resText
}
}).then(res => {
if (res.passwordUpdated) {
this.Elements.Msg.innerText = "Password updated.";
} else {
this.Elements.Msg.innerText = `Cannot update password due to: ${res.msg}`;
}
}).catch((err) => {
this.Elements.Msg.innerText = `Error: ${err}`;
}).finally(() => {
this.Elements.SubmitButton.disabled = false;
this.Elements.SubmitButton.querySelector(".swap").classList.remove("swap-active");
});
}
Elements = {
oldPassword: this.querySelector("#old-password") as DataInput,
newPassword: this.querySelector("#new-password") as DataInput,
Msg: this.querySelector("code") as HTMLElement,
SubmitButton: this.querySelector("#password-submit") as HTMLButtonElement,
}
}
customElements.define("shorter-password", ShorterPassword);
console.info("[shorter-password] registered")
================================================
FILE: src/scripts/utils/copy.ts
================================================
export function copyToClipboard(text: string) {
return new Promise((resolve, reject) => {
if (!navigator.clipboard) {
reject(new Error("Clipboard API not supported"));
return;
}
navigator.clipboard.writeText(text)
.then(() => resolve(void 0))
.catch(err => reject(err));
});
}
================================================
FILE: src/scripts/utils/filterObject.ts
================================================
/**
* Generic “object filter”. Works exactly like Array.filter,
* but the callback receives (key, value) instead of (value, index).
*
* @param obj The source object.
* @param predicate (key, value) => boolean – return true to keep the entry.
*
* @returns a new object typed as a *partial* of the original (because we
* don't know at compile time which keys survive).
*/
export default function filterObject (
obj: T,
predicate: (key: keyof T, value: T[keyof T]) => boolean
): Partial {
const result: Partial = {};
// `Object.keys` returns string[], so we cast it to the proper key type.
const keys = Object.keys(obj) as (keyof T)[];
for (const k of keys) {
const v = obj[k];
if (predicate(k, v)) {
// This cast is safe – we only ever assign a known property.
(result as any)[k] = v;
}
}
return result;
}
================================================
FILE: src/scripts/utils/getDefaultBackend.ts
================================================
export function getDefaultBackend () {
let URLObj = new URL(location.href);
URLObj.pathname = "";
URLObj.search = "";
URLObj.hash = "";
return URLObj.host === "localhost:4321" ? "http://localhost:8788" : URLObj.toString();
}
================================================
FILE: src/styles/app.scss
================================================
@import "tailwindcss";
@plugin "daisyui";
================================================
FILE: src/styles/import.css
================================================
@import "tailwindcss";
@plugin "daisyui" {
themes: "LightMint" --default;/* dark --prefersdark;*/
}
@plugin "daisyui/theme" {
name: "LightMint";
default: true;
prefersdark: false;
color-scheme: "light";
--color-base-100: oklch(98% 0.018 155.826);
--color-base-200: oklch(96% 0.044 156.743);
--color-base-300: oklch(92% 0.084 155.995);
--color-base-content: oklch(39% 0.095 152.535);
--color-primary: oklch(67% 0.182 276.935);
--color-primary-content: oklch(25% 0.09 281.288);
--color-secondary: oklch(67% 0.182 276.935);
--color-secondary-content: oklch(25% 0.09 281.288);
--color-accent: oklch(74% 0.16 232.661);
--color-accent-content: oklch(29% 0.066 243.157);
--color-neutral: oklch(26% 0.065 152.934);
--color-neutral-content: oklch(98% 0.018 155.826);
--color-info: oklch(70% 0.165 254.624);
--color-info-content: oklch(28% 0.091 267.935);
--color-success: oklch(76% 0.177 163.223);
--color-success-content: oklch(26% 0.051 172.552);
--color-warning: oklch(75% 0.183 55.934);
--color-warning-content: oklch(26% 0.079 36.259);
--color-error: oklch(71% 0.194 13.428);
--color-error-content: oklch(27% 0.105 12.094);
--radius-selector: 2rem;
--radius-field: 2rem;
--radius-box: 1rem;
--size-selector: 0.25rem;
--size-field: 0.25rem;
--border: 1px;
--depth: 1;
--noise: 1;
}
================================================
FILE: src/styles/index.scss
================================================
.main-card-con {
box-sizing: border-box;
width: 100%;
min-height: 100vh;
padding: 20px 0;
background-color: #121317;
color: #e3dfe6;
.main-card {
background-color: #292a2e;
margin: 0 auto;
width: 80%;
max-width: 1000px;
border-radius: 14px;
}
}
.contents {
padding: 24px 30px;
}
.flex-contents {
display: flex;
flex-wrap: wrap;
flex-flow: column;
gap: 12px
}
@media screen and (max-width: 512px) {
.main-card-con {
padding: 0;
background-color: #292a2e;
.main-card {
margin: 0;
width: 100%;
border-radius: 0;
}
}
}
================================================
FILE: src/styles/main.scss
================================================
// body {
// margin: 0;
// font-family: "Roboto", sans-serif, system-ui;
// }
// button {
// width: 100%;
// border: none;
// background-color: #bbc5e8;
// color: #25304c;
// padding: 12px 18px;
// border-radius: 25px;
// &:active {
// filter: brightness(0.85);
// }
// [data-icon] {
// color: #25304c;
// fill: #25304c;
// height: 1.25rem;
// width: 1.25rem;
// vertical-align: -0.3rem;
// }
// }
// code {
// background-color: #1f2229;
// padding: 12px 18px;
// border-radius: 8px;
// word-break: break-all;
// }
// a:link, a:visited {
// color: white;
// text-decoration: underline;
// text-decoration-thickness: 1px;
// text-decoration-style: dashed;
// &:hover {
// text-decoration-style: solid;
// }
// }
// [data-icon] {
// vertical-align: -0.125rem;
// }
================================================
FILE: tsconfig.json
================================================
{
"extends": "astro/tsconfigs/base",
"compilerOptions": {
"baseUrl": ".",
"typeRoots": ["./types", "./node_modules/@types"],
"paths": {
"@components/*": ["src/components/*"],
"@contents/*": ["src/content/*"],
"@layouts/*": ["src/layouts/*"],
"@scripts/*": ["src/scripts/*"],
"@styles/*": ["src/styles/*"],
"@config/*": ["src/config/*"]
}
}
}
================================================
FILE: types/worker-configuration.d.ts
================================================
// Generated by Wrangler by running `wrangler types ./types/worker-configuration.d.ts` (hash: 2569fdb35d6c7f3f62093f7ff8102897)
// Runtime types generated with workerd@1.20250408.0 2023-10-10
declare namespace Cloudflare {
interface Env {
EdgeSubDB: KVNamespace;
}
}
interface Env extends Cloudflare.Env {}
// Begin runtime types
/*! *****************************************************************************
Copyright (c) Cloudflare. All rights reserved.
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* eslint-disable */
// noinspection JSUnusedGlobalSymbols
declare var onmessage: never;
/**
* An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)
*/
declare class DOMException extends Error {
constructor(message?: string, name?: string);
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */
readonly message: string;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */
readonly name: string;
/**
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)
*/
readonly code: number;
static readonly INDEX_SIZE_ERR: number;
static readonly DOMSTRING_SIZE_ERR: number;
static readonly HIERARCHY_REQUEST_ERR: number;
static readonly WRONG_DOCUMENT_ERR: number;
static readonly INVALID_CHARACTER_ERR: number;
static readonly NO_DATA_ALLOWED_ERR: number;
static readonly NO_MODIFICATION_ALLOWED_ERR: number;
static readonly NOT_FOUND_ERR: number;
static readonly NOT_SUPPORTED_ERR: number;
static readonly INUSE_ATTRIBUTE_ERR: number;
static readonly INVALID_STATE_ERR: number;
static readonly SYNTAX_ERR: number;
static readonly INVALID_MODIFICATION_ERR: number;
static readonly NAMESPACE_ERR: number;
static readonly INVALID_ACCESS_ERR: number;
static readonly VALIDATION_ERR: number;
static readonly TYPE_MISMATCH_ERR: number;
static readonly SECURITY_ERR: number;
static readonly NETWORK_ERR: number;
static readonly ABORT_ERR: number;
static readonly URL_MISMATCH_ERR: number;
static readonly QUOTA_EXCEEDED_ERR: number;
static readonly TIMEOUT_ERR: number;
static readonly INVALID_NODE_TYPE_ERR: number;
static readonly DATA_CLONE_ERR: number;
get stack(): any;
set stack(value: any);
}
type WorkerGlobalScopeEventMap = {
fetch: FetchEvent;
scheduled: ScheduledEvent;
queue: QueueEvent;
unhandledrejection: PromiseRejectionEvent;
rejectionhandled: PromiseRejectionEvent;
};
declare abstract class WorkerGlobalScope extends EventTarget {
EventTarget: typeof EventTarget;
}
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */
interface Console {
"assert"(condition?: boolean, ...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */
clear(): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */
count(label?: string): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countreset_static) */
countReset(label?: string): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */
debug(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */
dir(item?: any, options?: any): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */
dirxml(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */
error(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */
group(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupcollapsed_static) */
groupCollapsed(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupend_static) */
groupEnd(): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */
info(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */
log(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */
table(tabularData?: any, properties?: string[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */
time(label?: string): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeend_static) */
timeEnd(label?: string): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timelog_static) */
timeLog(label?: string, ...data: any[]): void;
timeStamp(label?: string): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */
trace(...data: any[]): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */
warn(...data: any[]): void;
}
declare const console: Console;
type BufferSource = ArrayBufferView | ArrayBuffer;
type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
declare namespace WebAssembly {
class CompileError extends Error {
constructor(message?: string);
}
class RuntimeError extends Error {
constructor(message?: string);
}
type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128";
interface GlobalDescriptor {
value: ValueType;
mutable?: boolean;
}
class Global {
constructor(descriptor: GlobalDescriptor, value?: any);
value: any;
valueOf(): any;
}
type ImportValue = ExportValue | number;
type ModuleImports = Record;
type Imports = Record;
type ExportValue = Function | Global | Memory | Table;
type Exports = Record;
class Instance {
constructor(module: Module, imports?: Imports);
readonly exports: Exports;
}
interface MemoryDescriptor {
initial: number;
maximum?: number;
shared?: boolean;
}
class Memory {
constructor(descriptor: MemoryDescriptor);
readonly buffer: ArrayBuffer;
grow(delta: number): number;
}
type ImportExportKind = "function" | "global" | "memory" | "table";
interface ModuleExportDescriptor {
kind: ImportExportKind;
name: string;
}
interface ModuleImportDescriptor {
kind: ImportExportKind;
module: string;
name: string;
}
abstract class Module {
static customSections(module: Module, sectionName: string): ArrayBuffer[];
static exports(module: Module): ModuleExportDescriptor[];
static imports(module: Module): ModuleImportDescriptor[];
}
type TableKind = "anyfunc" | "externref";
interface TableDescriptor {
element: TableKind;
initial: number;
maximum?: number;
}
class Table {
constructor(descriptor: TableDescriptor, value?: any);
readonly length: number;
get(index: number): any;
grow(delta: number, value?: any): number;
set(index: number, value?: any): void;
}
function instantiate(module: Module, imports?: Imports): Promise;
function validate(bytes: BufferSource): boolean;
}
/**
* This ServiceWorker API interface represents the global execution context of a service worker.
* Available only in secure contexts.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)
*/
interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
DOMException: typeof DOMException;
WorkerGlobalScope: typeof WorkerGlobalScope;
btoa(data: string): string;
atob(data: string): string;
setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
clearTimeout(param1: number | null): void;
setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
clearInterval(param1: number | null): void;
queueMicrotask(task: Function): void;
structuredClone(value: T, options?: StructuredSerializeOptions): T;
reportError(error: any): void;
fetch(input: RequestInfo | URL, init?: RequestInit): Promise;
self: ServiceWorkerGlobalScope;
crypto: Crypto;
caches: CacheStorage;
scheduler: Scheduler;
performance: Performance;
Cloudflare: Cloudflare;
readonly origin: string;
Event: typeof Event;
ExtendableEvent: typeof ExtendableEvent;
CustomEvent: typeof CustomEvent;
PromiseRejectionEvent: typeof PromiseRejectionEvent;
FetchEvent: typeof FetchEvent;
TailEvent: typeof TailEvent;
TraceEvent: typeof TailEvent;
ScheduledEvent: typeof ScheduledEvent;
MessageEvent: typeof MessageEvent;
CloseEvent: typeof CloseEvent;
ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;
ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;
ReadableStream: typeof ReadableStream;
WritableStream: typeof WritableStream;
WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;
TransformStream: typeof TransformStream;
ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;
CountQueuingStrategy: typeof CountQueuingStrategy;
ErrorEvent: typeof ErrorEvent;
EventSource: typeof EventSource;
ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;
ReadableStreamDefaultController: typeof ReadableStreamDefaultController;
ReadableByteStreamController: typeof ReadableByteStreamController;
WritableStreamDefaultController: typeof WritableStreamDefaultController;
TransformStreamDefaultController: typeof TransformStreamDefaultController;
CompressionStream: typeof CompressionStream;
DecompressionStream: typeof DecompressionStream;
TextEncoderStream: typeof TextEncoderStream;
TextDecoderStream: typeof TextDecoderStream;
Headers: typeof Headers;
Body: typeof Body;
Request: typeof Request;
Response: typeof Response;
WebSocket: typeof WebSocket;
WebSocketPair: typeof WebSocketPair;
WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;
AbortController: typeof AbortController;
AbortSignal: typeof AbortSignal;
TextDecoder: typeof TextDecoder;
TextEncoder: typeof TextEncoder;
navigator: Navigator;
Navigator: typeof Navigator;
URL: typeof URL;
URLSearchParams: typeof URLSearchParams;
URLPattern: typeof URLPattern;
Blob: typeof Blob;
File: typeof File;
FormData: typeof FormData;
Crypto: typeof Crypto;
SubtleCrypto: typeof SubtleCrypto;
CryptoKey: typeof CryptoKey;
CacheStorage: typeof CacheStorage;
Cache: typeof Cache;
FixedLengthStream: typeof FixedLengthStream;
IdentityTransformStream: typeof IdentityTransformStream;
HTMLRewriter: typeof HTMLRewriter;
}
declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void;
declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void;
/**
* Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
*/
declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */
declare function btoa(data: string): string;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */
declare function atob(data: string): string;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */
declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setTimeout) */
declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearTimeout) */
declare function clearTimeout(param1: number | null): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */
declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/setInterval) */
declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */
declare function clearInterval(param1: number | null): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */
declare function queueMicrotask(task: Function): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone) */
declare function structuredClone(value: T, options?: StructuredSerializeOptions): T;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/reportError) */
declare function reportError(error: any): void;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */
declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise;
declare const self: ServiceWorkerGlobalScope;
/**
* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.
* The Workers runtime implements the full surface of this API, but with some differences in
* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)
* compared to those implemented in most browsers.
*
* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
*/
declare const crypto: Crypto;
/**
* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
*
* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
*/
declare const caches: CacheStorage;
declare const scheduler: Scheduler;
/**
* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
* as well as timing of subrequests and other operations.
*
* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
*/
declare const performance: Performance;
declare const Cloudflare: Cloudflare;
declare const origin: string;
declare const navigator: Navigator;
interface TestController {
}
interface ExecutionContext {
waitUntil(promise: Promise): void;
passThroughOnException(): void;
props: any;
}
type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise;
type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise;
type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise;
type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise;
type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise;
type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise;
type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise;
interface ExportedHandler {
fetch?: ExportedHandlerFetchHandler;
tail?: ExportedHandlerTailHandler;
trace?: ExportedHandlerTraceHandler;
tailStream?: ExportedHandlerTailStreamHandler;
scheduled?: ExportedHandlerScheduledHandler;
test?: ExportedHandlerTestHandler;
email?: EmailExportedHandler;
queue?: ExportedHandlerQueueHandler;
}
interface StructuredSerializeOptions {
transfer?: any[];
}
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */
declare abstract class PromiseRejectionEvent extends Event {
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */
readonly promise: Promise;
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */
readonly reason: any;
}
declare abstract class Navigator {
sendBeacon(url: string, body?: (ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams)): boolean;
readonly userAgent: string;
readonly hardwareConcurrency: number;
}
/**
* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
* as well as timing of subrequests and other operations.
*
* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
*/
interface Performance {
/* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */
readonly timeOrigin: number;
/* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */
now(): number;
}
interface AlarmInvocationInfo {
readonly isRetry: boolean;
readonly retryCount: number;
}
interface Cloudflare {
readonly compatibilityFlags: Record;
}
interface DurableObject {
fetch(request: Request): Response | Promise;
alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise;
webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise;
webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise;
webSocketError?(ws: WebSocket, error: unknown): void | Promise;
}
type DurableObjectStub = Fetcher & {
readonly id: DurableObjectId;
readonly name?: string;
};
interface DurableObjectId {
toString(): string;
equals(other: DurableObjectId): boolean;
readonly name?: string;
}
interface DurableObjectNamespace {
newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;
idFromName(name: string): DurableObjectId;
idFromString(id: string): DurableObjectId;
get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub;
jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace;
}
type DurableObjectJurisdiction = "eu" | "fedramp";
interface DurableObjectNamespaceNewUniqueIdOptions {
jurisdiction?: DurableObjectJurisdiction;
}
type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me";
interface DurableObjectNamespaceGetDurableObjectOptions {
locationHint?: DurableObjectLocationHint;
}
interface DurableObjectState {
waitUntil(promise: Promise): void;
readonly id: DurableObjectId;
readonly storage: DurableObjectStorage;
container?: Container;
blockConcurrencyWhile(callback: () => Promise): Promise;
acceptWebSocket(ws: WebSocket, tags?: string[]): void;
getWebSockets(tag?: string): WebSocket[];
setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;
getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;
getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;
setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;
getHibernatableWebSocketEventTimeout(): number | null;
getTags(ws: WebSocket): string[];
abort(reason?: string): void;
}
interface DurableObjectTransaction {
get(key: string, options?: DurableObjectGetOptions): Promise;
get(keys: string[], options?: DurableObjectGetOptions): Promise