diff --git a/.env.example b/.env.example
deleted file mode 100644
index 9ce34ae..0000000
--- a/.env.example
+++ /dev/null
@@ -1,25 +0,0 @@
-PORT=3420
-APP_ENV=development
-LOG_LEVEL=info
-
-PROXY_API_KEY=
-MANAGEMENT_API_KEY=
-REQUIRE_AUTH_FOR_PROXY=true
-REQUIRE_AUTH_FOR_MANAGEMENT=true
-
-CORS_ENABLED=true
-CORS_ORIGINS=*
-
-NETWORK_TIMEOUT=30000
-STRICT_TLS=true
-MAX_BODY_MB=100
-MAX_HEAP_MB=512
-MAX_RSS_MB=1024
-
-DISCORD_GLOBAL_RPS=50
-SERVICES_FILE=data/services.json
-
-SKIP_UPDATE_CHECK=false
-UPDATE_REPO=NodeByteLTD/ByteProxy
-
-# BYTEPROXY_TOKEN_EXAMPLE=
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 2d9a619..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-bin/
-coverage.out
-data/
-.env
-.env.local
diff --git a/CHANGELOG.md b/CHANGELOG.md
deleted file mode 100644
index 31f05e3..0000000
--- a/CHANGELOG.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# Changelog
-
-All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
-
-## [2.0.0] - 09/27/2026
-
-A rewrite of ByteProxy in Go. The HTTP routes are kept compatible with 1.x, but credential handling has changed. See the migration notes in the README.
-
-### Added
-
-- The service is a single static binary built only on the Go standard library.
-- An OpenAPI 3.1 spec is served at `/openapi.json`, with interactive reference docs at `/docs`. A test fails if any route is missing from the spec.
-- `X-Upstream-Authorization` header, so a caller can authenticate to the proxy with `Authorization: Bearer` and still send its own upstream credential.
-- Discord rate limiting per credential, following Discord's bucket hashes and major parameters, with a global requests-per-second cap (`DISCORD_GLOBAL_RPS`). A 429 is retried when the wait is short, and returned to the caller when it is longer than 30 seconds.
-- GitHub rate limiting per credential and resource (core, search, graphql).
-- Services added at runtime are saved to `SERVICES_FILE` and loaded again on startup.
-- `/up` liveness endpoint that is always served, even when memory pressure causes other requests to return 503.
-- Graceful shutdown on SIGINT and SIGTERM.
-- Makefile, Railpack config and `.env.example`.
-
-### Changed
-
-- The proxy no longer uses its own Discord or GitHub token. Callers send their own credential with each request. `DISCORD_BOT_TOKEN` and `GITHUB_TOKEN` are ignored, and a warning is logged if they are set.
-- Dynamic services can only read upstream tokens from env vars named `BYTEPROXY_TOKEN_*`.
-- If auth is required but no key is configured, startup fails with an error. Previously the proxy started without auth.
-- An update check that fails or finds a newer release logs a warning and never stops the process.
-- A configured service `User-Agent` always takes precedence over the caller's.
-
-### Fixed
-
-- Request and response bodies are forwarded as raw bytes, so multipart uploads and binary responses (images, archives) arrive intact.
-- A compressed upstream response is decoded once. `Content-Encoding` is no longer forwarded alongside an already decoded body.
-- Upstream timeouts return 504, and unreachable upstreams return 502, instead of a generic 500.
-- Encoded path segments, such as emoji in Discord reaction routes, are forwarded without being decoded.
-
-### Security
-
-- API keys are compared in constant time.
-- `api_key` query parameters, `X-Api-Key`, cookies and client forwarding headers are removed before a request goes upstream.
-- Key debug and diagnostics endpoints report only whether a key is configured, never any part of it. `/auth-status` no longer echoes the supplied key.
-- Upstream CORS headers are replaced with the proxy's own policy. A wildcard origin never allows credentials.
-- TLS 1.2 is the minimum version, and certificate verification cannot be skipped unless `STRICT_TLS=false` is set explicitly.
diff --git a/CNAME b/CNAME
new file mode 100644
index 0000000..035bab2
--- /dev/null
+++ b/CNAME
@@ -0,0 +1 @@
+proxy.nodebyte.co.uk
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 0c515cf..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,660 +0,0 @@
-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) 2026 NodeByte LTD
-
-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
-.
diff --git a/Makefile b/Makefile
deleted file mode 100644
index 634bb5f..0000000
--- a/Makefile
+++ /dev/null
@@ -1,39 +0,0 @@
-BINARY := byteproxy
-VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
-LDFLAGS := -s -w -X main.version=$(VERSION)
-
-.PHONY: all build run test race cover vet fmt fmt-check lint check clean
-
-all: check build
-
-build:
- CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/$(BINARY) .
-
-run:
- go run .
-
-test:
- go test -count=1 ./...
-
-race:
- go test -race -count=1 ./...
-
-cover:
- go test -count=1 -coverprofile=coverage.out ./...
- go tool cover -func=coverage.out
-
-vet:
- go vet ./...
-
-fmt:
- gofmt -w .
-
-fmt-check:
- @test -z "$$(gofmt -l .)" || (gofmt -l . && echo "run make fmt" && exit 1)
-
-lint: fmt-check vet
-
-check: lint test
-
-clean:
- rm -rf bin coverage.out
diff --git a/README.md b/README.md
index d28fd84..78c2ebc 100644
--- a/README.md
+++ b/README.md
@@ -1,191 +1,159 @@
-# ByteProxy
+# ByteProxy Docs
-A small HTTP proxy that sits between your services and third-party APIs such as Discord and GitHub. It follows each API's rate limits, retries short 429s, and forwards requests and responses unchanged, byte for byte.
+This directory contains additional documentation for the ByteProxy project.
-ByteProxy is written in Go and builds to a single static binary with no runtime dependencies.
+## Contents
-## Quick start
+- [Getting Started](#getting-started)
+- [Configuration Options](#configuration-options)
+- [API Reference](#api-reference)
+- [Service Management](#service-management)
+- [Troubleshooting](#troubleshooting)
-```sh
-cp .env.example .env
-# set PROXY_API_KEY and MANAGEMENT_API_KEY
-make run
-```
+## Getting Started
-The proxy listens on port `3420` by default. The API reference is at `http://localhost:3420/docs`, and the raw OpenAPI 3.1 spec is at `/openapi.json`.
+ByteProxy is a powerful API proxy server that forwards requests to various services like Discord, GitHub, and others.
-```sh
-curl http://localhost:3420/proxy/discord/v10/users/@me \
- -H "X-Api-Key: $PROXY_API_KEY" \
- -H "Authorization: Bot $DISCORD_TOKEN"
-```
+### Prerequisites
-## How requests are proxied
+- [Bun](https://bun.sh/) runtime (v1.0.0 or later)
+- Discord Bot Token (optional)
+- GitHub API Token (optional)
-A request to `/proxy/{service}/{path}` is sent to the service's base URL plus `{path}`, with the same method, query string, body and headers. The response status, headers and body are returned as is, and the proxy adds `X-Proxy-Service` and `X-Proxy-Duration`.
+### Installation
-Before a request is sent upstream, the proxy removes:
+1. Clone the repository:
+ ```bash
+ git clone https://github.com/ByteBrushStudios/ByteProxy.git
+ cd ByteProxy
+ ```
-- its own credentials (`X-Api-Key`, the `api_key` query parameter, and an `Authorization: Bearer` header that holds the proxy key)
-- cookies
-- hop-by-hop headers
-- client forwarding headers (`X-Forwarded-*`, `Forwarded`, `X-Real-Ip`, Cloudflare headers)
+2. Install dependencies:
+ ```bash
+ bun install
+ ```
-### Built-in services
+3. Set up environment variables:
+ ```bash
+ cp .env.example .env.local
+ ```
-| Key | Upstream | Rate limiting |
-|---|---|---|
-| `discord` | `https://discord.com/api/` | Per credential. Follows bucket hashes and major parameters, with a global requests-per-second cap. |
-| `github` | `https://api.github.com/` | Per credential and resource (core, search, graphql). |
+4. Edit `.env.local` with your API tokens and configuration settings.
-For Discord, `/proxy/discord/v10/...` and `/proxy/discord/api/v10/...` both map to `https://discord.com/api/v10/...`. A 429 is retried up to 3 times when the wait is 30 seconds or less. Longer waits are returned to the caller with Discord's original body. A global 429 pauses every request that uses that credential.
+5. Start the development server:
+ ```bash
+ bun run dev
+ ```
-## Authentication
+## Configuration Options
-The proxy and the upstream API are authenticated separately.
+ByteProxy is highly configurable through environment variables and the service registry in `src/config/index.ts`.
-### Proxy auth
+### Core Environment Variables
-When `REQUIRE_AUTH_FOR_PROXY` is on, `/proxy/*` accepts the key in any of these forms:
+| Variable | Description | Default |
+|----------|-------------|---------|
+| PORT | Server port | 3420 |
+| CORS_ENABLED | Enable CORS | true |
+| CORS_ORIGINS | Allowed origins | * |
+| LOG_LEVEL | Logging level (debug, info, warn, error) | info |
+| NETWORK_TIMEOUT | Request timeout in ms | 30000 |
+| NETWORK_RETRIES | Number of retry attempts | 2 |
+| STRICT_TLS | Enforce strict TLS validation | true |
-- `X-Api-Key: `
-- `Authorization: Bearer `
-- `?api_key=`
+### Security Variables
-`/manage/*` uses `MANAGEMENT_API_KEY` in the same way. If auth is required but its key is empty, the proxy refuses to start.
+| Variable | Description | Default |
+|----------|-------------|---------|
+| REQUIRE_AUTH_FOR_PROXY | Require API key for proxy endpoints | false |
+| REQUIRE_AUTH_FOR_MANAGEMENT | Require API key for management endpoints | false |
+| PROXY_API_KEY | API key for proxy routes | undefined |
+| MANAGEMENT_API_KEY | API key for management routes | undefined |
-### Upstream credentials
+### Service API Tokens
-The proxy does not hold a Discord or GitHub token of its own. Each caller sends its own credential, and the proxy uses the first one it finds:
+| Variable | Description | Service |
+|----------|-------------|---------|
+| DISCORD_BOT_TOKEN | Discord bot token | Discord API |
+| GITHUB_TOKEN | GitHub personal access token | GitHub API |
-1. `X-Upstream-Authorization`
-2. `Authorization`, unless it is the proxy key sent as a Bearer token
-3. For dynamic services only, the env var named in the service's `auth.tokenEnvVar`
+## API Reference
-Use `X-Upstream-Authorization` when you also use the `Authorization` header to send the proxy key:
+ByteProxy provides a comprehensive API divided into several categories:
-```sh
-curl http://localhost:3420/proxy/github/user \
- -H "Authorization: Bearer $PROXY_API_KEY" \
- -H "X-Upstream-Authorization: Bearer $GITHUB_TOKEN"
-```
+### Base Endpoints
+
+- `GET /` - Welcome page with links to documentation
+- `GET /up` - Server health and pressure status
+
+### Health Endpoints
+
+- `GET /health` - Basic health check
+- `GET /status` - Detailed server status
+
+### Proxy Endpoints
+
+- `ALL /proxy/:service/*` - Forward requests to configured services
+ - Example: `GET /proxy/github/users/octocat`
+
+### Management Endpoints
+
+- `GET /manage/services` - List all configured services
+- `GET /manage/services/:key` - Get service configuration
+- `POST /manage/services` - Add a new service
+- `POST /manage/services/:key/test` - Test service connectivity
+- `GET /manage/diagnostics` - System diagnostics
+- `GET /manage/key-debug` - API key information
-Rate limit state is tracked per credential, so several services can share one proxy without sharing limits. Credentials are hashed before they are used as keys, and are never logged.
+### Version Endpoints
-## Dynamic services
+- `GET /version/check` - Check for ByteProxy updates
-You can add other APIs at runtime through the management API. They are saved to `SERVICES_FILE` and loaded again on startup.
+## Service Management
-```sh
+You can dynamically add, configure, and test services through the management API.
+
+### Adding a New Service
+
+```bash
curl -X POST http://localhost:3420/manage/services \
- -H "X-Api-Key: $MANAGEMENT_API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "key": "status",
+ "key": "twitter",
"config": {
- "name": "Status API",
- "baseUrl": "https://status.example.com/api/",
- "headers": { "Accept": "application/json" },
- "rateLimit": { "maxRequests": 60, "windowMs": 60000 },
- "auth": { "type": "bearer", "tokenEnvVar": "BYTEPROXY_TOKEN_STATUS" }
+ "name": "Twitter API",
+ "baseUrl": "https://api.twitter.com/2/",
+ "headers": {
+ "User-Agent": "ByteProxy/0.1.0"
+ },
+ "auth": {
+ "type": "bearer",
+ "tokenEnvVar": "TWITTER_TOKEN"
+ }
}
}'
```
-- `key` must match `^[a-z0-9][a-z0-9_-]{0,31}$`.
-- `baseUrl` must be `http` or `https`.
-- Static `headers` cannot set `Authorization`, `Cookie`, `Host` or other headers that carry credentials or control framing. Use `auth` for credentials.
-- `auth.type` is `bearer`, `bot`, `basic` or `api-key`. `api-key` also needs `headerName`.
-- `auth.tokenEnvVar` must be named `BYTEPROXY_TOKEN_*`, so a management key cannot read arbitrary environment variables such as a database URL.
-
-A credential sent by the caller always takes precedence over the configured token. Built-in services cannot be removed.
-
-## Endpoints
-
-| Route | Auth | Purpose |
-|---|---|---|
-| `GET /` | none | Service info |
-| `GET /health`, `/status` | none | Health, uptime and memory |
-| `GET /up` | none | Liveness check, served even under memory pressure |
-| `GET /auth-status` | none | Which auth modes are enabled |
-| `GET /version`, `/version/check` | none | Current version and release check |
-| `GET /openapi.json`, `/docs` | none | API spec and reference |
-| `/proxy/{service}/{path}` | proxy | Forward a request |
-| `GET /proxy/services` | proxy | List services |
-| `GET /proxy/services/{service}/rate-limit` | proxy | Window limit status for a service |
-| `GET /proxy/auth-debug`, `/auth-test`, `/key-debug` | proxy | Auth troubleshooting |
-| `GET`, `POST /manage/services` | management | List or add services |
-| `GET`, `DELETE /manage/services/{key}` | management | Inspect or remove a service |
-| `POST /manage/services/{key}/test` | management | Check that a service's upstream is reachable |
-| `GET /manage/diagnostics`, `/manage/key-debug` | management | Configuration diagnostics |
-
-Errors are returned as JSON with an `error` message, for example `{"error": "Service 'foo' not configured"}`.
-
-| Status | Meaning |
-|---|---|
-| 401 | Missing or wrong proxy or management key |
-| 404 | Unknown service or route |
-| 413 | Request body larger than `MAX_BODY_MB` |
-| 429 | Rate limited by the proxy or upstream |
-| 502 | Upstream unreachable or TLS failure |
-| 503 | Memory pressure above `MAX_HEAP_MB` or `MAX_RSS_MB` |
-| 504 | Upstream did not respond within `NETWORK_TIMEOUT` |
-
-## Configuration
-
-Settings are read from the environment. `.env.local` and `.env` are also loaded, but they never override variables that are already set.
-
-| Variable | Default | Description |
-|---|---|---|
-| `PORT` | `3420` | Listen port |
-| `APP_ENV` | `local` | `production`, `development` or `local`. `development` skips the update check. Falls back to `NODE_ENV`. |
-| `LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` |
-| `PROXY_API_KEY` | | Key for `/proxy/*` |
-| `MANAGEMENT_API_KEY` | | Key for `/manage/*` |
-| `REQUIRE_AUTH_FOR_PROXY` | `false` | Require `PROXY_API_KEY` |
-| `REQUIRE_AUTH_FOR_MANAGEMENT` | `false` | Require `MANAGEMENT_API_KEY` |
-| `CORS_ENABLED` | `true` | Send CORS headers |
-| `CORS_ORIGINS` | `*` | Comma-separated allowed origins. Credentials are only allowed for listed origins, never for `*`. |
-| `NETWORK_TIMEOUT` | `30000` | Upstream timeout in milliseconds |
-| `STRICT_TLS` | `true` | Verify upstream certificates |
-| `MAX_BODY_MB` | `100` | Largest request body accepted |
-| `MAX_HEAP_MB` | `512` | Heap size above which requests get 503 |
-| `MAX_RSS_MB` | `1024` | Total memory held by the Go runtime above which requests get 503 |
-| `DISCORD_GLOBAL_RPS` | `50` | Discord global requests per second, per credential |
-| `SERVICES_FILE` | `data/services.json` | Where dynamic services are stored |
-| `SKIP_UPDATE_CHECK` | `false` | Skip the release check on startup |
-| `UPDATE_REPO` | `NodeByteLTD/ByteProxy` | GitHub repo checked for releases |
-| `BYTEPROXY_TOKEN_*` | | Upstream tokens that dynamic services may use |
-
-## Development
-
-| Command | What it does |
-|---|---|
-| `make run` | Run from source |
-| `make build` | Build `bin/byteproxy`, with the version taken from git |
-| `make test` | Run the tests |
-| `make race` | Run the tests with the race detector |
-| `make cover` | Print test coverage per function |
-| `make lint` | Check formatting and run `go vet` |
-| `make check` | Run lint and the tests |
-
-Requires Go 1.25 or newer. The tests start real HTTP servers on localhost and need no network access.
-
-## Deployment
-
-The repo includes a [Railpack](https://railpack.com) config (`railpack.json`), which builds the binary with the Go provider. It sets `SERVICES_FILE=/data/services.json`, so mount a persistent volume at `/data` or dynamic services are lost on redeploy.
-
-To run it anywhere else, build with `make build` and run `bin/byteproxy`. It handles SIGINT and SIGTERM by finishing in-flight requests before exiting.
-
-## Migrating from 1.x
-
-- Remove `DISCORD_BOT_TOKEN` and `GITHUB_TOKEN`. They are ignored, and a warning is logged if they are set. Every caller must now send its own upstream credential in `Authorization` or `X-Upstream-Authorization`.
-- A caller that sends the proxy key as `Authorization: Bearer` must move its upstream credential to `X-Upstream-Authorization`.
-- Rename any token env var used by a dynamic service to `BYTEPROXY_TOKEN_*`.
-- Dynamic services are now saved to disk. Services added under 1.x were only held in memory and must be added again once.
-- If `REQUIRE_AUTH_FOR_PROXY` or `REQUIRE_AUTH_FOR_MANAGEMENT` is `true`, set the matching key. 1.x started without auth in that case, and 2.x refuses to start.
-- The Swagger UI has been replaced by `/docs` and `/openapi.json`.
-
-## License
-
-See [LICENSE](LICENSE).
+### Testing Service Connectivity
+
+```bash
+curl -X POST http://localhost:3420/manage/services/github/test
+```
+
+## Troubleshooting
+
+If you encounter issues, check the following resources:
+
+1. System diagnostics at `/manage/diagnostics`
+2. Authentication settings at `/manage/key-debug`
+3. Console logs for detailed error messages
+4. Environment variable configuration
+
+Common issues:
+
+- **Authentication failures**: Check API tokens in .env.local
+- **TLS/SSL errors**: Consider setting STRICT_TLS=false for development
+- **404 errors**: Verify service keys and endpoint paths
+- **Rate limiting**: Check service configuration for rate limit settings
+
+For additional help, join our [Discord community](https://discord.gg/Vv2bdC44Ge) or create an issue on [GitHub](https://github.com/ByteBrushStudios/ByteProxy/issues).
diff --git a/_config.yml b/_config.yml
new file mode 100644
index 0000000..4844253
--- /dev/null
+++ b/_config.yml
@@ -0,0 +1,58 @@
+# ByteProxy Documentation - Jekyll Configuration
+
+# Site Settings
+title: ByteProxy
+description: Extensible web proxy for Discord, GitHub, and other APIs
+baseurl: ""
+url: ""
+repository: NodeByteLTD/ByteProxy
+
+# Theme settings
+remote_theme: pmarsceill/just-the-docs
+color_scheme: dark
+
+# Just the Docs settings
+aux_links:
+ "ByteProxy on GitHub":
+ - "https://github.com/NodeByteLTD/ByteProxy"
+ "Discord Community":
+ - "https://discord.gg/nodebyte"
+
+# Enable search
+search_enabled: true
+
+# Navigation structure
+nav_external_links:
+ - title: ByteProxy on GitHub
+ url: https://github.com/NodeByteLTD/ByteProxy
+ hide_icon: false
+
+# Enable callouts
+callouts:
+ note:
+ title: Note
+ color: blue
+ warning:
+ title: Warning
+ color: yellow
+ danger:
+ title: Caution
+ color: red
+
+# Footer content
+footer_content: "Copyright © 2026 NodeByte LTD. Distributed under AGPL-3.0 license."
+
+# Collections for organizing content
+collections:
+ guides:
+ output: true
+ permalink: /:collection/:path/
+
+# Default front matter
+defaults:
+ - scope:
+ path: ""
+ type: guides
+ values:
+ layout: default
+ nav_order: 1
diff --git a/api.md b/api.md
new file mode 100644
index 0000000..a72316d
--- /dev/null
+++ b/api.md
@@ -0,0 +1,437 @@
+---
+title: API Reference
+layout: default
+nav_order: 6
+has_children: true
+---
+
+# ByteProxy API Reference
+
+This document provides a comprehensive reference of all endpoints available in ByteProxy.
+
+> **Note:** The interactive API documentation is available at [/docs](http://localhost:3420/docs) when the server is running.
+
+## Base Endpoints
+
+### GET /
+
+Returns basic information about the ByteProxy API.
+
+**Response Example:**
+```json
+{
+ "message": "Welcome to ByteProxy, feel free to browse around!",
+ "source": "https://github.com/ByteBrushStudios/ByteProxy",
+ "documentation": "/docs",
+ "status": "/status",
+ "health": "/health",
+ "version": "v0.1.0-dev",
+ "checkUpdates": "/version/check"
+}
+```
+
+### GET /up
+
+View information about the server's pressure state.
+
+**Response Example:**
+```json
+{
+ "status": "ok",
+ "eventLoopDelay": 0.34,
+ "heapUsed": 21450240,
+ "rssBytes": 67584000,
+ "eventLoopUtilized": 0.002,
+ "healthy": true
+}
+```
+
+## Health Endpoints
+
+### GET /health
+
+Quick health check endpoint.
+
+**Response Example:**
+```json
+{
+ "status": "ok",
+ "uptime": 3600,
+ "timestamp": "2023-05-15T12:00:00.000Z"
+}
+```
+
+### GET /status
+
+Detailed status information.
+
+**Response Example:**
+```json
+{
+ "status": "ok",
+ "uptime": 3600,
+ "version": "v0.1.0-dev",
+ "services": {
+ "discord": {
+ "status": "ok",
+ "authConfigured": true
+ },
+ "github": {
+ "status": "ok",
+ "authConfigured": true
+ }
+ },
+ "system": {
+ "memoryUsage": {
+ "rss": 67584000,
+ "heapTotal": 33554432,
+ "heapUsed": 21450240,
+ "external": 1572864
+ },
+ "loadAverage": [1.2, 1.1, 0.95]
+ }
+}
+```
+
+## Proxy Endpoints
+
+### GET|POST|PUT|DELETE /proxy/:service/*
+
+Proxy requests to the specified service.
+
+**Parameters:**
+- `:service` - The service to proxy to (e.g., discord, github)
+- `*` - The path to forward to the service
+
+**Example:**
+```bash
+# Get GitHub user info
+curl http://localhost:3420/proxy/github/users/ByteBrushStudios
+
+# Send message to Discord
+curl -X POST http://localhost:3420/proxy/discord/channels/123456789/messages \
+ -H "Content-Type: application/json" \
+ -d '{"content": "Hello!"}'
+```
+
+## Management Endpoints
+
+### GET /manage/services
+
+List all configured services.
+
+**Response Example:**
+```json
+{
+ "services": [
+ {
+ "key": "discord",
+ "name": "Discord API",
+ "baseUrl": "https://discord.com/api/",
+ "hasAuth": true,
+ "authConfigured": true,
+ "rateLimit": {
+ "maxRequests": 50,
+ "windowMs": 60000
+ }
+ },
+ {
+ "key": "github",
+ "name": "GitHub API",
+ "baseUrl": "https://api.github.com/",
+ "hasAuth": true,
+ "authConfigured": true,
+ "rateLimit": {
+ "maxRequests": 60,
+ "windowMs": 3600000
+ }
+ }
+ ],
+ "count": 2
+}
+```
+
+### GET /manage/services/:key
+
+Get configuration for a specific service.
+
+**Parameters:**
+- `:key` - The service key
+
+**Response Example:**
+```json
+{
+ "key": "github",
+ "config": {
+ "name": "GitHub API",
+ "baseUrl": "https://api.github.com/",
+ "headers": {
+ "User-Agent": "ByteProxy/0.1.0",
+ "Accept": "application/vnd.github+json",
+ "X-GitHub-Api-Version": "2022-11-28"
+ },
+ "auth": {
+ "type": "bearer",
+ "tokenConfigured": true
+ },
+ "rateLimit": {
+ "maxRequests": 60,
+ "windowMs": 3600000
+ }
+ }
+}
+```
+
+### POST /manage/services
+
+Add a new service.
+
+**Request Body:**
+```json
+{
+ "key": "custom-api",
+ "config": {
+ "name": "Custom API",
+ "baseUrl": "https://api.example.com/",
+ "headers": {
+ "User-Agent": "ByteProxy/1.0"
+ }
+ }
+}
+```
+
+**Response Example:**
+```json
+{
+ "message": "Service 'custom-api' added successfully",
+ "key": "custom-api",
+ "config": {
+ "name": "Custom API",
+ "baseUrl": "https://api.example.com/",
+ "headers": {
+ "User-Agent": "ByteProxy/1.0"
+ }
+ }
+}
+```
+
+### POST /manage/services/:key/test
+
+Test connectivity to a service.
+
+**Parameters:**
+- `:key` - The service key
+
+**Response Example (Success):**
+```json
+{
+ "service": "github",
+ "status": "reachable",
+ "responseStatus": 200,
+ "duration": "123ms",
+ "baseUrl": "https://api.github.com/"
+}
+```
+
+**Response Example (Failure):**
+```json
+{
+ "service": "custom-api",
+ "status": "unreachable",
+ "error": "connect ECONNREFUSED 127.0.0.1:80",
+ "baseUrl": "https://api.example.com/",
+ "troubleshooting": {
+ "suggestions": [
+ "Check your internet connection",
+ "Verify the service URL is correct",
+ "Check if the service is experiencing downtime",
+ "If you see TLS/SSL errors, the service may have certificate issues"
+ ]
+ }
+}
+```
+
+### GET /manage/diagnostics
+
+Get system and network diagnostics.
+
+**Response Example:**
+```json
+{
+ "system": {
+ "platform": "linux",
+ "nodeVersion": "v18.12.1",
+ "runtime": "Bun",
+ "uptime": 3600
+ },
+ "network": {
+ "strictTLS": true,
+ "timeout": 30000,
+ "retryAttempts": 2
+ },
+ "environment": {
+ "timeZone": "UTC",
+ "currentTime": "2023-05-15T12:00:00.000Z",
+ "locale": "en-US"
+ },
+ "authentication": {
+ "discord": {
+ "tokenConfigured": true,
+ "envVar": "DISCORD_BOT_TOKEN",
+ "authType": "bot"
+ },
+ "github": {
+ "tokenConfigured": true,
+ "envVar": "GITHUB_TOKEN",
+ "authType": "bearer"
+ }
+ }
+}
+```
+
+### GET /manage/key-debug
+
+Get information about API keys.
+
+**Response Example:**
+```json
+{
+ "message": "API Key Debug Information",
+ "note": "This endpoint helps identify which key you should use",
+ "keyInfo": {
+ "managementKeyFormat": "abc123def456...",
+ "proxyKeyFormat": "xyz789uvw567...",
+ "managementKeyLength": 32,
+ "proxyKeyLength": 32,
+ "keyTypes": {
+ "management": "Required for /manage/* routes",
+ "proxy": "Required for /proxy/* routes"
+ }
+ },
+ "help": "For management routes, you must use the MANAGEMENT_API_KEY from your .env file"
+}
+```
+
+## Version Endpoints
+
+### GET /version/check
+
+Check for updates.
+
+**Response Example (Up to Date):**
+```json
+{
+ "currentVersion": "v0.1.0-dev",
+ "latestVersion": "v0.1.0",
+ "latestReleaseUrl": "https://github.com/ByteBrushStudios/ByteProxy/releases/tag/v0.1.0",
+ "isLatest": true,
+ "isPrerelease": false,
+ "releaseDate": "2023-05-15T10:00:00Z",
+ "updateAvailable": false
+}
+```
+
+**Response Example (Update Available):**
+```json
+{
+ "currentVersion": "v0.0.9-dev",
+ "latestVersion": "v0.1.0",
+ "latestReleaseUrl": "https://github.com/ByteBrushStudios/ByteProxy/releases/tag/v0.1.0",
+ "isLatest": false,
+ "isPrerelease": false,
+ "releaseDate": "2023-05-15T10:00:00Z",
+ "updateAvailable": true
+}
+```
+
+## Authentication
+
+When authentication is enabled, you must provide an API key using one of these methods:
+
+1. Bearer token: `Authorization: Bearer your-api-key`
+2. API key header: `x-api-key: your-api-key`
+3. Query parameter: `?api_key=your-api-key`
+
+## Error Responses
+
+All error responses follow this format:
+
+```json
+{
+ "error": "Error type",
+ "message": "Detailed error message",
+ "documentation": "/docs"
+}
+```
+
+Common error types:
+- Invalid request format (400)
+- Endpoint not found (404)
+- Internal server error (500)
+- Service unavailable (503)
+
+## Next Steps
+
+- [Usage Guide](usage.md)
+- [Configuration Reference](config.md)
+- [Troubleshooting](troubleshooting.md)
+ },
+ "configuration": {
+ "port": 3420,
+ "services": [...],
+ "logging": {
+ "enabled": true,
+ "level": "info"
+ },
+ "cors": {
+ "enabled": true,
+ "origins": ["*"]
+ }
+ }
+}
+```
+
+### Server Pressure
+
+```
+GET /up
+```
+
+**Response:**
+```json
+{
+ "status": "ok",
+ "eventLoopDelay": 0.45,
+ "heapUsed": 17661944,
+ "rssBytes": 75882496,
+ "eventLoopUtilized": 0.02,
+ "healthy": true
+}
+```
+
+## Root Endpoint
+
+```
+GET /
+```
+
+**Response:**
+```json
+{
+ "message": "ByteProxy API",
+ "version": "0.1.0",
+ "documentation": "/docs",
+ "health": "/health",
+ "status": "/status"
+}
+```
+
+## OpenAPI Documentation
+
+Interactive API documentation:
+
+```
+GET /docs
+```
+
+This page provides Swagger UI for exploring and testing all API endpoints.
diff --git a/auth.md b/auth.md
new file mode 100644
index 0000000..911b500
--- /dev/null
+++ b/auth.md
@@ -0,0 +1,92 @@
+---
+title: Authentication
+layout: default
+nav_order: 4
+parent: Security
+---
+
+# Authentication
+
+ByteProxy provides flexible authentication options to secure your API endpoints.
+
+## Overview
+
+Authentication in ByteProxy is configurable per-route type:
+- **Proxy routes** (`/proxy/*`) can use a dedicated API key
+- **Management routes** (`/manage/*`) can use a separate admin API key
+
+This separation allows you to share proxy access while maintaining control over management functions.
+
+## Configuration
+
+Authentication is configured in your `.env` file:
+
+```properties
+# API Security Settings
+PROXY_API_KEY=your_api_key_here
+MANAGEMENT_API_KEY=your_admin_key_here
+REQUIRE_AUTH_FOR_PROXY=true
+REQUIRE_AUTH_FOR_MANAGEMENT=true
+```
+
+You can disable authentication by setting:
+```properties
+REQUIRE_AUTH_FOR_PROXY=false
+REQUIRE_AUTH_FOR_MANAGEMENT=false
+```
+
+## Authentication Methods
+
+ByteProxy accepts authentication via three methods:
+
+### Bearer Token (Recommended)
+
+```
+Authorization: Bearer your_api_key_here
+```
+
+Example:
+```bash
+curl -H "Authorization: Bearer your_api_key_here" \
+ http://localhost:3420/proxy/github/users/octocat
+```
+
+### X-API-Key Header
+
+```
+x-api-key: your_api_key_here
+```
+
+Example:
+```bash
+curl -H "x-api-key: your_api_key_here" \
+ http://localhost:3420/proxy/github/users/octocat
+```
+
+### Query Parameter
+
+```
+?api_key=your_api_key_here
+```
+
+Example:
+```bash
+curl "http://localhost:3420/proxy/github/users/octocat?api_key=your_api_key_here"
+```
+
+## Security Considerations
+
+1. **Environment Variables**: Store API keys securely as environment variables
+2. **HTTPS**: Always use HTTPS in production to prevent key exposure
+3. **Key Rotation**: Rotate API keys periodically
+4. **Minimal Permissions**: Use separate keys with minimal permissions
+
+## Troubleshooting
+
+If you're seeing "Unauthorized" errors:
+
+1. Verify you're providing the correct API key
+2. Check that the key format matches exactly (including any special characters)
+3. Ensure your `.env` file has the proper keys defined
+4. Restart the server after changing environment variables
+5. Look for "Auth" related errors in the server logs
diff --git a/config.md b/config.md
new file mode 100644
index 0000000..654f1ed
--- /dev/null
+++ b/config.md
@@ -0,0 +1,160 @@
+---
+title: Configuration
+layout: default
+nav_order: 5
+---
+
+# ByteProxy Configuration Reference
+
+ByteProxy offers extensive configuration options through environment variables and dynamic configuration endpoints.
+
+## Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `PORT` | `3420` | The port number for the server |
+| `CORS_ENABLED` | `true` | Enable/disable CORS support |
+| `CORS_ORIGINS` | `*` | Comma-separated list of allowed origins |
+| `LOG_LEVEL` | `info` | Logging level (debug, info, warn, error) |
+| `REQUIRE_AUTH_FOR_PROXY` | `false` | Require authentication for proxy routes |
+| `REQUIRE_AUTH_FOR_MANAGEMENT` | `false` | Require authentication for management routes |
+| `PROXY_API_KEY` | | API key for proxy routes |
+| `MANAGEMENT_API_KEY` | | API key for management routes |
+| `NETWORK_TIMEOUT` | `30000` | Request timeout in milliseconds |
+| `NETWORK_RETRIES` | `2` | Number of retry attempts for failed requests |
+| `STRICT_TLS` | `true` | Enforce strict TLS certificate validation |
+| `SKIP_UPDATE_CHECK` | `false` | Skip checking for updates at startup |
+| `DISCORD_BOT_TOKEN` | | Discord bot token for authentication |
+| `GITHUB_TOKEN` | | GitHub personal access token |
+
+## Service Configuration
+
+Services are defined in `src/config/index.ts` and can be dynamically managed through the API.
+
+### Default Services
+
+ByteProxy comes with pre-configured services:
+
+#### Discord API
+
+```typescript
+{
+ id: 'discord',
+ name: 'Discord API',
+ baseUrl: 'https://discord.com/api/',
+ versionedBaseUrls: {
+ v10: 'https://discord.com/api/v10/',
+ v9: 'https://discord.com/api/v9/'
+ },
+ headers: {
+ 'User-Agent': 'DiscordBot (https://github.com/ByteBrushStudios/ByteProxy, 0.1.0)',
+ 'Content-Type': 'application/json'
+ },
+ rateLimit: {
+ maxRequests: 50,
+ windowMs: 60000
+ },
+ auth: {
+ type: 'bot',
+ tokenEnvVar: 'DISCORD_BOT_TOKEN'
+ }
+}
+```
+
+#### GitHub API
+
+```typescript
+{
+ id: 'github',
+ name: 'GitHub API',
+ baseUrl: 'https://api.github.com/',
+ headers: {
+ 'User-Agent': 'ByteProxy/0.1.0',
+ 'Accept': 'application/vnd.github+json',
+ 'X-GitHub-Api-Version': '2022-11-28'
+ },
+ rateLimit: {
+ maxRequests: 60,
+ windowMs: 3600000
+ },
+ auth: {
+ type: 'bearer',
+ tokenEnvVar: 'GITHUB_TOKEN'
+ }
+}
+```
+
+### Adding Custom Services
+
+You can add custom services at runtime:
+
+```bash
+curl -X POST http://localhost:3420/manage/services \
+ -H "Content-Type: application/json" \
+ -d '{
+ "key": "custom-api",
+ "config": {
+ "name": "Custom API",
+ "baseUrl": "https://api.example.com/",
+ "headers": {
+ "User-Agent": "ByteProxy/1.0",
+ "Content-Type": "application/json"
+ },
+ "rateLimit": {
+ "maxRequests": 100,
+ "windowMs": 60000
+ },
+ "auth": {
+ "type": "bearer",
+ "tokenEnvVar": "CUSTOM_API_TOKEN"
+ }
+ }
+ }'
+```
+
+### Service Configuration Properties
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `name` | string | Display name for the service |
+| `baseUrl` | string | Base URL for API requests |
+| `versionedBaseUrls` | object | Optional versioned endpoints |
+| `headers` | object | Default headers to send with every request |
+| `rateLimit.maxRequests` | number | Maximum requests allowed |
+| `rateLimit.windowMs` | number | Time window for rate limiting in milliseconds |
+| `auth.type` | string | Auth type: 'bearer', 'basic', 'api-key', or 'bot' |
+| `auth.tokenEnvVar` | string | Environment variable containing the auth token |
+| `auth.headerName` | string | Custom header name for api-key auth type |
+
+## Configuration Management
+
+### View Configuration
+
+Access runtime configuration through the management endpoints:
+
+```bash
+# List all services
+curl http://localhost:3420/manage/services
+
+# Get specific service configuration
+curl http://localhost:3420/manage/services/discord
+
+# View diagnostics (includes configuration info)
+curl http://localhost:3420/manage/diagnostics
+```
+
+### Testing Configuration
+
+```bash
+# Test service connectivity
+curl -X POST http://localhost:3420/manage/services/github/test
+
+# Check authentication status
+curl http://localhost:3420/manage/key-debug
+```
+
+## Next Steps
+
+- [Usage Guide](usage.md)
+- [API Reference](api.md)
+- [Troubleshooting](troubleshooting.md)
diff --git a/deployment.md b/deployment.md
new file mode 100644
index 0000000..865a7fd
--- /dev/null
+++ b/deployment.md
@@ -0,0 +1,26 @@
+---
+title: Deployment
+layout: default
+nav_order: 7
+has_children: true
+---
+
+# Deployment
+
+This section covers how to deploy ByteProxy in various environments.
+
+## Topics
+
+- [Self-Hosting](self-host.md) - Run ByteProxy on your own infrastructure
+- Docker Deployment - Containerized deployment options
+- Cloud Deployment - Hosting on cloud platforms
+- Reverse Proxy Setup - Using Nginx, Caddy, or other reverse proxies
+
+## Deployment Checklist
+
+- [ ] Configure environment variables
+- [ ] Set up proper authentication
+- [ ] Configure HTTPS
+- [ ] Set up logging
+- [ ] Configure monitoring
+- [ ] Test all services
diff --git a/getting-started.md b/getting-started.md
new file mode 100644
index 0000000..11aa46b
--- /dev/null
+++ b/getting-started.md
@@ -0,0 +1,113 @@
+---
+title: Getting Started
+layout: default
+nav_order: 2
+---
+
+# Getting Started with ByteProxy
+
+This guide will help you get ByteProxy up and running quickly.
+
+## Prerequisites
+
+- [Bun](https://bun.sh/) (recommended) or Node.js 18+
+- Git
+- Basic understanding of REST APIs
+- API tokens for services you want to proxy (Discord, GitHub, etc.)
+
+## Installation
+
+### 1. Clone the Repository
+
+```bash
+git clone https://github.com/ByteBrushStudios/ByteProxy.git
+cd ByteProxy
+```
+
+### 2. Install Dependencies
+
+```bash
+# Using Bun (recommended)
+bun install
+
+# Using npm
+npm install
+```
+
+### 3. Configure Environment
+
+```bash
+# Copy the example environment file
+cp .env.example .env.local
+
+# Edit with your preferred editor
+nano .env.local
+```
+
+At minimum, configure:
+- `PORT` (default: 3420)
+- Service tokens:
+ - `DISCORD_BOT_TOKEN` (if using Discord)
+ - `GITHUB_TOKEN` (if using GitHub)
+
+### 4. Start the Server
+
+```bash
+# Development mode
+bun run dev
+
+# Production mode
+bun run build
+bun run start
+```
+
+## Quick Verification
+
+Once ByteProxy is running, check the following endpoints to verify it's working correctly:
+
+1. Open [http://localhost:3420](http://localhost:3420) in your browser
+ - You should see the welcome message
+
+2. Visit the [API Documentation](http://localhost:3420/docs)
+ - This provides interactive Swagger documentation
+
+3. Check the [Health Endpoint](http://localhost:3420/health)
+ - Should return `{"status":"ok",...}`
+
+## Making Your First Proxy Request
+
+### GitHub Example
+
+```bash
+# Get information about a GitHub user
+curl http://localhost:3420/proxy/github/users/ByteBrushStudios
+```
+
+### Discord Example
+
+```bash
+# Get information about your bot
+curl http://localhost:3420/proxy/discord/users/@me
+```
+
+## Next Steps
+
+Now that you have ByteProxy running, you can:
+
+1. **Explore the API:** Use the [Swagger Documentation](http://localhost:3420/docs)
+2. **Add Custom Services:** See [Adding Services](usage.md#adding-custom-services)
+3. **Configure Authentication:** See [Security & Authentication](security.md)
+4. **Integrate with Your Application:** Build frontends that use ByteProxy as a backend
+
+## Detailed Guides
+
+- [Complete Usage Guide](usage.md)
+- [Configuration Reference](config.md)
+- [Self-Hosting Guide](self-host.md)
+- [Troubleshooting](troubleshooting.md)
+- [API Reference](api.md)
+
+## Need Help?
+
+- [GitHub Issues](https://github.com/ByteBrushStudios/ByteProxy/issues)
+- [Discord Community](https://discord.gg/Vv2bdC44Ge)
diff --git a/go.mod b/go.mod
deleted file mode 100644
index cd428f3..0000000
--- a/go.mod
+++ /dev/null
@@ -1,3 +0,0 @@
-module github.com/NodeByteLTD/ByteProxy
-
-go 1.25
diff --git a/index.md b/index.md
new file mode 100644
index 0000000..f5c8275
--- /dev/null
+++ b/index.md
@@ -0,0 +1,45 @@
+---
+title: Home
+layout: home
+nav_order: 1
+permalink: /
+---
+
+# ByteProxy Documentation
+
+Welcome to ByteProxy!
+A powerful, extensible web proxy for Discord, GitHub, and more.
+
+## Features
+
+- Multi-service proxying (Discord, GitHub, custom APIs)
+- Rate limiting, authentication, and dynamic service management
+- Health/status endpoints, diagnostics, and logging
+- TypeScript, Elysia, Bun/Node support
+
+## Authentication Options
+
+ByteProxy supports multiple authentication methods:
+
+- API Key via Bearer token: `Authorization: Bearer YOUR_API_KEY`
+- API Key via header: `x-api-key: YOUR_API_KEY`
+- API Key via query parameter: `?api_key=YOUR_API_KEY`
+
+Authentication can be enabled/disabled in the configuration. For detailed information, see our [Authentication Guide](auth.md).
+
+## Quick Links
+
+- [Getting Started](getting-started.md)
+- [Usage Guide](usage.md)
+- [Authentication](auth.md)
+- [Self-Hosting](self-host.md)
+- [Configuration Reference](config.md)
+- [API Reference](api.md)
+- [Service Management](services.md)
+- [Troubleshooting](troubleshooting.md)
+- [Contributing](contributing.md)
+- [Changelog](changelog.md)
+
+---
+
+Built by [ByteBrush Studios](https://github.com/ByteBrushStudios) and [CodeMeAPixel](https://codemeapixel.dev)
diff --git a/internal/config/config.go b/internal/config/config.go
deleted file mode 100644
index 247f25e..0000000
--- a/internal/config/config.go
+++ /dev/null
@@ -1,135 +0,0 @@
-package config
-
-import (
- "errors"
- "log/slog"
- "os"
- "strconv"
- "strings"
- "time"
-)
-
-type Settings struct {
- Port int
- CORSEnabled bool
- CORSOrigins []string
- LogLevel slog.Level
- Timeout time.Duration
- StrictTLS bool
- ProxyAPIKey string
- ManagementAPIKey string
- RequireProxyAuth bool
- RequireManagementAuth bool
- DiscordGlobalRPS int
- SkipUpdateCheck bool
- UpdateRepo string
- ServicesFile string
- MaxBodyBytes int64
- MaxHeapBytes uint64
- MaxSysBytes uint64
- Environment string
-}
-
-func env(key, def string) string {
- if v, ok := os.LookupEnv(key); ok && strings.TrimSpace(v) != "" {
- return strings.TrimSpace(v)
- }
- return def
-}
-
-func envInt(key string, def int) int {
- v, err := strconv.Atoi(env(key, ""))
- if err != nil || v <= 0 {
- return def
- }
- return v
-}
-
-func environment() string {
- switch strings.ToLower(env("APP_ENV", env("NODE_ENV", "local"))) {
- case "production", "prod":
- return "prod"
- case "development", "dev":
- return "dev"
- default:
- return "local"
- }
-}
-
-func level(s string) slog.Level {
- switch strings.ToLower(s) {
- case "debug":
- return slog.LevelDebug
- case "warn", "warning":
- return slog.LevelWarn
- case "error":
- return slog.LevelError
- default:
- return slog.LevelInfo
- }
-}
-
-func Load() (Settings, error) {
- var origins []string
- for _, o := range strings.Split(env("CORS_ORIGINS", "*"), ",") {
- if o = strings.TrimSpace(o); o != "" {
- origins = append(origins, o)
- }
- }
-
- s := Settings{
- Port: envInt("PORT", 3420),
- CORSEnabled: env("CORS_ENABLED", "true") != "false",
- CORSOrigins: origins,
- LogLevel: level(env("LOG_LEVEL", "info")),
- Timeout: time.Duration(envInt("NETWORK_TIMEOUT", 30000)) * time.Millisecond,
- StrictTLS: env("STRICT_TLS", "true") != "false",
- ProxyAPIKey: env("PROXY_API_KEY", ""),
- ManagementAPIKey: env("MANAGEMENT_API_KEY", ""),
- RequireProxyAuth: env("REQUIRE_AUTH_FOR_PROXY", "false") == "true",
- RequireManagementAuth: env("REQUIRE_AUTH_FOR_MANAGEMENT", "false") == "true",
- DiscordGlobalRPS: envInt("DISCORD_GLOBAL_RPS", 50),
- SkipUpdateCheck: env("SKIP_UPDATE_CHECK", "false") == "true",
- UpdateRepo: env("UPDATE_REPO", "NodeByteLTD/ByteProxy"),
- ServicesFile: env("SERVICES_FILE", "data/services.json"),
- MaxBodyBytes: int64(envInt("MAX_BODY_MB", 100)) << 20,
- MaxHeapBytes: uint64(envInt("MAX_HEAP_MB", 512)) << 20,
- MaxSysBytes: uint64(envInt("MAX_RSS_MB", 1024)) << 20,
- Environment: environment(),
- }
-
- var errs []error
- if s.RequireProxyAuth && s.ProxyAPIKey == "" {
- errs = append(errs, errors.New("REQUIRE_AUTH_FOR_PROXY=true but PROXY_API_KEY is empty"))
- }
- if s.RequireManagementAuth && s.ManagementAPIKey == "" {
- errs = append(errs, errors.New("REQUIRE_AUTH_FOR_MANAGEMENT=true but MANAGEMENT_API_KEY is empty"))
- }
- return s, errors.Join(errs...)
-}
-
-func LoadDotEnv(files ...string) {
- for _, file := range files {
- data, err := os.ReadFile(file)
- if err != nil {
- continue
- }
- for _, line := range strings.Split(string(data), "\n") {
- line = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "export "))
- if line == "" || strings.HasPrefix(line, "#") {
- continue
- }
- key, value, ok := strings.Cut(line, "=")
- if !ok {
- continue
- }
- key, value = strings.TrimSpace(key), strings.TrimSpace(value)
- if n := len(value); n >= 2 && (value[0] == '"' && value[n-1] == '"' || value[0] == '\'' && value[n-1] == '\'') {
- value = value[1 : n-1]
- }
- if _, exists := os.LookupEnv(key); !exists {
- os.Setenv(key, value)
- }
- }
- }
-}
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
deleted file mode 100644
index 67ef5a5..0000000
--- a/internal/config/config_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package config
-
-import (
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestAuthRequiredWithoutKeyFails(t *testing.T) {
- t.Setenv("REQUIRE_AUTH_FOR_PROXY", "true")
- t.Setenv("PROXY_API_KEY", "")
- if _, err := Load(); err == nil {
- t.Fatal("expected an error when proxy auth is required without a key")
- }
- t.Setenv("PROXY_API_KEY", "k")
- if _, err := Load(); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestDefaults(t *testing.T) {
- s, err := Load()
- if err != nil {
- t.Fatal(err)
- }
- if s.Port != 3420 || s.UpdateRepo != "NodeByteLTD/ByteProxy" || !s.StrictTLS || s.DiscordGlobalRPS != 50 {
- t.Fatalf("unexpected defaults %+v", s)
- }
-}
-
-func TestDotEnvDoesNotOverride(t *testing.T) {
- dir := t.TempDir()
- file := filepath.Join(dir, ".env")
- os.WriteFile(file, []byte("# comment\nBP_TEST_A=\"from file\"\nexport BP_TEST_B=b\nBP_TEST_C=file\n"), 0o600)
- t.Setenv("BP_TEST_C", "process")
- os.Unsetenv("BP_TEST_A")
- os.Unsetenv("BP_TEST_B")
- t.Cleanup(func() { os.Unsetenv("BP_TEST_A"); os.Unsetenv("BP_TEST_B") })
- LoadDotEnv(file)
- if os.Getenv("BP_TEST_A") != "from file" || os.Getenv("BP_TEST_B") != "b" || os.Getenv("BP_TEST_C") != "process" {
- t.Fatalf("A=%q B=%q C=%q", os.Getenv("BP_TEST_A"), os.Getenv("BP_TEST_B"), os.Getenv("BP_TEST_C"))
- }
-}
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
deleted file mode 100644
index 6150bde..0000000
--- a/internal/proxy/proxy.go
+++ /dev/null
@@ -1,311 +0,0 @@
-package proxy
-
-import (
- "bytes"
- "context"
- "crypto/sha256"
- "crypto/subtle"
- "crypto/tls"
- "encoding/base64"
- "encoding/hex"
- "errors"
- "fmt"
- "io"
- "log/slog"
- "net"
- "net/http"
- "net/url"
- "os"
- "strings"
- "time"
-
- "github.com/NodeByteLTD/ByteProxy/internal/ratelimit"
- "github.com/NodeByteLTD/ByteProxy/internal/registry"
-)
-
-const (
- discordMaxAttempts = 3
- githubMaxAttempts = 3
- maxRetryWait = 30 * time.Second
-)
-
-type Error struct {
- Status int
- Message string
-}
-
-func (e *Error) Error() string { return e.Message }
-
-var strippedRequestHeaders = []string{
- "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "Proxy-Connection",
- "Te", "Trailer", "Transfer-Encoding", "Upgrade", "Host", "Content-Length", "Accept-Encoding",
- "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "Forwarded", "X-Real-Ip",
- "Cf-Connecting-Ip", "Cf-Ipcountry", "Cf-Ray", "Cf-Visitor", "True-Client-Ip",
- "Authorization", "X-Upstream-Authorization", "X-Api-Key", "Cookie",
-}
-
-var StrippedResponseHeaders = []string{
- "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Connection", "Te", "Trailer",
- "Transfer-Encoding", "Upgrade", "Content-Length",
-}
-
-type Request struct {
- ServiceKey string
- Service registry.Service
- Method string
- TargetURL string
- Path string
- Header http.Header
- Body []byte
- ProxyKey string
-}
-
-type Forwarder struct {
- Client *http.Client
- discord *ratelimit.Discord
- github *ratelimit.GitHub
- Window *ratelimit.Window
- logger *slog.Logger
-}
-
-func NewForwarder(timeout time.Duration, strictTLS bool, discordRPS int, logger *slog.Logger) *Forwarder {
- transport := &http.Transport{
- DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
- TLSClientConfig: &tls.Config{InsecureSkipVerify: !strictTLS, MinVersion: tls.VersionTLS12},
- TLSHandshakeTimeout: 10 * time.Second,
- ResponseHeaderTimeout: timeout,
- ExpectContinueTimeout: time.Second,
- MaxIdleConns: 256,
- MaxIdleConnsPerHost: 64,
- IdleConnTimeout: 90 * time.Second,
- ForceAttemptHTTP2: true,
- }
- return &Forwarder{
- Client: &http.Client{Transport: transport},
- discord: ratelimit.NewDiscord(discordRPS),
- github: ratelimit.NewGitHub(),
- Window: ratelimit.NewWindow(),
- logger: logger,
- }
-}
-
-func (f *Forwarder) StartPruning(ctx context.Context) {
- go func() {
- t := time.NewTicker(5 * time.Minute)
- defer t.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-t.C:
- f.discord.Prune(10 * time.Minute)
- f.github.Prune(time.Hour)
- }
- }
- }()
-}
-
-func KeyEquals(provided, key string) bool {
- if provided == "" || key == "" {
- return false
- }
- hp, hk := sha256.Sum256([]byte(provided)), sha256.Sum256([]byte(key))
- return subtle.ConstantTimeCompare(hp[:], hk[:]) == 1
-}
-
-func IsProxyBearer(authorization, proxyKey string) bool {
- if !strings.HasPrefix(authorization, "Bearer ") {
- return false
- }
- return KeyEquals(strings.TrimSpace(authorization[len("Bearer "):]), proxyKey)
-}
-
-func formatToken(authType, token string) string {
- switch authType {
- case "bot":
- return "Bot " + token
- case "bearer":
- return "Bearer " + token
- case "basic":
- return "Basic " + base64.StdEncoding.EncodeToString([]byte(token))
- default:
- return token
- }
-}
-
-func BuildHeaders(req Request) (http.Header, string) {
- out := http.Header{}
- for k, v := range req.Service.Headers {
- out.Set(k, v)
- }
- for _, token := range strings.Split(req.Header.Get("Connection"), ",") {
- if token = strings.TrimSpace(token); token != "" {
- req.Header.Del(token)
- }
- }
- for k, vs := range req.Header {
- out.Del(k)
- for _, v := range vs {
- out.Add(k, v)
- }
- }
- for _, h := range strippedRequestHeaders {
- out.Del(h)
- }
- for k, v := range req.Service.Headers {
- if http.CanonicalHeaderKey(k) == "User-Agent" {
- out.Set(k, v)
- }
- }
-
- upstream := req.Header.Get("X-Upstream-Authorization")
- if upstream == "" {
- if a := req.Header.Get("Authorization"); a != "" && !IsProxyBearer(a, req.ProxyKey) {
- upstream = a
- }
- }
- if upstream == "" {
- if a := req.Service.Auth; a != nil && registry.TokenEnvAllowed(a.TokenEnvVar) {
- if token := os.Getenv(a.TokenEnvVar); token != "" {
- upstream = formatToken(a.Type, token)
- }
- }
- }
-
- cred := "anonymous"
- if upstream != "" {
- if a := req.Service.Auth; a != nil && a.Type == "api-key" && a.HeaderName != "" {
- out.Set(a.HeaderName, upstream)
- } else {
- out.Set("Authorization", upstream)
- }
- sum := sha256.Sum256([]byte(upstream))
- cred = hex.EncodeToString(sum[:12])
- }
- if len(req.Body) > 0 && out.Get("Content-Type") == "" {
- out.Set("Content-Type", "application/json")
- }
- return out, cred
-}
-
-func (f *Forwarder) Do(ctx context.Context, req Request) (*http.Response, error) {
- headers, cred := BuildHeaders(req)
- switch req.ServiceKey {
- case "discord":
- return f.doDiscord(ctx, req, headers, cred)
- case "github":
- return f.doGitHub(ctx, req, headers, cred)
- }
- if rl := req.Service.RateLimit; rl != nil {
- if ok, resetIn := f.Window.Allow(req.ServiceKey, rl.MaxRequests, time.Duration(rl.WindowMs)*time.Millisecond); !ok {
- return nil, &Error{http.StatusTooManyRequests, fmt.Sprintf("Rate limit exceeded for %s. Reset in %d seconds.", req.ServiceKey, int(resetIn.Seconds()+0.999))}
- }
- }
- return f.send(ctx, req, headers)
-}
-
-func (f *Forwarder) doDiscord(ctx context.Context, req Request, headers http.Header, cred string) (*http.Response, error) {
- for attempt := 1; ; attempt++ {
- route, err := f.discord.Acquire(ctx, cred, req.Method, req.Path)
- if err != nil {
- return nil, contextError(err)
- }
- resp, err := f.send(ctx, req, headers)
- if err != nil {
- return nil, err
- }
- f.discord.Update(cred, route, req.Path, resp.Header)
- if resp.StatusCode != http.StatusTooManyRequests || attempt == discordMaxAttempts {
- return resp, nil
- }
- body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
- resp.Body.Close()
- wait := ratelimit.DiscordRetryAfter(resp.Header, body)
- if resp.Header.Get("X-RateLimit-Global") == "true" {
- f.discord.BlockGlobal(cred, wait)
- }
- if wait > maxRetryWait {
- resp.Body = io.NopCloser(bytes.NewReader(body))
- return resp, nil
- }
- f.logger.Warn("discord 429, retrying", "path", req.Path, "attempt", attempt, "wait", wait, "global", resp.Header.Get("X-RateLimit-Global") == "true")
- if err := sleepCtx(ctx, wait); err != nil {
- return nil, contextError(err)
- }
- }
-}
-
-func (f *Forwarder) doGitHub(ctx context.Context, req Request, headers http.Header, cred string) (*http.Response, error) {
- for attempt := 1; ; attempt++ {
- resource, err := f.github.Acquire(ctx, cred, req.Path)
- if err != nil {
- return nil, contextError(err)
- }
- resp, err := f.send(ctx, req, headers)
- if err != nil {
- return nil, err
- }
- f.github.Update(cred, resource, resp.Header)
- wait, retry := ratelimit.GitHubRetryAfter(resp.StatusCode, resp.Header)
- if !retry || attempt == githubMaxAttempts || wait > maxRetryWait {
- return resp, nil
- }
- io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
- resp.Body.Close()
- f.logger.Warn("github rate limited, retrying", "path", req.Path, "status", resp.StatusCode, "attempt", attempt, "wait", wait)
- if err := sleepCtx(ctx, wait); err != nil {
- return nil, contextError(err)
- }
- }
-}
-
-func sleepCtx(ctx context.Context, d time.Duration) error {
- t := time.NewTimer(d)
- defer t.Stop()
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-t.C:
- return nil
- }
-}
-
-func contextError(err error) error {
- if errors.Is(err, context.DeadlineExceeded) {
- return &Error{http.StatusGatewayTimeout, "Timed out waiting for the upstream rate limit to reset"}
- }
- return &Error{http.StatusBadGateway, "Request cancelled"}
-}
-
-func (f *Forwarder) send(ctx context.Context, req Request, headers http.Header) (*http.Response, error) {
- var body io.Reader
- if len(req.Body) > 0 {
- body = bytes.NewReader(req.Body)
- }
- r, err := http.NewRequestWithContext(ctx, req.Method, req.TargetURL, body)
- if err != nil {
- return nil, &Error{http.StatusBadRequest, "Invalid upstream request: " + err.Error()}
- }
- r.Header = headers.Clone()
- resp, err := f.Client.Do(r)
- if err == nil {
- return resp, nil
- }
-
- host := r.URL.Host
- var netErr net.Error
- var urlErr *url.Error
- var certErr *tls.CertificateVerificationError
- switch {
- case errors.Is(err, context.Canceled):
- return nil, &Error{http.StatusBadGateway, "Request cancelled by the caller"}
- case errors.Is(err, context.DeadlineExceeded), errors.As(err, &netErr) && netErr.Timeout():
- return nil, &Error{http.StatusGatewayTimeout, "Upstream timed out (" + host + ")"}
- case errors.As(err, &certErr), strings.Contains(err.Error(), "x509"), strings.Contains(err.Error(), "tls:"):
- return nil, &Error{http.StatusBadGateway, "TLS error connecting to " + host + ". Check the upstream certificate and system clock."}
- case errors.As(err, &urlErr):
- return nil, &Error{http.StatusBadGateway, "Unable to reach " + host}
- default:
- return nil, &Error{http.StatusBadGateway, "Upstream request failed: " + err.Error()}
- }
-}
diff --git a/internal/ratelimit/ratelimit.go b/internal/ratelimit/ratelimit.go
deleted file mode 100644
index 8c982bd..0000000
--- a/internal/ratelimit/ratelimit.go
+++ /dev/null
@@ -1,371 +0,0 @@
-package ratelimit
-
-import (
- "context"
- "encoding/json"
- "hash/fnv"
- "math"
- "net/http"
- "regexp"
- "strconv"
- "strings"
- "sync"
- "time"
-)
-
-const stripes = 256
-
-type striped [stripes]sync.Mutex
-
-func (s *striped) lock(key string) *sync.Mutex {
- h := fnv.New32a()
- h.Write([]byte(key))
- return &s[h.Sum32()%stripes]
-}
-
-func sleep(ctx context.Context, d time.Duration) error {
- if d <= 0 {
- return nil
- }
- t := time.NewTimer(d)
- defer t.Stop()
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-t.C:
- return nil
- }
-}
-
-func headerSeconds(h http.Header, name string) (time.Duration, bool) {
- v := h.Get(name)
- if v == "" {
- return 0, false
- }
- f, err := strconv.ParseFloat(v, 64)
- if err != nil || f < 0 || math.IsInf(f, 0) {
- return 0, false
- }
- return time.Duration(f * float64(time.Second)), true
-}
-
-type bucketState struct {
- remaining int
- resetAt time.Time
- lastSeen time.Time
-}
-
-type tokenBucket struct {
- tokens float64
- last time.Time
- blocked time.Time
- lastSeen time.Time
-}
-
-type Discord struct {
- rps float64
- mu sync.Mutex
- global map[string]*tokenBucket
- routeBucket map[string]string
- routeSeen map[string]time.Time
- state map[string]*bucketState
- locks striped
-}
-
-var majorParam = regexp.MustCompile(`^/(?:(channels|guilds)/(\d+)|webhooks/(\d+)(?:/([^/?]+))?)`)
-
-func NewDiscord(globalRPS int) *Discord {
- if globalRPS <= 0 {
- globalRPS = 50
- }
- return &Discord{
- rps: float64(globalRPS),
- global: map[string]*tokenBucket{},
- routeBucket: map[string]string{},
- routeSeen: map[string]time.Time{},
- state: map[string]*bucketState{},
- }
-}
-
-func DiscordRouteKey(method, path string) string {
- path, _, _ = strings.Cut(path, "?")
- return strings.ToUpper(method) + " " + path
-}
-
-func DiscordMajor(path string) string {
- m := majorParam.FindStringSubmatch(path)
- switch {
- case m == nil:
- return ""
- case m[1] != "":
- return m[1] + "/" + m[2]
- case m[4] != "":
- return "webhooks/" + m[3] + "/" + m[4]
- default:
- return "webhooks/" + m[3]
- }
-}
-
-func (d *Discord) bucketKey(cred, route, path string) string {
- d.mu.Lock()
- defer d.mu.Unlock()
- if hash, ok := d.routeBucket[cred+"|"+route]; ok {
- return cred + "|" + hash + "|" + DiscordMajor(path)
- }
- return cred + "|" + route
-}
-
-func (d *Discord) waitGlobal(ctx context.Context, cred string) error {
- for {
- d.mu.Lock()
- now := time.Now()
- b := d.global[cred]
- if b == nil {
- b = &tokenBucket{tokens: d.rps, last: now}
- d.global[cred] = b
- }
- b.lastSeen = now
- var wait time.Duration
- if now.Before(b.blocked) {
- wait = b.blocked.Sub(now)
- } else {
- b.tokens = math.Min(d.rps, b.tokens+now.Sub(b.last).Seconds()*d.rps)
- b.last = now
- if b.tokens >= 1 {
- b.tokens--
- d.mu.Unlock()
- return nil
- }
- wait = time.Duration((1 - b.tokens) / d.rps * float64(time.Second))
- }
- d.mu.Unlock()
- if err := sleep(ctx, max(wait, time.Millisecond)); err != nil {
- return err
- }
- }
-}
-
-func (d *Discord) Acquire(ctx context.Context, cred, method, path string) (string, error) {
- route := DiscordRouteKey(method, path)
- if err := d.waitGlobal(ctx, cred); err != nil {
- return "", err
- }
- key := d.bucketKey(cred, route, path)
- lock := d.locks.lock(key)
- lock.Lock()
- defer lock.Unlock()
-
- d.mu.Lock()
- var wait time.Duration
- if st := d.state[key]; st != nil && st.remaining <= 0 {
- wait = time.Until(st.resetAt)
- }
- d.mu.Unlock()
- if err := sleep(ctx, wait); err != nil {
- return "", err
- }
-
- d.mu.Lock()
- if st := d.state[key]; st != nil {
- if time.Now().After(st.resetAt) {
- delete(d.state, key)
- } else {
- st.remaining--
- }
- }
- d.mu.Unlock()
- return route, nil
-}
-
-func (d *Discord) Update(cred, route, path string, h http.Header) {
- remaining, err1 := strconv.Atoi(h.Get("X-RateLimit-Remaining"))
- resetAfter, ok := headerSeconds(h, "X-RateLimit-Reset-After")
- if err1 != nil || !ok {
- return
- }
- now := time.Now()
- d.mu.Lock()
- defer d.mu.Unlock()
- key := cred + "|" + route
- if hash := h.Get("X-RateLimit-Bucket"); hash != "" {
- d.routeBucket[cred+"|"+route] = hash
- d.routeSeen[cred+"|"+route] = now
- key = cred + "|" + hash + "|" + DiscordMajor(path)
- }
- d.state[key] = &bucketState{remaining: remaining, resetAt: now.Add(resetAfter), lastSeen: now}
-}
-
-func (d *Discord) BlockGlobal(cred string, wait time.Duration) {
- d.mu.Lock()
- defer d.mu.Unlock()
- b := d.global[cred]
- if b == nil {
- b = &tokenBucket{tokens: 0, last: time.Now()}
- d.global[cred] = b
- }
- if until := time.Now().Add(wait); until.After(b.blocked) {
- b.blocked = until
- }
-}
-
-func DiscordRetryAfter(h http.Header, body []byte) time.Duration {
- if d, ok := headerSeconds(h, "Retry-After"); ok {
- return d
- }
- var payload struct {
- RetryAfter *float64 `json:"retry_after"`
- }
- if json.Unmarshal(body, &payload) == nil && payload.RetryAfter != nil && *payload.RetryAfter >= 0 {
- return time.Duration(*payload.RetryAfter * float64(time.Second))
- }
- return time.Second
-}
-
-func (d *Discord) Prune(olderThan time.Duration) {
- cutoff := time.Now().Add(-olderThan)
- d.mu.Lock()
- defer d.mu.Unlock()
- for k, st := range d.state {
- if st.lastSeen.Before(cutoff) {
- delete(d.state, k)
- }
- }
- for k, seen := range d.routeSeen {
- if seen.Before(cutoff) {
- delete(d.routeSeen, k)
- delete(d.routeBucket, k)
- }
- }
- for k, b := range d.global {
- if b.lastSeen.Before(cutoff) && time.Now().After(b.blocked) {
- delete(d.global, k)
- }
- }
-}
-
-type resourceState struct {
- remaining int
- resetAt time.Time
- lastSeen time.Time
-}
-
-type GitHub struct {
- mu sync.Mutex
- state map[string]*resourceState
- locks striped
-}
-
-func NewGitHub() *GitHub { return &GitHub{state: map[string]*resourceState{}} }
-
-func GitHubResource(path string) string {
- switch {
- case strings.HasPrefix(path, "/search"):
- return "search"
- case strings.HasPrefix(path, "/graphql"):
- return "graphql"
- default:
- return "core"
- }
-}
-
-func (g *GitHub) Acquire(ctx context.Context, cred, path string) (string, error) {
- resource := GitHubResource(path)
- key := cred + "|" + resource
- lock := g.locks.lock(key)
- lock.Lock()
- defer lock.Unlock()
-
- g.mu.Lock()
- var wait time.Duration
- if st := g.state[key]; st != nil && st.remaining <= 0 {
- wait = time.Until(st.resetAt)
- }
- g.mu.Unlock()
- if err := sleep(ctx, wait); err != nil {
- return "", err
- }
-
- g.mu.Lock()
- if st := g.state[key]; st != nil {
- st.remaining--
- }
- g.mu.Unlock()
- return resource, nil
-}
-
-func (g *GitHub) Update(cred, fallback string, h http.Header) {
- remaining, err1 := strconv.Atoi(h.Get("X-RateLimit-Remaining"))
- reset, err2 := strconv.ParseInt(h.Get("X-RateLimit-Reset"), 10, 64)
- if err1 != nil || err2 != nil {
- return
- }
- resource := h.Get("X-RateLimit-Resource")
- if resource == "" {
- resource = fallback
- }
- g.mu.Lock()
- defer g.mu.Unlock()
- g.state[cred+"|"+resource] = &resourceState{remaining: remaining, resetAt: time.Unix(reset, 0), lastSeen: time.Now()}
-}
-
-func GitHubRetryAfter(status int, h http.Header) (time.Duration, bool) {
- if status != http.StatusForbidden && status != http.StatusTooManyRequests {
- return 0, false
- }
- return headerSeconds(h, "Retry-After")
-}
-
-func (g *GitHub) Prune(olderThan time.Duration) {
- cutoff := time.Now().Add(-olderThan)
- g.mu.Lock()
- defer g.mu.Unlock()
- for k, st := range g.state {
- if st.lastSeen.Before(cutoff) {
- delete(g.state, k)
- }
- }
-}
-
-type windowState struct {
- count int
- resetAt time.Time
-}
-
-type Window struct {
- mu sync.Mutex
- state map[string]*windowState
-}
-
-func NewWindow() *Window { return &Window{state: map[string]*windowState{}} }
-
-func (w *Window) Allow(key string, max int, window time.Duration) (bool, time.Duration) {
- w.mu.Lock()
- defer w.mu.Unlock()
- now := time.Now()
- st := w.state[key]
- if st == nil || now.After(st.resetAt) {
- w.state[key] = &windowState{count: 1, resetAt: now.Add(window)}
- return true, 0
- }
- if st.count >= max {
- return false, st.resetAt.Sub(now)
- }
- st.count++
- return true, 0
-}
-
-func (w *Window) Status(key string, max int) (int, time.Time) {
- w.mu.Lock()
- defer w.mu.Unlock()
- st := w.state[key]
- if st == nil || time.Now().After(st.resetAt) {
- return max, time.Time{}
- }
- return max - min(st.count, max), st.resetAt
-}
-
-func (w *Window) Remove(key string) {
- w.mu.Lock()
- defer w.mu.Unlock()
- delete(w.state, key)
-}
diff --git a/internal/ratelimit/ratelimit_test.go b/internal/ratelimit/ratelimit_test.go
deleted file mode 100644
index 99d79f3..0000000
--- a/internal/ratelimit/ratelimit_test.go
+++ /dev/null
@@ -1,123 +0,0 @@
-package ratelimit
-
-import (
- "context"
- "net/http"
- "testing"
- "time"
-)
-
-func TestDiscordMajor(t *testing.T) {
- for path, want := range map[string]string{
- "/channels/123/messages": "channels/123",
- "/guilds/456/members/7": "guilds/456",
- "/webhooks/1/tok-en/messages": "webhooks/1/tok-en",
- "/webhooks/1": "webhooks/1",
- "/users/@me": "",
- } {
- if got := DiscordMajor(path); got != want {
- t.Errorf("%s: got %q want %q", path, got, want)
- }
- }
-}
-
-func TestDiscordBucketWaitsForReset(t *testing.T) {
- d := NewDiscord(50)
- ctx := context.Background()
- route, err := d.Acquire(ctx, "c", "POST", "/channels/1/messages")
- if err != nil {
- t.Fatal(err)
- }
- h := http.Header{}
- h.Set("X-RateLimit-Remaining", "0")
- h.Set("X-RateLimit-Reset-After", "0.2")
- h.Set("X-RateLimit-Bucket", "hash")
- d.Update("c", route, "/channels/1/messages", h)
-
- start := time.Now()
- if _, err := d.Acquire(ctx, "c", "POST", "/channels/1/messages"); err != nil {
- t.Fatal(err)
- }
- if waited := time.Since(start); waited < 150*time.Millisecond {
- t.Fatalf("did not wait for bucket reset (%v)", waited)
- }
-
- start = time.Now()
- if _, err := d.Acquire(ctx, "c", "POST", "/channels/2/messages"); err != nil {
- t.Fatal(err)
- }
- if time.Since(start) > 50*time.Millisecond {
- t.Fatal("a different channel shared the exhausted bucket")
- }
- start = time.Now()
- if _, err := d.Acquire(ctx, "other", "POST", "/channels/1/messages"); err != nil {
- t.Fatal(err)
- }
- if time.Since(start) > 50*time.Millisecond {
- t.Fatal("a different credential shared the exhausted bucket")
- }
-}
-
-func TestDiscordGlobalLimit(t *testing.T) {
- d := NewDiscord(5)
- ctx := context.Background()
- start := time.Now()
- for i := 0; i < 8; i++ {
- if _, err := d.Acquire(ctx, "c", "GET", "/users/@me"); err != nil {
- t.Fatal(err)
- }
- }
- if elapsed := time.Since(start); elapsed < 450*time.Millisecond {
- t.Fatalf("8 requests at 5 rps finished in %v", elapsed)
- }
-}
-
-func TestDiscordBlockGlobalAndCancel(t *testing.T) {
- d := NewDiscord(50)
- d.BlockGlobal("c", time.Hour)
- ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
- defer cancel()
- if _, err := d.Acquire(ctx, "c", "GET", "/users/@me"); err == nil {
- t.Fatal("expected context error while globally blocked")
- }
-}
-
-func TestDiscordRetryAfter(t *testing.T) {
- h := http.Header{}
- if got := DiscordRetryAfter(h, []byte(`{"retry_after":1.5}`)); got != 1500*time.Millisecond {
- t.Fatalf("body: %v", got)
- }
- h.Set("Retry-After", "2")
- if got := DiscordRetryAfter(h, nil); got != 2*time.Second {
- t.Fatalf("header: %v", got)
- }
- if got := DiscordRetryAfter(http.Header{}, []byte("nope")); got != time.Second {
- t.Fatalf("default: %v", got)
- }
-}
-
-func TestGitHubRetryAfterOnlyOnLimitStatuses(t *testing.T) {
- h := http.Header{}
- h.Set("Retry-After", "3")
- if _, ok := GitHubRetryAfter(202, h); ok {
- t.Fatal("retried a 202")
- }
- if d, ok := GitHubRetryAfter(403, h); !ok || d != 3*time.Second {
- t.Fatalf("403: %v %v", d, ok)
- }
-}
-
-func TestWindow(t *testing.T) {
- w := NewWindow()
- for i := 0; i < 2; i++ {
- if ok, _ := w.Allow("s", 2, time.Minute); !ok {
- t.Fatal("rejected within limit")
- }
- }
- if ok, reset := w.Allow("s", 2, time.Minute); ok || reset <= 0 {
- t.Fatal("allowed over limit")
- }
- if remaining, _ := w.Status("s", 2); remaining != 0 {
- t.Fatalf("remaining %d", remaining)
- }
-}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
deleted file mode 100644
index 89b3f36..0000000
--- a/internal/registry/registry.go
+++ /dev/null
@@ -1,247 +0,0 @@
-package registry
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "net/url"
- "os"
- "path/filepath"
- "regexp"
- "sort"
- "strings"
- "sync"
-)
-
-var (
- keyPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
- tokenEnvPattern = regexp.MustCompile(`^BYTEPROXY_TOKEN_[A-Z0-9_]+$`)
- headerPattern = regexp.MustCompile(`^[A-Za-z0-9!#$%&'*+.^_|~-]+$`)
-
- ErrExists = errors.New("service already exists")
- ErrNotFound = errors.New("service not found")
- ErrBuiltin = errors.New("built-in services can't be changed or removed")
-)
-
-var forbiddenStaticHeaders = map[string]bool{
- "authorization": true,
- "x-upstream-authorization": true,
- "x-api-key": true,
- "host": true,
- "cookie": true,
- "content-length": true,
- "transfer-encoding": true,
- "connection": true,
-}
-
-var authTypes = map[string]bool{"bearer": true, "basic": true, "api-key": true, "bot": true}
-
-type ValidationError struct{ Msg string }
-
-func (e *ValidationError) Error() string { return e.Msg }
-
-type RateLimit struct {
- MaxRequests int `json:"maxRequests"`
- WindowMs int64 `json:"windowMs"`
-}
-
-type Auth struct {
- Type string `json:"type"`
- TokenEnvVar string `json:"tokenEnvVar,omitempty"`
- HeaderName string `json:"headerName,omitempty"`
-}
-
-type Service struct {
- Name string `json:"name"`
- BaseURL string `json:"baseUrl"`
- Headers map[string]string `json:"headers,omitempty"`
- RateLimit *RateLimit `json:"rateLimit,omitempty"`
- Auth *Auth `json:"auth,omitempty"`
- Builtin bool `json:"-"`
-}
-
-func TokenEnvAllowed(name string) bool { return tokenEnvPattern.MatchString(name) }
-
-func Builtins(version, discordBase, githubBase string) map[string]Service {
- return map[string]Service{
- "discord": {
- Name: "Discord API",
- BaseURL: discordBase,
- Headers: map[string]string{
- "User-Agent": fmt.Sprintf("DiscordBot (https://github.com/ByteBrushStudios/ByteProxy, %s)", version),
- },
- Builtin: true,
- },
- "github": {
- Name: "GitHub API",
- BaseURL: githubBase,
- Headers: map[string]string{
- "User-Agent": "ByteProxy/" + version,
- "Accept": "application/vnd.github+json",
- "X-GitHub-Api-Version": "2022-11-28",
- },
- Builtin: true,
- },
- }
-}
-
-func Validate(key string, svc Service) error {
- if !keyPattern.MatchString(key) {
- return &ValidationError{"key must be 1-32 lowercase letters, digits, '-' or '_', starting with a letter or digit"}
- }
- if strings.TrimSpace(svc.Name) == "" || len(svc.Name) > 100 {
- return &ValidationError{"config.name is required (max 100 characters)"}
- }
- u, err := url.Parse(svc.BaseURL)
- if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
- return &ValidationError{"config.baseUrl must be an absolute http(s) URL"}
- }
- for name := range svc.Headers {
- if !headerPattern.MatchString(name) {
- return &ValidationError{fmt.Sprintf("config.headers: %q is not a valid header name", name)}
- }
- if forbiddenStaticHeaders[strings.ToLower(name)] {
- return &ValidationError{fmt.Sprintf("config.headers: %q can't be set statically; use auth or caller headers", name)}
- }
- }
- if rl := svc.RateLimit; rl != nil && (rl.MaxRequests <= 0 || rl.WindowMs <= 0) {
- return &ValidationError{"config.rateLimit.maxRequests and windowMs must be positive"}
- }
- if a := svc.Auth; a != nil {
- if !authTypes[a.Type] {
- return &ValidationError{"config.auth.type must be one of bearer, basic, api-key, bot"}
- }
- if a.Type == "api-key" && !headerPattern.MatchString(a.HeaderName) {
- return &ValidationError{"config.auth.headerName is required for api-key auth"}
- }
- if a.TokenEnvVar != "" && !TokenEnvAllowed(a.TokenEnvVar) {
- return &ValidationError{"config.auth.tokenEnvVar must be named BYTEPROXY_TOKEN_; other environment variables can't be used as upstream credentials"}
- }
- }
- return nil
-}
-
-type Registry struct {
- mu sync.RWMutex
- builtin map[string]Service
- dynamic map[string]Service
- file string
-}
-
-func New(file string, builtins map[string]Service) (*Registry, error) {
- r := &Registry{builtin: builtins, dynamic: map[string]Service{}, file: file}
- if file == "" {
- return r, nil
- }
- data, err := os.ReadFile(file)
- if errors.Is(err, os.ErrNotExist) {
- return r, nil
- }
- if err != nil {
- return nil, fmt.Errorf("reading %s: %w", file, err)
- }
- var stored map[string]Service
- if err := json.Unmarshal(data, &stored); err != nil {
- return nil, fmt.Errorf("parsing %s: %w", file, err)
- }
- for key, svc := range stored {
- if _, clash := builtins[key]; clash {
- return nil, fmt.Errorf("%s: %q clashes with a built-in service", file, key)
- }
- if err := Validate(key, svc); err != nil {
- return nil, fmt.Errorf("%s: service %q: %w", file, key, err)
- }
- r.dynamic[key] = svc
- }
- return r, nil
-}
-
-func (r *Registry) Get(key string) (Service, bool) {
- r.mu.RLock()
- defer r.mu.RUnlock()
- if svc, ok := r.builtin[key]; ok {
- return svc, true
- }
- svc, ok := r.dynamic[key]
- return svc, ok
-}
-
-func (r *Registry) Keys() []string {
- r.mu.RLock()
- defer r.mu.RUnlock()
- var builtin, dynamic []string
- for k := range r.builtin {
- builtin = append(builtin, k)
- }
- for k := range r.dynamic {
- dynamic = append(dynamic, k)
- }
- sort.Strings(builtin)
- sort.Strings(dynamic)
- return append(builtin, dynamic...)
-}
-
-func (r *Registry) Add(key string, svc Service) error {
- if err := Validate(key, svc); err != nil {
- return err
- }
- svc.Builtin = false
- r.mu.Lock()
- defer r.mu.Unlock()
- if _, ok := r.builtin[key]; ok {
- return ErrExists
- }
- if _, ok := r.dynamic[key]; ok {
- return ErrExists
- }
- r.dynamic[key] = svc
- if err := r.saveLocked(); err != nil {
- delete(r.dynamic, key)
- return err
- }
- return nil
-}
-
-func (r *Registry) Remove(key string) error {
- r.mu.Lock()
- defer r.mu.Unlock()
- if _, ok := r.builtin[key]; ok {
- return ErrBuiltin
- }
- svc, ok := r.dynamic[key]
- if !ok {
- return ErrNotFound
- }
- delete(r.dynamic, key)
- if err := r.saveLocked(); err != nil {
- r.dynamic[key] = svc
- return err
- }
- return nil
-}
-
-func (r *Registry) saveLocked() error {
- if r.file == "" {
- return nil
- }
- data, err := json.MarshalIndent(r.dynamic, "", " ")
- if err != nil {
- return err
- }
- if err := os.MkdirAll(filepath.Dir(r.file), 0o755); err != nil {
- return fmt.Errorf("creating %s: %w", filepath.Dir(r.file), err)
- }
- tmp, err := os.CreateTemp(filepath.Dir(r.file), ".services-*.json")
- if err != nil {
- return err
- }
- defer os.Remove(tmp.Name())
- if _, err := tmp.Write(append(data, '\n')); err != nil {
- tmp.Close()
- return err
- }
- if err := tmp.Close(); err != nil {
- return err
- }
- return os.Rename(tmp.Name(), r.file)
-}
diff --git a/internal/server/docs.go b/internal/server/docs.go
deleted file mode 100644
index 8b6f4ee..0000000
--- a/internal/server/docs.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package server
-
-import (
- _ "embed"
- "net/http"
- "strings"
-)
-
-//go:embed openapi.json
-var openAPISpec string
-
-const docsPage = `
-
-
-
-
- ByteProxy API
-
-
-
-
-
-
-`
-
-func (s *Server) handleOpenAPI(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Header().Set("Cache-Control", "public, max-age=300")
- w.Write([]byte(strings.Replace(openAPISpec, "__VERSION__", s.version, 1)))
-}
-
-func (s *Server) handleDocs(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; font-src https://fonts.gstatic.com https://cdn.jsdelivr.net data:; img-src 'self' data: https:; connect-src 'self'")
- w.Write([]byte(docsPage))
-}
diff --git a/internal/server/handlers.go b/internal/server/handlers.go
deleted file mode 100644
index 7eb435e..0000000
--- a/internal/server/handlers.go
+++ /dev/null
@@ -1,559 +0,0 @@
-package server
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "os"
- "regexp"
- "runtime"
- "strconv"
- "strings"
- "time"
-
- "github.com/NodeByteLTD/ByteProxy/internal/proxy"
- "github.com/NodeByteLTD/ByteProxy/internal/registry"
-)
-
-var (
- discordAPIPrefix = regexp.MustCompile(`^/api(/|$)`)
- discordVersion = regexp.MustCompile(`^/(v\d+)(/|$)`)
-)
-
-func (s *Server) appVersion() string {
- if s.settings.Environment == "prod" {
- return "v" + s.version
- }
- return "v" + s.version + "-" + s.settings.Environment
-}
-
-func (s *Server) uptime() float64 { return time.Since(s.started).Seconds() }
-
-func stripAPIKeyParam(rawQuery string) string {
- if rawQuery == "" {
- return ""
- }
- var kept []string
- for _, pair := range strings.Split(rawQuery, "&") {
- name, _, _ := strings.Cut(pair, "=")
- if decoded, err := url.QueryUnescape(name); err == nil && decoded == "api_key" {
- continue
- }
- if pair != "" {
- kept = append(kept, pair)
- }
- }
- return strings.Join(kept, "&")
-}
-
-func (s *Server) handleProxy(w http.ResponseWriter, r *http.Request) {
- service := r.PathValue("service")
- svc, ok := s.reg.Get(service)
- if !ok {
- writeJSON(w, http.StatusNotFound, map[string]any{
- "error": fmt.Sprintf("Service '%s' not configured", service),
- "availableServices": s.reg.Keys(),
- })
- return
- }
-
- path := strings.TrimPrefix(r.URL.EscapedPath(), "/proxy/"+url.PathEscape(service))
- base := strings.TrimRight(svc.BaseURL, "/")
-
- if service == "discord" {
- path = discordAPIPrefix.ReplaceAllString(path, "/")
- if m := discordVersion.FindStringSubmatch(path); m != nil {
- base += "/" + m[1]
- path = strings.TrimPrefix(path, "/"+m[1])
- }
- }
- if service == "github" && strings.HasPrefix(path, "/org/") {
- writeJSON(w, http.StatusBadRequest, map[string]any{
- "error": "Invalid GitHub API path. Did you mean '/orgs/:org' or '/orgs/:org/repos'? The GitHub API does not support '/org/'.",
- "hint": "Use '/proxy/github/orgs/ORG_NAME' or '/proxy/github/orgs/ORG_NAME/repos' instead.",
- })
- return
- }
-
- var body []byte
- if r.Method != http.MethodGet && r.Method != http.MethodHead {
- var err error
- body, err = io.ReadAll(http.MaxBytesReader(w, r.Body, s.settings.MaxBodyBytes))
- if err != nil {
- var tooLarge *http.MaxBytesError
- if errors.As(err, &tooLarge) {
- writeJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": fmt.Sprintf("Request body exceeds %d bytes", s.settings.MaxBodyBytes), "service": service})
- return
- }
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": "Failed to read request body", "service": service})
- return
- }
- }
-
- target := base + path
- if q := stripAPIKeyParam(r.URL.RawQuery); q != "" {
- target += "?" + q
- }
- limiterPath, _ := url.PathUnescape(path)
-
- start := time.Now()
- resp, err := s.fwd.Do(r.Context(), proxy.Request{
- ServiceKey: service,
- Service: svc,
- Method: r.Method,
- TargetURL: target,
- Path: limiterPath,
- Header: r.Header.Clone(),
- Body: body,
- ProxyKey: s.settings.ProxyAPIKey,
- })
- if err != nil {
- status := http.StatusInternalServerError
- var perr *proxy.Error
- if errors.As(err, &perr) {
- status = perr.Status
- }
- s.logger.Error("proxy request failed", "service", service, "method", r.Method, "path", limiterPath, "status", status, "error", err.Error())
- w.Header().Set("X-Proxy-Service", service)
- w.Header().Set("X-Proxy-Error", "true")
- writeJSON(w, status, map[string]any{
- "error": err.Error(),
- "service": service,
- "path": limiterPath,
- "troubleshooting": map[string]string{"hint": "Check /manage/diagnostics for configuration and network details"},
- })
- return
- }
- defer resp.Body.Close()
-
- h := w.Header()
- for k, vs := range resp.Header {
- if strings.HasPrefix(k, "Access-Control-") {
- continue
- }
- for _, v := range vs {
- h.Add(k, v)
- }
- }
- for _, name := range proxy.StrippedResponseHeaders {
- h.Del(name)
- }
- if !resp.Uncompressed && resp.ContentLength >= 0 {
- h.Set("Content-Length", strconv.FormatInt(resp.ContentLength, 10))
- }
- h.Set("X-Proxy-Service", service)
- h.Set("X-Proxy-Duration", fmt.Sprintf("%dms", time.Since(start).Milliseconds()))
- w.WriteHeader(resp.StatusCode)
- if r.Method != http.MethodHead {
- io.Copy(w, resp.Body)
- }
- s.logger.Info("proxied", "service", service, "method", r.Method, "path", limiterPath, "status", resp.StatusCode, "duration", time.Since(start))
-}
-
-func (s *Server) handleRoot(w http.ResponseWriter, _ *http.Request) {
- writeJSON(w, http.StatusOK, map[string]any{
- "message": "Welcome to ByteProxy, feel free to browse around!",
- "source": "https://github.com/NodeByteLTD/ByteProxy",
- "status": "/status",
- "health": "/health",
- "version": s.appVersion(),
- "checkUpdates": "/version/check",
- "documentation": "https://proxy.nodebyte.co.uk",
- })
-}
-
-func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
- keys := s.reg.Keys()
- writeJSON(w, http.StatusOK, map[string]any{
- "status": "healthy",
- "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
- "uptime": s.uptime(),
- "version": s.appVersion(),
- "services": map[string]any{"total": len(keys), "available": keys},
- "config": map[string]any{
- "port": s.settings.Port,
- "logging": map[string]any{"level": s.settings.LogLevel.String()},
- "cors": map[string]any{"enabled": s.settings.CORSEnabled, "origins": s.settings.CORSOrigins},
- },
- })
-}
-
-func (s *Server) serviceSummary(key string, svc registry.Service) map[string]any {
- return map[string]any{
- "key": key,
- "name": svc.Name,
- "baseUrl": svc.BaseURL,
- "builtin": svc.Builtin,
- "hasAuth": svc.Auth != nil,
- "authTokenConfigured": svc.Auth != nil && svc.Auth.TokenEnvVar != "" && os.Getenv(svc.Auth.TokenEnvVar) != "",
- "rateLimit": svc.RateLimit,
- }
-}
-
-func (s *Server) summaries() []map[string]any {
- var out []map[string]any
- for _, key := range s.reg.Keys() {
- if svc, ok := s.reg.Get(key); ok {
- out = append(out, s.serviceSummary(key, svc))
- }
- }
- return out
-}
-
-func (s *Server) handleStatus(w http.ResponseWriter, _ *http.Request) {
- var m runtime.MemStats
- runtime.ReadMemStats(&m)
- writeJSON(w, http.StatusOK, map[string]any{
- "application": map[string]any{
- "name": "ByteProxy",
- "version": s.version,
- "description": "Extensible web proxy for Discord, GitHub, and other APIs",
- },
- "runtime": map[string]any{
- "go": runtime.Version(),
- "platform": runtime.GOOS + "/" + runtime.GOARCH,
- "uptime": s.uptime(),
- "memory": map[string]any{"heapAlloc": m.HeapAlloc, "sys": m.Sys, "numGC": m.NumGC},
- "goroutines": runtime.NumGoroutine(),
- },
- "configuration": map[string]any{
- "port": s.settings.Port,
- "services": s.summaries(),
- "logging": map[string]any{"level": s.settings.LogLevel.String()},
- "cors": map[string]any{"enabled": s.settings.CORSEnabled, "origins": s.settings.CORSOrigins},
- },
- })
-}
-
-func (s *Server) handleAuthStatus(w http.ResponseWriter, r *http.Request) {
- redacted := *r.URL
- redacted.RawQuery = stripAPIKeyParam(r.URL.RawQuery)
- var segments []string
- for _, seg := range strings.Split(r.URL.Path, "/") {
- if seg != "" {
- segments = append(segments, seg)
- }
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "path": r.URL.Path,
- "authConfig": map[string]bool{
- "proxyAuthRequired": s.settings.RequireProxyAuth,
- "managementAuthRequired": s.settings.RequireManagementAuth,
- "proxyKeyConfigured": s.settings.ProxyAPIKey != "",
- "managementKeyConfigured": s.settings.ManagementAPIKey != "",
- },
- "requestInfo": map[string]any{
- "method": r.Method,
- "hasAuthHeader": r.Header.Get("Authorization") != "",
- "hasApiKeyHeader": r.Header.Get("X-Api-Key") != "",
- "hasQueryKey": r.URL.Query().Get("api_key") != "",
- "fullUrl": redacted.String(),
- "pathSegments": segments,
- },
- "help": "This endpoint helps diagnose authentication issues",
- })
-}
-
-func (s *Server) handleUp(w http.ResponseWriter, _ *http.Request) {
- status := s.pressure.status()
- status["status"] = "ok"
- writeJSON(w, http.StatusOK, status)
-}
-
-func (s *Server) handleVersion(w http.ResponseWriter, _ *http.Request) {
- full := s.appVersion()
- semver, env, _ := strings.Cut(full, "-")
- if env == "" {
- env = "prod"
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "version": full,
- "semver": semver,
- "environment": env,
- "builtWith": map[string]string{"go": runtime.Version()},
- })
-}
-
-type UpdateInfo struct {
- CurrentVersion string `json:"currentVersion"`
- LatestVersion *string `json:"latestVersion"`
- LatestReleaseURL *string `json:"latestReleaseUrl"`
- IsLatest bool `json:"isLatest"`
- IsPrerelease bool `json:"isPrerelease"`
- ReleaseDate *string `json:"releaseDate"`
- UpdateAvailable bool `json:"updateAvailable"`
- Error string `json:"error,omitempty"`
-}
-
-func compareVersions(a, b string) int {
- pa, pb := strings.Split(strings.TrimPrefix(a, "v"), "."), strings.Split(strings.TrimPrefix(b, "v"), ".")
- for i := 0; i < max(len(pa), len(pb)); i++ {
- var x, y int
- if i < len(pa) {
- x, _ = strconv.Atoi(pa[i])
- }
- if i < len(pb) {
- y, _ = strconv.Atoi(pb[i])
- }
- if x != y {
- return x - y
- }
- }
- return 0
-}
-
-func (s *Server) CheckForUpdates(ctx context.Context) UpdateInfo {
- info := UpdateInfo{CurrentVersion: s.appVersion(), IsLatest: true}
- ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
- defer cancel()
- req, _ := http.NewRequestWithContext(ctx, http.MethodGet, s.UpdateURL, nil)
- req.Header.Set("Accept", "application/vnd.github+json")
- req.Header.Set("User-Agent", "ByteProxy-UpdateChecker/"+s.version)
- resp, err := s.fwd.Client.Do(req)
- if err != nil {
- info.Error = err.Error()
- return info
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- info.Error = fmt.Sprintf("GitHub responded with %d", resp.StatusCode)
- return info
- }
- var releases []struct {
- TagName string `json:"tag_name"`
- HTMLURL string `json:"html_url"`
- PublishedAt string `json:"published_at"`
- Prerelease bool `json:"prerelease"`
- }
- if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&releases); err != nil || len(releases) == 0 {
- return info
- }
- latest := releases[0]
- for _, rel := range releases {
- if !rel.Prerelease {
- latest = rel
- break
- }
- }
- info.LatestVersion, info.LatestReleaseURL, info.ReleaseDate = &latest.TagName, &latest.HTMLURL, &latest.PublishedAt
- info.IsPrerelease = latest.Prerelease
- info.UpdateAvailable = compareVersions(s.version, latest.TagName) < 0
- info.IsLatest = !info.UpdateAvailable
- return info
-}
-
-func (s *Server) handleVersionCheck(w http.ResponseWriter, r *http.Request) {
- info := s.CheckForUpdates(r.Context())
- writeJSON(w, http.StatusOK, struct {
- UpdateInfo
- CheckTime string `json:"checkTime"`
- }{info, time.Now().UTC().Format(time.RFC3339)})
-}
-
-func (s *Server) handleProxyServices(w http.ResponseWriter, _ *http.Request) {
- list := s.summaries()
- writeJSON(w, http.StatusOK, map[string]any{"services": list, "count": len(list)})
-}
-
-func (s *Server) handleProxyRateLimit(w http.ResponseWriter, r *http.Request) {
- key := r.PathValue("service")
- svc, ok := s.reg.Get(key)
- if !ok || svc.RateLimit == nil {
- writeJSON(w, http.StatusNotFound, map[string]any{"error": "Service not found or rate limiting not configured", "service": key})
- return
- }
- remaining, resetAt := s.fwd.Window.Status(key, svc.RateLimit.MaxRequests)
- resetIn, resetMs := 0, int64(0)
- if !resetAt.IsZero() {
- resetMs = resetAt.UnixMilli()
- resetIn = int(time.Until(resetAt).Seconds() + 0.999)
- }
- writeJSON(w, http.StatusOK, map[string]any{"service": key, "remaining": remaining, "resetTime": resetMs, "resetIn": resetIn})
-}
-
-func (s *Server) handleAuthDebug(w http.ResponseWriter, r *http.Request) {
- provided := func(b bool) string {
- if b {
- return "provided"
- }
- return "not provided"
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "status": "success",
- "message": "Authentication successful",
- "timestamp": time.Now().UTC().Format(time.RFC3339),
- "authMethod": map[string]string{
- "bearer": provided(strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ")),
- "xApiKey": provided(r.Header.Get("X-Api-Key") != ""),
- "queryParam": provided(r.URL.Query().Get("api_key") != ""),
- },
- "help": "If you see this message, your authentication is working correctly.",
- })
-}
-
-func (s *Server) handleAuthTest(w http.ResponseWriter, _ *http.Request) {
- writeJSON(w, http.StatusOK, map[string]any{"status": "success", "message": "Authentication successful", "timestamp": time.Now().UTC().Format(time.RFC3339)})
-}
-
-func (s *Server) keyDebug() map[string]any {
- return map[string]any{
- "proxyAuthRequired": s.settings.RequireProxyAuth,
- "managementAuthRequired": s.settings.RequireManagementAuth,
- "proxyKeyConfigured": s.settings.ProxyAPIKey != "",
- "managementKeyConfigured": s.settings.ManagementAPIKey != "",
- "keyTypes": map[string]string{
- "proxy": "Required for /proxy/* routes (PROXY_API_KEY)",
- "management": "Required for /manage/* routes (MANAGEMENT_API_KEY)",
- },
- }
-}
-
-func (s *Server) handleProxyKeyDebug(w http.ResponseWriter, _ *http.Request) {
- writeJSON(w, http.StatusOK, map[string]any{"message": "API Key Debug Information", "keyInfo": s.keyDebug()})
-}
-
-func (s *Server) handleManageKeyDebug(w http.ResponseWriter, _ *http.Request) {
- writeJSON(w, http.StatusOK, map[string]any{"message": "API Key Debug Information", "keyInfo": s.keyDebug()})
-}
-
-func (s *Server) handleListServices(w http.ResponseWriter, _ *http.Request) {
- list := s.summaries()
- writeJSON(w, http.StatusOK, map[string]any{"services": list, "count": len(list)})
-}
-
-func (s *Server) handleAddService(w http.ResponseWriter, r *http.Request) {
- var payload struct {
- Key string `json:"key"`
- Config *registry.Service `json:"config"`
- }
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&payload); err != nil || payload.Key == "" || payload.Config == nil {
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": "Body must be JSON: {\"key\": string, \"config\": {...}}"})
- return
- }
- err := s.reg.Add(payload.Key, *payload.Config)
- var verr *registry.ValidationError
- switch {
- case errors.As(err, &verr):
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": verr.Msg})
- case errors.Is(err, registry.ErrExists):
- writeJSON(w, http.StatusConflict, map[string]any{"error": fmt.Sprintf("Service '%s' already exists", payload.Key)})
- case err != nil:
- s.logger.Error("failed to add service", "key", payload.Key, "error", err)
- writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "Failed to save service"})
- default:
- s.logger.Info("service added", "key", payload.Key, "baseUrl", payload.Config.BaseURL)
- writeJSON(w, http.StatusOK, map[string]any{"message": fmt.Sprintf("Service '%s' added successfully", payload.Key), "key": payload.Key, "config": payload.Config})
- }
-}
-
-func (s *Server) handleGetService(w http.ResponseWriter, r *http.Request) {
- key := r.PathValue("key")
- svc, ok := s.reg.Get(key)
- if !ok {
- writeJSON(w, http.StatusNotFound, map[string]any{"error": fmt.Sprintf("Service '%s' not found", key)})
- return
- }
- cfg := map[string]any{"name": svc.Name, "baseUrl": svc.BaseURL, "headers": svc.Headers, "rateLimit": svc.RateLimit, "builtin": svc.Builtin}
- if svc.Auth != nil {
- cfg["auth"] = map[string]any{
- "type": svc.Auth.Type,
- "tokenEnvVar": svc.Auth.TokenEnvVar,
- "headerName": svc.Auth.HeaderName,
- "tokenConfigured": svc.Auth.TokenEnvVar != "" && os.Getenv(svc.Auth.TokenEnvVar) != "",
- }
- }
- writeJSON(w, http.StatusOK, map[string]any{"key": key, "config": cfg})
-}
-
-func (s *Server) handleRemoveService(w http.ResponseWriter, r *http.Request) {
- key := r.PathValue("key")
- switch err := s.reg.Remove(key); {
- case errors.Is(err, registry.ErrBuiltin):
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})
- case errors.Is(err, registry.ErrNotFound):
- writeJSON(w, http.StatusNotFound, map[string]any{"error": fmt.Sprintf("Service '%s' not found", key)})
- case err != nil:
- s.logger.Error("failed to remove service", "key", key, "error", err)
- writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "Failed to save services"})
- default:
- s.fwd.Window.Remove(key)
- s.logger.Info("service removed", "key", key)
- writeJSON(w, http.StatusOK, map[string]any{"message": fmt.Sprintf("Service '%s' removed", key)})
- }
-}
-
-func (s *Server) handleTestService(w http.ResponseWriter, r *http.Request) {
- key := r.PathValue("key")
- svc, ok := s.reg.Get(key)
- if !ok {
- writeJSON(w, http.StatusNotFound, map[string]any{"error": fmt.Sprintf("Service '%s' not found", key)})
- return
- }
- ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
- defer cancel()
- req, _ := http.NewRequestWithContext(ctx, http.MethodHead, svc.BaseURL, nil)
- for k, v := range svc.Headers {
- req.Header.Set(k, v)
- }
- start := time.Now()
- resp, err := s.fwd.Client.Do(req)
- if err != nil {
- writeJSON(w, http.StatusOK, map[string]any{"service": key, "status": "unreachable", "error": err.Error(), "baseUrl": svc.BaseURL})
- return
- }
- resp.Body.Close()
- writeJSON(w, http.StatusOK, map[string]any{
- "service": key,
- "status": "reachable",
- "responseStatus": resp.StatusCode,
- "duration": fmt.Sprintf("%dms", time.Since(start).Milliseconds()),
- "baseUrl": svc.BaseURL,
- })
-}
-
-func (s *Server) handleDiagnostics(w http.ResponseWriter, _ *http.Request) {
- auth := map[string]any{}
- for _, key := range s.reg.Keys() {
- svc, _ := s.reg.Get(key)
- if svc.Auth == nil {
- continue
- }
- auth[key] = map[string]any{
- "authType": svc.Auth.Type,
- "envVar": svc.Auth.TokenEnvVar,
- "tokenConfigured": svc.Auth.TokenEnvVar != "" && os.Getenv(svc.Auth.TokenEnvVar) != "",
- }
- }
- zone, _ := time.Now().Zone()
- writeJSON(w, http.StatusOK, map[string]any{
- "system": map[string]any{
- "platform": runtime.GOOS + "/" + runtime.GOARCH,
- "go": runtime.Version(),
- "runtime": "Go",
- "uptime": s.uptime(),
- },
- "network": map[string]any{
- "strictTLS": s.settings.StrictTLS,
- "timeoutMs": s.settings.Timeout.Milliseconds(),
- },
- "environment": map[string]any{
- "timeZone": zone,
- "currentTime": time.Now().UTC().Format(time.RFC3339),
- },
- "authentication": auth,
- "upstreamCredentials": "Callers send their own upstream credentials in X-Upstream-Authorization (or Authorization when the proxy key is sent via X-Api-Key). Dynamic services may use BYTEPROXY_TOKEN_* environment variables.",
- })
-}
-
-func (s *Server) handleNotFound(w http.ResponseWriter, r *http.Request) {
- s.logger.Warn("unknown endpoint", "path", r.URL.Path, "method", r.Method)
- writeJSON(w, http.StatusNotFound, map[string]any{
- "error": "Endpoint not found",
- "message": fmt.Sprintf("The endpoint '%s' does not exist", r.URL.Path),
- "quickStart": map[string]string{"proxy": "/proxy/:service/*", "health": "/health", "management": "/manage/services"},
- })
-}
diff --git a/internal/server/openapi.json b/internal/server/openapi.json
deleted file mode 100644
index bf79c42..0000000
--- a/internal/server/openapi.json
+++ /dev/null
@@ -1,223 +0,0 @@
-{
- "openapi": "3.1.0",
- "info": {
- "title": "ByteProxy",
- "version": "__VERSION__",
- "description": "Extensible proxy for Discord, GitHub and other APIs with per-credential rate limiting.\n\n**Proxy authentication.** When `REQUIRE_AUTH_FOR_PROXY=true`, `/proxy/*` requires `PROXY_API_KEY` via `X-Api-Key`, `Authorization: Bearer`, or `?api_key=`. When `REQUIRE_AUTH_FOR_MANAGEMENT=true`, `/manage/*` requires `MANAGEMENT_API_KEY` the same way.\n\n**Upstream credentials.** ByteProxy holds no shared bot token. Callers authenticate to the upstream API themselves: send `X-Upstream-Authorization: Bot ` (or `Bearer `), or send your normal `Authorization` header when the proxy key travels in `X-Api-Key`. Rate limits are tracked per upstream credential. Dynamic services may instead use a server-side `BYTEPROXY_TOKEN_*` environment variable.",
- "license": { "name": "AGPL-3.0-only", "url": "https://www.gnu.org/licenses/agpl-3.0.html" }
- },
- "externalDocs": { "description": "Source", "url": "https://github.com/NodeByteLTD/ByteProxy" },
- "tags": [
- { "name": "Base" },
- { "name": "Health" },
- { "name": "Proxy" },
- { "name": "Management" },
- { "name": "Debug" }
- ],
- "components": {
- "securitySchemes": {
- "apiKeyHeader": { "type": "apiKey", "in": "header", "name": "X-Api-Key" },
- "bearerAuth": { "type": "http", "scheme": "bearer", "bearerFormat": "API key" },
- "apiKeyQuery": { "type": "apiKey", "in": "query", "name": "api_key" }
- },
- "parameters": {
- "service": { "name": "service", "in": "path", "required": true, "schema": { "type": "string" }, "example": "discord" },
- "key": { "name": "key", "in": "path", "required": true, "schema": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]{0,31}$" } },
- "upstreamAuthorization": {
- "name": "X-Upstream-Authorization",
- "in": "header",
- "required": false,
- "description": "Credential forwarded to the upstream as Authorization (or the service's api-key header). Takes precedence over the caller's own Authorization header.",
- "schema": { "type": "string" },
- "example": "Bot MTA..."
- }
- },
- "schemas": {
- "Error": {
- "type": "object",
- "properties": { "error": { "type": "string" }, "service": { "type": "string" }, "path": { "type": "string" } },
- "required": ["error"]
- },
- "RateLimit": {
- "type": "object",
- "properties": { "maxRequests": { "type": "integer", "minimum": 1 }, "windowMs": { "type": "integer", "minimum": 1 } },
- "required": ["maxRequests", "windowMs"]
- },
- "Auth": {
- "type": "object",
- "properties": {
- "type": { "type": "string", "enum": ["bearer", "basic", "api-key", "bot"] },
- "tokenEnvVar": { "type": "string", "pattern": "^BYTEPROXY_TOKEN_[A-Z0-9_]+$", "description": "Optional server-side credential. Only BYTEPROXY_TOKEN_* variables are allowed." },
- "headerName": { "type": "string", "description": "Required for api-key auth." }
- },
- "required": ["type"]
- },
- "ServiceConfig": {
- "type": "object",
- "properties": {
- "name": { "type": "string", "maxLength": 100 },
- "baseUrl": { "type": "string", "format": "uri", "description": "Absolute http(s) URL." },
- "headers": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Static headers. Authorization, Cookie, Host and X-Api-Key can't be set here." },
- "rateLimit": { "$ref": "#/components/schemas/RateLimit" },
- "auth": { "$ref": "#/components/schemas/Auth" }
- },
- "required": ["name", "baseUrl"]
- },
- "ServiceSummary": {
- "type": "object",
- "properties": {
- "key": { "type": "string" },
- "name": { "type": "string" },
- "baseUrl": { "type": "string" },
- "builtin": { "type": "boolean" },
- "hasAuth": { "type": "boolean" },
- "authTokenConfigured": { "type": "boolean" },
- "rateLimit": { "oneOf": [{ "$ref": "#/components/schemas/RateLimit" }, { "type": "null" }] }
- }
- },
- "ServiceList": {
- "type": "object",
- "properties": { "services": { "type": "array", "items": { "$ref": "#/components/schemas/ServiceSummary" } }, "count": { "type": "integer" } }
- },
- "UpdateInfo": {
- "type": "object",
- "properties": {
- "currentVersion": { "type": "string" },
- "latestVersion": { "type": ["string", "null"] },
- "latestReleaseUrl": { "type": ["string", "null"] },
- "isLatest": { "type": "boolean" },
- "isPrerelease": { "type": "boolean" },
- "releaseDate": { "type": ["string", "null"] },
- "updateAvailable": { "type": "boolean" },
- "checkTime": { "type": "string", "format": "date-time" }
- }
- },
- "KeyDebug": {
- "type": "object",
- "properties": {
- "message": { "type": "string" },
- "keyInfo": {
- "type": "object",
- "properties": {
- "proxyAuthRequired": { "type": "boolean" },
- "managementAuthRequired": { "type": "boolean" },
- "proxyKeyConfigured": { "type": "boolean" },
- "managementKeyConfigured": { "type": "boolean" }
- }
- }
- }
- }
- },
- "responses": {
- "Unauthorized": { "description": "Missing or invalid API key", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
- "NotFound": { "description": "Not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
- "Json": { "description": "OK", "content": { "application/json": { "schema": { "type": "object" } } } }
- }
- },
- "paths": {
- "/": { "get": { "tags": ["Base"], "summary": "API root", "operationId": "root", "responses": { "200": { "$ref": "#/components/responses/Json" } } } },
- "/health": { "get": { "tags": ["Health"], "summary": "Health check", "operationId": "health", "responses": { "200": { "$ref": "#/components/responses/Json" }, "503": { "description": "Under memory pressure" } } } },
- "/status": { "get": { "tags": ["Health"], "summary": "Runtime, configuration and service status", "operationId": "status", "responses": { "200": { "$ref": "#/components/responses/Json" } } } },
- "/auth-status": { "get": { "tags": ["Debug"], "summary": "Show how a request would authenticate", "operationId": "authStatus", "responses": { "200": { "$ref": "#/components/responses/Json" } } } },
- "/up": { "get": { "tags": ["Health"], "summary": "Memory pressure status", "operationId": "up", "responses": { "200": { "$ref": "#/components/responses/Json" } } } },
- "/version": { "get": { "tags": ["Base"], "summary": "Running version", "operationId": "version", "responses": { "200": { "$ref": "#/components/responses/Json" } } } },
- "/version/check": {
- "get": {
- "tags": ["Base"],
- "summary": "Check GitHub for a newer release",
- "operationId": "versionCheck",
- "responses": { "200": { "description": "Update information", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UpdateInfo" } } } } }
- }
- },
- "/openapi.json": { "get": { "tags": ["Base"], "summary": "This OpenAPI document", "operationId": "openapi", "responses": { "200": { "$ref": "#/components/responses/Json" } } } },
- "/docs": { "get": { "tags": ["Base"], "summary": "Interactive API reference", "operationId": "docs", "responses": { "200": { "description": "HTML page", "content": { "text/html": {} } } } } },
- "/proxy/services": {
- "get": {
- "tags": ["Proxy"],
- "summary": "List proxyable services",
- "operationId": "proxyListServices",
- "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }],
- "responses": { "200": { "description": "Services", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ServiceList" } } } }, "401": { "$ref": "#/components/responses/Unauthorized" } }
- }
- },
- "/proxy/services/{service}/rate-limit": {
- "get": {
- "tags": ["Proxy"],
- "summary": "Window rate-limit status for a custom service",
- "operationId": "proxyRateLimit",
- "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }],
- "parameters": [{ "$ref": "#/components/parameters/service" }],
- "responses": {
- "200": { "description": "Status", "content": { "application/json": { "schema": { "type": "object", "properties": { "service": { "type": "string" }, "remaining": { "type": "integer" }, "resetTime": { "type": "integer", "description": "Unix ms, 0 when idle" }, "resetIn": { "type": "integer", "description": "Seconds" } } } } } },
- "401": { "$ref": "#/components/responses/Unauthorized" },
- "404": { "$ref": "#/components/responses/NotFound" }
- }
- }
- },
- "/proxy/auth-debug": { "get": { "tags": ["Debug"], "summary": "Confirm proxy authentication works", "operationId": "proxyAuthDebug", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "$ref": "#/components/responses/Json" }, "401": { "$ref": "#/components/responses/Unauthorized" } } } },
- "/proxy/auth-test": { "get": { "tags": ["Debug"], "summary": "Minimal proxy authentication test", "operationId": "proxyAuthTest", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "$ref": "#/components/responses/Json" }, "401": { "$ref": "#/components/responses/Unauthorized" } } } },
- "/proxy/key-debug": { "get": { "tags": ["Debug"], "summary": "Which keys are configured (no key material)", "operationId": "proxyKeyDebug", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "description": "Key status", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/KeyDebug" } } } }, "401": { "$ref": "#/components/responses/Unauthorized" } } } },
- "/proxy/{service}": {
- "summary": "Proxy to a service root",
- "parameters": [{ "$ref": "#/components/parameters/service" }, { "$ref": "#/components/parameters/upstreamAuthorization" }],
- "get": { "tags": ["Proxy"], "operationId": "proxyRootGet", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "default": { "description": "Upstream response, passed through" } } }
- },
- "/proxy/{service}/{path}": {
- "summary": "Proxy any request to a service",
- "description": "Forwards the method, path, query, headers and body to the service's base URL and streams the response back. For `discord`, a leading `/api` is stripped and `/vN` selects the API version (`/proxy/discord/v10/users/@me`). `api_key` is never forwarded. Discord 429s are retried up to 3 times (waits over 30s are returned to the caller); GitHub secondary limits likewise. Responses carry `X-Proxy-Service` and `X-Proxy-Duration`.",
- "parameters": [
- { "$ref": "#/components/parameters/service" },
- { "name": "path", "in": "path", "required": true, "description": "Remaining path, may contain slashes", "schema": { "type": "string" }, "example": "v10/users/@me" },
- { "$ref": "#/components/parameters/upstreamAuthorization" }
- ],
- "get": { "tags": ["Proxy"], "operationId": "proxyGet", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "default": { "description": "Upstream response" }, "401": { "$ref": "#/components/responses/Unauthorized" }, "404": { "$ref": "#/components/responses/NotFound" }, "429": { "description": "Custom service window limit exceeded" }, "502": { "description": "Upstream unreachable" }, "504": { "description": "Upstream timed out" } } },
- "post": { "tags": ["Proxy"], "operationId": "proxyPost", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "requestBody": { "description": "Forwarded byte for byte (JSON, multipart, anything)", "content": { "*/*": {} } }, "responses": { "default": { "description": "Upstream response" }, "413": { "description": "Body larger than MAX_BODY_MB" } } },
- "put": { "tags": ["Proxy"], "operationId": "proxyPut", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "requestBody": { "content": { "*/*": {} } }, "responses": { "default": { "description": "Upstream response" } } },
- "patch": { "tags": ["Proxy"], "operationId": "proxyPatch", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "requestBody": { "content": { "*/*": {} } }, "responses": { "default": { "description": "Upstream response" } } },
- "delete": { "tags": ["Proxy"], "operationId": "proxyDelete", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "default": { "description": "Upstream response" } } },
- "head": { "tags": ["Proxy"], "operationId": "proxyHead", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "default": { "description": "Upstream response headers" } } }
- },
- "/manage/services": {
- "get": {
- "tags": ["Management"],
- "summary": "List all services",
- "operationId": "manageListServices",
- "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }],
- "responses": { "200": { "description": "Services", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ServiceList" } } } }, "401": { "$ref": "#/components/responses/Unauthorized" } }
- },
- "post": {
- "tags": ["Management"],
- "summary": "Register a service",
- "description": "Adds a service and saves it to SERVICES_FILE so it survives restarts.",
- "operationId": "manageAddService",
- "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }],
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": { "type": "object", "properties": { "key": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]{0,31}$" }, "config": { "$ref": "#/components/schemas/ServiceConfig" } }, "required": ["key", "config"] },
- "example": { "key": "status", "config": { "name": "Status API", "baseUrl": "https://status.example.com/api/", "rateLimit": { "maxRequests": 60, "windowMs": 60000 } } }
- }
- }
- },
- "responses": {
- "200": { "$ref": "#/components/responses/Json" },
- "400": { "description": "Invalid configuration", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
- "401": { "$ref": "#/components/responses/Unauthorized" },
- "409": { "description": "Key already exists", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
- }
- }
- },
- "/manage/services/{key}": {
- "parameters": [{ "$ref": "#/components/parameters/key" }],
- "get": { "tags": ["Management"], "summary": "Get a service", "operationId": "manageGetService", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "$ref": "#/components/responses/Json" }, "401": { "$ref": "#/components/responses/Unauthorized" }, "404": { "$ref": "#/components/responses/NotFound" } } },
- "delete": { "tags": ["Management"], "summary": "Remove a dynamic service", "operationId": "manageRemoveService", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "$ref": "#/components/responses/Json" }, "400": { "description": "Built-in services can't be removed" }, "401": { "$ref": "#/components/responses/Unauthorized" }, "404": { "$ref": "#/components/responses/NotFound" } } }
- },
- "/manage/services/{key}/test": {
- "parameters": [{ "$ref": "#/components/parameters/key" }],
- "post": { "tags": ["Management"], "summary": "Check a service's base URL is reachable", "operationId": "manageTestService", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "$ref": "#/components/responses/Json" }, "401": { "$ref": "#/components/responses/Unauthorized" }, "404": { "$ref": "#/components/responses/NotFound" } } }
- },
- "/manage/diagnostics": { "get": { "tags": ["Management"], "summary": "System and configuration diagnostics", "operationId": "manageDiagnostics", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "$ref": "#/components/responses/Json" }, "401": { "$ref": "#/components/responses/Unauthorized" } } } },
- "/manage/key-debug": { "get": { "tags": ["Debug"], "summary": "Which keys are configured (no key material)", "operationId": "manageKeyDebug", "security": [{ "apiKeyHeader": [] }, { "bearerAuth": [] }, { "apiKeyQuery": [] }], "responses": { "200": { "description": "Key status", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/KeyDebug" } } } }, "401": { "$ref": "#/components/responses/Unauthorized" } } } }
- }
-}
diff --git a/internal/server/server.go b/internal/server/server.go
deleted file mode 100644
index 79abebd..0000000
--- a/internal/server/server.go
+++ /dev/null
@@ -1,265 +0,0 @@
-package server
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "net/http"
- "runtime"
- "slices"
- "strings"
- "sync"
- "time"
-
- "github.com/NodeByteLTD/ByteProxy/internal/config"
- "github.com/NodeByteLTD/ByteProxy/internal/proxy"
- "github.com/NodeByteLTD/ByteProxy/internal/registry"
-)
-
-const exposedHeaders = "X-Proxy-Service, X-Proxy-Duration, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-RateLimit-Reset-After, X-RateLimit-Bucket, X-RateLimit-Resource, Retry-After"
-
-type Server struct {
- settings config.Settings
- reg *registry.Registry
- fwd *proxy.Forwarder
- logger *slog.Logger
- version string
- started time.Time
- mux *http.ServeMux
- pressure *pressure
- UpdateURL string
-}
-
-func New(settings config.Settings, reg *registry.Registry, version string, logger *slog.Logger) *Server {
- s := &Server{
- settings: settings,
- reg: reg,
- fwd: proxy.NewForwarder(settings.Timeout, settings.StrictTLS, settings.DiscordGlobalRPS, logger),
- logger: logger,
- version: version,
- started: time.Now(),
- mux: http.NewServeMux(),
- pressure: &pressure{maxHeap: settings.MaxHeapBytes, maxSys: settings.MaxSysBytes},
- UpdateURL: fmt.Sprintf("https://api.github.com/repos/%s/releases", settings.UpdateRepo),
- }
- s.routes()
- return s
-}
-
-func (s *Server) Start(ctx context.Context) {
- s.fwd.StartPruning(ctx)
- s.pressure.start(ctx)
-}
-
-type route struct {
- pattern string
- handler http.HandlerFunc
-}
-
-func (s *Server) routeTable() []route {
- return []route{
- {"GET /{$}", s.handleRoot},
- {"GET /health", s.handleHealth},
- {"GET /status", s.handleStatus},
- {"GET /auth-status", s.handleAuthStatus},
- {"GET /up", s.handleUp},
- {"GET /version", s.handleVersion},
- {"GET /version/{$}", s.handleVersion},
- {"GET /version/check", s.handleVersionCheck},
- {"GET /openapi.json", s.handleOpenAPI},
- {"GET /docs", s.handleDocs},
-
- {"GET /proxy/services", s.handleProxyServices},
- {"GET /proxy/services/{service}/rate-limit", s.handleProxyRateLimit},
- {"GET /proxy/auth-debug", s.handleAuthDebug},
- {"GET /proxy/auth-test", s.handleAuthTest},
- {"GET /proxy/key-debug", s.handleProxyKeyDebug},
- {"/proxy/{service}", s.handleProxy},
- {"/proxy/{service}/{path...}", s.handleProxy},
-
- {"GET /manage/services", s.handleListServices},
- {"POST /manage/services", s.handleAddService},
- {"GET /manage/services/{key}", s.handleGetService},
- {"DELETE /manage/services/{key}", s.handleRemoveService},
- {"POST /manage/services/{key}/test", s.handleTestService},
- {"GET /manage/diagnostics", s.handleDiagnostics},
- {"GET /manage/key-debug", s.handleManageKeyDebug},
-
- {"/", s.handleNotFound},
- }
-}
-
-func (s *Server) routes() {
- for _, r := range s.routeTable() {
- s.mux.HandleFunc(r.pattern, r.handler)
- }
-}
-
-type statusRecorder struct {
- http.ResponseWriter
- status int
-}
-
-func (r *statusRecorder) WriteHeader(code int) {
- r.status = code
- r.ResponseWriter.WriteHeader(code)
-}
-
-func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
-
-func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
- start := time.Now()
- defer func() {
- if p := recover(); p != nil {
- s.logger.Error("panic serving request", "path", r.URL.Path, "panic", p)
- writeJSON(rec, http.StatusInternalServerError, map[string]any{"error": "Internal server error"})
- }
- s.logger.Debug("request", "method", r.Method, "path", r.URL.Path, "status", rec.status, "duration", time.Since(start))
- }()
-
- s.applyCORS(rec, r)
- if r.Method == http.MethodOptions {
- if s.settings.CORSEnabled {
- rec.Header().Set("Access-Control-Max-Age", "86400")
- }
- rec.WriteHeader(http.StatusNoContent)
- return
- }
- if r.URL.Path != "/up" {
- if kind, value, bad := s.pressure.check(); bad {
- writeJSON(rec, http.StatusServiceUnavailable, map[string]any{
- "error": "Server under pressure", "type": kind, "value": value, "message": "Service Unavailable",
- })
- return
- }
- }
- if !s.checkAuth(rec, r) {
- return
- }
- s.mux.ServeHTTP(rec, r)
-}
-
-func (s *Server) applyCORS(w http.ResponseWriter, r *http.Request) {
- if !s.settings.CORSEnabled {
- return
- }
- h := w.Header()
- origin := r.Header.Get("Origin")
- switch {
- case slices.Contains(s.settings.CORSOrigins, "*"):
- h.Set("Access-Control-Allow-Origin", "*")
- case origin != "" && slices.Contains(s.settings.CORSOrigins, origin):
- h.Set("Access-Control-Allow-Origin", origin)
- h.Set("Access-Control-Allow-Credentials", "true")
- h.Add("Vary", "Origin")
- default:
- return
- }
- h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
- h.Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-Api-Key, X-Upstream-Authorization, X-Audit-Log-Reason")
- h.Set("Access-Control-Expose-Headers", exposedHeaders)
-}
-
-func (s *Server) keyFor(path string) (kind, key string, required bool) {
- switch {
- case strings.HasPrefix(path, "/proxy/"):
- return "proxy", s.settings.ProxyAPIKey, s.settings.RequireProxyAuth
- case strings.HasPrefix(path, "/manage/"):
- return "management", s.settings.ManagementAPIKey, s.settings.RequireManagementAuth
- }
- return "", "", false
-}
-
-func providedKeyMatches(r *http.Request, key string) bool {
- return proxy.IsProxyBearer(r.Header.Get("Authorization"), key) ||
- proxy.KeyEquals(strings.TrimSpace(r.Header.Get("X-Api-Key")), key) ||
- proxy.KeyEquals(strings.TrimSpace(r.URL.Query().Get("api_key")), key)
-}
-
-func (s *Server) checkAuth(w http.ResponseWriter, r *http.Request) bool {
- kind, key, required := s.keyFor(r.URL.Path)
- if !required || providedKeyMatches(r, key) {
- return true
- }
- envVar := "PROXY_API_KEY"
- if kind == "management" {
- envVar = "MANAGEMENT_API_KEY"
- }
- noAuth := r.Header.Get("Authorization") == "" && r.Header.Get("X-Api-Key") == "" && r.URL.Query().Get("api_key") == ""
- message := fmt.Sprintf("Authentication failed. Invalid API key for %s routes.", kind)
- if noAuth {
- message = fmt.Sprintf("No authentication provided. API key required for %s routes.", kind)
- }
- s.logger.Warn("unauthorized request", "kind", kind, "path", r.URL.Path, "method", r.Method)
- writeJSON(w, http.StatusUnauthorized, map[string]any{
- "error": "Unauthorized",
- "message": message,
- "howToAuthenticate": []string{
- `Add header: "X-Api-Key: YOUR_API_KEY"`,
- `Add header: "Authorization: Bearer YOUR_API_KEY" (then send upstream credentials in X-Upstream-Authorization)`,
- `Add query param: "?api_key=YOUR_API_KEY"`,
- },
- "keyHelp": map[string]string{"requiredKeyType": kind, "envVar": envVar},
- })
- return false
-}
-
-func writeJSON(w http.ResponseWriter, status int, v any) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- json.NewEncoder(w).Encode(v)
-}
-
-type pressure struct {
- mu sync.RWMutex
- maxHeap uint64
- maxSys uint64
- heap uint64
- sys uint64
- goroutines int
-}
-
-func (p *pressure) sample() {
- var m runtime.MemStats
- runtime.ReadMemStats(&m)
- p.mu.Lock()
- p.heap, p.sys, p.goroutines = m.HeapAlloc, m.Sys, runtime.NumGoroutine()
- p.mu.Unlock()
-}
-
-func (p *pressure) start(ctx context.Context) {
- p.sample()
- go func() {
- t := time.NewTicker(time.Second)
- defer t.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-t.C:
- p.sample()
- }
- }
- }()
-}
-
-func (p *pressure) check() (string, uint64, bool) {
- p.mu.RLock()
- defer p.mu.RUnlock()
- switch {
- case p.maxHeap > 0 && p.heap > p.maxHeap:
- return "heapUsedBytes", p.heap, true
- case p.maxSys > 0 && p.sys > p.maxSys:
- return "rssBytes", p.sys, true
- }
- return "", 0, false
-}
-
-func (p *pressure) status() map[string]any {
- p.mu.RLock()
- defer p.mu.RUnlock()
- healthy := !(p.maxHeap > 0 && p.heap > p.maxHeap) && !(p.maxSys > 0 && p.sys > p.maxSys)
- return map[string]any{"heapUsed": p.heap, "rssBytes": p.sys, "goroutines": p.goroutines, "healthy": healthy}
-}
diff --git a/internal/server/server_test.go b/internal/server/server_test.go
deleted file mode 100644
index fafb216..0000000
--- a/internal/server/server_test.go
+++ /dev/null
@@ -1,603 +0,0 @@
-package server
-
-import (
- "bytes"
- "compress/gzip"
- "encoding/json"
- "io"
- "log/slog"
- "mime/multipart"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/NodeByteLTD/ByteProxy/internal/config"
- "github.com/NodeByteLTD/ByteProxy/internal/registry"
-)
-
-const proxyKey = "test-proxy-key-123"
-const manageKey = "test-manage-key-456"
-
-var png = []byte{0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 3, 255, 254}
-
-type seen struct {
- Method string
- Path string
- Query string
- Header http.Header
- Body []byte
-}
-
-type upstream struct {
- *httptest.Server
- mu sync.Mutex
- last seen
- hits atomic.Int32
- handler func(w http.ResponseWriter, r *http.Request) bool
-}
-
-func (u *upstream) lastSeen() seen {
- u.mu.Lock()
- defer u.mu.Unlock()
- return u.last
-}
-
-func newUpstream(t *testing.T) *upstream {
- u := &upstream{}
- u.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- body, _ := io.ReadAll(r.Body)
- u.mu.Lock()
- u.last = seen{r.Method, r.URL.EscapedPath(), r.URL.RawQuery, r.Header.Clone(), body}
- h := u.handler
- u.mu.Unlock()
- u.hits.Add(1)
- if h != nil && h(w, r) {
- return
- }
- switch {
- case strings.HasSuffix(r.URL.Path, "/gzip"):
- w.Header().Set("Content-Type", "application/json")
- w.Header().Set("Content-Encoding", "gzip")
- gz := gzip.NewWriter(w)
- gz.Write([]byte(`{"hello":"compressed"}`))
- gz.Close()
- case strings.HasSuffix(r.URL.Path, "/png"):
- w.Header().Set("Content-Type", "image/png")
- w.Write(png)
- case strings.HasSuffix(r.URL.Path, "/ratelimited"):
- w.Header().Set("X-RateLimit-Remaining", "5")
- w.Header().Set("X-RateLimit-Reset-After", "1")
- w.Header().Set("X-RateLimit-Bucket", "abc")
- w.Header().Set("Access-Control-Allow-Origin", "https://evil.example")
- w.Write([]byte(`{}`))
- case strings.HasSuffix(r.URL.Path, "/slow"):
- time.Sleep(300 * time.Millisecond)
- w.Write([]byte(`{}`))
- default:
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]string{"ok": "true"})
- }
- }))
- t.Cleanup(u.Close)
- return u
-}
-
-type env struct {
- up *upstream
- proxy *httptest.Server
- reg *registry.Registry
- file string
- settings config.Settings
-}
-
-func baseSettings() config.Settings {
- return config.Settings{
- Port: 0,
- CORSEnabled: true,
- CORSOrigins: []string{"*"},
- LogLevel: slog.LevelError,
- Timeout: 2 * time.Second,
- StrictTLS: true,
- ProxyAPIKey: proxyKey,
- ManagementAPIKey: manageKey,
- RequireProxyAuth: true,
- RequireManagementAuth: true,
- DiscordGlobalRPS: 50,
- ServicesFile: "",
- MaxBodyBytes: 1 << 20,
- Environment: "local",
- }
-}
-
-func newEnv(t *testing.T, mutate ...func(*config.Settings)) *env {
- t.Helper()
- up := newUpstream(t)
- settings := baseSettings()
- for _, m := range mutate {
- m(&settings)
- }
- file := filepath.Join(t.TempDir(), "services.json")
- reg, err := registry.New(file, registry.Builtins("test", up.URL+"/api/", up.URL+"/gh/"))
- if err != nil {
- t.Fatal(err)
- }
- if err := reg.Add("fake", registry.Service{Name: "Fake", BaseURL: up.URL + "/fake/", Headers: map[string]string{"User-Agent": "test"}}); err != nil {
- t.Fatal(err)
- }
- if err := reg.Add("dead", registry.Service{Name: "Dead", BaseURL: "http://127.0.0.1:1/"}); err != nil {
- t.Fatal(err)
- }
- logger := slog.New(slog.NewTextHandler(io.Discard, nil))
- srv := New(settings, reg, "2.0.0", logger)
- ts := httptest.NewServer(srv)
- t.Cleanup(ts.Close)
- return &env{up: up, proxy: ts, reg: reg, file: file, settings: settings}
-}
-
-var client = &http.Client{Transport: &http.Transport{DisableCompression: true}}
-
-func (e *env) do(t *testing.T, method, path string, body io.Reader, headers map[string]string) *http.Response {
- t.Helper()
- req, err := http.NewRequest(method, e.proxy.URL+path, body)
- if err != nil {
- t.Fatal(err)
- }
- for k, v := range headers {
- req.Header.Set(k, v)
- }
- resp, err := client.Do(req)
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { resp.Body.Close() })
- return resp
-}
-
-func key(extra map[string]string) map[string]string {
- h := map[string]string{"X-Api-Key": proxyKey}
- for k, v := range extra {
- h[k] = v
- }
- return h
-}
-
-func readAll(t *testing.T, r io.Reader) []byte {
- t.Helper()
- b, err := io.ReadAll(r)
- if err != nil {
- t.Fatal(err)
- }
- return b
-}
-
-func TestMultipartForwardedIntact(t *testing.T) {
- e := newEnv(t)
- var buf bytes.Buffer
- mw := multipart.NewWriter(&buf)
- mw.WriteField("payload_json", `{"content":"hi"}`)
- fw, _ := mw.CreateFormFile("files[0]", "a.png")
- fw.Write(png)
- mw.Close()
-
- resp := e.do(t, "POST", "/proxy/fake/upload", &buf, key(map[string]string{"Content-Type": mw.FormDataContentType()}))
- got := e.up.lastSeen()
- if resp.StatusCode != 200 {
- t.Fatalf("status %d", resp.StatusCode)
- }
- if ct := got.Header.Values("Content-Type"); len(ct) != 1 || ct[0] != mw.FormDataContentType() {
- t.Fatalf("content-type %q", ct)
- }
- if !bytes.Contains(got.Body, png) {
- t.Fatalf("file bytes missing from %d-byte body", len(got.Body))
- }
-}
-
-func TestJSONBodyAndMethod(t *testing.T) {
- e := newEnv(t)
- e.do(t, "PATCH", "/proxy/fake/json", strings.NewReader(`{"a":1}`), key(map[string]string{"Content-Type": "application/json"}))
- got := e.up.lastSeen()
- if got.Method != "PATCH" || string(got.Body) != `{"a":1}` {
- t.Fatalf("got %s %q", got.Method, got.Body)
- }
-}
-
-func TestBodyWithoutContentTypeDefaultsToJSON(t *testing.T) {
- e := newEnv(t)
- e.do(t, "POST", "/proxy/fake/json", strings.NewReader(`{"a":1}`), key(nil))
- if ct := e.up.lastSeen().Header.Get("Content-Type"); ct != "application/json" {
- t.Fatalf("content-type %q", ct)
- }
-}
-
-func TestGzipDecodedAndHeaderStripped(t *testing.T) {
- e := newEnv(t)
- resp := e.do(t, "GET", "/proxy/fake/gzip", nil, key(nil))
- if ce := resp.Header.Get("Content-Encoding"); ce != "" {
- t.Fatalf("content-encoding %q leaked", ce)
- }
- if body := readAll(t, resp.Body); string(body) != `{"hello":"compressed"}` {
- t.Fatalf("body %q", body)
- }
-}
-
-func TestBinaryIntact(t *testing.T) {
- e := newEnv(t)
- resp := e.do(t, "GET", "/proxy/fake/png", nil, key(nil))
- if body := readAll(t, resp.Body); !bytes.Equal(body, png) {
- t.Fatalf("binary changed: %v", body)
- }
- if resp.Header.Get("Content-Type") != "image/png" {
- t.Fatal("content-type lost")
- }
- if resp.Header.Get("Content-Length") != "10" {
- t.Fatalf("content-length %q", resp.Header.Get("Content-Length"))
- }
-}
-
-func TestProxySecretsNotForwarded(t *testing.T) {
- e := newEnv(t)
- e.do(t, "GET", "/proxy/fake/q?api_key="+proxyKey+"&x=1&y=a%20b", nil, key(nil))
- got := e.up.lastSeen()
- if got.Query != "x=1&y=a%20b" {
- t.Fatalf("query %q", got.Query)
- }
- if got.Header.Get("X-Api-Key") != "" {
- t.Fatal("x-api-key forwarded")
- }
-
- e.do(t, "GET", "/proxy/fake/q", nil, map[string]string{"Authorization": "Bearer " + proxyKey})
- if a := e.up.lastSeen().Header.Get("Authorization"); a != "" {
- t.Fatalf("proxy bearer key forwarded as %q", a)
- }
-}
-
-func TestCallerAuthorizationForwarded(t *testing.T) {
- e := newEnv(t)
- e.do(t, "GET", "/proxy/fake/me", nil, key(map[string]string{"Authorization": "Bot caller-token"}))
- if a := e.up.lastSeen().Header.Get("Authorization"); a != "Bot caller-token" {
- t.Fatalf("authorization %q", a)
- }
-}
-
-func TestUpstreamAuthorizationWins(t *testing.T) {
- e := newEnv(t)
- e.do(t, "GET", "/proxy/fake/me", nil, map[string]string{"Authorization": "Bearer " + proxyKey, "X-Upstream-Authorization": "Bot popplio"})
- got := e.up.lastSeen()
- if got.Header.Get("Authorization") != "Bot popplio" || got.Header.Get("X-Upstream-Authorization") != "" {
- t.Fatalf("headers %v", got.Header)
- }
-}
-
-func TestCookiesAndForwardingHeadersStripped(t *testing.T) {
- e := newEnv(t)
- e.do(t, "GET", "/proxy/fake/x", nil, key(map[string]string{"Cookie": "a=b", "X-Forwarded-For": "1.2.3.4", "X-Audit-Log-Reason": "kept"}))
- got := e.up.lastSeen()
- if got.Header.Get("Cookie") != "" || got.Header.Get("X-Forwarded-For") != "" {
- t.Fatalf("leaked headers %v", got.Header)
- }
- if got.Header.Get("X-Audit-Log-Reason") != "kept" {
- t.Fatal("regular header dropped")
- }
-}
-
-func TestGETSendsNoBody(t *testing.T) {
- e := newEnv(t)
- e.do(t, "GET", "/proxy/fake/get", nil, key(nil))
- got := e.up.lastSeen()
- if len(got.Body) != 0 || got.Header.Get("Content-Type") != "" {
- t.Fatalf("body %q content-type %q", got.Body, got.Header.Get("Content-Type"))
- }
-}
-
-func TestRateLimitHeadersPassThroughButNotUpstreamCORS(t *testing.T) {
- e := newEnv(t)
- resp := e.do(t, "GET", "/proxy/fake/ratelimited", nil, key(nil))
- if resp.Header.Get("X-RateLimit-Bucket") != "abc" {
- t.Fatal("rate limit header dropped")
- }
- if resp.Header.Get("Access-Control-Allow-Origin") != "*" {
- t.Fatalf("CORS header %q", resp.Header.Get("Access-Control-Allow-Origin"))
- }
- if resp.Header.Get("X-Proxy-Service") != "fake" || resp.Header.Get("X-Proxy-Duration") == "" {
- t.Fatal("proxy headers missing")
- }
-}
-
-func TestAuth(t *testing.T) {
- e := newEnv(t)
- if resp := e.do(t, "GET", "/proxy/fake/x", nil, map[string]string{"X-Api-Key": "wrong"}); resp.StatusCode != 401 {
- t.Fatalf("wrong key: %d", resp.StatusCode)
- }
- if resp := e.do(t, "GET", "/proxy/fake/x", nil, nil); resp.StatusCode != 401 {
- t.Fatalf("no key: %d", resp.StatusCode)
- }
- if resp := e.do(t, "GET", "/proxy/fake/x?api_key="+proxyKey, nil, nil); resp.StatusCode != 200 {
- t.Fatalf("query key: %d", resp.StatusCode)
- }
- if resp := e.do(t, "GET", "/manage/services", nil, key(nil)); resp.StatusCode != 401 {
- t.Fatalf("proxy key on manage: %d", resp.StatusCode)
- }
- if resp := e.do(t, "GET", "/health", nil, nil); resp.StatusCode != 200 {
- t.Fatalf("health: %d", resp.StatusCode)
- }
-}
-
-func TestAuthDisabled(t *testing.T) {
- e := newEnv(t, func(s *config.Settings) { s.RequireProxyAuth = false })
- if resp := e.do(t, "GET", "/proxy/fake/x", nil, nil); resp.StatusCode != 200 {
- t.Fatalf("status %d", resp.StatusCode)
- }
-}
-
-func TestErrors(t *testing.T) {
- e := newEnv(t, func(s *config.Settings) { s.Timeout = 100 * time.Millisecond })
- cases := []struct {
- path string
- status int
- }{
- {"/proxy/nope/x", 404},
- {"/proxy/dead/x", 502},
- {"/proxy/fake/slow", 504},
- {"/nothing-here", 404},
- }
- for _, c := range cases {
- resp := e.do(t, "GET", c.path, nil, key(nil))
- if resp.StatusCode != c.status {
- t.Errorf("%s: got %d want %d", c.path, resp.StatusCode, c.status)
- }
- if !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
- t.Errorf("%s: not JSON", c.path)
- }
- }
-}
-
-func TestBodyTooLarge(t *testing.T) {
- e := newEnv(t, func(s *config.Settings) { s.MaxBodyBytes = 16 })
- resp := e.do(t, "POST", "/proxy/fake/x", strings.NewReader(strings.Repeat("a", 64)), key(nil))
- if resp.StatusCode != 413 {
- t.Fatalf("status %d", resp.StatusCode)
- }
-}
-
-func TestKeyDebugHasNoKeyMaterial(t *testing.T) {
- e := newEnv(t)
- for _, p := range []string{"/proxy/key-debug", "/manage/key-debug", "/manage/diagnostics"} {
- headers := key(nil)
- if strings.HasPrefix(p, "/manage") {
- headers = map[string]string{"X-Api-Key": manageKey}
- }
- body := string(readAll(t, e.do(t, "GET", p, nil, headers).Body))
- if strings.Contains(body, "test-") || strings.Contains(body, "123") || strings.Contains(body, "456") {
- t.Errorf("%s leaks key material: %s", p, body)
- }
- }
- body := string(readAll(t, e.do(t, "GET", "/auth-status?api_key=secret-value", nil, nil).Body))
- if strings.Contains(body, "secret-value") {
- t.Errorf("auth-status echoes api_key: %s", body)
- }
-}
-
-func TestDiscordPathShaping(t *testing.T) {
- e := newEnv(t)
- for path, want := range map[string]string{
- "/proxy/discord/v10/users/@me": "/api/v10/users/@me",
- "/proxy/discord/api/v10/users/@me": "/api/v10/users/@me",
- "/proxy/discord/v9/channels/1/messages": "/api/v9/channels/1/messages",
- "/proxy/discord/channels/1/messages/2/reactions/%F0%9F%91%8D/@me": "/api/channels/1/messages/2/reactions/%F0%9F%91%8D/@me",
- } {
- e.do(t, "GET", path, nil, key(map[string]string{"Authorization": "Bot x"}))
- if got := e.up.lastSeen().Path; got != want {
- t.Errorf("%s -> %s, want %s", path, got, want)
- }
- }
- if ua := e.up.lastSeen().Header.Get("User-Agent"); !strings.HasPrefix(ua, "DiscordBot (") {
- t.Errorf("user-agent %q", ua)
- }
-}
-
-func TestDiscord429Retried(t *testing.T) {
- e := newEnv(t)
- var calls atomic.Int32
- e.up.handler = func(w http.ResponseWriter, r *http.Request) bool {
- if calls.Add(1) == 1 {
- w.Header().Set("Retry-After", "0.05")
- w.WriteHeader(429)
- w.Write([]byte(`{"retry_after":0.05,"global":false}`))
- return true
- }
- return false
- }
- resp := e.do(t, "POST", "/proxy/discord/v10/channels/1/messages", strings.NewReader(`{"content":"x"}`), key(map[string]string{"Authorization": "Bot x"}))
- if resp.StatusCode != 200 || calls.Load() != 2 {
- t.Fatalf("status %d after %d calls", resp.StatusCode, calls.Load())
- }
- if string(e.up.lastSeen().Body) != `{"content":"x"}` {
- t.Fatal("retry lost the body")
- }
-}
-
-func TestDiscordLong429ReturnedToCaller(t *testing.T) {
- e := newEnv(t)
- e.up.handler = func(w http.ResponseWriter, r *http.Request) bool {
- w.Header().Set("Retry-After", "3600")
- w.WriteHeader(429)
- w.Write([]byte(`{"retry_after":3600}`))
- return true
- }
- start := time.Now()
- resp := e.do(t, "GET", "/proxy/discord/v10/users/@me", nil, key(map[string]string{"Authorization": "Bot x"}))
- if resp.StatusCode != 429 || time.Since(start) > 5*time.Second {
- t.Fatalf("status %d after %v", resp.StatusCode, time.Since(start))
- }
- if body := readAll(t, resp.Body); !strings.Contains(string(body), "3600") {
- t.Fatalf("body %q", body)
- }
-}
-
-func TestGitHubOrgHint(t *testing.T) {
- e := newEnv(t)
- if resp := e.do(t, "GET", "/proxy/github/org/foo", nil, key(nil)); resp.StatusCode != 400 {
- t.Fatalf("status %d", resp.StatusCode)
- }
-}
-
-func TestWindowRateLimit(t *testing.T) {
- e := newEnv(t)
- if err := e.reg.Add("limited", registry.Service{Name: "Limited", BaseURL: e.up.URL + "/", RateLimit: ®istry.RateLimit{MaxRequests: 2, WindowMs: 60000}}); err != nil {
- t.Fatal(err)
- }
- statuses := []int{}
- for i := 0; i < 3; i++ {
- statuses = append(statuses, e.do(t, "GET", "/proxy/limited/x", nil, key(nil)).StatusCode)
- }
- if statuses[0] != 200 || statuses[1] != 200 || statuses[2] != 429 {
- t.Fatalf("statuses %v", statuses)
- }
- resp := e.do(t, "GET", "/proxy/services/limited/rate-limit", nil, key(nil))
- var body map[string]any
- json.Unmarshal(readAll(t, resp.Body), &body)
- if body["remaining"] != float64(0) {
- t.Fatalf("status %v", body)
- }
-}
-
-func TestManagementLifecycleAndPersistence(t *testing.T) {
- e := newEnv(t)
- h := map[string]string{"X-Api-Key": manageKey, "Content-Type": "application/json"}
-
- bad := `{"key":"steal","config":{"name":"x","baseUrl":"https://evil.example/","auth":{"type":"bearer","tokenEnvVar":"DATABASE_URL"}}}`
- if resp := e.do(t, "POST", "/manage/services", strings.NewReader(bad), h); resp.StatusCode != 400 {
- t.Fatalf("disallowed env var accepted: %d", resp.StatusCode)
- }
- badHeader := `{"key":"hdr","config":{"name":"x","baseUrl":"https://example.com/","headers":{"Authorization":"Bearer x"}}}`
- if resp := e.do(t, "POST", "/manage/services", strings.NewReader(badHeader), h); resp.StatusCode != 400 {
- t.Fatalf("static Authorization accepted: %d", resp.StatusCode)
- }
-
- t.Setenv("BYTEPROXY_TOKEN_STATUS", "server-side-token")
- good := `{"key":"status","config":{"name":"Status","baseUrl":"` + e.up.URL + `/status/","auth":{"type":"bearer","tokenEnvVar":"BYTEPROXY_TOKEN_STATUS"}}}`
- if resp := e.do(t, "POST", "/manage/services", strings.NewReader(good), h); resp.StatusCode != 200 {
- t.Fatalf("add: %d %s", resp.StatusCode, readAll(t, resp.Body))
- }
- if resp := e.do(t, "POST", "/manage/services", strings.NewReader(good), h); resp.StatusCode != 409 {
- t.Fatalf("duplicate: %d", resp.StatusCode)
- }
-
- e.do(t, "GET", "/proxy/status/ping", nil, key(nil))
- if a := e.up.lastSeen().Header.Get("Authorization"); a != "Bearer server-side-token" {
- t.Fatalf("server token not applied: %q", a)
- }
- e.do(t, "GET", "/proxy/status/ping", nil, key(map[string]string{"X-Upstream-Authorization": "Bearer caller"}))
- if a := e.up.lastSeen().Header.Get("Authorization"); a != "Bearer caller" {
- t.Fatalf("caller credential should win: %q", a)
- }
-
- data, err := os.ReadFile(e.file)
- if err != nil || !strings.Contains(string(data), `"status"`) {
- t.Fatalf("not persisted: %v %s", err, data)
- }
- reloaded, err := registry.New(e.file, registry.Builtins("test", "https://a/", "https://b/"))
- if err != nil {
- t.Fatal(err)
- }
- if _, ok := reloaded.Get("status"); !ok {
- t.Fatal("service not reloaded from disk")
- }
-
- if resp := e.do(t, "DELETE", "/manage/services/discord", nil, h); resp.StatusCode != 400 {
- t.Fatalf("builtin removal: %d", resp.StatusCode)
- }
- if resp := e.do(t, "DELETE", "/manage/services/status", nil, h); resp.StatusCode != 200 {
- t.Fatalf("remove: %d", resp.StatusCode)
- }
- if resp := e.do(t, "DELETE", "/manage/services/status", nil, h); resp.StatusCode != 404 {
- t.Fatalf("remove again: %d", resp.StatusCode)
- }
-}
-
-func TestCORS(t *testing.T) {
- e := newEnv(t)
- resp := e.do(t, "OPTIONS", "/proxy/fake/x", nil, map[string]string{"Origin": "https://app.example", "Access-Control-Request-Method": "POST"})
- if resp.StatusCode != 204 || resp.Header.Get("Access-Control-Allow-Origin") != "*" {
- t.Fatalf("preflight %d %v", resp.StatusCode, resp.Header)
- }
- if resp.Header.Get("Access-Control-Allow-Credentials") != "" {
- t.Fatal("wildcard origin must not allow credentials")
- }
- if !strings.Contains(resp.Header.Get("Access-Control-Allow-Headers"), "X-Upstream-Authorization") {
- t.Fatal("X-Upstream-Authorization not allowed")
- }
-
- e2 := newEnv(t, func(s *config.Settings) { s.CORSOrigins = []string{"https://app.example"} })
- resp = e2.do(t, "GET", "/health", nil, map[string]string{"Origin": "https://app.example"})
- if resp.Header.Get("Access-Control-Allow-Origin") != "https://app.example" || resp.Header.Get("Access-Control-Allow-Credentials") != "true" {
- t.Fatalf("allowlisted origin %v", resp.Header)
- }
- resp = e2.do(t, "GET", "/health", nil, map[string]string{"Origin": "https://evil.example"})
- if resp.Header.Get("Access-Control-Allow-Origin") != "" {
- t.Fatal("unlisted origin allowed")
- }
-}
-
-func TestOpenAPICoversEveryRoute(t *testing.T) {
- var spec struct {
- OpenAPI string `json:"openapi"`
- Paths map[string]map[string]json.RawMessage `json:"paths"`
- }
- if err := json.Unmarshal([]byte(openAPISpec), &spec); err != nil {
- t.Fatalf("openapi.json is invalid JSON: %v", err)
- }
- if spec.OpenAPI != "3.1.0" {
- t.Fatalf("openapi version %q", spec.OpenAPI)
- }
- s := New(baseSettings(), mustRegistry(t), "2.0.0", slog.New(slog.NewTextHandler(io.Discard, nil)))
- for _, r := range s.routeTable() {
- method, path, hasMethod := strings.Cut(r.pattern, " ")
- if !hasMethod {
- method, path = "", r.pattern
- }
- if path == "/" || strings.HasSuffix(path, "/{$}") && path != "/{$}" {
- continue
- }
- path = strings.ReplaceAll(strings.ReplaceAll(path, "{$}", ""), "...}", "}")
- if path == "" {
- path = "/"
- }
- ops, ok := spec.Paths[path]
- if !ok {
- t.Errorf("route %q is not documented in openapi.json", r.pattern)
- continue
- }
- if method != "" {
- if _, ok := ops[strings.ToLower(method)]; !ok {
- t.Errorf("route %q: method %s not documented", r.pattern, method)
- }
- }
- }
-}
-
-func mustRegistry(t *testing.T) *registry.Registry {
- reg, err := registry.New("", registry.Builtins("test", "https://discord.com/api/", "https://api.github.com/"))
- if err != nil {
- t.Fatal(err)
- }
- return reg
-}
-
-func TestDocsServed(t *testing.T) {
- e := newEnv(t)
- resp := e.do(t, "GET", "/openapi.json", nil, nil)
- body := readAll(t, resp.Body)
- if resp.StatusCode != 200 || !json.Valid(body) || !bytes.Contains(body, []byte(`"version": "2.0.0"`)) {
- t.Fatalf("openapi.json %d", resp.StatusCode)
- }
- if resp := e.do(t, "GET", "/docs", nil, nil); resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") {
- t.Fatalf("docs %d", resp.StatusCode)
- }
-}
diff --git a/main.go b/main.go
deleted file mode 100644
index 58e1cc7..0000000
--- a/main.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package main
-
-import (
- "context"
- "errors"
- "fmt"
- "log/slog"
- "net/http"
- "os"
- "os/signal"
- "syscall"
- "time"
-
- "github.com/NodeByteLTD/ByteProxy/internal/config"
- "github.com/NodeByteLTD/ByteProxy/internal/registry"
- "github.com/NodeByteLTD/ByteProxy/internal/server"
-)
-
-var version = "2.0.0"
-
-func main() {
- config.LoadDotEnv(".env.local", ".env")
- settings, err := config.Load()
- if err != nil {
- fmt.Fprintln(os.Stderr, "invalid configuration:", err)
- os.Exit(1)
- }
-
- logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: settings.LogLevel}))
- slog.SetDefault(logger)
-
- for _, name := range []string{"DISCORD_BOT_TOKEN", "GITHUB_TOKEN"} {
- if os.Getenv(name) != "" {
- logger.Warn(name + " is set but no longer used; callers must send their own upstream credentials")
- }
- }
- if !settings.RequireManagementAuth {
- logger.Warn("management API authentication is disabled (REQUIRE_AUTH_FOR_MANAGEMENT=false); anyone who can reach this server can register services")
- }
-
- reg, err := registry.New(settings.ServicesFile, registry.Builtins(version, "https://discord.com/api/", "https://api.github.com/"))
- if err != nil {
- logger.Error("failed to load services", "error", err)
- os.Exit(1)
- }
-
- srv := server.New(settings, reg, version, logger)
- ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
- defer stop()
- srv.Start(ctx)
-
- if !settings.SkipUpdateCheck && settings.Environment != "dev" {
- go func() {
- info := srv.CheckForUpdates(ctx)
- switch {
- case info.Error != "":
- logger.Warn("update check failed", "error", info.Error)
- case info.UpdateAvailable:
- logger.Warn("a newer ByteProxy release is available", "current", info.CurrentVersion, "latest", *info.LatestVersion, "url", *info.LatestReleaseURL)
- }
- }()
- }
-
- httpServer := &http.Server{
- Addr: fmt.Sprintf(":%d", settings.Port),
- Handler: srv,
- ReadHeaderTimeout: 10 * time.Second,
- IdleTimeout: 120 * time.Second,
- }
- go func() {
- logger.Info("ByteProxy started", "port", settings.Port, "version", version, "services", len(reg.Keys()))
- if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
- logger.Error("server stopped", "error", err)
- stop()
- }
- }()
-
- <-ctx.Done()
- logger.Info("shutting down")
- shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
- defer cancel()
- if err := httpServer.Shutdown(shutdownCtx); err != nil {
- logger.Error("graceful shutdown failed", "error", err)
- }
-}
diff --git a/railpack.json b/railpack.json
deleted file mode 100644
index c19dd55..0000000
--- a/railpack.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "$schema": "https://schema.railpack.com",
- "provider": "golang",
- "packages": {
- "go": "1.25"
- },
- "deploy": {
- "variables": {
- "APP_ENV": "production",
- "SERVICES_FILE": "/data/services.json"
- }
- }
-}
diff --git a/security.md b/security.md
new file mode 100644
index 0000000..2072fe1
--- /dev/null
+++ b/security.md
@@ -0,0 +1,25 @@
+---
+title: Security
+layout: default
+nav_order: 4
+has_children: true
+---
+
+# Security
+
+This section covers security aspects of ByteProxy including authentication, API keys, and best practices.
+
+## Topics
+
+- [Authentication](auth.md) - How to secure your ByteProxy instance
+- Rate Limiting - Protect your services from abuse
+- SSL/TLS Configuration - Secure communication
+- Access Control - Managing who can access what
+
+## Security Best Practices
+
+1. **Always use HTTPS** in production environments
+2. **Rotate API keys** periodically
+3. **Limit access** to management endpoints
+4. **Monitor logs** for suspicious activity
+5. **Keep ByteProxy updated** to the latest version
diff --git a/self-host.md b/self-host.md
new file mode 100644
index 0000000..69e6da1
--- /dev/null
+++ b/self-host.md
@@ -0,0 +1,244 @@
+---
+title: Self-Hosting
+layout: default
+nav_order: 7
+parent: Deployment
+---
+
+# ByteProxy Self-Hosting Guide
+
+This guide covers how to self-host ByteProxy on your own infrastructure.
+
+## System Requirements
+
+- Node.js 18+ or Bun 1.0.0+
+- 512MB RAM minimum (1GB recommended)
+- 100MB disk space
+
+## Installation Options
+
+### Option 1: Direct Install
+
+```bash
+# Clone the repository
+git clone https://github.com/ByteBrushStudios/ByteProxy.git
+cd ByteProxy
+
+# Install dependencies (using Bun - recommended)
+bun install
+
+# Or using npm
+npm install
+
+# Create environment file
+cp .env.example .env.local
+
+# Edit your configuration
+nano .env.local
+```
+
+### Option 2: Using Docker
+
+```bash
+# Pull the image
+docker pull bytebrushstudios/byteproxy:latest
+
+# Create a directory for config
+mkdir -p ~/byteproxy/config
+cd ~/byteproxy
+
+# Create environment file
+curl -o .env https://raw.githubusercontent.com/ByteBrushStudios/ByteProxy/main/.env.example
+nano .env
+
+# Run the container
+docker run -d \
+ --name byteproxy \
+ -p 3420:3420 \
+ --env-file .env \
+ bytebrushstudios/byteproxy:latest
+```
+
+## Configuration
+
+At minimum, you'll need to:
+
+1. Set the `PORT` if you want to change the default 3420
+2. Configure service tokens:
+ - `DISCORD_BOT_TOKEN` - For Discord API integration
+ - `GITHUB_TOKEN` - For GitHub API integration
+3. Set security options:
+ - `REQUIRE_AUTH_FOR_PROXY` - Enable/disable proxy endpoint authentication
+ - `REQUIRE_AUTH_FOR_MANAGEMENT` - Enable/disable management endpoint authentication
+ - `PROXY_API_KEY` - Set your proxy API key
+ - `MANAGEMENT_API_KEY` - Set your management API key
+
+See the [Configuration Reference](config.md) for all options.
+
+## Running in Production
+
+### Using Bun (Recommended)
+
+```bash
+# Build the TypeScript code
+bun run build
+
+# Start the server
+NODE_ENV=production bun run start
+```
+
+### Using Node.js
+
+```bash
+# Build the TypeScript code
+npm run build
+
+# Start the server
+NODE_ENV=production npm run start
+```
+
+### Using Process Managers
+
+For better reliability, use a process manager:
+
+#### PM2
+
+```bash
+npm install -g pm2
+pm2 start dist/index.js --name byteproxy
+pm2 save
+```
+
+#### Systemd
+
+Create a service file `/etc/systemd/system/byteproxy.service`:
+
+```ini
+[Unit]
+Description=ByteProxy Server
+After=network.target
+
+[Service]
+Type=simple
+User=your-user
+WorkingDirectory=/path/to/byteproxy
+ExecStart=/usr/bin/bun run dist/index.js
+Restart=on-failure
+Environment=NODE_ENV=production
+Environment=PORT=3420
+
+[Install]
+WantedBy=multi-user.target
+```
+
+Then enable and start:
+
+```bash
+sudo systemctl enable byteproxy
+sudo systemctl start byteproxy
+```
+
+## Using with a Reverse Proxy
+
+### Nginx Configuration
+
+```nginx
+server {
+ listen 80;
+ server_name proxy.yourdomain.com;
+
+ location / {
+ proxy_pass http://localhost:3420;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection 'upgrade';
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_cache_bypass $http_upgrade;
+ }
+}
+```
+
+### Caddy Configuration
+
+```
+# Caddyfile
+proxy.yourdomain.com {
+ reverse_proxy localhost:3420
+}
+```
+
+## Security Considerations
+
+### API Keys
+
+In production, always enable authentication:
+
+```
+PROXY_API_KEY=your_long_random_secure_key
+MANAGEMENT_API_KEY=different_long_random_secure_key
+REQUIRE_AUTH_FOR_PROXY=true
+REQUIRE_AUTH_FOR_MANAGEMENT=true
+```
+
+Generate secure keys with:
+```bash
+# Using OpenSSL
+openssl rand -hex 32
+
+# Using Node.js
+node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
+```
+
+### TLS/HTTPS
+
+Always use HTTPS in production. Options:
+
+1. **Reverse Proxy**: Place ByteProxy behind Nginx/Caddy/Traefik
+2. **Cloud Provider**: Use platform SSL features
+3. **Cloudflare**: Add your ByteProxy instance to Cloudflare
+
+## Performance Tuning
+
+### Environment Variables
+
+```
+# Maximum number of concurrent connections
+MAX_CONNECTIONS=100
+
+# Timeouts (ms)
+REQUEST_TIMEOUT=30000
+
+# TLS settings
+STRICT_TLS=true
+```
+
+### Health Monitoring
+
+Set up monitoring for:
+- `/up` endpoint for basic liveness
+- `/health` for detailed health status
+- `/status` for application metrics
+
+## Troubleshooting
+
+- **Logs**: ByteProxy logs to stdout/stderr by default
+- **Diagnostics**: Visit `/manage/diagnostics` for system info
+- **Connectivity**: Check `/manage/services/{service}/test` endpoints
+
+## Upgrading
+
+```bash
+git pull
+bun install
+bun run build
+# Restart your service
+```
+
+## Next Steps
+
+- [Configuration Reference](config.md) - Detailed config options
+- [API Reference](api.md) - Complete API documentation
+- [Troubleshooting](troubleshooting.md) - Common issues and solutions
diff --git a/support.md b/support.md
new file mode 100644
index 0000000..d462b9a
--- /dev/null
+++ b/support.md
@@ -0,0 +1,24 @@
+---
+title: Support
+layout: default
+nav_order: 8
+has_children: true
+---
+
+# Support
+
+Need help with ByteProxy? You're in the right place.
+
+## Topics
+
+- [Troubleshooting](troubleshooting.md) - Common issues and solutions
+- [FAQ](faq.md) - Frequently asked questions
+- Community Resources - Get help from the community
+
+## Getting Help
+
+If you can't find a solution in the documentation:
+
+1. Check the [GitHub Issues](https://github.com/ByteBrushStudios/ByteProxy/issues)
+2. Join our [Discord community](https://discord.gg/Vv2bdC44Ge)
+3. Open a new issue if you've found a bug
diff --git a/troubleshooting.md b/troubleshooting.md
new file mode 100644
index 0000000..b4f2726
--- /dev/null
+++ b/troubleshooting.md
@@ -0,0 +1,246 @@
+---
+title: Troubleshooting
+layout: default
+nav_order: 8
+parent: Support
+---
+
+# ByteProxy Troubleshooting
+
+Common issues and solutions when working with ByteProxy.
+
+## Diagnostics
+
+ByteProxy provides built-in diagnostics to help troubleshoot issues:
+
+```bash
+# View system diagnostics
+curl http://localhost:3420/manage/diagnostics
+
+# Check health status
+curl http://localhost:3420/health
+
+# Check detailed status
+curl http://localhost:3420/status
+
+# Test service connectivity
+curl -X POST http://localhost:3420/manage/services/discord/test
+```
+
+## Common Issues
+
+### Connection Issues
+
+#### 503 Server Under Pressure
+
+**Symptom:** Requests return 503 with "Server under pressure" message.
+
+**Solution:**
+- Check server resources (memory, CPU)
+- Increase available resources
+- Reduce load or scale horizontally
+- Adjust pressure thresholds in `src/services/up.ts`
+
+#### TLS/SSL Certificate Errors
+
+**Symptom:** Requests to secure services fail with certificate errors.
+
+**Solutions:**
+- Ensure your system date/time is correct
+- Update your CA certificates
+- For development only, set `STRICT_TLS=false`
+- Check if a corporate firewall is intercepting SSL
+
+### Authentication Issues
+
+#### 401/403 Errors from Backend Services
+
+**Symptom:** Requests to Discord, GitHub, etc. return 401 or 403.
+
+**Solutions:**
+- Verify your tokens in `.env.local` are correct and not expired
+- Check that tokens have the necessary permissions
+- Ensure environment variables are loaded correctly
+- Use `/manage/diagnostics` to verify token configuration
+- Restart the server after updating environment variables
+
+#### API Key Authentication Failing
+
+**Symptom:** Authentication to ByteProxy fails with 401.
+
+**Solutions:**
+- Check that the correct API key is being used
+- Verify the authentication method (header, bearer, query)
+- Use `/manage/key-debug` to check key information
+- Ensure `REQUIRE_AUTH_FOR_PROXY` or `REQUIRE_AUTH_FOR_MANAGEMENT` are enabled
+
+### Rate Limiting
+
+#### 429 Too Many Requests
+
+**Symptom:** Service returns 429 errors.
+
+**Solutions:**
+- Reduce request frequency
+- Implement client-side rate limiting
+- Adjust service rate limit configuration
+- Use a token with higher rate limits
+
+### Operational Issues
+
+#### Server Won't Start
+
+**Symptom:** Server fails to start up.
+
+**Solutions:**
+- Check if the port is already in use
+- Verify environment variables are correctly formatted
+- Check for syntax errors in custom code
+- Review startup logs for specific errors
+- Set `SKIP_UPDATE_CHECK=true` if update checking is failing
+
+#### High Memory Usage
+
+**Symptom:** Server consuming excessive memory.
+
+**Solutions:**
+- Monitor memory usage with `/up` endpoint
+- Check for memory leaks in custom code
+- Reduce max concurrent connections
+- Set appropriate heap limits for Node.js or Bun
+
+### Proxy Behavior Issues
+
+#### Request Transformation Problems
+
+**Symptom:** Requests not correctly forwarded to backend services.
+
+**Solutions:**
+- Check service configuration (baseUrl, headers)
+- Verify URL path construction
+- Use curl with `-v` flag to debug request/response details
+- Ensure content types are correctly set
+
+#### CORS Issues
+
+**Symptom:** Browser requests fail with CORS errors.
+
+**Solutions:**
+- Ensure `CORS_ENABLED=true`
+- Add the origin to `CORS_ORIGINS` (comma-separated)
+- Check that preflight requests are handled correctly
+- Verify that credentials mode is properly configured
+
+## Common Error Codes
+
+| Code | Description | Troubleshooting |
+|------|-------------|-----------------|
+| 400 | Bad Request | Check request format and parameters |
+| 401 | Unauthorized | Verify API keys or service tokens |
+| 403 | Forbidden | Check permissions and authentication scope |
+| 404 | Not Found | Verify endpoint path and service availability |
+| 429 | Too Many Requests | Implement rate limiting or backoff |
+| 500 | Internal Server Error | Check server logs for errors |
+| 502 | Bad Gateway | Check backend service connectivity |
+| 503 | Service Unavailable | Check resource utilization with `/up` |
+| 504 | Gateway Timeout | Increase `NETWORK_TIMEOUT` or check service responsiveness |
+
+## Logs
+
+Check the server logs for detailed error information. By default, logs are output to the console, but you can redirect them to a file:
+
+```bash
+bun run start > byteproxy.log 2>&1
+```
+
+Increase log verbosity by setting `LOG_LEVEL=debug` in your environment variables.
+
+## Getting Help
+
+If you're still experiencing issues:
+
+1. [Create an issue](https://github.com/ByteBrushStudios/ByteProxy/issues) on GitHub
+2. [Join our Discord](https://discord.gg/Vv2bdC44Ge) for community support
+3. Check the [API Reference](api.md) for endpoint details
+4. Review the [Configuration Guide](config.md) for proper setup
+
+## Updating ByteProxy
+
+If you're experiencing issues, ensure you're on the latest version:
+
+```bash
+# Pull latest changes
+git pull origin main
+
+# Install dependencies
+bun install
+
+# Rebuild
+bun run build
+
+# Restart the server
+bun run start
+```
+ curl http://localhost:3420/proxy/services/github/rate-limit
+ ```
+
+2. **Adjust Rate Limits:**
+ ```typescript
+ // In config
+ rateLimit: {
+ maxRequests: 100, // Increase from default
+ windowMs: 60000
+ }
+ ```
+
+3. **Implement Request Batching:**
+ - Group multiple API calls into fewer requests
+
+4. **Add Delay Between Requests:**
+ - Spread requests over time
+
+## Common Errors
+
+### "Service not configured"
+
+**Solution:**
+- Check available services:
+ ```bash
+ curl http://localhost:3420/proxy/services
+ ```
+- Add missing service through management API or config
+
+### "Invalid GitHub API path"
+
+**Solution:**
+- Check GitHub API documentation for correct path format
+- Common mistake: using `/org/` instead of `/orgs/`
+
+### WebSocket Proxy Errors
+
+**Solution:**
+- Ensure `ws` package is installed
+- Enable WebSocket support with `ws: true` option
+- Check client WebSocket connection code
+
+## Getting Support
+
+If you're still having issues:
+
+1. **Check Logs:**
+ ```bash
+ # Set logging to debug level
+ LOGGING_LEVEL=debug bun run dev
+ ```
+
+2. **Open an Issue:**
+ - https://github.com/ByteBrushStudios/Proxy/issues
+
+3. **Join Discord:**
+ - https://discord.gg/Vv2bdC44Ge
+
+4. **Provide Details:**
+ - ByteProxy version
+ - Node.js/Bun version
+ - Full error message
+ - Steps to reproduce
diff --git a/usage.md b/usage.md
new file mode 100644
index 0000000..dfc1b76
--- /dev/null
+++ b/usage.md
@@ -0,0 +1,123 @@
+---
+title: Usage Guide
+layout: default
+nav_order: 3
+---
+
+# ByteProxy Usage Guide
+
+This guide explains how to use ByteProxy for different service integrations.
+
+## Proxy Endpoints
+
+All proxy requests follow this pattern:
+
+```
+http://localhost:3420/proxy/{service}/{endpoint}
+```
+
+Where:
+- `{service}` is a configured service (e.g., `discord`, `github`)
+- `{endpoint}` is the API endpoint you want to access
+
+### Example Requests
+
+#### Discord API
+
+```bash
+# Get current user (requires DISCORD_BOT_TOKEN in .env)
+curl http://localhost:3420/proxy/discord/users/@me
+
+# Get guild information
+curl http://localhost:3420/proxy/discord/guilds/957420716142252062
+```
+
+#### GitHub API
+
+```bash
+# Get user information (requires GITHUB_TOKEN in .env)
+curl http://localhost:3420/proxy/github/users/ByteBrushStudios
+
+# Get repository information
+curl http://localhost:3420/proxy/github/repos/ByteBrushStudios/Proxy
+```
+
+## Authentication
+
+ByteProxy offers two types of authentication:
+
+1. **Proxy Authentication**: Securing access to the proxy itself
+2. **Service Authentication**: Managing tokens for third-party APIs
+
+### Proxy Authentication
+
+When enabled, all proxy requests require an API key:
+
+```bash
+# Using Authorization header (preferred)
+curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost:3420/proxy/discord/users/@me
+
+# Using x-api-key header
+curl -H "x-api-key: YOUR_API_KEY" http://localhost:3420/proxy/discord/users/@me
+
+# Using query parameter (less secure, for testing)
+curl "http://localhost:3420/proxy/discord/users/@me?api_key=YOUR_API_KEY"
+```
+
+Configure this in your `.env` file:
+```
+PROXY_API_KEY=your_secure_key_here
+REQUIRE_AUTH_FOR_PROXY=true
+```
+
+### Service Authentication
+
+ByteProxy automatically adds service authentication tokens from your environment variables:
+
+```env
+# For Discord API
+DISCORD_BOT_TOKEN=your_discord_bot_token
+
+# For GitHub API
+GITHUB_TOKEN=your_github_personal_access_token
+```
+
+## Error Handling
+
+ByteProxy provides detailed error messages:
+
+```json
+{
+ "error": "Rate limit exceeded for discord. Reset in 25 seconds.",
+ "service": "discord",
+ "path": "/users/@me",
+ "troubleshooting": {
+ "hint": "Check /manage/diagnostics for network troubleshooting tips",
+ "documentation": "/docs"
+ }
+}
+```
+
+## Rate Limiting
+
+Each service has configurable rate limits:
+
+```
+GET /proxy/services/discord/rate-limit
+```
+
+Response:
+```json
+{
+ "service": "discord",
+ "remaining": 45,
+ "resetTime": 1626701234567,
+ "resetIn": 25
+}
+```
+
+## Next Steps
+
+- [Service Configuration](config.md) - Configure new services
+- [Self-Hosting Guide](self-host.md) - Deploy ByteProxy
+- [API Reference](api.md) - Complete API documentation