├── .eslintignore ├── .eslintrc.json ├── .gitattributes ├── .github └── workflows │ └── lint.yml ├── .gitignore ├── .prettierignore ├── .prettierrc.json ├── LICENSE ├── README.md ├── bin.js ├── docs └── V2-UPGRADE-GUIDE.md ├── examples ├── basic.js ├── basic.mjs ├── express.mjs ├── overHttpProxy.mjs ├── overSocksProxy.mjs ├── overTor.mjs ├── setupProxy.js └── static.mjs ├── package-lock.json ├── package.json ├── src ├── BareServer.ts ├── Meta.ts ├── V1.ts ├── V1Types.d.ts ├── V2.ts ├── V3.ts ├── V3Types.d.ts ├── cli.ts ├── createServer.ts ├── encodeProtocol.ts ├── env.d.ts ├── headerUtil.ts ├── remoteUtil.ts ├── requestUtil.ts └── splitHeaderUtil.ts └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | /dist 2 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "plugins": ["@typescript-eslint"], 5 | "env": { 6 | "node": true 7 | }, 8 | "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"], 9 | "rules": { 10 | "indent": "off", 11 | "quotes": "off", 12 | "no-constant-condition": [ 13 | "error", 14 | { 15 | "checkLoops": false 16 | } 17 | ], 18 | "no-lone-blocks": "off", 19 | "eqeqeq": "error", 20 | "prefer-const": "error", 21 | "no-var": "error", 22 | "@typescript-eslint/consistent-type-imports": "error", 23 | "@typescript-eslint/no-non-null-assertion": "off" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | # Trigger the workflow on push or pull request, 5 | # but only for the main branch 6 | push: 7 | branches: 8 | - master 9 | pull_request: 10 | branches: 11 | - master 12 | 13 | jobs: 14 | run-linters: 15 | name: Run linters 16 | runs-on: linux 17 | 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v2 21 | 22 | - name: Setup Node.js environment 23 | uses: actions/setup-node@v3 24 | with: 25 | node-version: 18 26 | 27 | # ESLint and Prettier must be in `package.json` 28 | - name: Install Node.js dependencies 29 | run: npm ci 30 | 31 | - name: Run linters 32 | uses: wearerequired/lint-action@v2 33 | with: 34 | eslint: true 35 | eslint_extensions: js,ts,tsx 36 | prettier: true 37 | prettier_extensions: js,ts,tsx,json,md 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /dist 3 | /.vscode -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | /dist 2 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "useTabs": true, 3 | "singleQuote": true 4 | } 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TOMP Bare Server 2 | 3 | This repository implements the TompHTTP bare server. See the specification [here](https://github.com/tomphttp/specifications/blob/master/BareServer.md). 4 | 5 | ## Upgrading 6 | 7 | A guide for updating from v1 to v2 can be found [here](./docs/V2-UPGRADE-GUIDE.md). 8 | 9 | ## Usage 10 | 11 | We provide a command-line interface for creating a server. 12 | 13 | For more features, specify the `--help` option when running the CLI. 14 | 15 | ## Quickstart 16 | 17 | 1. Install Bare Server Node globally 18 | 19 | ```sh 20 | npm install --global @tomphttp/bare-server-node 21 | ``` 22 | 23 | 2. Start the server 24 | 25 | ```sh 26 | npx bare-server-node 27 | ``` 28 | 29 | Optionally start the server localhost:8080: 30 | 31 | ```sh 32 | npx bare-server-node --port 8080 --host localhost 33 | ``` 34 | 35 | ## Programically create a bare server 36 | 37 | See [examples/](https://github.com/tomphttp/bare-server-node/tree/master/examples). 38 | 39 | ## Development 40 | 41 | See the [wiki](https://github.com/tomphttp/bare-server-node/wiki). 42 | -------------------------------------------------------------------------------- /bin.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | require('./dist/cli.js'); 3 | -------------------------------------------------------------------------------- /docs/V2-UPGRADE-GUIDE.md: -------------------------------------------------------------------------------- 1 | # Upgrade to @tomphttp/bare-server-node v2.x 2 | 3 | @tomphttp/bare-server-node v2.x brings about many changes that provide a more stable API. However, many of these changes mean that apps written for @tomphttp/bare-server-node v1.x needs to be updated to work with @tomphttp/bare-server-node v2.x. This document helps you make this transition. 4 | 5 | ## No more default exports 6 | 7 | In v2.x, the way you import the library has been updated for better maintainability. 8 | 9 | You should import `createBareServer` using named imports instead. 10 | 11 | Use the following code snippet to update the way you import the library: 12 | 13 | ```js 14 | // old way 15 | import createBareServer from '@tomphttp/bare-server-node'; 16 | 17 | // new way 18 | import { createBareServer } from '@tomphttp/bare-server-node'; 19 | ``` 20 | -------------------------------------------------------------------------------- /examples/basic.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-var-requires */ 2 | const http = require('node:http'); 3 | const { createBareServer } = require('@tomphttp/bare-server-node'); 4 | 5 | const httpServer = http.createServer(); 6 | 7 | const bareServer = createBareServer('/'); 8 | 9 | httpServer.on('request', (req, res) => { 10 | if (bareServer.shouldRoute(req)) { 11 | bareServer.routeRequest(req, res); 12 | } else { 13 | res.writeHead(400); 14 | res.end('Not found.'); 15 | } 16 | }); 17 | 18 | httpServer.on('upgrade', (req, socket, head) => { 19 | if (bareServer.shouldRoute(req)) { 20 | bareServer.routeUpgrade(req, socket, head); 21 | } else { 22 | socket.end(); 23 | } 24 | }); 25 | 26 | httpServer.on('listening', () => { 27 | console.log('HTTP server listening'); 28 | }); 29 | 30 | httpServer.listen({ 31 | port: 8080, 32 | }); 33 | -------------------------------------------------------------------------------- /examples/basic.mjs: -------------------------------------------------------------------------------- 1 | import http from 'node:http'; 2 | import { createBareServer } from '@tomphttp/bare-server-node'; 3 | 4 | const httpServer = http.createServer(); 5 | 6 | const bareServer = createBareServer('/'); 7 | 8 | httpServer.on('request', (req, res) => { 9 | if (bareServer.shouldRoute(req)) { 10 | bareServer.routeRequest(req, res); 11 | } else { 12 | res.writeHead(400); 13 | res.end('Not found.'); 14 | } 15 | }); 16 | 17 | httpServer.on('upgrade', (req, socket, head) => { 18 | if (bareServer.shouldRoute(req)) { 19 | bareServer.routeUpgrade(req, socket, head); 20 | } else { 21 | socket.end(); 22 | } 23 | }); 24 | 25 | httpServer.on('listening', () => { 26 | console.log('HTTP server listening'); 27 | }); 28 | 29 | httpServer.listen({ 30 | port: 8080, 31 | }); 32 | -------------------------------------------------------------------------------- /examples/express.mjs: -------------------------------------------------------------------------------- 1 | import http from 'node:http'; 2 | import { createBareServer } from '@tomphttp/bare-server-node'; 3 | import express from 'express'; 4 | 5 | const httpServer = http.createServer(); 6 | 7 | const app = express(); 8 | 9 | app.get('/', (req, res) => { 10 | res.send('Hello, World!'); 11 | }); 12 | 13 | const bareServer = createBareServer('/bare/'); 14 | 15 | httpServer.on('request', (req, res) => { 16 | if (bareServer.shouldRoute(req)) { 17 | bareServer.routeRequest(req, res); 18 | } else { 19 | app(req, res); 20 | } 21 | }); 22 | 23 | httpServer.on('upgrade', (req, socket, head) => { 24 | if (bareServer.shouldRoute(req)) { 25 | bareServer.routeUpgrade(req, socket, head); 26 | } else { 27 | socket.end(); 28 | } 29 | }); 30 | 31 | httpServer.on('listening', () => { 32 | console.log('HTTP server listening'); 33 | }); 34 | 35 | httpServer.listen({ 36 | port: 8080, 37 | }); 38 | -------------------------------------------------------------------------------- /examples/overHttpProxy.mjs: -------------------------------------------------------------------------------- 1 | import http from 'node:http'; 2 | import { createBareServer } from '@tomphttp/bare-server-node'; 3 | import HttpsProxyAgent from 'https-proxy-agent'; 4 | 5 | const httpProxyAgent = new HttpsProxyAgent('http://168.63.76.32:3128'); 6 | 7 | const httpServer = http.createServer(); 8 | 9 | const bareServer = createBareServer('/', { 10 | httpAgent: httpProxyAgent, 11 | httpsAgent: httpProxyAgent, 12 | }); 13 | 14 | httpServer.on('request', (req, res) => { 15 | if (bareServer.shouldRoute(req)) { 16 | bareServer.routeRequest(req, res); 17 | } else { 18 | res.writeHead(400); 19 | res.end('Not found.'); 20 | } 21 | }); 22 | 23 | httpServer.on('upgrade', (req, socket, head) => { 24 | if (bareServer.shouldRoute(req)) { 25 | bareServer.routeUpgrade(req, socket, head); 26 | } else { 27 | socket.end(); 28 | } 29 | }); 30 | 31 | httpServer.on('listening', () => { 32 | console.log('HTTP server listening'); 33 | }); 34 | 35 | httpServer.listen({ 36 | port: 8080, 37 | }); 38 | -------------------------------------------------------------------------------- /examples/overSocksProxy.mjs: -------------------------------------------------------------------------------- 1 | import http from 'node:http'; 2 | import { createBareServer } from '@tomphttp/bare-server-node'; 3 | import { SocksProxyAgent } from 'socks-proxy-agent'; 4 | 5 | const socksProxyAgent = new SocksProxyAgent( 6 | 'socks://your-name@gmail.com:abcdef12345124@br41.nordvpn.com', 7 | ); 8 | 9 | const httpServer = http.createServer(); 10 | 11 | const bareServer = createBareServer('/', { 12 | httpAgent: socksProxyAgent, 13 | httpsAgent: socksProxyAgent, 14 | }); 15 | 16 | httpServer.on('request', (req, res) => { 17 | if (bareServer.shouldRoute(req)) { 18 | bareServer.routeRequest(req, res); 19 | } else { 20 | res.writeHead(400); 21 | res.end('Not found.'); 22 | } 23 | }); 24 | 25 | httpServer.on('upgrade', (req, socket, head) => { 26 | if (bareServer.shouldRoute(req)) { 27 | bareServer.routeUpgrade(req, socket, head); 28 | } else { 29 | socket.end(); 30 | } 31 | }); 32 | 33 | httpServer.on('listening', () => { 34 | console.log('HTTP server listening'); 35 | }); 36 | 37 | httpServer.listen({ 38 | port: 8080, 39 | }); 40 | -------------------------------------------------------------------------------- /examples/overTor.mjs: -------------------------------------------------------------------------------- 1 | import http from 'node:http'; 2 | import { createBareServer } from '@tomphttp/bare-server-node'; 3 | import { SocksProxyAgent } from 'socks-proxy-agent'; 4 | 5 | // TOR daemon listens on port 9050 by default 6 | const socksProxyAgent = new SocksProxyAgent( 7 | `socks://127.0.0.1:${process.env.TOR_PORT || '9050'}`, 8 | ); 9 | 10 | const httpServer = http.createServer(); 11 | 12 | const bareServer = createBareServer('/', { 13 | httpAgent: socksProxyAgent, 14 | httpsAgent: socksProxyAgent, 15 | }); 16 | 17 | httpServer.on('request', (req, res) => { 18 | if (bareServer.shouldRoute(req)) { 19 | bareServer.routeRequest(req, res); 20 | } else { 21 | res.writeHead(400); 22 | res.end('Not found.'); 23 | } 24 | }); 25 | 26 | httpServer.on('upgrade', (req, socket, head) => { 27 | if (bareServer.shouldRoute(req)) { 28 | bareServer.routeUpgrade(req, socket, head); 29 | } else { 30 | socket.end(); 31 | } 32 | }); 33 | 34 | httpServer.on('listening', () => { 35 | console.log('HTTP server listening'); 36 | }); 37 | 38 | httpServer.listen({ 39 | port: 8080, 40 | }); 41 | -------------------------------------------------------------------------------- /examples/setupProxy.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Example of using src/setupProxy.js to register a Bare server in your Create React App development server. 3 | * See https://create-react-app.dev/docs/proxying-api-requests-in-development/ 4 | */ 5 | /* eslint-disable @typescript-eslint/no-var-requires */ 6 | const { createBareServer } = require('@tomphttp/bare-server-node'); 7 | 8 | /** 9 | * Entry point called by react-scripts during development (npm start) 10 | * @param {import('express').Express} app 11 | */ 12 | function setupProxy(app) { 13 | const bareServer = createBareServer('/bare/'); 14 | 15 | app.use((req, res, next) => { 16 | if (bareServer.shouldRoute(req)) bareServer.routeRequest(req, res); 17 | else next(); 18 | }); 19 | } 20 | 21 | module.exports = setupProxy; 22 | -------------------------------------------------------------------------------- /examples/static.mjs: -------------------------------------------------------------------------------- 1 | /** 2 | * Example of serving static files and running a bare server. 3 | * This is a very common setup. 4 | */ 5 | import { createServer } from 'node:http'; 6 | import { fileURLToPath } from 'node:url'; 7 | import { createBareServer } from '@tomphttp/bare-server-node'; 8 | import serveStatic from 'serve-static'; 9 | 10 | const httpServer = createServer(); 11 | 12 | // Run the Bare server in the /bare/ namespace. This will prevent conflicts between the static files and the bare server. 13 | const bareServer = createBareServer('/bare/'); 14 | 15 | // The static root is usually relative to the main script in projects that use the Bare server. 16 | // ie. if static.js is at /src/static.js, public will be /public/ 17 | // ideally, you will point the public directory relative to the current working directory 18 | // serveStatic('./public/') 19 | // This would ignore the relative location of static.js 20 | const serve = serveStatic( 21 | fileURLToPath(new URL('../public/', import.meta.url)), 22 | { 23 | fallthrough: false, 24 | }, 25 | ); 26 | 27 | httpServer.on('request', (req, res) => { 28 | if (bareServer.shouldRoute(req)) { 29 | bareServer.routeRequest(req, res); 30 | } else { 31 | serve(req, res, (err) => { 32 | res.writeHead(err?.statusCode || 500, { 33 | 'Content-Type': 'text/plain', 34 | }); 35 | res.end(err?.stack); 36 | }); 37 | } 38 | }); 39 | 40 | httpServer.on('upgrade', (req, socket, head) => { 41 | if (bareServer.shouldRoute(req)) { 42 | bareServer.routeUpgrade(req, socket, head); 43 | } else { 44 | socket.end(); 45 | } 46 | }); 47 | 48 | httpServer.on('listening', () => { 49 | console.log('HTTP server listening'); 50 | }); 51 | 52 | httpServer.listen({ 53 | port: 8080, 54 | }); 55 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@tomphttp/bare-server-node", 3 | "description": "The Bare Server implementation in NodeJS.", 4 | "version": "2.0.5", 5 | "homepage": "https://github.com/tomphttp", 6 | "bugs": { 7 | "url": "https://github.com/tomphttp/bare-server-node/issues" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/tomphttp/bare-server-node.git" 12 | }, 13 | "author": { 14 | "name": "TOMP Development", 15 | "url": "https://github.com/tomphttp" 16 | }, 17 | "keywords": [ 18 | "proxy", 19 | "tomp", 20 | "tomphttp" 21 | ], 22 | "license": "GPL-3.0", 23 | "type": "commonjs", 24 | "engines": { 25 | "node": ">=18.0.0" 26 | }, 27 | "bin": { 28 | "bare-server-node": "bin.js" 29 | }, 30 | "main": "dist/createServer.js", 31 | "types": "dist/createServer.d.ts", 32 | "files": [ 33 | "dist", 34 | "bin.js" 35 | ], 36 | "scripts": { 37 | "build": "tsc", 38 | "dev": "tsc --watch" 39 | }, 40 | "dependencies": { 41 | "async-exit-hook": "^2.0.1", 42 | "commander": "^10.0.1", 43 | "dotenv": "^16.0.3", 44 | "http-errors": "^2.0.0", 45 | "ipaddr.js": "^2.1.0", 46 | "source-map-support": "^0.5.21", 47 | "ws": "^8.18.0" 48 | }, 49 | "devDependencies": { 50 | "@ianvs/prettier-plugin-sort-imports": "^4.1.1", 51 | "@types/async-exit-hook": "^2.0.0", 52 | "@types/http-errors": "^2.0.1", 53 | "@types/node": "^18.16.19", 54 | "@types/source-map-support": "^0.5.6", 55 | "@types/ws": "^8.5.4", 56 | "@typescript-eslint/eslint-plugin": "^5.59.7", 57 | "@typescript-eslint/parser": "^5.59.7", 58 | "eslint": "^8.41.0", 59 | "prettier": "^3.2.5", 60 | "typescript": "^5.0.4", 61 | "undici": "^5.22.1" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/BareServer.ts: -------------------------------------------------------------------------------- 1 | import type { LookupOneOptions } from 'node:dns'; 2 | import EventEmitter from 'node:events'; 3 | import { readFileSync } from 'node:fs'; 4 | import type { 5 | Agent as HttpAgent, 6 | IncomingMessage, 7 | ServerResponse, 8 | } from 'node:http'; 9 | import type { Agent as HttpsAgent } from 'node:https'; 10 | import { join } from 'node:path'; 11 | import { Readable, type Duplex } from 'node:stream'; 12 | import type { ReadableStream } from 'node:stream/web'; 13 | import createHttpError from 'http-errors'; 14 | import type WebSocket from 'ws'; 15 | // @internal 16 | import type { JSONDatabaseAdapter } from './Meta.js'; 17 | import { nullMethod } from './requestUtil.js'; 18 | 19 | export interface BareRequest extends Request { 20 | native: IncomingMessage; 21 | } 22 | 23 | export interface BareErrorBody { 24 | code: string; 25 | id: string; 26 | message?: string; 27 | stack?: string; 28 | } 29 | 30 | export class BareError extends Error { 31 | status: number; 32 | body: BareErrorBody; 33 | constructor(status: number, body: BareErrorBody) { 34 | super(body.message || body.code); 35 | this.status = status; 36 | this.body = body; 37 | } 38 | } 39 | 40 | export const pkg = JSON.parse( 41 | readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'), 42 | ) as { version: string }; 43 | 44 | const project: BareProject = { 45 | name: 'bare-server-node', 46 | description: 'TOMPHTTP NodeJS Bare Server', 47 | repository: 'https://github.com/tomphttp/bare-server-node', 48 | version: pkg.version, 49 | }; 50 | 51 | export function json(status: number, json: T) { 52 | const send = Buffer.from(JSON.stringify(json, null, '\t')); 53 | 54 | return new Response(send, { 55 | status, 56 | headers: { 57 | 'content-type': 'application/json', 58 | 'content-length': send.byteLength.toString(), 59 | }, 60 | }); 61 | } 62 | 63 | export type BareMaintainer = { 64 | email?: string; 65 | website?: string; 66 | }; 67 | 68 | export type BareProject = { 69 | name?: string; 70 | description?: string; 71 | email?: string; 72 | website?: string; 73 | repository?: string; 74 | version?: string; 75 | }; 76 | 77 | export type BareLanguage = 78 | | 'NodeJS' 79 | | 'ServiceWorker' 80 | | 'Deno' 81 | | 'Java' 82 | | 'PHP' 83 | | 'Rust' 84 | | 'C' 85 | | 'C++' 86 | | 'C#' 87 | | 'Ruby' 88 | | 'Go' 89 | | 'Crystal' 90 | | 'Shell' 91 | | string; 92 | 93 | export type BareManifest = { 94 | maintainer?: BareMaintainer; 95 | project?: BareProject; 96 | versions: string[]; 97 | language: BareLanguage; 98 | memoryUsage?: number; 99 | }; 100 | 101 | export interface Options { 102 | logErrors: boolean; 103 | /** 104 | * Callback for filtering the remote URL. 105 | * @returns Nothing 106 | * @throws An error if the remote is bad. 107 | */ 108 | filterRemote?: (remote: Readonly) => Promise | void; 109 | /** 110 | * DNS lookup 111 | * May not get called when remote.host is an IP 112 | * Use in combination with filterRemote to block IPs 113 | */ 114 | lookup: ( 115 | hostname: string, 116 | options: LookupOneOptions, 117 | callback: ( 118 | err: NodeJS.ErrnoException | null, 119 | address: string, 120 | family: number, 121 | ) => void, 122 | ) => void; 123 | localAddress?: string; 124 | family?: number; 125 | maintainer?: BareMaintainer; 126 | httpAgent: HttpAgent; 127 | httpsAgent: HttpsAgent; 128 | database: JSONDatabaseAdapter; 129 | wss: WebSocket.Server; 130 | } 131 | 132 | export type RouteCallback = ( 133 | request: BareRequest, 134 | response: ServerResponse, 135 | options: Options, 136 | ) => Promise | Response; 137 | 138 | export type SocketRouteCallback = ( 139 | request: BareRequest, 140 | socket: Duplex, 141 | head: Buffer, 142 | options: Options, 143 | ) => Promise | void; 144 | 145 | export default class Server extends EventEmitter { 146 | directory: string; 147 | routes = new Map(); 148 | socketRoutes = new Map(); 149 | versions: string[] = []; 150 | private closed = false; 151 | private options: Options; 152 | /** 153 | * @internal 154 | */ 155 | constructor(directory: string, options: Options) { 156 | super(); 157 | this.directory = directory; 158 | this.options = options; 159 | } 160 | /** 161 | * Remove all timers and listeners 162 | */ 163 | close() { 164 | this.closed = true; 165 | this.emit('close'); 166 | } 167 | shouldRoute(request: IncomingMessage): boolean { 168 | return ( 169 | !this.closed && 170 | request.url !== undefined && 171 | request.url.startsWith(this.directory) 172 | ); 173 | } 174 | get instanceInfo(): BareManifest { 175 | return { 176 | versions: this.versions, 177 | language: 'NodeJS', 178 | memoryUsage: 179 | Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100, 180 | maintainer: this.options.maintainer, 181 | project, 182 | }; 183 | } 184 | async routeUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer) { 185 | const request = new Request(new URL(req.url!, 'http://bare-server-node'), { 186 | method: req.method, 187 | body: nullMethod.includes(req.method || '') ? undefined : req, 188 | headers: req.headers as HeadersInit, 189 | }) as BareRequest; 190 | 191 | request.native = req; 192 | 193 | const service = new URL(request.url).pathname.slice( 194 | this.directory.length - 1, 195 | ); 196 | 197 | if (this.socketRoutes.has(service)) { 198 | const call = this.socketRoutes.get(service)!; 199 | 200 | try { 201 | await call(request, socket, head, this.options); 202 | } catch (error) { 203 | if (this.options.logErrors) { 204 | console.error(error); 205 | } 206 | 207 | socket.end(); 208 | } 209 | } else { 210 | socket.end(); 211 | } 212 | } 213 | async routeRequest(req: IncomingMessage, res: ServerResponse) { 214 | const request = new Request(new URL(req.url!, 'http://bare-server-node'), { 215 | method: req.method, 216 | body: nullMethod.includes(req.method || '') ? undefined : req, 217 | headers: req.headers as HeadersInit, 218 | duplex: 'half', 219 | }) as BareRequest; 220 | 221 | request.native = req; 222 | 223 | const service = new URL(request.url).pathname.slice( 224 | this.directory.length - 1, 225 | ); 226 | let response: Response; 227 | 228 | try { 229 | if (request.method === 'OPTIONS') { 230 | response = new Response(undefined, { status: 200 }); 231 | } else if (service === '/') { 232 | response = json(200, this.instanceInfo); 233 | } else if (this.routes.has(service)) { 234 | const call = this.routes.get(service)!; 235 | response = await call(request, res, this.options); 236 | } else { 237 | throw new createHttpError.NotFound(); 238 | } 239 | } catch (error) { 240 | if (this.options.logErrors) console.error(error); 241 | 242 | if (createHttpError.isHttpError(error)) { 243 | response = json(error.statusCode, { 244 | code: 'UNKNOWN', 245 | id: `error.${error.name}`, 246 | message: error.message, 247 | stack: error.stack, 248 | }); 249 | } else if (error instanceof Error) { 250 | response = json(500, { 251 | code: 'UNKNOWN', 252 | id: `error.${error.name}`, 253 | message: error.message, 254 | stack: error.stack, 255 | }); 256 | } else { 257 | response = json(500, { 258 | code: 'UNKNOWN', 259 | id: 'error.Exception', 260 | message: error, 261 | stack: new Error(error).stack, 262 | }); 263 | } 264 | 265 | if (!(response instanceof Response)) { 266 | if (this.options.logErrors) { 267 | console.error( 268 | 'Cannot', 269 | request.method, 270 | new URL(request.url).pathname, 271 | ': Route did not return a response.', 272 | ); 273 | } 274 | 275 | throw new createHttpError.InternalServerError(); 276 | } 277 | } 278 | 279 | response.headers.set('x-robots-tag', 'noindex'); 280 | response.headers.set('access-control-allow-headers', '*'); 281 | response.headers.set('access-control-allow-origin', '*'); 282 | response.headers.set('access-control-allow-methods', '*'); 283 | response.headers.set('access-control-expose-headers', '*'); 284 | // don't fetch preflight on every request... 285 | // instead, fetch preflight every 10 minutes 286 | response.headers.set('access-control-max-age', '7200'); 287 | 288 | res.writeHead( 289 | response.status, 290 | response.statusText, 291 | Object.fromEntries(response.headers), 292 | ); 293 | 294 | if (response.body) { 295 | const body = Readable.fromWeb(response.body as ReadableStream); 296 | body.pipe(res); 297 | res.on('close', () => body.destroy()); 298 | } else res.end(); 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /src/Meta.ts: -------------------------------------------------------------------------------- 1 | import type { BareHeaders } from './requestUtil'; 2 | 3 | export interface MetaV1 { 4 | v: 1; 5 | response?: { 6 | headers: BareHeaders; 7 | }; 8 | } 9 | 10 | export interface MetaV2 { 11 | v: 2; 12 | response?: { status: number; statusText: string; headers: BareHeaders }; 13 | sendHeaders: BareHeaders; 14 | remote: string; 15 | forwardHeaders: string[]; 16 | } 17 | 18 | export default interface CommonMeta { 19 | value: MetaV1 | MetaV2; 20 | expires: number; 21 | } 22 | 23 | export interface Database { 24 | get(key: string): string | undefined | PromiseLike; 25 | set(key: string, value: string): unknown; 26 | has(key: string): boolean | PromiseLike; 27 | delete(key: string): boolean | PromiseLike; 28 | entries(): 29 | | IterableIterator<[string, string]> 30 | | PromiseLike>; 31 | } 32 | 33 | /** 34 | * @internal 35 | */ 36 | export class JSONDatabaseAdapter { 37 | impl: Database; 38 | constructor(impl: Database) { 39 | this.impl = impl; 40 | } 41 | async get(key: string) { 42 | const res = await this.impl.get(key); 43 | if (typeof res === 'string') return JSON.parse(res) as CommonMeta; 44 | } 45 | async set(key: string, value: CommonMeta) { 46 | return await this.impl.set(key, JSON.stringify(value)); 47 | } 48 | async has(key: string) { 49 | return await this.impl.has(key); 50 | } 51 | async delete(key: string) { 52 | return await this.impl.delete(key); 53 | } 54 | async *[Symbol.asyncIterator]() { 55 | for (const [id, value] of await this.impl.entries()) { 56 | yield [id, JSON.parse(value)] as [string, CommonMeta]; 57 | } 58 | } 59 | } 60 | 61 | /** 62 | * Routine 63 | */ 64 | export async function cleanupDatabase(database: Database) { 65 | const adapter = new JSONDatabaseAdapter(database); 66 | 67 | for await (const [id, { expires }] of adapter) 68 | if (expires < Date.now()) database.delete(id); 69 | } 70 | -------------------------------------------------------------------------------- /src/V1.ts: -------------------------------------------------------------------------------- 1 | import { Readable } from 'node:stream'; 2 | import type { 3 | BareRequest, 4 | RouteCallback, 5 | SocketRouteCallback, 6 | } from './BareServer.js'; 7 | import type Server from './BareServer.js'; 8 | import { BareError, json } from './BareServer.js'; 9 | import { decodeProtocol } from './encodeProtocol.js'; 10 | import { 11 | flattenHeader, 12 | mapHeadersFromArray, 13 | rawHeaderNames, 14 | } from './headerUtil.js'; 15 | import type { BareRemote } from './remoteUtil.js'; 16 | import { remoteToURL } from './remoteUtil.js'; 17 | import type { BareHeaders } from './requestUtil.js'; 18 | import { bareFetch, bareUpgradeFetch, randomHex } from './requestUtil.js'; 19 | import type { BareV1Meta, BareV1MetaRes } from './V1Types.js'; 20 | 21 | const forbiddenSendHeaders = [ 22 | 'connection', 23 | 'content-length', 24 | 'transfer-encoding', 25 | ]; 26 | 27 | const forbiddenForwardHeaders: string[] = [ 28 | 'connection', 29 | 'transfer-encoding', 30 | 'origin', 31 | 'referer', 32 | ]; 33 | 34 | const validProtocols: string[] = ['http:', 'https:', 'ws:', 'wss:']; 35 | 36 | function loadForwardedHeaders( 37 | forward: string[], 38 | target: BareHeaders, 39 | request: BareRequest, 40 | ) { 41 | for (const header of forward) { 42 | const value = request.headers.get(header); 43 | if (value !== null) target[header] = value; 44 | } 45 | } 46 | 47 | interface BareHeaderData { 48 | remote: URL; 49 | headers: BareHeaders; 50 | } 51 | 52 | function readHeaders(request: BareRequest): BareHeaderData { 53 | const remote: Partial & { [key: string]: string | number } = 54 | Object.create(null); 55 | const headers: BareHeaders = Object.create(null); 56 | 57 | for (const remoteProp of ['host', 'port', 'protocol', 'path']) { 58 | const header = `x-bare-${remoteProp}`; 59 | const value = request.headers.get(header)!; 60 | 61 | if (value === null) 62 | throw new BareError(400, { 63 | code: 'MISSING_BARE_HEADER', 64 | id: `request.headers.${header}`, 65 | message: `Header was not specified.`, 66 | }); 67 | 68 | switch (remoteProp) { 69 | case 'port': 70 | if (isNaN(parseInt(value))) { 71 | throw new BareError(400, { 72 | code: 'INVALID_BARE_HEADER', 73 | id: `request.headers.${header}`, 74 | message: `Header was not a valid integer.`, 75 | }); 76 | } 77 | break; 78 | case 'protocol': 79 | if (!validProtocols.includes(value)) { 80 | throw new BareError(400, { 81 | code: 'INVALID_BARE_HEADER', 82 | id: `request.headers.${header}`, 83 | message: `Header was invalid`, 84 | }); 85 | } 86 | break; 87 | } 88 | 89 | remote[remoteProp] = value; 90 | } 91 | 92 | const xBareHeaders = request.headers.get('x-bare-headers'); 93 | 94 | if (xBareHeaders === null) 95 | throw new BareError(400, { 96 | code: 'MISSING_BARE_HEADER', 97 | id: `request.headers.x-bare-headers`, 98 | message: `Header was not specified.`, 99 | }); 100 | 101 | try { 102 | const json = JSON.parse(xBareHeaders) as Record; 103 | 104 | for (const header in json) { 105 | if (forbiddenSendHeaders.includes(header.toLowerCase())) continue; 106 | 107 | const value = json[header]; 108 | 109 | if (typeof value === 'string') { 110 | headers[header] = value; 111 | } else if (Array.isArray(value)) { 112 | const array: string[] = []; 113 | 114 | for (const val of value) { 115 | if (typeof val !== 'string') { 116 | throw new BareError(400, { 117 | code: 'INVALID_BARE_HEADER', 118 | id: `bare.headers.${header}`, 119 | message: `Header was not a String.`, 120 | }); 121 | } 122 | 123 | array.push(val); 124 | } 125 | 126 | headers[header] = array; 127 | } else { 128 | throw new BareError(400, { 129 | code: 'INVALID_BARE_HEADER', 130 | id: `bare.headers.${header}`, 131 | message: `Header was not a String.`, 132 | }); 133 | } 134 | } 135 | } catch (error) { 136 | if (error instanceof SyntaxError) { 137 | throw new BareError(400, { 138 | code: 'INVALID_BARE_HEADER', 139 | id: `request.headers.x-bare-headers`, 140 | message: `Header contained invalid JSON. (${error.message})`, 141 | }); 142 | } else { 143 | throw error; 144 | } 145 | } 146 | 147 | const xBareForwardHeaders = request.headers.get('x-bare-forward-headers'); 148 | 149 | if (xBareForwardHeaders === null) 150 | throw new BareError(400, { 151 | code: 'MISSING_BARE_HEADER', 152 | id: `request.headers.x-bare-forward-headers`, 153 | message: `Header was not specified.`, 154 | }); 155 | 156 | try { 157 | const parsed = JSON.parse(xBareForwardHeaders); 158 | const forwardHeaders: string[] = []; 159 | 160 | for (let header of parsed) { 161 | header = header.toLowerCase(); 162 | 163 | // just ignore 164 | if (forbiddenForwardHeaders.includes(header)) continue; 165 | forwardHeaders.push(header); 166 | } 167 | 168 | loadForwardedHeaders(forwardHeaders, headers, request); 169 | } catch (error) { 170 | throw new BareError(400, { 171 | code: 'INVALID_BARE_HEADER', 172 | id: `request.headers.x-bare-forward-headers`, 173 | message: `Header contained invalid JSON. (${ 174 | error instanceof Error ? error.message : error 175 | })`, 176 | }); 177 | } 178 | 179 | return { remote: remoteToURL(remote as BareRemote), headers }; 180 | } 181 | 182 | const tunnelRequest: RouteCallback = async (request, res, options) => { 183 | const abort = new AbortController(); 184 | 185 | request.native.on('close', () => { 186 | if (!request.native.complete) abort.abort(); 187 | }); 188 | 189 | res.on('close', () => { 190 | abort.abort(); 191 | }); 192 | 193 | const { remote, headers } = readHeaders(request); 194 | 195 | const response = await bareFetch( 196 | request, 197 | abort.signal, 198 | headers, 199 | remote, 200 | options, 201 | ); 202 | 203 | const responseHeaders = new Headers(); 204 | 205 | for (const header in response.headers) { 206 | if (header === 'content-encoding' || header === 'x-content-encoding') 207 | responseHeaders.set( 208 | 'content-encoding', 209 | flattenHeader(response.headers[header]!), 210 | ); 211 | else if (header === 'content-length') 212 | responseHeaders.set( 213 | 'content-length', 214 | flattenHeader(response.headers[header]!), 215 | ); 216 | } 217 | 218 | responseHeaders.set( 219 | 'x-bare-headers', 220 | JSON.stringify( 221 | mapHeadersFromArray(rawHeaderNames(response.rawHeaders), { 222 | ...(response.headers), 223 | }), 224 | ), 225 | ); 226 | 227 | responseHeaders.set('x-bare-status', response.statusCode!.toString()); 228 | responseHeaders.set('x-bare-status-text', response.statusMessage!); 229 | 230 | return new Response(Readable.toWeb(response), { 231 | status: 200, 232 | headers: responseHeaders, 233 | }); 234 | }; 235 | 236 | const metaExpiration = 30e3; 237 | 238 | const wsMeta: RouteCallback = async (request, res, options) => { 239 | if (request.method === 'OPTIONS') { 240 | return new Response(undefined, { status: 200 }); 241 | } 242 | 243 | const id = request.headers.get('x-bare-id'); 244 | 245 | if (id === null) 246 | throw new BareError(400, { 247 | code: 'MISSING_BARE_HEADER', 248 | id: 'request.headers.x-bare-id', 249 | message: 'Header was not specified', 250 | }); 251 | 252 | const meta = await options.database.get(id); 253 | 254 | // check if meta isn't undefined and if the version equals 1 255 | if (meta?.value.v !== 1) 256 | throw new BareError(400, { 257 | code: 'INVALID_BARE_HEADER', 258 | id: 'request.headers.x-bare-id', 259 | message: 'Unregistered ID', 260 | }); 261 | 262 | await options.database.delete(id); 263 | 264 | return json(200, { 265 | headers: meta.value.response?.headers, 266 | } as BareV1MetaRes); 267 | }; 268 | 269 | const wsNewMeta: RouteCallback = async (request, res, options) => { 270 | const id = randomHex(16); 271 | 272 | await options.database.set(id, { 273 | value: { v: 1 }, 274 | expires: Date.now() + metaExpiration, 275 | }); 276 | 277 | return new Response(Buffer.from(id)); 278 | }; 279 | 280 | const tunnelSocket: SocketRouteCallback = async ( 281 | request, 282 | socket, 283 | head, 284 | options, 285 | ) => { 286 | const abort = new AbortController(); 287 | 288 | request.native.on('close', () => { 289 | if (!request.native.complete) abort.abort(); 290 | }); 291 | 292 | socket.on('close', () => { 293 | abort.abort(); 294 | }); 295 | 296 | if (!request.headers.has('sec-websocket-protocol')) { 297 | socket.end(); 298 | return; 299 | } 300 | 301 | const [firstProtocol, data] = request.headers 302 | .get('sec-websocket-protocol')! 303 | .split(/,\s*/g); 304 | 305 | if (firstProtocol !== 'bare') { 306 | socket.end(); 307 | return; 308 | } 309 | 310 | const { 311 | remote, 312 | headers, 313 | forward_headers: forwardHeaders, 314 | id, 315 | } = JSON.parse(decodeProtocol(data)) as BareV1Meta; 316 | 317 | loadForwardedHeaders(forwardHeaders, headers, request); 318 | 319 | const [remoteResponse, remoteSocket] = await bareUpgradeFetch( 320 | request, 321 | abort.signal, 322 | headers, 323 | remoteToURL(remote), 324 | options, 325 | ); 326 | 327 | remoteSocket.on('close', () => { 328 | // console.log('Remote closed'); 329 | socket.end(); 330 | }); 331 | 332 | socket.on('close', () => { 333 | // console.log('Serving closed'); 334 | remoteSocket.end(); 335 | }); 336 | 337 | remoteSocket.on('error', (error) => { 338 | if (options.logErrors) { 339 | console.error('Remote socket error:', error); 340 | } 341 | socket.end(); 342 | }); 343 | 344 | socket.on('error', (error) => { 345 | if (options.logErrors) { 346 | console.error('Serving socket error:', error); 347 | } 348 | remoteSocket.end(); 349 | }); 350 | 351 | if (typeof id === 'string') { 352 | const meta = await options.database.get(id); 353 | 354 | if (meta?.value.v === 1) { 355 | meta.value.response = { 356 | headers: mapHeadersFromArray( 357 | rawHeaderNames(remoteResponse.rawHeaders), 358 | { 359 | ...(remoteResponse.headers), 360 | }, 361 | ), 362 | }; 363 | await options.database.set(id, meta); 364 | } 365 | } 366 | 367 | const responseHeaders = [ 368 | `HTTP/1.1 101 Switching Protocols`, 369 | `Upgrade: websocket`, 370 | `Connection: Upgrade`, 371 | `Sec-WebSocket-Protocol: bare`, 372 | `Sec-WebSocket-Accept: ${remoteResponse.headers['sec-websocket-accept']}`, 373 | ]; 374 | 375 | if ('sec-websocket-extensions' in remoteResponse.headers) { 376 | responseHeaders.push( 377 | `Sec-WebSocket-Extensions: ${remoteResponse.headers['sec-websocket-extensions']}`, 378 | ); 379 | } 380 | 381 | socket.write(responseHeaders.concat('', '').join('\r\n')); 382 | 383 | remoteSocket.pipe(socket); 384 | socket.pipe(remoteSocket); 385 | }; 386 | 387 | export default function registerV1(server: Server) { 388 | server.routes.set('/v1/', tunnelRequest); 389 | server.routes.set('/v1/ws-new-meta', wsNewMeta); 390 | server.routes.set('/v1/ws-meta', wsMeta); 391 | server.socketRoutes.set('/v1/', tunnelSocket); 392 | server.versions.push('v1'); 393 | } 394 | -------------------------------------------------------------------------------- /src/V1Types.d.ts: -------------------------------------------------------------------------------- 1 | import type { BareRemote } from './remoteUtil'; 2 | import type { BareHeaders } from './requestUtil'; 3 | 4 | export interface BareV1Meta { 5 | remote: BareRemote; 6 | headers: BareHeaders; 7 | forward_headers: string[]; 8 | id?: string; 9 | } 10 | 11 | export interface BareV1MetaRes { 12 | headers: BareHeaders; 13 | } 14 | -------------------------------------------------------------------------------- /src/V2.ts: -------------------------------------------------------------------------------- 1 | import { Readable } from 'node:stream'; 2 | import type { 3 | BareRequest, 4 | RouteCallback, 5 | SocketRouteCallback, 6 | } from './BareServer.js'; 7 | import { BareError } from './BareServer.js'; 8 | import type Server from './BareServer.js'; 9 | import { 10 | flattenHeader, 11 | mapHeadersFromArray, 12 | rawHeaderNames, 13 | } from './headerUtil.js'; 14 | import type { BareRemote } from './remoteUtil.js'; 15 | import { remoteToURL } from './remoteUtil.js'; 16 | import type { BareHeaders } from './requestUtil.js'; 17 | import { 18 | bareFetch, 19 | bareUpgradeFetch, 20 | nullBodyStatus, 21 | randomHex, 22 | } from './requestUtil.js'; 23 | import { joinHeaders, splitHeaders } from './splitHeaderUtil.js'; 24 | 25 | const validProtocols: string[] = ['http:', 'https:', 'ws:', 'wss:']; 26 | 27 | const forbiddenSendHeaders = [ 28 | 'connection', 29 | 'content-length', 30 | 'transfer-encoding', 31 | ]; 32 | 33 | const forbiddenForwardHeaders: string[] = [ 34 | 'connection', 35 | 'transfer-encoding', 36 | 'host', 37 | 'origin', 38 | 'referer', 39 | ]; 40 | 41 | const forbiddenPassHeaders: string[] = [ 42 | 'vary', 43 | 'connection', 44 | 'transfer-encoding', 45 | 'access-control-allow-headers', 46 | 'access-control-allow-methods', 47 | 'access-control-expose-headers', 48 | 'access-control-max-age', 49 | 'access-control-request-headers', 50 | 'access-control-request-method', 51 | ]; 52 | 53 | // common defaults 54 | const defaultForwardHeaders: string[] = [ 55 | 'accept-encoding', 56 | 'accept-language', 57 | 'sec-websocket-extensions', 58 | 'sec-websocket-key', 59 | 'sec-websocket-version', 60 | ]; 61 | 62 | const defaultPassHeaders: string[] = [ 63 | 'content-encoding', 64 | 'content-length', 65 | 'last-modified', 66 | ]; 67 | 68 | // defaults if the client provides a cache key 69 | const defaultCacheForwardHeaders: string[] = [ 70 | 'if-modified-since', 71 | 'if-none-match', 72 | 'cache-control', 73 | ]; 74 | 75 | const defaultCachePassHeaders: string[] = ['cache-control', 'etag']; 76 | 77 | const cacheNotModified = 304; 78 | 79 | function loadForwardedHeaders( 80 | forward: string[], 81 | target: BareHeaders, 82 | request: BareRequest, 83 | ) { 84 | for (const header of forward) { 85 | if (request.headers.has(header)) { 86 | target[header] = request.headers.get(header)!; 87 | } 88 | } 89 | } 90 | 91 | const splitHeaderValue = /,\s*/g; 92 | 93 | interface BareHeaderData { 94 | remote: URL; 95 | sendHeaders: BareHeaders; 96 | passHeaders: string[]; 97 | passStatus: number[]; 98 | forwardHeaders: string[]; 99 | } 100 | 101 | function readHeaders(request: BareRequest): BareHeaderData { 102 | const remote: Partial & { [key: string]: string | number } = 103 | Object.create(null); 104 | const sendHeaders: BareHeaders = Object.create(null); 105 | const passHeaders = [...defaultPassHeaders]; 106 | const passStatus = []; 107 | const forwardHeaders = [...defaultForwardHeaders]; 108 | 109 | // should be unique 110 | const cache = new URL(request.url).searchParams.has('cache'); 111 | 112 | if (cache) { 113 | passHeaders.push(...defaultCachePassHeaders); 114 | passStatus.push(cacheNotModified); 115 | forwardHeaders.push(...defaultCacheForwardHeaders); 116 | } 117 | 118 | const headers = joinHeaders(request.headers); 119 | 120 | for (const remoteProp of ['host', 'port', 'protocol', 'path']) { 121 | const header = `x-bare-${remoteProp}`; 122 | const value = headers.get(header); 123 | 124 | if (value === null) 125 | throw new BareError(400, { 126 | code: 'MISSING_BARE_HEADER', 127 | id: `request.headers.${header}`, 128 | message: `Header was not specified.`, 129 | }); 130 | 131 | switch (remoteProp) { 132 | case 'port': 133 | if (isNaN(parseInt(value))) { 134 | throw new BareError(400, { 135 | code: 'INVALID_BARE_HEADER', 136 | id: `request.headers.${header}`, 137 | message: `Header was not a valid integer.`, 138 | }); 139 | } 140 | break; 141 | case 'protocol': 142 | if (!validProtocols.includes(value)) { 143 | throw new BareError(400, { 144 | code: 'INVALID_BARE_HEADER', 145 | id: `request.headers.${header}`, 146 | message: `Header was invalid`, 147 | }); 148 | } 149 | break; 150 | } 151 | 152 | remote[remoteProp] = value; 153 | } 154 | 155 | const xBareHeaders = headers.get('x-bare-headers'); 156 | 157 | if (xBareHeaders === null) 158 | throw new BareError(400, { 159 | code: 'MISSING_BARE_HEADER', 160 | id: `request.headers.x-bare-headers`, 161 | message: `Header was not specified.`, 162 | }); 163 | 164 | try { 165 | const json = JSON.parse(xBareHeaders) as Record; 166 | 167 | for (const header in json) { 168 | if (forbiddenSendHeaders.includes(header.toLowerCase())) continue; 169 | 170 | const value = json[header]; 171 | 172 | if (typeof value === 'string') { 173 | sendHeaders[header] = value; 174 | } else if (Array.isArray(value)) { 175 | const array: string[] = []; 176 | 177 | for (const val of value) { 178 | if (typeof val !== 'string') { 179 | throw new BareError(400, { 180 | code: 'INVALID_BARE_HEADER', 181 | id: `bare.headers.${header}`, 182 | message: `Header was not a String.`, 183 | }); 184 | } 185 | 186 | array.push(val); 187 | } 188 | 189 | sendHeaders[header] = array; 190 | } else 191 | throw new BareError(400, { 192 | code: 'INVALID_BARE_HEADER', 193 | id: `bare.headers.${header}`, 194 | message: `Header was not a String.`, 195 | }); 196 | } 197 | } catch (error) { 198 | if (error instanceof SyntaxError) { 199 | throw new BareError(400, { 200 | code: 'INVALID_BARE_HEADER', 201 | id: `request.headers.x-bare-headers`, 202 | message: `Header contained invalid JSON. (${error.message})`, 203 | }); 204 | } else { 205 | throw error; 206 | } 207 | } 208 | 209 | if (headers.has('x-bare-pass-status')) { 210 | const parsed = headers.get('x-bare-pass-status')!.split(splitHeaderValue); 211 | 212 | for (const value of parsed) { 213 | const number = parseInt(value); 214 | 215 | if (isNaN(number)) { 216 | throw new BareError(400, { 217 | code: 'INVALID_BARE_HEADER', 218 | id: `request.headers.x-bare-pass-status`, 219 | message: `Array contained non-number value.`, 220 | }); 221 | } else { 222 | passStatus.push(number); 223 | } 224 | } 225 | } 226 | 227 | if (headers.has('x-bare-pass-headers')) { 228 | const parsed = headers.get('x-bare-pass-headers')!.split(splitHeaderValue); 229 | 230 | for (let header of parsed) { 231 | header = header.toLowerCase(); 232 | 233 | if (forbiddenPassHeaders.includes(header)) { 234 | throw new BareError(400, { 235 | code: 'FORBIDDEN_BARE_HEADER', 236 | id: `request.headers.x-bare-forward-headers`, 237 | message: `A forbidden header was passed.`, 238 | }); 239 | } else { 240 | passHeaders.push(header); 241 | } 242 | } 243 | } 244 | 245 | if (headers.has('x-bare-forward-headers')) { 246 | const parsed = headers 247 | .get('x-bare-forward-headers')! 248 | .split(splitHeaderValue); 249 | 250 | for (let header of parsed) { 251 | header = header.toLowerCase(); 252 | 253 | if (forbiddenForwardHeaders.includes(header)) { 254 | throw new BareError(400, { 255 | code: 'FORBIDDEN_BARE_HEADER', 256 | id: `request.headers.x-bare-forward-headers`, 257 | message: `A forbidden header was forwarded.`, 258 | }); 259 | } else { 260 | forwardHeaders.push(header); 261 | } 262 | } 263 | } 264 | 265 | return { 266 | remote: remoteToURL(remote as BareRemote), 267 | sendHeaders, 268 | passHeaders, 269 | passStatus, 270 | forwardHeaders, 271 | }; 272 | } 273 | 274 | const tunnelRequest: RouteCallback = async (request, res, options) => { 275 | const abort = new AbortController(); 276 | 277 | request.native.on('close', () => { 278 | if (!request.native.complete) abort.abort(); 279 | }); 280 | 281 | res.on('close', () => { 282 | abort.abort(); 283 | }); 284 | 285 | const { remote, sendHeaders, passHeaders, passStatus, forwardHeaders } = 286 | readHeaders(request); 287 | 288 | loadForwardedHeaders(forwardHeaders, sendHeaders, request); 289 | 290 | const response = await bareFetch( 291 | request, 292 | abort.signal, 293 | sendHeaders, 294 | remote, 295 | options, 296 | ); 297 | 298 | const responseHeaders = new Headers(); 299 | 300 | for (const header of passHeaders) { 301 | if (!(header in response.headers)) continue; 302 | responseHeaders.set(header, flattenHeader(response.headers[header]!)); 303 | } 304 | 305 | const status = passStatus.includes(response.statusCode!) 306 | ? response.statusCode! 307 | : 200; 308 | 309 | if (status !== cacheNotModified) { 310 | responseHeaders.set('x-bare-status', response.statusCode!.toString()); 311 | responseHeaders.set('x-bare-status-text', response.statusMessage!); 312 | responseHeaders.set( 313 | 'x-bare-headers', 314 | JSON.stringify( 315 | mapHeadersFromArray(rawHeaderNames(response.rawHeaders), { 316 | ...(response.headers), 317 | }), 318 | ), 319 | ); 320 | } 321 | 322 | return new Response( 323 | nullBodyStatus.includes(status) ? undefined : Readable.toWeb(response), 324 | { 325 | status, 326 | headers: splitHeaders(responseHeaders), 327 | }, 328 | ); 329 | }; 330 | 331 | const metaExpiration = 30e3; 332 | 333 | const getMeta: RouteCallback = async (request, res, options) => { 334 | if (request.method === 'OPTIONS') { 335 | return new Response(undefined, { status: 200 }); 336 | } 337 | 338 | const id = request.headers.get('x-bare-id'); 339 | 340 | if (id === null) 341 | throw new BareError(400, { 342 | code: 'MISSING_BARE_HEADER', 343 | id: 'request.headers.x-bare-id', 344 | message: 'Header was not specified', 345 | }); 346 | 347 | const meta = await options.database.get(id); 348 | 349 | if (meta?.value.v !== 2) 350 | throw new BareError(400, { 351 | code: 'INVALID_BARE_HEADER', 352 | id: 'request.headers.x-bare-id', 353 | message: 'Unregistered ID', 354 | }); 355 | 356 | if (!meta.value.response) 357 | throw new BareError(400, { 358 | code: 'INVALID_BARE_HEADER', 359 | id: 'request.headers.x-bare-id', 360 | message: 'Meta not ready', 361 | }); 362 | 363 | await options.database.delete(id); 364 | 365 | const responseHeaders = new Headers(); 366 | 367 | responseHeaders.set('x-bare-status', meta.value.response.status.toString()); 368 | responseHeaders.set('x-bare-status-text', meta.value.response.statusText); 369 | responseHeaders.set( 370 | 'x-bare-headers', 371 | JSON.stringify(meta.value.response.headers), 372 | ); 373 | 374 | return new Response(undefined, { 375 | status: 200, 376 | headers: splitHeaders(responseHeaders), 377 | }); 378 | }; 379 | 380 | const newMeta: RouteCallback = async (request, res, options) => { 381 | const { remote, sendHeaders, forwardHeaders } = readHeaders(request); 382 | 383 | const id = randomHex(16); 384 | 385 | await options.database.set(id, { 386 | expires: Date.now() + metaExpiration, 387 | value: { 388 | v: 2, 389 | remote: remote.toString(), 390 | sendHeaders, 391 | forwardHeaders, 392 | }, 393 | }); 394 | 395 | return new Response(Buffer.from(id)); 396 | }; 397 | 398 | const tunnelSocket: SocketRouteCallback = async ( 399 | request, 400 | socket, 401 | head, 402 | options, 403 | ) => { 404 | const abort = new AbortController(); 405 | 406 | request.native.on('close', () => { 407 | if (!request.native.complete) abort.abort(); 408 | }); 409 | 410 | socket.on('close', () => { 411 | abort.abort(); 412 | }); 413 | 414 | if (!request.headers.has('sec-websocket-protocol')) { 415 | socket.end(); 416 | return; 417 | } 418 | 419 | const id = request.headers.get('sec-websocket-protocol')!; 420 | const meta = await options.database.get(id); 421 | 422 | if (meta?.value.v !== 2) { 423 | socket.end(); 424 | return; 425 | } 426 | 427 | loadForwardedHeaders( 428 | meta.value.forwardHeaders, 429 | meta.value.sendHeaders, 430 | request, 431 | ); 432 | 433 | const [remoteResponse, remoteSocket] = await bareUpgradeFetch( 434 | request, 435 | abort.signal, 436 | meta.value.sendHeaders, 437 | new URL(meta.value.remote), 438 | options, 439 | ); 440 | 441 | remoteSocket.on('close', () => { 442 | socket.end(); 443 | }); 444 | 445 | socket.on('close', () => { 446 | remoteSocket.end(); 447 | }); 448 | 449 | remoteSocket.on('error', (error) => { 450 | if (options.logErrors) { 451 | console.error('Remote socket error:', error); 452 | } 453 | 454 | socket.end(); 455 | }); 456 | 457 | socket.on('error', (error) => { 458 | if (options.logErrors) { 459 | console.error('Serving socket error:', error); 460 | } 461 | 462 | remoteSocket.end(); 463 | }); 464 | 465 | const remoteHeaders = new Headers(remoteResponse.headers as HeadersInit); 466 | 467 | meta.value.response = { 468 | headers: mapHeadersFromArray(rawHeaderNames(remoteResponse.rawHeaders), { 469 | ...(remoteResponse.headers), 470 | }), 471 | status: remoteResponse.statusCode!, 472 | statusText: remoteResponse.statusMessage!, 473 | }; 474 | 475 | await options.database.set(id, meta); 476 | 477 | const responseHeaders = [ 478 | `HTTP/1.1 101 Switching Protocols`, 479 | `Upgrade: websocket`, 480 | `Connection: Upgrade`, 481 | `Sec-WebSocket-Protocol: ${id}`, 482 | ]; 483 | 484 | if (remoteHeaders.has('sec-websocket-extensions')) { 485 | responseHeaders.push( 486 | `Sec-WebSocket-Extensions: ${remoteHeaders.get( 487 | 'sec-websocket-extensions', 488 | )}`, 489 | ); 490 | } 491 | 492 | if (remoteHeaders.has('sec-websocket-accept')) { 493 | responseHeaders.push( 494 | `Sec-WebSocket-Accept: ${remoteHeaders.get('sec-websocket-accept')}`, 495 | ); 496 | } 497 | 498 | socket.write(responseHeaders.concat('', '').join('\r\n')); 499 | 500 | remoteSocket.pipe(socket); 501 | socket.pipe(remoteSocket); 502 | }; 503 | 504 | export default function registerV2(server: Server) { 505 | server.routes.set('/v2/', tunnelRequest); 506 | server.routes.set('/v2/ws-new-meta', newMeta); 507 | server.routes.set('/v2/ws-meta', getMeta); 508 | server.socketRoutes.set('/v2/', tunnelSocket); 509 | server.versions.push('v2'); 510 | } 511 | -------------------------------------------------------------------------------- /src/V3.ts: -------------------------------------------------------------------------------- 1 | import { Readable } from 'node:stream'; 2 | import type WebSocket from 'ws'; 3 | import type { MessageEvent } from 'ws'; 4 | import type { 5 | BareRequest, 6 | RouteCallback, 7 | SocketRouteCallback, 8 | } from './BareServer.js'; 9 | import { BareError } from './BareServer.js'; 10 | import type Server from './BareServer.js'; 11 | import { 12 | flattenHeader, 13 | mapHeadersFromArray, 14 | rawHeaderNames, 15 | } from './headerUtil.js'; 16 | import { remoteToURL, urlToRemote } from './remoteUtil.js'; 17 | import type { BareHeaders } from './requestUtil.js'; 18 | import { bareFetch, nullBodyStatus, webSocketFetch } from './requestUtil.js'; 19 | import { joinHeaders, splitHeaders } from './splitHeaderUtil.js'; 20 | import type { SocketClientToServer, SocketServerToClient } from './V3Types.js'; 21 | 22 | const forbiddenSendHeaders = [ 23 | 'connection', 24 | 'content-length', 25 | 'transfer-encoding', 26 | ]; 27 | 28 | const forbiddenForwardHeaders: string[] = [ 29 | 'connection', 30 | 'transfer-encoding', 31 | 'host', 32 | 'origin', 33 | 'referer', 34 | ]; 35 | 36 | const forbiddenPassHeaders: string[] = [ 37 | 'vary', 38 | 'connection', 39 | 'transfer-encoding', 40 | 'access-control-allow-headers', 41 | 'access-control-allow-methods', 42 | 'access-control-expose-headers', 43 | 'access-control-max-age', 44 | 'access-control-request-headers', 45 | 'access-control-request-method', 46 | ]; 47 | 48 | // common defaults 49 | const defaultForwardHeaders: string[] = ['accept-encoding', 'accept-language']; 50 | 51 | const defaultPassHeaders: string[] = [ 52 | 'content-encoding', 53 | 'content-length', 54 | 'last-modified', 55 | ]; 56 | 57 | // defaults if the client provides a cache key 58 | const defaultCacheForwardHeaders: string[] = [ 59 | 'if-modified-since', 60 | 'if-none-match', 61 | 'cache-control', 62 | ]; 63 | 64 | const defaultCachePassHeaders: string[] = ['cache-control', 'etag']; 65 | 66 | const cacheNotModified = 304; 67 | 68 | function loadForwardedHeaders( 69 | forward: string[], 70 | target: BareHeaders, 71 | request: BareRequest, 72 | ) { 73 | for (const header of forward) { 74 | if (request.headers.has(header)) { 75 | target[header] = request.headers.get(header)!; 76 | } 77 | } 78 | } 79 | 80 | const splitHeaderValue = /,\s*/g; 81 | 82 | interface BareHeaderData { 83 | remote: URL; 84 | sendHeaders: BareHeaders; 85 | passHeaders: string[]; 86 | passStatus: number[]; 87 | forwardHeaders: string[]; 88 | } 89 | 90 | function readHeaders(request: BareRequest): BareHeaderData { 91 | const sendHeaders: BareHeaders = Object.create(null); 92 | const passHeaders = [...defaultPassHeaders]; 93 | const passStatus = []; 94 | const forwardHeaders = [...defaultForwardHeaders]; 95 | 96 | // should be unique 97 | const cache = new URL(request.url).searchParams.has('cache'); 98 | 99 | if (cache) { 100 | passHeaders.push(...defaultCachePassHeaders); 101 | passStatus.push(cacheNotModified); 102 | forwardHeaders.push(...defaultCacheForwardHeaders); 103 | } 104 | 105 | const headers = joinHeaders(request.headers); 106 | 107 | const xBareURL = headers.get('x-bare-url'); 108 | 109 | if (xBareURL === null) 110 | throw new BareError(400, { 111 | code: 'MISSING_BARE_HEADER', 112 | id: `request.headers.x-bare-url`, 113 | message: `Header was not specified.`, 114 | }); 115 | 116 | const remote = urlToRemote(new URL(xBareURL)); 117 | 118 | const xBareHeaders = headers.get('x-bare-headers'); 119 | 120 | if (xBareHeaders === null) 121 | throw new BareError(400, { 122 | code: 'MISSING_BARE_HEADER', 123 | id: `request.headers.x-bare-headers`, 124 | message: `Header was not specified.`, 125 | }); 126 | 127 | try { 128 | const json = JSON.parse(xBareHeaders) as Record; 129 | 130 | for (const header in json) { 131 | if (forbiddenSendHeaders.includes(header.toLowerCase())) continue; 132 | 133 | const value = json[header]; 134 | 135 | if (typeof value === 'string') { 136 | sendHeaders[header] = value; 137 | } else if (Array.isArray(value)) { 138 | const array: string[] = []; 139 | 140 | for (const val of value) { 141 | if (typeof val !== 'string') { 142 | throw new BareError(400, { 143 | code: 'INVALID_BARE_HEADER', 144 | id: `bare.headers.${header}`, 145 | message: `Header was not a String.`, 146 | }); 147 | } 148 | 149 | array.push(val); 150 | } 151 | 152 | sendHeaders[header] = array; 153 | } else { 154 | throw new BareError(400, { 155 | code: 'INVALID_BARE_HEADER', 156 | id: `bare.headers.${header}`, 157 | message: `Header was not a String.`, 158 | }); 159 | } 160 | } 161 | } catch (error) { 162 | if (error instanceof SyntaxError) { 163 | throw new BareError(400, { 164 | code: 'INVALID_BARE_HEADER', 165 | id: `request.headers.x-bare-headers`, 166 | message: `Header contained invalid JSON. (${error.message})`, 167 | }); 168 | } else { 169 | throw error; 170 | } 171 | } 172 | 173 | if (headers.has('x-bare-pass-status')) { 174 | const parsed = headers.get('x-bare-pass-status')!.split(splitHeaderValue); 175 | 176 | for (const value of parsed) { 177 | const number = parseInt(value); 178 | 179 | if (isNaN(number)) { 180 | throw new BareError(400, { 181 | code: 'INVALID_BARE_HEADER', 182 | id: `request.headers.x-bare-pass-status`, 183 | message: `Array contained non-number value.`, 184 | }); 185 | } else { 186 | passStatus.push(number); 187 | } 188 | } 189 | } 190 | 191 | if (headers.has('x-bare-pass-headers')) { 192 | const parsed = headers.get('x-bare-pass-headers')!.split(splitHeaderValue); 193 | 194 | for (let header of parsed) { 195 | header = header.toLowerCase(); 196 | 197 | if (forbiddenPassHeaders.includes(header)) { 198 | throw new BareError(400, { 199 | code: 'FORBIDDEN_BARE_HEADER', 200 | id: `request.headers.x-bare-forward-headers`, 201 | message: `A forbidden header was passed.`, 202 | }); 203 | } else { 204 | passHeaders.push(header); 205 | } 206 | } 207 | } 208 | 209 | if (headers.has('x-bare-forward-headers')) { 210 | const parsed = headers 211 | .get('x-bare-forward-headers')! 212 | .split(splitHeaderValue); 213 | 214 | for (let header of parsed) { 215 | header = header.toLowerCase(); 216 | 217 | if (forbiddenForwardHeaders.includes(header)) { 218 | throw new BareError(400, { 219 | code: 'FORBIDDEN_BARE_HEADER', 220 | id: `request.headers.x-bare-forward-headers`, 221 | message: `A forbidden header was forwarded.`, 222 | }); 223 | } else { 224 | forwardHeaders.push(header); 225 | } 226 | } 227 | } 228 | 229 | return { 230 | remote: remoteToURL(remote), 231 | sendHeaders, 232 | passHeaders, 233 | passStatus, 234 | forwardHeaders, 235 | }; 236 | } 237 | 238 | const tunnelRequest: RouteCallback = async (request, res, options) => { 239 | const abort = new AbortController(); 240 | 241 | request.native.on('close', () => { 242 | if (!request.native.complete) abort.abort(); 243 | }); 244 | 245 | res.on('close', () => { 246 | abort.abort(); 247 | }); 248 | 249 | const { remote, sendHeaders, passHeaders, passStatus, forwardHeaders } = 250 | readHeaders(request); 251 | 252 | loadForwardedHeaders(forwardHeaders, sendHeaders, request); 253 | 254 | const response = await bareFetch( 255 | request, 256 | abort.signal, 257 | sendHeaders, 258 | remote, 259 | options, 260 | ); 261 | 262 | const responseHeaders = new Headers(); 263 | 264 | for (const header of passHeaders) { 265 | if (!(header in response.headers)) continue; 266 | responseHeaders.set(header, flattenHeader(response.headers[header]!)); 267 | } 268 | 269 | const status = passStatus.includes(response.statusCode!) 270 | ? response.statusCode! 271 | : 200; 272 | 273 | if (status !== cacheNotModified) { 274 | responseHeaders.set('x-bare-status', response.statusCode!.toString()); 275 | responseHeaders.set('x-bare-status-text', response.statusMessage!); 276 | responseHeaders.set( 277 | 'x-bare-headers', 278 | JSON.stringify( 279 | mapHeadersFromArray(rawHeaderNames(response.rawHeaders), { 280 | ...(response.headers), 281 | }), 282 | ), 283 | ); 284 | } 285 | 286 | return new Response( 287 | nullBodyStatus.includes(status) ? undefined : Readable.toWeb(response), 288 | { 289 | status, 290 | headers: splitHeaders(responseHeaders), 291 | }, 292 | ); 293 | }; 294 | 295 | function readSocket(socket: WebSocket): Promise { 296 | return new Promise((resolve, reject) => { 297 | const messageListener = (event: MessageEvent) => { 298 | cleanup(); 299 | 300 | if (typeof event.data !== 'string') 301 | return reject( 302 | new TypeError('the first websocket message was not a text frame'), 303 | ); 304 | 305 | try { 306 | resolve(JSON.parse(event.data)); 307 | } catch (err) { 308 | reject(err); 309 | } 310 | }; 311 | 312 | const closeListener = () => { 313 | cleanup(); 314 | }; 315 | 316 | const cleanup = () => { 317 | socket.removeEventListener('message', messageListener); 318 | socket.removeEventListener('close', closeListener); 319 | clearTimeout(timeout); 320 | }; 321 | 322 | const timeout = setTimeout(() => { 323 | cleanup(); 324 | reject(new Error('Timed out before metadata could be read')); 325 | }, 10e3); 326 | 327 | socket.addEventListener('message', messageListener); 328 | socket.addEventListener('close', closeListener); 329 | }); 330 | } 331 | 332 | const tunnelSocket: SocketRouteCallback = async ( 333 | request, 334 | socket, 335 | head, 336 | options, 337 | ) => 338 | options.wss.handleUpgrade(request.native, socket, head, async (client) => { 339 | let _remoteSocket: WebSocket | undefined; 340 | 341 | try { 342 | const connectPacket = await readSocket(client); 343 | 344 | if (connectPacket.type !== 'connect') 345 | throw new Error('Client did not send open packet.'); 346 | 347 | loadForwardedHeaders( 348 | connectPacket.forwardHeaders, 349 | connectPacket.headers, 350 | request, 351 | ); 352 | 353 | const [remoteReq, remoteSocket] = await webSocketFetch( 354 | request, 355 | connectPacket.headers, 356 | new URL(connectPacket.remote), 357 | connectPacket.protocols, 358 | options, 359 | ); 360 | 361 | _remoteSocket = remoteSocket; 362 | 363 | const setCookieHeader = remoteReq.headers['set-cookie']; 364 | const setCookies = 365 | setCookieHeader !== undefined 366 | ? Array.isArray(setCookieHeader) 367 | ? setCookieHeader 368 | : [setCookieHeader] 369 | : []; 370 | 371 | client.send( 372 | JSON.stringify({ 373 | type: 'open', 374 | protocol: remoteSocket.protocol, 375 | setCookies, 376 | } as SocketServerToClient), 377 | // use callback to wait for this message to buffer and finally send before doing any piping 378 | // otherwise the client will receive a random message from the remote before our open message 379 | () => { 380 | remoteSocket.addEventListener('message', (event) => { 381 | client.send(event.data); 382 | }); 383 | 384 | client.addEventListener('message', (event) => { 385 | remoteSocket.send(event.data); 386 | }); 387 | 388 | remoteSocket.addEventListener('close', () => { 389 | client.close(); 390 | }); 391 | 392 | client.addEventListener('close', () => { 393 | remoteSocket.close(); 394 | }); 395 | 396 | remoteSocket.addEventListener('error', (error) => { 397 | if (options.logErrors) { 398 | console.error('Remote socket error:', error); 399 | } 400 | 401 | client.close(); 402 | }); 403 | 404 | client.addEventListener('error', (error) => { 405 | if (options.logErrors) { 406 | console.error('Serving socket error:', error); 407 | } 408 | 409 | remoteSocket.close(); 410 | }); 411 | }, 412 | ); 413 | } catch (err) { 414 | if (options.logErrors) console.error(err); 415 | client.close(); 416 | if (_remoteSocket) _remoteSocket.close(); 417 | } 418 | }); 419 | 420 | export default function registerV3(server: Server) { 421 | server.routes.set('/v3/', tunnelRequest); 422 | server.socketRoutes.set('/v3/', tunnelSocket); 423 | server.versions.push('v3'); 424 | } 425 | -------------------------------------------------------------------------------- /src/V3Types.d.ts: -------------------------------------------------------------------------------- 1 | import type { BareHeaders } from './requestUtil.js'; 2 | 3 | export type SocketClientToServer = { 4 | type: 'connect'; 5 | /** 6 | * Remote to connect to 7 | */ 8 | remote: string; 9 | /** 10 | * An array of protocols to attempt to connect to. 11 | */ 12 | protocols: string[]; 13 | /** 14 | * Headers to send to the remote. Usually Cookie, Origin, and User-Agent. 15 | */ 16 | headers: BareHeaders; 17 | /** 18 | * Forwards to forward from the WebSocket handshake (eg. User-Agent) 19 | */ 20 | forwardHeaders: string[]; 21 | }; 22 | 23 | export type SocketServerToClient = { 24 | type: 'open'; 25 | /** 26 | * The protocl that the remote chose. 27 | */ 28 | protocol: string; 29 | /** 30 | * A list of cookies that correspond to the remote's set-cookies 31 | */ 32 | setCookies: string[]; 33 | }; 34 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register.js'; 2 | import { readFile } from 'node:fs/promises'; 3 | import { createServer } from 'node:http'; 4 | import exitHook from 'async-exit-hook'; 5 | import { Command } from 'commander'; 6 | import { config } from 'dotenv'; 7 | import { pkg } from './BareServer.js'; 8 | import type { BareServerInit, IPFamily } from './createServer.js'; 9 | import { createBareServer } from './createServer.js'; 10 | 11 | config(); 12 | 13 | const program = new Command(); 14 | 15 | program 16 | .alias('server') 17 | .version(pkg.version) 18 | .option('-d, --directory ', 'Bare directory', '/') 19 | .option('-h, --host ', 'Listening host', process.env.HOST || '0.0.0.0') 20 | .option( 21 | '-p, --port ', 22 | 'Listening port', 23 | (val: string) => { 24 | const valN = Number(val); 25 | if (isNaN(valN)) throw new Error('Bad port'); 26 | return valN; 27 | }, 28 | process.env.PORT ? Number(process.env.PORT) : 80, 29 | ) 30 | .option('-e, --errors', 'Error logging', 'ERRORS' in process.env) 31 | .option( 32 | '-la, --local-address
', 33 | 'Address/network interface', 34 | process.env.LOCAL_ADDRESS, 35 | ) 36 | .option( 37 | '-f, --family <0|4|6>', 38 | 'IP address family used when looking up host/hostnames. Default is 0', 39 | (val: string) => { 40 | const valN = Number(val); 41 | if (isNaN(valN)) throw new Error('Bad family'); 42 | return valN; 43 | }, 44 | process.env.IP_FAMILY ? Number(process.env.IP_FAMILY) : 0, 45 | ) 46 | .option( 47 | '-nbl, --no-block-local', 48 | 'When set, local IP addresses/DNS records are NOT blocked.', 49 | ) 50 | .option( 51 | '-m, --maintainer <{email?:string,website?:string}>', 52 | 'Inline maintainer data', 53 | ) 54 | .option( 55 | '-mf, --maintainer-file ', 56 | 'Path to a file containing the maintainer data', 57 | ) 58 | .action( 59 | async ({ 60 | directory, 61 | errors, 62 | host, 63 | port, 64 | localAddress, 65 | family, 66 | maintainer, 67 | maintainerFile, 68 | blockLocal, 69 | }: { 70 | directory: string; 71 | errors: boolean; 72 | host: string; 73 | port: number; 74 | localAddress?: string; 75 | family?: number; 76 | maintainer?: string; 77 | maintainerFile?: string; 78 | blockLocal?: boolean; 79 | }) => { 80 | const config: BareServerInit = { 81 | logErrors: errors, 82 | localAddress, 83 | family: family as IPFamily, 84 | blockLocal, 85 | maintainer: maintainer 86 | ? JSON.parse(maintainer) 87 | : maintainerFile 88 | ? JSON.parse(await readFile(maintainerFile, 'utf-8')) 89 | : undefined, 90 | }; 91 | const bareServer = createBareServer(directory, config); 92 | 93 | console.log('Error Logging:', errors); 94 | console.log( 95 | 'URL: ', 96 | `http://${host === '0.0.0.0' ? 'localhost' : host}${ 97 | port === 80 ? '' : `:${port}` 98 | }${directory}`, 99 | ); 100 | console.log('Maintainer: ', config.maintainer); 101 | 102 | const server = createServer(); 103 | 104 | server.on('request', (req, res) => { 105 | if (bareServer.shouldRoute(req)) { 106 | bareServer.routeRequest(req, res); 107 | } else { 108 | res.writeHead(400); 109 | res.end('Not found.'); 110 | } 111 | }); 112 | 113 | server.on('upgrade', (req, socket, head) => { 114 | if (bareServer.shouldRoute(req)) { 115 | bareServer.routeUpgrade(req, socket, head); 116 | } else { 117 | socket.end(); 118 | } 119 | }); 120 | 121 | server.listen({ 122 | host: host, 123 | port: port, 124 | }); 125 | 126 | exitHook(() => { 127 | bareServer.close(); 128 | server.close(); 129 | }); 130 | }, 131 | ); 132 | 133 | program.parse(process.argv); 134 | -------------------------------------------------------------------------------- /src/createServer.ts: -------------------------------------------------------------------------------- 1 | import { lookup } from 'node:dns'; 2 | import { Agent as HttpAgent } from 'node:http'; 3 | import { Agent as HttpsAgent } from 'node:https'; 4 | import { isValid, parse } from 'ipaddr.js'; 5 | import { WebSocketServer } from 'ws'; 6 | import BareServer from './BareServer.js'; 7 | import type { BareMaintainer, Options } from './BareServer.js'; 8 | import type { Database } from './Meta.js'; 9 | import { cleanupDatabase, JSONDatabaseAdapter } from './Meta.js'; 10 | import registerV1 from './V1.js'; 11 | import registerV2 from './V2.js'; 12 | import registerV3 from './V3.js'; 13 | 14 | export const validIPFamily: number[] = [0, 4, 6]; 15 | 16 | export type IPFamily = 0 | 4 | 6; 17 | 18 | export interface BareServerInit { 19 | logErrors?: boolean; 20 | localAddress?: string; 21 | /** 22 | * When set, the default logic for blocking local IP addresses is disabled. 23 | */ 24 | filterRemote?: Options['filterRemote']; 25 | /** 26 | * When set, the default logic for blocking local IP addresses is disabled. 27 | */ 28 | lookup?: Options['lookup']; 29 | /** 30 | * If local IP addresses/DNS records should be blocked. 31 | * @default true 32 | */ 33 | blockLocal?: boolean; 34 | /** 35 | * IP address family to use when resolving `host` or `hostname`. Valid values are `0`, `4`, and `6`. When unspecified/0, both IP v4 and v6 will be used. 36 | */ 37 | family?: IPFamily | number; 38 | maintainer?: BareMaintainer; 39 | httpAgent?: HttpAgent; 40 | httpsAgent?: HttpsAgent; 41 | /** 42 | * If legacy clients should be supported (v1 & v2). If this is set to false, the database can be safely ignored. 43 | * @default true 44 | */ 45 | legacySupport?: boolean; 46 | database?: Database; 47 | } 48 | 49 | export interface Address { 50 | address: string; 51 | family: number; 52 | } 53 | 54 | /** 55 | * Converts the address and family of a DNS lookup callback into an array if it wasn't already 56 | */ 57 | export function toAddressArray(address: string | Address[], family?: number) { 58 | if (typeof address === 'string') 59 | return [ 60 | { 61 | address, 62 | family, 63 | }, 64 | ] as Address[]; 65 | else return address; 66 | } 67 | 68 | /** 69 | * Create a Bare server. 70 | * This will handle all lifecycles for unspecified options (httpAgent, httpsAgent, metaMap). 71 | */ 72 | export function createBareServer(directory: string, init: BareServerInit = {}) { 73 | if (typeof directory !== 'string') 74 | throw new Error('Directory must be specified.'); 75 | if (!directory.startsWith('/') || !directory.endsWith('/')) 76 | throw new RangeError('Directory must start and end with /'); 77 | init.logErrors ??= false; 78 | 79 | const cleanup: (() => void)[] = []; 80 | 81 | if (typeof init.family === 'number' && !validIPFamily.includes(init.family)) 82 | throw new RangeError('init.family must be one of: 0, 4, 6'); 83 | 84 | if (init.blockLocal ?? true) { 85 | init.filterRemote ??= (url) => { 86 | // if the remote is an IP then it didn't go through the init.lookup hook 87 | // isValid determines if this is so 88 | if (isValid(url.hostname) && parse(url.hostname).range() !== 'unicast') 89 | throw new RangeError('Forbidden IP'); 90 | }; 91 | 92 | init.lookup ??= (hostname, options, callback) => 93 | lookup(hostname, options, (err, address, family) => { 94 | if ( 95 | address && 96 | toAddressArray(address, family).some( 97 | ({ address }) => parse(address).range() !== 'unicast', 98 | ) 99 | ) 100 | callback(new RangeError('Forbidden IP'), '', -1); 101 | else callback(err, address, family); 102 | }); 103 | } 104 | 105 | if (!init.httpAgent) { 106 | const httpAgent = new HttpAgent({ 107 | keepAlive: true, 108 | }); 109 | init.httpAgent = httpAgent; 110 | cleanup.push(() => httpAgent.destroy()); 111 | } 112 | 113 | if (!init.httpsAgent) { 114 | const httpsAgent = new HttpsAgent({ 115 | keepAlive: true, 116 | }); 117 | init.httpsAgent = httpsAgent; 118 | cleanup.push(() => httpsAgent.destroy()); 119 | } 120 | 121 | if (!init.database) { 122 | const database = new Map(); 123 | const interval = setInterval(() => cleanupDatabase(database), 1000); 124 | init.database = database; 125 | cleanup.push(() => clearInterval(interval)); 126 | } 127 | 128 | const server = new BareServer(directory, { 129 | ...(init as Required), 130 | database: new JSONDatabaseAdapter(init.database), 131 | wss: new WebSocketServer({ noServer: true }), 132 | }); 133 | 134 | init.legacySupport ??= true; 135 | 136 | if (init.legacySupport) { 137 | registerV1(server); 138 | registerV2(server); 139 | } 140 | 141 | registerV3(server); 142 | 143 | server.once('close', () => { 144 | for (const cb of cleanup) cb(); 145 | }); 146 | 147 | return server; 148 | } 149 | -------------------------------------------------------------------------------- /src/encodeProtocol.ts: -------------------------------------------------------------------------------- 1 | const validChars = 2 | "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"; 3 | const reserveChar = '%'; 4 | 5 | export function validProtocol(protocol: string): boolean { 6 | for (let i = 0; i < protocol.length; i++) { 7 | const char = protocol[i]; 8 | 9 | if (!validChars.includes(char)) { 10 | return false; 11 | } 12 | } 13 | 14 | return true; 15 | } 16 | 17 | export function encodeProtocol(protocol: string): string { 18 | let result = ''; 19 | 20 | for (let i = 0; i < protocol.length; i++) { 21 | const char = protocol[i]; 22 | 23 | if (validChars.includes(char) && char !== reserveChar) { 24 | result += char; 25 | } else { 26 | const code = char.charCodeAt(0); 27 | result += reserveChar + code.toString(16).padStart(2, '0'); 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | 34 | export function decodeProtocol(protocol: string): string { 35 | let result = ''; 36 | 37 | for (let i = 0; i < protocol.length; i++) { 38 | const char = protocol[i]; 39 | 40 | if (char === reserveChar) { 41 | const code = parseInt(protocol.slice(i + 1, i + 3), 16); 42 | const decoded = String.fromCharCode(code); 43 | 44 | result += decoded; 45 | i += 2; 46 | } else { 47 | result += char; 48 | } 49 | } 50 | 51 | return result; 52 | } 53 | -------------------------------------------------------------------------------- /src/env.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/consistent-type-imports */ 2 | 3 | // these global definitions are only needed to make Typescript work: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/60924 4 | // the `fetch` is already available as part of the Node.js Runtime >= 18.x which we use 5 | import { 6 | type FormData as FormDataType, 7 | type HeadersInit as HeadersInitType, 8 | type Headers as HeadersType, 9 | type Request as RequestType, 10 | type Response as ResponseType, 11 | } from 'undici'; 12 | 13 | declare global { 14 | // Re-export undici fetch function and various classes to global scope. 15 | // These are classes and functions expected to be at global scope according to Node.js v18 API 16 | // documentation. 17 | // See: https://nodejs.org/dist/latest-v18.x/docs/api/globals.html 18 | // eslint-disable-next-line no-var 19 | export var { 20 | FormData, 21 | Headers, 22 | Request, 23 | Response, 24 | fetch, 25 | }: typeof import('undici'); 26 | 27 | type FormData = FormDataType; 28 | type HeadersInit = HeadersInitType; 29 | type Headers = HeadersType; 30 | type Request = RequestType; 31 | type Response = ResponseType; 32 | } 33 | -------------------------------------------------------------------------------- /src/headerUtil.ts: -------------------------------------------------------------------------------- 1 | import type { BareHeaders } from './requestUtil.js'; 2 | 3 | export function objectFromRawHeaders(raw: string[]): BareHeaders { 4 | const result: BareHeaders = Object.create(null); 5 | 6 | for (let i = 0; i < raw.length; i += 2) { 7 | const [header, value] = raw.slice(i, i + 2); 8 | if (header in result) { 9 | const v = result[header]; 10 | if (Array.isArray(v)) v.push(value); 11 | else result[header] = [v, value]; 12 | } else result[header] = value; 13 | } 14 | 15 | return result; 16 | } 17 | 18 | export function rawHeaderNames(raw: string[]) { 19 | const result: string[] = []; 20 | 21 | for (let i = 0; i < raw.length; i += 2) { 22 | if (!result.includes(raw[i])) result.push(raw[i]); 23 | } 24 | 25 | return result; 26 | } 27 | 28 | export function mapHeadersFromArray(from: string[], to: BareHeaders) { 29 | for (const header of from) { 30 | if (header.toLowerCase() in to) { 31 | const value = to[header.toLowerCase()]; 32 | delete to[header.toLowerCase()]; 33 | to[header] = value; 34 | } 35 | } 36 | 37 | return to; 38 | } 39 | 40 | /** 41 | * Converts a header into an HTTP-ready comma joined header. 42 | */ 43 | export function flattenHeader(value: string | string[]) { 44 | return Array.isArray(value) ? value.join(', ') : value; 45 | } 46 | -------------------------------------------------------------------------------- /src/remoteUtil.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Utilities for converting remotes to URLs 3 | */ 4 | 5 | export interface BareRemote { 6 | host: string; 7 | port: number | string; 8 | path: string; 9 | protocol: string; 10 | } 11 | 12 | export function remoteToURL(remote: BareRemote) { 13 | return new URL( 14 | `${remote.protocol}${remote.host}:${remote.port}${remote.path}`, 15 | ); 16 | } 17 | 18 | export function resolvePort(url: URL) { 19 | if (url.port) return Number(url.port); 20 | 21 | switch (url.protocol) { 22 | case 'ws:': 23 | case 'http:': 24 | return 80; 25 | case 'wss:': 26 | case 'https:': 27 | return 443; 28 | default: 29 | // maybe blob 30 | return 0; 31 | } 32 | } 33 | 34 | export function urlToRemote(url: URL) { 35 | return { 36 | protocol: url.protocol, 37 | host: url.hostname, 38 | port: resolvePort(url), 39 | path: url.pathname + url.search, 40 | } as BareRemote; 41 | } 42 | -------------------------------------------------------------------------------- /src/requestUtil.ts: -------------------------------------------------------------------------------- 1 | import { getRandomValues } from 'node:crypto'; 2 | import type { ClientRequest, IncomingMessage, RequestOptions } from 'node:http'; 3 | import { request as httpRequest } from 'node:http'; 4 | import { request as httpsRequest } from 'node:https'; 5 | import { Readable, type Duplex } from 'node:stream'; 6 | import type { ErrorEvent } from 'ws'; 7 | import WebSocket from 'ws'; 8 | import { BareError } from './BareServer.js'; 9 | import type { BareRequest, Options } from './BareServer.js'; 10 | 11 | export type BareHeaders = Record; 12 | 13 | export const nullMethod = ['GET', 'HEAD']; 14 | export const nullBodyStatus = [101, 204, 205, 304]; 15 | 16 | export function randomHex(byteLength: number) { 17 | const bytes = new Uint8Array(byteLength); 18 | getRandomValues(bytes); 19 | let hex = ''; 20 | for (const byte of bytes) hex += byte.toString(16).padStart(2, '0'); 21 | return hex; 22 | } 23 | 24 | function outgoingError(error: T): T | BareError { 25 | if (error instanceof Error) { 26 | switch ((error).code) { 27 | case 'ENOTFOUND': 28 | return new BareError(500, { 29 | code: 'HOST_NOT_FOUND', 30 | id: 'request', 31 | message: 'The specified host could not be resolved.', 32 | }); 33 | case 'ECONNREFUSED': 34 | return new BareError(500, { 35 | code: 'CONNECTION_REFUSED', 36 | id: 'response', 37 | message: 'The remote rejected the request.', 38 | }); 39 | case 'ECONNRESET': 40 | return new BareError(500, { 41 | code: 'CONNECTION_RESET', 42 | id: 'response', 43 | message: 'The request was forcibly closed.', 44 | }); 45 | case 'ETIMEOUT': 46 | return new BareError(500, { 47 | code: 'CONNECTION_TIMEOUT', 48 | id: 'response', 49 | message: 'The response timed out.', 50 | }); 51 | } 52 | } 53 | 54 | return error; 55 | } 56 | 57 | export async function bareFetch( 58 | request: BareRequest, 59 | signal: AbortSignal, 60 | requestHeaders: BareHeaders, 61 | remote: URL, 62 | options: Options, 63 | ): Promise { 64 | if (options.filterRemote) await options.filterRemote(remote); 65 | 66 | const req: RequestOptions = { 67 | method: request.method, 68 | headers: requestHeaders, 69 | setHost: false, 70 | signal, 71 | localAddress: options.localAddress, 72 | family: options.family, 73 | lookup: options.lookup, 74 | }; 75 | 76 | let outgoing: ClientRequest; 77 | 78 | // NodeJS will convert the URL into HTTP options automatically 79 | // see https://github.com/nodejs/node/blob/e30e71665cab94118833cc536a43750703b19633/lib/internal/url.js#L1277 80 | 81 | if (remote.protocol === 'https:') 82 | outgoing = httpsRequest(remote, { 83 | ...req, 84 | agent: options.httpsAgent, 85 | }); 86 | else if (remote.protocol === 'http:') 87 | outgoing = httpRequest(remote, { 88 | ...req, 89 | agent: options.httpAgent, 90 | }); 91 | else throw new RangeError(`Unsupported protocol: '${remote.protocol}'`); 92 | 93 | if (request.body) Readable.fromWeb(request.body).pipe(outgoing); 94 | else outgoing.end(); 95 | 96 | return await new Promise((resolve, reject) => { 97 | outgoing.on('response', (response: IncomingMessage) => { 98 | resolve(response); 99 | }); 100 | 101 | outgoing.on('upgrade', (req, socket) => { 102 | reject('Remote did not send a response'); 103 | socket.destroy(); 104 | }); 105 | 106 | outgoing.on('error', (error: Error) => { 107 | reject(outgoingError(error)); 108 | }); 109 | }); 110 | } 111 | 112 | export async function bareUpgradeFetch( 113 | request: BareRequest, 114 | signal: AbortSignal, 115 | requestHeaders: BareHeaders, 116 | remote: URL, 117 | options: Options, 118 | ): Promise<[res: IncomingMessage, socket: Duplex, head: Buffer]> { 119 | if (options.filterRemote) await options.filterRemote(remote); 120 | 121 | const req: RequestOptions = { 122 | headers: requestHeaders, 123 | method: request.method, 124 | timeout: 12e3, 125 | setHost: false, 126 | signal, 127 | localAddress: options.localAddress, 128 | family: options.family, 129 | lookup: options.lookup, 130 | }; 131 | 132 | let outgoing: ClientRequest; 133 | 134 | // NodeJS will convert the URL into HTTP options automatically 135 | // see https://github.com/nodejs/node/blob/e30e71665cab94118833cc536a43750703b19633/lib/internal/url.js#L1277 136 | 137 | // calling .replace on remote may look like it replaces other occurrences of wss:, but it only replaces the first which is remote.protocol 138 | 139 | if (remote.protocol === 'wss:') 140 | outgoing = httpsRequest(remote.toString().replace('wss:', 'https:'), { 141 | ...req, 142 | agent: options.httpsAgent, 143 | }); 144 | else if (remote.protocol === 'ws:') 145 | outgoing = httpRequest(remote.toString().replace('ws:', 'http:'), { 146 | ...req, 147 | agent: options.httpAgent, 148 | }); 149 | else throw new RangeError(`Unsupported protocol: '${remote.protocol}'`); 150 | 151 | outgoing.end(); 152 | 153 | return await new Promise((resolve, reject) => { 154 | outgoing.on('response', (res) => { 155 | reject(new Error('Remote did not upgrade the WebSocket')); 156 | res.destroy(); 157 | }); 158 | 159 | outgoing.on('upgrade', (res, socket, head) => { 160 | resolve([res, socket, head]); 161 | }); 162 | 163 | outgoing.on('error', (error) => { 164 | reject(outgoingError(error)); 165 | }); 166 | }); 167 | } 168 | 169 | export async function webSocketFetch( 170 | request: BareRequest, 171 | requestHeaders: BareHeaders, 172 | remote: URL, 173 | protocols: string[], 174 | options: Options, 175 | ): Promise<[req: IncomingMessage, socket: WebSocket]> { 176 | if (options.filterRemote) await options.filterRemote(remote); 177 | 178 | const req = { 179 | headers: requestHeaders, 180 | method: request.method, 181 | timeout: 12e3, 182 | setHost: false, 183 | localAddress: options.localAddress, 184 | family: options.family, 185 | lookup: options.lookup, 186 | }; 187 | 188 | let outgoing: WebSocket; 189 | 190 | if (remote.protocol === 'wss:') 191 | outgoing = new WebSocket(remote, protocols, { 192 | ...req, 193 | agent: options.httpsAgent, 194 | }); 195 | else if (remote.protocol === 'ws:') 196 | outgoing = new WebSocket(remote, protocols, { 197 | ...req, 198 | agent: options.httpAgent, 199 | }); 200 | else throw new RangeError(`Unsupported protocol: '${remote.protocol}'`); 201 | 202 | return await new Promise((resolve, reject) => { 203 | let request: IncomingMessage | undefined; 204 | 205 | const cleanup = () => { 206 | outgoing.removeEventListener('open', openListener); 207 | outgoing.removeEventListener('open', openListener); 208 | }; 209 | 210 | outgoing.on('upgrade', (req) => { 211 | request = req; 212 | }); 213 | 214 | const openListener = () => { 215 | cleanup(); 216 | resolve([request!, outgoing]); 217 | }; 218 | 219 | const errorListener = (event: ErrorEvent) => { 220 | cleanup(); 221 | reject(outgoingError(event.error)); 222 | }; 223 | 224 | outgoing.addEventListener('open', openListener); 225 | outgoing.addEventListener('error', errorListener); 226 | }); 227 | } 228 | -------------------------------------------------------------------------------- /src/splitHeaderUtil.ts: -------------------------------------------------------------------------------- 1 | import { BareError } from './BareServer.js'; 2 | 3 | const MAX_HEADER_VALUE = 3072; 4 | 5 | /** 6 | * 7 | * Splits headers according to spec 8 | * @param headers 9 | * @returns Split headers 10 | */ 11 | export function splitHeaders(headers: Headers): Headers { 12 | const output = new Headers(headers); 13 | 14 | if (headers.has('x-bare-headers')) { 15 | const value = headers.get('x-bare-headers')!; 16 | 17 | if (value.length > MAX_HEADER_VALUE) { 18 | output.delete('x-bare-headers'); 19 | 20 | let split = 0; 21 | 22 | for (let i = 0; i < value.length; i += MAX_HEADER_VALUE) { 23 | const part = value.slice(i, i + MAX_HEADER_VALUE); 24 | 25 | const id = split++; 26 | output.set(`x-bare-headers-${id}`, `;${part}`); 27 | } 28 | } 29 | } 30 | 31 | return output; 32 | } 33 | 34 | /** 35 | * Joins headers according to spec 36 | * @param headers 37 | * @returns Joined headers 38 | */ 39 | export function joinHeaders(headers: Headers): Headers { 40 | const output = new Headers(headers); 41 | 42 | const prefix = 'x-bare-headers'; 43 | 44 | if (headers.has(`${prefix}-0`)) { 45 | const join: string[] = []; 46 | 47 | for (const [header, value] of headers) { 48 | if (!header.startsWith(prefix)) { 49 | continue; 50 | } 51 | 52 | if (!value.startsWith(';')) { 53 | throw new BareError(400, { 54 | code: 'INVALID_BARE_HEADER', 55 | id: `request.headers.${header}`, 56 | message: `Value didn't begin with semi-colon.`, 57 | }); 58 | } 59 | 60 | const id = parseInt(header.slice(prefix.length + 1)); 61 | 62 | join[id] = value.slice(1); 63 | 64 | output.delete(header); 65 | } 66 | 67 | output.set(prefix, join.join('')); 68 | } 69 | 70 | return output; 71 | } 72 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "dist", 4 | "lib": ["ESNext"], 5 | "target": "ESNext", 6 | "module": "Node16", 7 | "moduleResolution": "Node16", 8 | "strict": true, 9 | "stripInternal": true, 10 | "esModuleInterop": true, 11 | "declaration": true, 12 | "sourceMap": true, 13 | "resolveJsonModule": false 14 | }, 15 | "include": ["src"] 16 | } 17 | --------------------------------------------------------------------------------