├── .gitignore ├── .prettierrc ├── LICENSE.txt ├── README.md ├── banner.svg ├── example.js ├── lerna.json ├── package.json ├── packages ├── data │ ├── README.md │ ├── package.json │ ├── src │ │ ├── assertions.test.ts │ │ ├── assertions.ts │ │ ├── enums.ts │ │ ├── index.ts │ │ ├── matchmaking.test.ts │ │ ├── matchmaking.ts │ │ ├── pretty-enums.ts │ │ └── types.ts │ └── tsconfig.build.json ├── hazel │ ├── README.md │ ├── package.json │ ├── src │ │ ├── index.ts │ │ └── udp.ts │ └── tsconfig.build.json ├── packets │ ├── README.md │ ├── package.json │ ├── src │ │ ├── game-data.ts │ │ ├── game-options.ts │ │ ├── generator.ts │ │ ├── index.ts │ │ └── parser.ts │ └── tsconfig.build.json ├── sus │ ├── README.md │ ├── package.json │ ├── src │ │ ├── among-us.ts │ │ └── index.ts │ └── tsconfig.build.json └── util │ ├── README.md │ ├── package.json │ ├── src │ ├── codes.test.ts │ ├── codes.ts │ ├── index.ts │ ├── manipulation.test.ts │ ├── manipulation.ts │ ├── vector.test.ts │ └── vector.ts │ └── tsconfig.build.json ├── tsconfig.build.json ├── tsconfig.json ├── typedoc.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # Snowpack dependency directory (https://snowpack.dev/) 45 | web_modules/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | .parcel-cache 78 | 79 | # Next.js build output 80 | .next 81 | out 82 | 83 | # Nuxt.js build / generate output 84 | .nuxt 85 | dist 86 | 87 | # Gatsby files 88 | .cache/ 89 | # Comment in the public line in if your project uses Gatsby and not Next.js 90 | # https://nextjs.org/blog/next-9-1#public-directory-support 91 | # public 92 | 93 | # vuepress build output 94 | .vuepress/dist 95 | 96 | # Serverless directories 97 | .serverless/ 98 | 99 | # FuseBox cache 100 | .fusebox/ 101 | 102 | # DynamoDB Local files 103 | .dynamodb/ 104 | 105 | # TernJS port file 106 | .tern-port 107 | 108 | # Stores VSCode versions used for testing VSCode extensions 109 | .vscode-test 110 | 111 | # yarn v2 112 | .yarn/cache 113 | .yarn/unplugged 114 | .yarn/build-state.yml 115 | .yarn/install-state.gz 116 | .pnp.* 117 | 118 | docs 119 | .vercel 120 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "none", 3 | "singleQuote": true, 4 | "semi": false 5 | } -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Developers that use our General Public Licenses protect your rights 3 | with two steps: (1) assert copyright on the software, and (2) offer 4 | you this License which gives you legal permission to copy, distribute 5 | and/or modify the software. 6 | 7 | A secondary benefit of defending all users' freedom is that 8 | improvements made in alternate versions of the program, if they 9 | receive widespread use, become available for other developers to 10 | incorporate. Many developers of free software are heartened and 11 | encouraged by the resulting cooperation. However, in the case of 12 | software used on network servers, this result may fail to come about. 13 | The GNU General Public License permits making a modified version and 14 | letting the public access it on a server without ever releasing its 15 | source code to the public. 16 | 17 | The GNU Affero General Public License is designed specifically to 18 | ensure that, in such cases, the modified source code becomes available 19 | to the community. It requires the operator of a network server to 20 | provide the source code of the modified version running there to the 21 | users of that server. Therefore, public use of a modified version, on 22 | a publicly accessible server, gives the public access to the source 23 | code of the modified version. 24 | 25 | An older license, called the Affero General Public License and 26 | published by Affero, was designed to accomplish similar goals. This is 27 | a different license, not a version of the Affero GPL, but Affero has 28 | released a new version of the Affero GPL which permits relicensing under 29 | this license. 30 | 31 | The precise terms and conditions for copying, distribution and 32 | modification follow. 33 | 34 | TERMS AND CONDITIONS 35 | 36 | 0. Definitions. 37 | 38 | "This License" refers to version 3 of the GNU Affero General Public License. 39 | 40 | "Copyright" also means copyright-like laws that apply to other kinds of 41 | works, such as semiconductor masks. 42 | 43 | "The Program" refers to any copyrightable work licensed under this 44 | License. Each licensee is addressed as "you". "Licensees" and 45 | "recipients" may be individuals or organizations. 46 | 47 | To "modify" a work means to copy from or adapt all or part of the work 48 | in a fashion requiring copyright permission, other than the making of an 49 | exact copy. The resulting work is called a "modified version" of the 50 | earlier work or a work "based on" the earlier work. 51 | 52 | A "covered work" means either the unmodified Program or a work based 53 | on the Program. 54 | 55 | To "propagate" a work means to do anything with it that, without 56 | permission, would make you directly or secondarily liable for 57 | infringement under applicable copyright law, except executing it on a 58 | computer or modifying a private copy. Propagation includes copying, 59 | distribution (with or without modification), making available to the 60 | public, and in some countries other activities as well. 61 | 62 | To "convey" a work means any kind of propagation that enables other 63 | parties to make or receive copies. Mere interaction with a user through 64 | a computer network, with no transfer of a copy, is not conveying. 65 | 66 | An interactive user interface displays "Appropriate Legal Notices" 67 | to the extent that it includes a convenient and prominently visible 68 | feature that (1) displays an appropriate copyright notice, and (2) 69 | tells the user that there is no warranty for the work (except to the 70 | extent that warranties are provided), that licensees may convey the 71 | work under this License, and how to view a copy of this License. If 72 | the interface presents a list of user commands or options, such as a 73 | menu, a prominent item in the list meets this criterion. 74 | 75 | 1. Source Code. 76 | 77 | The "source code" for a work means the preferred form of the work 78 | for making modifications to it. "Object code" means any non-source 79 | form of a work. 80 | 81 | A "Standard Interface" means an interface that either is an official 82 | standard defined by a recognized standards body, or, in the case of 83 | interfaces specified for a particular programming language, one that 84 | is widely used among developers working in that language. 85 | 86 | The "System Libraries" of an executable work include anything, other 87 | than the work as a whole, that (a) is included in the normal form of 88 | packaging a Major Component, but which is not part of that Major 89 | Component, and (b) serves only to enable use of the work with that 90 | Major Component, or to implement a Standard Interface for which an 91 | implementation is available to the public in source code form. A 92 | "Major Component", in this context, means a major essential component 93 | (kernel, window system, and so on) of the specific operating system 94 | (if any) on which the executable work runs, or a compiler used to 95 | produce the work, or an object code interpreter used to run it. 96 | 97 | The "Corresponding Source" for a work in object code form means all 98 | the source code needed to generate, install, and (for an executable 99 | work) run the object code and to modify the work, including scripts to 100 | control those activities. However, it does not include the work's 101 | System Libraries, or general-purpose tools or generally available free 102 | programs which are used unmodified in performing those activities but 103 | which are not part of the work. For example, Corresponding Source 104 | includes interface definition files associated with source files for 105 | the work, and the source code for shared libraries and dynamically 106 | linked subprograms that the work is specifically designed to require, 107 | such as by intimate data communication or control flow between those 108 | subprograms and other parts of the work. 109 | 110 | The Corresponding Source need not include anything that users 111 | can regenerate automatically from other parts of the Corresponding 112 | Source. 113 | 114 | The Corresponding Source for a work in source code form is that 115 | same work. 116 | 117 | 2. Basic Permissions. 118 | 119 | All rights granted under this License are granted for the term of 120 | copyright on the Program, and are irrevocable provided the stated 121 | conditions are met. This License explicitly affirms your unlimited 122 | permission to run the unmodified Program. The output from running a 123 | covered work is covered by this License only if the output, given its 124 | content, constitutes a covered work. This License acknowledges your 125 | rights of fair use or other equivalent, as provided by copyright law. 126 | 127 | You may make, run and propagate covered works that you do not 128 | convey, without conditions so long as your license otherwise remains 129 | in force. You may convey covered works to others for the sole purpose 130 | of having them make modifications exclusively for you, or provide you 131 | with facilities for running those works, provided that you comply with 132 | the terms of this License in conveying all material for which you do 133 | not control copyright. Those thus making or running the covered works 134 | for you must do so exclusively on your behalf, under your direction 135 | and control, on terms that prohibit them from making any copies of 136 | your copyrighted material outside their relationship with you. 137 | 138 | Conveying under any other circumstances is permitted solely under 139 | the conditions stated below. Sublicensing is not allowed; section 10 140 | makes it unnecessary. 141 | 142 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 143 | 144 | No covered work shall be deemed part of an effective technological 145 | measure under any applicable law fulfilling obligations under article 146 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 147 | similar laws prohibiting or restricting circumvention of such 148 | measures. 149 | 150 | When you convey a covered work, you waive any legal power to forbid 151 | circumvention of technological measures to the extent such circumvention 152 | is effected by exercising rights under this License with respect to 153 | the covered work, and you disclaim any intention to limit operation or 154 | modification of the work as a means of enforcing, against the work's 155 | users, your or third parties' legal rights to forbid circumvention of 156 | technological measures. 157 | 158 | 4. Conveying Verbatim Copies. 159 | 160 | You may convey verbatim copies of the Program's source code as you 161 | receive it, in any medium, provided that you conspicuously and 162 | appropriately publish on each copy an appropriate copyright notice; 163 | keep intact all notices stating that this License and any 164 | non-permissive terms added in accord with section 7 apply to the code; 165 | keep intact all notices of the absence of any warranty; and give all 166 | recipients a copy of this License along with the Program. 167 | 168 | You may charge any price or no price for each copy that you convey, 169 | and you may offer support or warranty protection for a fee. 170 | 171 | 5. Conveying Modified Source Versions. 172 | 173 | You may convey a work based on the Program, or the modifications to 174 | produce it from the Program, in the form of source code under the 175 | terms of section 4, provided that you also meet all of these conditions: 176 | 177 | a) The work must carry prominent notices stating that you modified 178 | it, and giving a relevant date. 179 | 180 | b) The work must carry prominent notices stating that it is 181 | released under this License and any conditions added under section 182 | 7. This requirement modifies the requirement in section 4 to 183 | "keep intact all notices". 184 | 185 | c) You must license the entire work, as a whole, under this 186 | License to anyone who comes into possession of a copy. This 187 | License will therefore apply, along with any applicable section 7 188 | additional terms, to the whole of the work, and all its parts, 189 | regardless of how they are packaged. This License gives no 190 | permission to license the work in any other way, but it does not 191 | invalidate such permission if you have separately received it. 192 | 193 | d) If the work has interactive user interfaces, each must display 194 | Appropriate Legal Notices; however, if the Program has interactive 195 | interfaces that do not display Appropriate Legal Notices, your 196 | work need not make them do so. 197 | 198 | A compilation of a covered work with other separate and independent 199 | works, which are not by their nature extensions of the covered work, 200 | and which are not combined with it such as to form a larger program, 201 | in or on a volume of a storage or distribution medium, is called an 202 | "aggregate" if the compilation and its resulting copyright are not 203 | used to limit the access or legal rights of the compilation's users 204 | beyond what the individual works permit. Inclusion of a covered work 205 | in an aggregate does not cause this License to apply to the other 206 | parts of the aggregate. 207 | 208 | 6. Conveying Non-Source Forms. 209 | 210 | You may convey a covered work in object code form under the terms 211 | of sections 4 and 5, provided that you also convey the 212 | machine-readable Corresponding Source under the terms of this License, 213 | in one of these ways: 214 | 215 | a) Convey the object code in, or embodied in, a physical product 216 | (including a physical distribution medium), accompanied by the 217 | Corresponding Source fixed on a durable physical medium 218 | customarily used for software interchange. 219 | 220 | b) Convey the object code in, or embodied in, a physical product 221 | (including a physical distribution medium), accompanied by a 222 | written offer, valid for at least three years and valid for as 223 | long as you offer spare parts or customer support for that product 224 | model, to give anyone who possesses the object code either (1) a 225 | copy of the Corresponding Source for all the software in the 226 | product that is covered by this License, on a durable physical 227 | medium customarily used for software interchange, for a price no 228 | more than your reasonable cost of physically performing this 229 | conveying of source, or (2) access to copy the 230 | Corresponding Source from a network server at no charge. 231 | 232 | c) Convey individual copies of the object code with a copy of the 233 | written offer to provide the Corresponding Source. This 234 | alternative is allowed only occasionally and noncommercially, and 235 | only if you received the object code with such an offer, in accord 236 | with subsection 6b. 237 | 238 | d) Convey the object code by offering access from a designated 239 | place (gratis or for a charge), and offer equivalent access to the 240 | Corresponding Source in the same way through the same place at no 241 | further charge. You need not require recipients to copy the 242 | Corresponding Source along with the object code. If the place to 243 | copy the object code is a network server, the Corresponding Source 244 | may be on a different server (operated by you or a third party) 245 | that supports equivalent copying facilities, provided you maintain 246 | clear directions next to the object code saying where to find the 247 | Corresponding Source. Regardless of what server hosts the 248 | Corresponding Source, you remain obligated to ensure that it is 249 | available for as long as needed to satisfy these requirements. 250 | 251 | e) Convey the object code using peer-to-peer transmission, provided 252 | you inform other peers where the object code and Corresponding 253 | Source of the work are being offered to the general public at no 254 | charge under subsection 6d. 255 | 256 | A separable portion of the object code, whose source code is excluded 257 | from the Corresponding Source as a System Library, need not be 258 | included in conveying the object code work. 259 | 260 | A "User Product" is either (1) a "consumer product", which means any 261 | tangible personal property which is normally used for personal, family, 262 | or household purposes, or (2) anything designed or sold for incorporation 263 | into a dwelling. In determining whether a product is a consumer product, 264 | doubtful cases shall be resolved in favor of coverage. For a particular 265 | product received by a particular user, "normally used" refers to a 266 | typical or common use of that class of product, regardless of the status 267 | of the particular user or of the way in which the particular user 268 | actually uses, or expects or is expected to use, the product. A product 269 | is a consumer product regardless of whether the product has substantial 270 | commercial, industrial or non-consumer uses, unless such uses represent 271 | the only significant mode of use of the product. 272 | 273 | "Installation Information" for a User Product means any methods, 274 | procedures, authorization keys, or other information required to install 275 | and execute modified versions of a covered work in that User Product from 276 | a modified version of its Corresponding Source. The information must 277 | suffice to ensure that the continued functioning of the modified object 278 | code is in no case prevented or interfered with solely because 279 | modification has been made. 280 | 281 | If you convey an object code work under this section in, or with, or 282 | specifically for use in, a User Product, and the conveying occurs as 283 | part of a transaction in which the right of possession and use of the 284 | User Product is transferred to the recipient in perpetuity or for a 285 | fixed term (regardless of how the transaction is characterized), the 286 | Corresponding Source conveyed under this section must be accompanied 287 | by the Installation Information. But this requirement does not apply 288 | if neither you nor any third party retains the ability to install 289 | modified object code on the User Product (for example, the work has 290 | been installed in ROM). 291 | 292 | The requirement to provide Installation Information does not include a 293 | requirement to continue to provide support service, warranty, or updates 294 | for a work that has been modified or installed by the recipient, or for 295 | the User Product in which it has been modified or installed. Access to a 296 | network may be denied when the modification itself materially and 297 | adversely affects the operation of the network or violates the rules and 298 | protocols for communication across the network. 299 | 300 | Corresponding Source conveyed, and Installation Information provided, 301 | in accord with this section must be in a format that is publicly 302 | documented (and with an implementation available to the public in 303 | source code form), and must require no special password or key for 304 | unpacking, reading or copying. 305 | 306 | 7. Additional Terms. 307 | 308 | "Additional permissions" are terms that supplement the terms of this 309 | License by making exceptions from one or more of its conditions. 310 | Additional permissions that are applicable to the entire Program shall 311 | be treated as though they were included in this License, to the extent 312 | that they are valid under applicable law. If additional permissions 313 | apply only to part of the Program, that part may be used separately 314 | under those permissions, but the entire Program remains governed by 315 | this License without regard to the additional permissions. 316 | 317 | When you convey a copy of a covered work, you may at your option 318 | remove any additional permissions from that copy, or from any part of 319 | it. (Additional permissions may be written to require their own 320 | removal in certain cases when you modify the work.) You may place 321 | additional permissions on material, added by you to a covered work, 322 | for which you have or can give appropriate copyright permission. 323 | 324 | Notwithstanding any other provision of this License, for material you 325 | add to a covered work, you may (if authorized by the copyright holders of 326 | that material) supplement the terms of this License with terms: 327 | 328 | a) Disclaiming warranty or limiting liability differently from the 329 | terms of sections 15 and 16 of this License; or 330 | 331 | b) Requiring preservation of specified reasonable legal notices or 332 | author attributions in that material or in the Appropriate Legal 333 | Notices displayed by works containing it; or 334 | 335 | c) Prohibiting misrepresentation of the origin of that material, or 336 | requiring that modified versions of such material be marked in 337 | reasonable ways as different from the original version; or 338 | 339 | d) Limiting the use for publicity purposes of names of licensors or 340 | authors of the material; or 341 | 342 | e) Declining to grant rights under trademark law for use of some 343 | trade names, trademarks, or service marks; or 344 | 345 | f) Requiring indemnification of licensors and authors of that 346 | material by anyone who conveys the material (or modified versions of 347 | it) with contractual assumptions of liability to the recipient, for 348 | any liability that these contractual assumptions directly impose on 349 | those licensors and authors. 350 | 351 | All other non-permissive additional terms are considered "further 352 | restrictions" within the meaning of section 10. If the Program as you 353 | received it, or any part of it, contains a notice stating that it is 354 | governed by this License along with a term that is a further 355 | restriction, you may remove that term. If a license document contains 356 | a further restriction but permits relicensing or conveying under this 357 | License, you may add to a covered work material governed by the terms 358 | of that license document, provided that the further restriction does 359 | not survive such relicensing or conveying. 360 | 361 | If you add terms to a covered work in accord with this section, you 362 | must place, in the relevant source files, a statement of the 363 | additional terms that apply to those files, or a notice indicating 364 | where to find the applicable terms. 365 | 366 | Additional terms, permissive or non-permissive, may be stated in the 367 | form of a separately written license, or stated as exceptions; 368 | the above requirements apply either way. 369 | 370 | 8. Termination. 371 | 372 | You may not propagate or modify a covered work except as expressly 373 | provided under this License. Any attempt otherwise to propagate or 374 | modify it is void, and will automatically terminate your rights under 375 | this License (including any patent licenses granted under the third 376 | paragraph of section 11). 377 | 378 | However, if you cease all violation of this License, then your 379 | license from a particular copyright holder is reinstated (a) 380 | provisionally, unless and until the copyright holder explicitly and 381 | finally terminates your license, and (b) permanently, if the copyright 382 | holder fails to notify you of the violation by some reasonable means 383 | prior to 60 days after the cessation. 384 | 385 | Moreover, your license from a particular copyright holder is 386 | reinstated permanently if the copyright holder notifies you of the 387 | violation by some reasonable means, this is the first time you have 388 | received notice of violation of this License (for any work) from that 389 | copyright holder, and you cure the violation prior to 30 days after 390 | your receipt of the notice. 391 | 392 | Termination of your rights under this section does not terminate the 393 | licenses of parties who have received copies or rights from you under 394 | this License. If your rights have been terminated and not permanently 395 | reinstated, you do not qualify to receive new licenses for the same 396 | material under section 10. 397 | 398 | 9. Acceptance Not Required for Having Copies. 399 | 400 | You are not required to accept this License in order to receive or 401 | run a copy of the Program. Ancillary propagation of a covered work 402 | occurring solely as a consequence of using peer-to-peer transmission 403 | to receive a copy likewise does not require acceptance. However, 404 | nothing other than this License grants you permission to propagate or 405 | modify any covered work. These actions infringe copyright if you do 406 | not accept this License. Therefore, by modifying or propagating a 407 | covered work, you indicate your acceptance of this License to do so. 408 | 409 | 10. Automatic Licensing of Downstream Recipients. 410 | 411 | Each time you convey a covered work, the recipient automatically 412 | receives a license from the original licensors, to run, modify and 413 | propagate that work, subject to this License. You are not responsible 414 | for enforcing compliance by third parties with this License. 415 | 416 | An "entity transaction" is a transaction transferring control of an 417 | organization, or substantially all assets of one, or subdividing an 418 | organization, or merging organizations. If propagation of a covered 419 | work results from an entity transaction, each party to that 420 | transaction who receives a copy of the work also receives whatever 421 | licenses to the work the party's predecessor in interest had or could 422 | give under the previous paragraph, plus a right to possession of the 423 | Corresponding Source of the work from the predecessor in interest, if 424 | the predecessor has it or can get it with reasonable efforts. 425 | 426 | You may not impose any further restrictions on the exercise of the 427 | rights granted or affirmed under this License. For example, you may 428 | not impose a license fee, royalty, or other charge for exercise of 429 | rights granted under this License, and you may not initiate litigation 430 | (including a cross-claim or counterclaim in a lawsuit) alleging that 431 | any patent claim is infringed by making, using, selling, offering for 432 | sale, or importing the Program or any portion of it. 433 | 434 | 11. Patents. 435 | 436 | A "contributor" is a copyright holder who authorizes use under this 437 | License of the Program or a work on which the Program is based. The 438 | work thus licensed is called the contributor's "contributor version". 439 | 440 | A contributor's "essential patent claims" are all patent claims 441 | owned or controlled by the contributor, whether already acquired or 442 | hereafter acquired, that would be infringed by some manner, permitted 443 | by this License, of making, using, or selling its contributor version, 444 | but do not include claims that would be infringed only as a 445 | consequence of further modification of the contributor version. For 446 | purposes of this definition, "control" includes the right to grant 447 | patent sublicenses in a manner consistent with the requirements of 448 | this License. 449 | 450 | Each contributor grants you a non-exclusive, worldwide, royalty-free 451 | patent license under the contributor's essential patent claims, to 452 | make, use, sell, offer for sale, import and otherwise run, modify and 453 | propagate the contents of its contributor version. 454 | 455 | In the following three paragraphs, a "patent license" is any express 456 | agreement or commitment, however denominated, not to enforce a patent 457 | (such as an express permission to practice a patent or covenant not to 458 | sue for patent infringement). To "grant" such a patent license to a 459 | party means to make such an agreement or commitment not to enforce a 460 | patent against the party. 461 | 462 | If you convey a covered work, knowingly relying on a patent license, 463 | and the Corresponding Source of the work is not available for anyone 464 | to copy, free of charge and under the terms of this License, through a 465 | publicly available network server or other readily accessible means, 466 | then you must either (1) cause the Corresponding Source to be so 467 | available, or (2) arrange to deprive yourself of the benefit of the 468 | patent license for this particular work, or (3) arrange, in a manner 469 | consistent with the requirements of this License, to extend the patent 470 | license to downstream recipients. "Knowingly relying" means you have 471 | actual knowledge that, but for the patent license, your conveying the 472 | covered work in a country, or your recipient's use of the covered work 473 | in a country, would infringe one or more identifiable patents in that 474 | country that you have reason to believe are valid. 475 | 476 | If, pursuant to or in connection with a single transaction or 477 | arrangement, you convey, or propagate by procuring conveyance of, a 478 | covered work, and grant a patent license to some of the parties 479 | receiving the covered work authorizing them to use, propagate, modify 480 | or convey a specific copy of the covered work, then the patent license 481 | you grant is automatically extended to all recipients of the covered 482 | work and works based on it. 483 | 484 | A patent license is "discriminatory" if it does not include within 485 | the scope of its coverage, prohibits the exercise of, or is 486 | conditioned on the non-exercise of one or more of the rights that are 487 | specifically granted under this License. You may not convey a covered 488 | work if you are a party to an arrangement with a third party that is 489 | in the business of distributing software, under which you make payment 490 | to the third party based on the extent of your activity of conveying 491 | the work, and under which the third party grants, to any of the 492 | parties who would receive the covered work from you, a discriminatory 493 | patent license (a) in connection with copies of the covered work 494 | conveyed by you (or copies made from those copies), or (b) primarily 495 | for and in connection with specific products or compilations that 496 | contain the covered work, unless you entered into that arrangement, 497 | or that patent license was granted, prior to 28 March 2007. 498 | 499 | Nothing in this License shall be construed as excluding or limiting 500 | any implied license or other defenses to infringement that may 501 | otherwise be available to you under applicable patent law. 502 | 503 | 12. No Surrender of Others' Freedom. 504 | 505 | If conditions are imposed on you (whether by court order, agreement or 506 | otherwise) that contradict the conditions of this License, they do not 507 | excuse you from the conditions of this License. If you cannot convey a 508 | covered work so as to satisfy simultaneously your obligations under this 509 | License and any other pertinent obligations, then as a consequence you may 510 | not convey it at all. For example, if you agree to terms that obligate you 511 | to collect a royalty for further conveying from those to whom you convey 512 | the Program, the only way you could satisfy both those terms and this 513 | License would be to refrain entirely from conveying the Program. 514 | 515 | 13. Remote Network Interaction; Use with the GNU General Public License. 516 | 517 | Notwithstanding any other provision of this License, if you modify the 518 | Program, your modified version must prominently offer all users 519 | interacting with it remotely through a computer network (if your version 520 | supports such interaction) an opportunity to receive the Corresponding 521 | Source of your version by providing access to the Corresponding Source 522 | from a network server at no charge, through some standard or customary 523 | means of facilitating copying of software. This Corresponding Source 524 | shall include the Corresponding Source for any work covered by version 3 525 | of the GNU General Public License that is incorporated pursuant to the 526 | following paragraph. 527 | 528 | Notwithstanding any other provision of this License, you have 529 | permission to link or combine any covered work with a work licensed 530 | under version 3 of the GNU General Public License into a single 531 | combined work, and to convey the resulting work. The terms of this 532 | License will continue to apply to the part which is the covered work, 533 | but the work with which it is combined will remain governed by version 534 | 3 of the GNU General Public License. 535 | 536 | 14. Revised Versions of this License. 537 | 538 | The Free Software Foundation may publish revised and/or new versions of 539 | the GNU Affero General Public License from time to time. Such new versions 540 | will be similar in spirit to the present version, but may differ in detail to 541 | address new problems or concerns. 542 | 543 | Each version is given a distinguishing version number. If the 544 | Program specifies that a certain numbered version of the GNU Affero General 545 | Public License "or any later version" applies to it, you have the 546 | option of following the terms and conditions either of that numbered 547 | version or of any later version published by the Free Software 548 | Foundation. If the Program does not specify a version number of the 549 | GNU Affero General Public License, you may choose any version ever published 550 | by the Free Software Foundation. 551 | 552 | If the Program specifies that a proxy can decide which future 553 | versions of the GNU Affero General Public License can be used, that proxy's 554 | public statement of acceptance of a version permanently authorizes you 555 | to choose that version for the Program. 556 | 557 | Later license versions may give you additional or different 558 | permissions. However, no additional obligations are imposed on any 559 | author or copyright holder as a result of your choosing to follow a 560 | later version. 561 | 562 | 15. Disclaimer of Warranty. 563 | 564 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 565 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 566 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 567 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 568 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 569 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 570 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 571 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 572 | 573 | 16. Limitation of Liability. 574 | 575 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 576 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 577 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 578 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 579 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 580 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 581 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 582 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 583 | SUCH DAMAGES. 584 | 585 | 17. Interpretation of Sections 15 and 16. 586 | 587 | If the disclaimer of warranty and limitation of liability provided 588 | above cannot be given local legal effect according to their terms, 589 | reviewing courts shall apply local law that most closely approximates 590 | an absolute waiver of all civil liability in connection with the 591 | Program, unless a warranty or assumption of liability accompanies a 592 | copy of the Program in return for a fee. 593 | 594 | END OF TERMS AND CONDITIONS 595 | 596 | How to Apply These Terms to Your New Programs 597 | 598 | If you develop a new program, and you want it to be of the greatest 599 | possible use to the public, the best way to achieve this is to make it 600 | free software which everyone can redistribute and change under these terms. 601 | 602 | To do so, attach the following notices to the program. It is safest 603 | to attach them to the start of each source file to most effectively 604 | state the exclusion of warranty; and each file should have at least 605 | the "copyright" line and a pointer to where the full notice is found. 606 | 607 | 608 | Copyright (C) 609 | 610 | This program is free software: you can redistribute it and/or modify 611 | it under the terms of the GNU Affero General Public License as published 612 | by the Free Software Foundation, either version 3 of the License, or 613 | (at your option) any later version. 614 | 615 | This program is distributed in the hope that it will be useful, 616 | but WITHOUT ANY WARRANTY; without even the implied warranty of 617 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 618 | GNU Affero General Public License for more details. 619 | 620 | You should have received a copy of the GNU Affero General Public License 621 | along with this program. If not, see . 622 | 623 | Also add information on how to contact you by electronic and paper mail. 624 | 625 | If your software can interact with users remotely through a computer 626 | network, you should also make sure that it provides a way for users to 627 | get its source. For example, if your program is a web application, its 628 | interface could display a "Source" link that leads users to an archive 629 | of the code. There are many ways you could offer source, and different 630 | solutions will be better for different programs; see section 13 for the 631 | specific requirements. 632 | 633 | You should also get your employer (if you work as a programmer) or school, 634 | if any, to sign a "copyright disclaimer" for the program, if necessary. 635 | For more information on this, and how to apply and follow the GNU AGPL, see 636 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > 🚩 **This project is archived!** 🚩 2 | > 3 | > *This was really fun! I enjoyed reverse-engineering Among Us and learning a lot of new things. Right now I don't play the game anymore and I don't find it fun to work on this anymore. Luckily, it isn't yet developed enough that anyone depends on it.* 4 | > 5 | > *While this definitely was and would've been the best Among Us JS library, you'll have to find alternatives.* 6 | 7 | ![Among JS](https://raw.githubusercontent.com/kognise/among-js/main/banner.svg) 8 | 9 | ## About Among JS 10 | 11 | Among JS is a set of utilities for interacting with the Among Us protocol written in TypeScript. It's composed of several self-contained libraries which are all published to NPM: 12 | 13 | - Data: constants, enums, types, static game data, and more ([docs](https://among-js-docs.vercel.app/modules/data.html)) 14 | - Hazel: a library for interacting with the Hazel network protocol ([docs](https://among-js-docs.vercel.app/modules/hazel.html)) 15 | - Packets: rich Among Us packet parsing and serialization with a programmer-friendly API ([docs](https://among-js-docs.vercel.app/modules/packets.html)) 16 | - Sus: simple and expressive object-oriented library for easily making bots and clients ([docs](https://among-js-docs.vercel.app/modules/sus.html)) 17 | - Util: general utilities for reading bytes and more ([docs](https://among-js-docs.vercel.app/modules/util.html)) 18 | 19 | Among JS was designed with browser support in mind, meaning when the Hazel library supports WebSocket transports you'll be able to run Among Us bots and clients fully on the web *as well as* Node.js! 20 | 21 | In it's current state not all packets and events are supported but I'm focusing on rapid iteration. Every current feature is fully manually tested and stable. Currently unit test coverage is low but increasing. 22 | 23 | You can find more information about the protocol in this [freshly made wiki](https://wiki.weewoo.net/wiki/Protocol) I helped create. 24 | 25 | They're a bit of a WIP, but feel free to [read the documentation](https://among-js-docs.vercel.app/). If you have any feedback, create a GitHub issue or shoot be a DM on Discord @Kognise#6356. 26 | 27 | ## Requirements 28 | - Node.js 12.x or higher 29 | 30 | ## Development 31 | git clone https://github.com/kognise/among-js.git 32 | cd among-js 33 | yarn install && yarn dev 34 | node example.js (to run the example file) 35 | -------------------------------------------------------------------------------- /banner.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | const { AmongUsSocket } = require('@among-js/sus') 2 | const { PlayerColor, matchmakingServers } = require('@among-js/data') 3 | const consola = require('consola') 4 | 5 | consola.wrapAll() 6 | 7 | const code = 'PXKXFF' 8 | const username = 'asdas' 9 | const color = PlayerColor.Orange 10 | 11 | const s = new AmongUsSocket(username) 12 | 13 | 14 | // Follow the first player to move. 15 | let firstNetId 16 | s.on('playerMove', async (netId, position, velocity) => { 17 | if (!firstNetId) firstNetId = netId 18 | if (netId !== firstNetId) return 19 | 20 | await s.move(position, velocity) 21 | }) 22 | 23 | 24 | ;(async () => { 25 | await s.connect(22023, matchmakingServers.NA[2]) 26 | consola.info(`Connected to server as ${username}`) 27 | 28 | const joined = await s.joinGame(code) 29 | consola.success(`Joined game ${code}`) 30 | consola.info(`Player id: ${joined.playerClientId}, host id: ${joined.hostClientId}`) 31 | 32 | await s.spawn(color) 33 | consola.success('Spawned player') 34 | })().catch(consola.error) 35 | 36 | 37 | // Clean up the socket cleanly to avoid reconnection issues. 38 | process.on('SIGINT', () => { 39 | consola.info('Closing sockets') 40 | s.s.disconnect() 41 | process.exit() 42 | }) 43 | -------------------------------------------------------------------------------- /lerna.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "registry": "https://registry.npmjs.org/", 4 | "publishConfig": { 5 | "access": "public" 6 | }, 7 | "npmClient": "yarn", 8 | "useWorkspaces": true, 9 | "packages": [ 10 | "packages/*" 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "among-js", 3 | "private": true, 4 | "devDependencies": { 5 | "@strictsoftware/typedoc-plugin-monorepo": "^0.3.1", 6 | "@types/node": "^14.11.8", 7 | "lerna": "^3.15.0", 8 | "tsdx": "^0.14.0", 9 | "typedoc": "^0.19.2", 10 | "typedoc-plugin-remove-references": "^0.0.5", 11 | "typescript": "^3.9.7" 12 | }, 13 | "workspaces": [ 14 | "packages/*" 15 | ], 16 | "scripts": { 17 | "lerna": "lerna", 18 | "dev": "lerna run dev --stream --parallel", 19 | "lint": "lerna run lint -- --fix", 20 | "test": "lerna run test --", 21 | "build": "lerna run build", 22 | "prepublish": "lerna run prepublish" 23 | }, 24 | "license": "AGPL-3.0-or-later", 25 | "dependencies": { 26 | "consola": "^2.15.0" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /packages/data/README.md: -------------------------------------------------------------------------------- 1 | # Data | Among JS 2 | 3 | Among Us constants, enums, types, static game data, and more. This is part of Among JS, a simple and flexible library for interacting with the Among Us protocol. You can find documentation [here](https://among-js-docs.vercel.app/modules/data.html). 4 | 5 | The data is currently organized into 4 groups: 6 | 7 | - Enums: constants for flags, packet types, and game data like colors 8 | - Types: rich types for packets and mother structured data 9 | - Static: data taken from the game such as matchmaking servers and map layouts 10 | - Utilities: type assertions and functions to convert enums to human-readable text -------------------------------------------------------------------------------- /packages/data/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@among-js/data", 3 | "version": "0.2.0", 4 | "description": "Among JS game data", 5 | "author": "Felix Mattick ", 6 | "scripts": { 7 | "dev": "tsdx watch --tsconfig tsconfig.build.json --verbose --noClean", 8 | "build": "tsdx build --tsconfig tsconfig.build.json", 9 | "lint": "tsdx lint", 10 | "test": "tsdx test", 11 | "prepublish": "yarn build" 12 | }, 13 | "main": "dist/index.js", 14 | "module": "dist/utils.esm.js", 15 | "typings": "dist/index.d.ts", 16 | "files": [ 17 | "README.md", 18 | "dist" 19 | ], 20 | "dependencies": { 21 | "@among-js/util": "^0.2.0", 22 | "bytebuffer": "^5.0.1", 23 | "tslib": "^2.0.0" 24 | }, 25 | "devDependencies": { 26 | "@types/bytebuffer": "^5.0.41" 27 | }, 28 | "publishConfig": { 29 | "access": "public" 30 | }, 31 | "license": "AGPL-3.0-or-later", 32 | "gitHead": "141d2a1f5f6583f2bcd37bb783244e6c10007c3a" 33 | } 34 | -------------------------------------------------------------------------------- /packages/data/src/assertions.test.ts: -------------------------------------------------------------------------------- 1 | import { 2 | assertJoinGameErrorPayloadPacket, 3 | assertJoinGameRequestPayloadPacket 4 | } from './assertions' 5 | import { PayloadType } from './enums' 6 | import { 7 | JoinGameErrorPayloadPacket, 8 | JoinGameRequestPayloadPacket 9 | } from './types' 10 | 11 | const joinGameRequest: 12 | | JoinGameErrorPayloadPacket 13 | | JoinGameRequestPayloadPacket = { 14 | type: PayloadType.JoinGame, 15 | code: -1 16 | } 17 | 18 | const joinGameError: 19 | | JoinGameErrorPayloadPacket 20 | | JoinGameRequestPayloadPacket = { 21 | type: PayloadType.JoinGame, 22 | reason: new Error('oh noes uwu') 23 | } 24 | 25 | test('assertJoinGameErrorPayloadPacket', () => { 26 | expect(() => assertJoinGameErrorPayloadPacket(joinGameError)).not.toThrow() 27 | expect(() => assertJoinGameErrorPayloadPacket(joinGameRequest)).toThrow() 28 | 29 | expect(() => 30 | assertJoinGameRequestPayloadPacket(joinGameRequest) 31 | ).not.toThrow() 32 | expect(() => assertJoinGameRequestPayloadPacket(joinGameError)).toThrow() 33 | }) 34 | -------------------------------------------------------------------------------- /packages/data/src/assertions.ts: -------------------------------------------------------------------------------- 1 | import assert from 'assert' 2 | import { 3 | JoinGameErrorPayloadPacket, 4 | JoinGameRequestPayloadPacket 5 | } from './types' 6 | 7 | /** 8 | * Assert that the packet is an error (server -> client) instead of a join request. 9 | * 10 | * @param value Join error or join request 11 | */ 12 | export function assertJoinGameErrorPayloadPacket( 13 | value: JoinGameErrorPayloadPacket | JoinGameRequestPayloadPacket 14 | ): asserts value is JoinGameErrorPayloadPacket { 15 | assert('reason' in value, 'assertJoinGameErrorPayloadPacket failed') 16 | } 17 | 18 | /** 19 | * Assert that the packet is a join request (client -> server) instead of an error. 20 | * 21 | * @param value Join error or join request 22 | */ 23 | export function assertJoinGameRequestPayloadPacket( 24 | value: JoinGameErrorPayloadPacket | JoinGameRequestPayloadPacket 25 | ): asserts value is JoinGameRequestPayloadPacket { 26 | assert('code' in value, 'assertJoinGameRequestPayloadPacket failed') 27 | } 28 | -------------------------------------------------------------------------------- /packages/data/src/enums.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Base packet types. {@link https://wiki.weewoo.net/wiki/Protocol} 3 | */ 4 | export enum PacketType { 5 | Normal = 0, 6 | Reliable = 1, 7 | Hello = 8, 8 | Disconnect = 9, 9 | Acknowledgement = 10, 10 | Ping = 12 11 | } 12 | 13 | /** 14 | * Packet payload types. {@link https://wiki.weewoo.net/wiki/Protocol#Reliable_Packets} 15 | */ 16 | export enum PayloadType { 17 | CreateGame = 0, 18 | JoinGame, 19 | StartGame, 20 | RemoveGame, 21 | RemovePlayer, 22 | GameData, 23 | GameDataTo, 24 | JoinedGame, 25 | EndGame, 26 | AlterGame = 10, 27 | KickPlayer, 28 | WaitForHost, 29 | Redirect, 30 | ReselectServer, 31 | GetGameList = 9, 32 | GetGameListV2 = 16 33 | } 34 | 35 | /** 36 | * Game data (and game data to) types. {@link https://wiki.weewoo.net/wiki/Protocol#5.2C_6_-_Game_Data_and_Game_Data_To} 37 | */ 38 | export enum GameDataType { 39 | Data = 1, 40 | RPC, 41 | Spawn = 4, 42 | Despawn, 43 | SceneChange, 44 | Ready, 45 | ChangeSettings 46 | } 47 | 48 | /** 49 | * Remote procedure call types. https://wiki.weewoo.net/wiki/Protocol#2_-_RPC_Game_Data 50 | */ 51 | export enum RPCFlag { 52 | PlayAnimation = 0, 53 | CompleteTask, 54 | SyncSettings, 55 | SetInfected, 56 | Exiled, 57 | CheckName, 58 | SetName, 59 | CheckColor, 60 | SetColor, 61 | SetHat, 62 | SetSkin, 63 | ReportDeadBody, 64 | MurderPlayer, 65 | SendChat, 66 | StartMeeting, 67 | SetScanner, 68 | SendChatNote, 69 | SetPet, 70 | SetStartCounter, 71 | EnterVent, 72 | ExitVent, 73 | SnapTo, 74 | Close, 75 | VotingComplete, 76 | CastVote, 77 | ClearVote, 78 | AddVote, 79 | CloseDoorsOfType, 80 | RepairSystem, 81 | SetTasks, 82 | UpdateGameData 83 | } 84 | 85 | /** 86 | * Disconnect reasons. You can get the pretty form with `prettyDisconnectReason`. 87 | */ 88 | export enum DisconnectReason { 89 | None = 0, 90 | GameFull, 91 | GameStarted, 92 | GameNotFound, 93 | CustomLegacy, 94 | OutdatedClient, 95 | Banned, 96 | Kicked, 97 | Custom, 98 | InvalidUsername, 99 | Hacking, 100 | Force = 16, 101 | BadConnection, 102 | GameNotFound2, 103 | ServerClosed, 104 | ServerOverloaded 105 | } 106 | 107 | /** 108 | * Options for scene change requests. OnlineGame is currently the only option. 109 | */ 110 | export enum SceneChangeLocation { 111 | OnlineGame = 'OnlineGame' 112 | } 113 | 114 | /** 115 | * In-game player colors. 116 | */ 117 | export enum PlayerColor { 118 | Red = 0, 119 | Blue, 120 | DarkGreen, 121 | Pink, 122 | Orange, 123 | Yellow, 124 | Black, 125 | White, 126 | Purple, 127 | Brown, 128 | Cyan, 129 | Lime 130 | } 131 | 132 | /** 133 | * Playable maps. 134 | */ 135 | export enum AmongUsMap { 136 | Skeld = 0, 137 | MIRA, 138 | Polus 139 | } 140 | 141 | /** 142 | * Supported chat and interface languages. 143 | */ 144 | export enum Language { 145 | Other = 0b00000000_00000000_00000000_00000001, 146 | Spanish = 0b00000000_00000000_00000000_00000010, 147 | Korean = 0b00000000_00000000_00000000_00000100, 148 | Russian = 0b00000000_00000000_00000000_00001000, 149 | Portuguese = 0b00000000_00000000_00000000_00010000, 150 | Arabic = 0b00000000_00000000_00000000_00100000, 151 | Filipino = 0b00000000_00000000_00000000_01000000, 152 | Polish = 0b00000000_00000000_00000000_10000000, 153 | English = 0b00000000_00000000_00000001_00000000 154 | } 155 | 156 | /** 157 | * Locations for tasks. 158 | */ 159 | export enum Location { 160 | Hallway = 0, 161 | Storage, 162 | Cafeteria, 163 | Reactor, 164 | UpperEngine, 165 | Nav, 166 | Admin, 167 | Electrical, 168 | O2, 169 | Shields, 170 | MedBay, 171 | Security, 172 | Weapons, 173 | LowerEngine, 174 | Comms, 175 | ShipTasks, 176 | Doors, 177 | Sabotage, 178 | Decontamination, 179 | Launchpad, 180 | LockerRoom, 181 | Laboratory, 182 | Balcony, 183 | Office, 184 | Greenhouse 185 | } 186 | 187 | /** 188 | * In-game tasks that appear in the task list. 189 | */ 190 | export enum TaskType { 191 | SubmitScan = 0, 192 | PrimeShields, 193 | FuelEngines, 194 | ChartCourse, 195 | StartReactor, 196 | SwipeCard, 197 | ClearAsteroids, 198 | UploadData, 199 | InspectSample, 200 | EmptyChute, 201 | EmptyGarbage, 202 | AlignEngineOutput, 203 | FixWiring, 204 | CalibrateDistributor, 205 | DivertPower, 206 | UnlockManifolds, 207 | ResetReactor, 208 | FixLights, 209 | CleanO2Filter, 210 | FixComms, 211 | RestoreOxygen, 212 | StabilizeSteering, 213 | AssembleArtifact, 214 | SortSamples, 215 | MeasureWeather, 216 | EnterIdCode 217 | } 218 | 219 | /** 220 | * Reasons for games ending. 221 | */ 222 | export enum GameOverReason { 223 | CrewmatesByVote = 0, 224 | CrewmatesByTask, 225 | ImpostorByVote, 226 | ImpostorByKill, 227 | ImpostorBySabotage, 228 | ImpostorDisconnect, 229 | CrewmatesDisconnect 230 | } 231 | 232 | /** 233 | * Task bar updates game options setting. 234 | */ 235 | export enum TaskBarUpdates { 236 | Always = 0, 237 | Meetings, 238 | Never 239 | } 240 | -------------------------------------------------------------------------------- /packages/data/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './enums' 2 | export * from './types' 3 | export * from './assertions' 4 | export * from './pretty-enums' 5 | export * from './matchmaking' 6 | -------------------------------------------------------------------------------- /packages/data/src/matchmaking.test.ts: -------------------------------------------------------------------------------- 1 | import { matchmakingServers } from './matchmaking' 2 | 3 | test('servers exist', () => { 4 | expect(matchmakingServers.NA).toBeTruthy() 5 | expect(matchmakingServers.EU).toBeTruthy() 6 | expect(matchmakingServers.ASIA).toBeTruthy() 7 | }) 8 | -------------------------------------------------------------------------------- /packages/data/src/matchmaking.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Known matchmaking servers by region. 3 | */ 4 | export const matchmakingServers = { 5 | NA: [ 6 | '50.116.1.42', 7 | '45.79.5.6', 8 | '104.237.135.186', 9 | '198.58.99.71', 10 | '45.79.67.124', 11 | '45.79.40.75', 12 | '45.79.67.124', 13 | '198.58.115.57' 14 | ], 15 | EU: ['172.105.249.25', '172.105.251.170'], 16 | ASIA: ['172.104.96.99', '139.162.111.196', '172.104.96.99'] 17 | } 18 | -------------------------------------------------------------------------------- /packages/data/src/pretty-enums.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @packageDocumentation 3 | * Functions to convert enums into human-readable names for debugging. 4 | */ 5 | 6 | import { 7 | PayloadType, 8 | DisconnectReason, 9 | RPCFlag, 10 | GameDataType, 11 | PlayerColor, 12 | TaskType 13 | } from './enums' 14 | 15 | /** 16 | * Convert a payload type to a human-readable string. 17 | * 18 | * @param type Payload type 19 | */ 20 | export const prettyPayloadType = (type: PayloadType) => { 21 | switch (type) { 22 | case PayloadType.CreateGame: 23 | return 'create game' 24 | case PayloadType.JoinGame: 25 | return 'join game' 26 | case PayloadType.StartGame: 27 | return 'start game' 28 | case PayloadType.RemoveGame: 29 | return 'remove game' 30 | case PayloadType.RemovePlayer: 31 | return 'remove player' 32 | case PayloadType.GameData: 33 | return 'game data' 34 | case PayloadType.GameDataTo: 35 | return 'game data (to)' 36 | case PayloadType.JoinedGame: 37 | return 'joined game' 38 | case PayloadType.EndGame: 39 | return 'end game' 40 | case PayloadType.AlterGame: 41 | return 'alter game' 42 | case PayloadType.KickPlayer: 43 | return 'kick player' 44 | case PayloadType.WaitForHost: 45 | return 'wait for host' 46 | case PayloadType.Redirect: 47 | return 'redirect' 48 | case PayloadType.ReselectServer: 49 | return 'reselect server' 50 | 51 | case PayloadType.GetGameList: 52 | case PayloadType.GetGameListV2: 53 | return 'get game list' 54 | 55 | default: 56 | return `unknown (${type})` 57 | } 58 | } 59 | 60 | /** 61 | * Convert a disconnect reason to a human-readable string as found in the game. 62 | * 63 | * @param reason Disconnect reason 64 | */ 65 | export const prettyDisconnectReason = (reason: DisconnectReason) => { 66 | switch (reason) { 67 | case DisconnectReason.GameFull: 68 | return 'The game you tried to join is full.\nCheck with the host to see if you can join next round.' 69 | case DisconnectReason.GameStarted: 70 | return 'The game you tried to join already started.\nCheck with the host to see if you can join next round.' 71 | case DisconnectReason.OutdatedClient: 72 | return 'You are running an older version of the game.\nPlease update to play with others.' 73 | 74 | case DisconnectReason.Banned: 75 | return 'You were banned from the room.\nYou cannot rejoin that room.' 76 | case DisconnectReason.Kicked: 77 | return 'You were kicked from the room.\nYou cannot rejoin that room.' 78 | 79 | case DisconnectReason.InvalidUsername: 80 | return 'Server refused username.' 81 | case DisconnectReason.Hacking: 82 | return 'You were banned for hacking.\nPlease stop.' 83 | case DisconnectReason.BadConnection: 84 | return 'You disconnected from the host.\nIf this happens often, check your WiFi strength.' 85 | 86 | case DisconnectReason.ServerClosed: 87 | return 'The server stopped this game. Possibly due to inactivity.' 88 | case DisconnectReason.ServerOverloaded: 89 | return 'The Among Us servers are overloaded.\nSorry! Please try again later!' 90 | 91 | case DisconnectReason.GameNotFound: 92 | case DisconnectReason.GameNotFound2: 93 | return `Could not find the game you're looking for.` 94 | 95 | case DisconnectReason.CustomLegacy: 96 | case DisconnectReason.Custom: 97 | return 'Custom' 98 | 99 | case DisconnectReason.None: 100 | case DisconnectReason.Force: 101 | return 'Forcibly disconnected from the server:\nThe remote sent a disconnect request.' 102 | } 103 | } 104 | 105 | /** 106 | * Convert an RPC flag to a human-readable string 107 | * 108 | * @param type RPC flag 109 | */ 110 | export const prettyRPCFlag = (type: RPCFlag) => { 111 | switch (type) { 112 | case RPCFlag.PlayAnimation: 113 | return 'PlayAnimation' 114 | case RPCFlag.CompleteTask: 115 | return 'CompleteTask' 116 | case RPCFlag.SyncSettings: 117 | return 'SyncSettings' 118 | case RPCFlag.SetInfected: 119 | return 'SetInfected' 120 | case RPCFlag.Exiled: 121 | return 'Exiled' 122 | case RPCFlag.CheckName: 123 | return 'CheckName' 124 | case RPCFlag.SetName: 125 | return 'SetName' 126 | case RPCFlag.CheckColor: 127 | return 'CheckColor' 128 | case RPCFlag.SetColor: 129 | return 'SetColor' 130 | case RPCFlag.SetHat: 131 | return 'SetHat' 132 | case RPCFlag.SetSkin: 133 | return 'SetSkin' 134 | case RPCFlag.ReportDeadBody: 135 | return 'ReportDeadBody' 136 | case RPCFlag.MurderPlayer: 137 | return 'MurderPlayer' 138 | case RPCFlag.SendChat: 139 | return 'SendChat' 140 | case RPCFlag.StartMeeting: 141 | return 'StartMeeting' 142 | case RPCFlag.SetScanner: 143 | return 'SetScanner' 144 | case RPCFlag.SendChatNote: 145 | return 'SendChatNote' 146 | case RPCFlag.SetPet: 147 | return 'SetPet' 148 | case RPCFlag.SetStartCounter: 149 | return 'SetStartCounter' 150 | case RPCFlag.EnterVent: 151 | return 'EnterVent' 152 | case RPCFlag.ExitVent: 153 | return 'ExitVent' 154 | case RPCFlag.SnapTo: 155 | return 'SnapTo' 156 | case RPCFlag.Close: 157 | return 'Close' 158 | case RPCFlag.VotingComplete: 159 | return 'VotingComplete' 160 | case RPCFlag.CastVote: 161 | return 'CastVote' 162 | case RPCFlag.ClearVote: 163 | return 'ClearVote' 164 | case RPCFlag.AddVote: 165 | return 'AddVote' 166 | case RPCFlag.CloseDoorsOfType: 167 | return 'CloseDoorsOfType' 168 | case RPCFlag.RepairSystem: 169 | return 'RepairSystem' 170 | case RPCFlag.SetTasks: 171 | return 'SetTasks' 172 | case RPCFlag.UpdateGameData: 173 | return 'UpdateGameData' 174 | } 175 | } 176 | 177 | /** 178 | * Convert a game data type to a human-readable string. 179 | * 180 | * @param type Game data type 181 | */ 182 | export const prettyGameDataType = (type: GameDataType) => { 183 | switch (type) { 184 | case GameDataType.Data: 185 | return 'generic data' 186 | case GameDataType.RPC: 187 | return 'rpc' 188 | case GameDataType.Spawn: 189 | return 'spawn' 190 | case GameDataType.Despawn: 191 | return 'despawn' 192 | case GameDataType.SceneChange: 193 | return 'scene change' 194 | case GameDataType.Ready: 195 | return 'ready' 196 | case GameDataType.ChangeSettings: 197 | return 'change settings' 198 | } 199 | } 200 | 201 | /** 202 | * Convert a player color to a human-readable string. 203 | * 204 | * @param color Player color 205 | */ 206 | export const prettyPlayerColor = (color: PlayerColor) => { 207 | switch (color) { 208 | case PlayerColor.Red: 209 | return 'red' 210 | case PlayerColor.Blue: 211 | return 'blue' 212 | case PlayerColor.DarkGreen: 213 | return 'dark green' 214 | case PlayerColor.Pink: 215 | return 'pink' 216 | case PlayerColor.Orange: 217 | return 'orange' 218 | case PlayerColor.Yellow: 219 | return 'yellow' 220 | case PlayerColor.Black: 221 | return 'black' 222 | case PlayerColor.White: 223 | return 'white' 224 | case PlayerColor.Purple: 225 | return 'purple' 226 | case PlayerColor.Brown: 227 | return 'brown' 228 | case PlayerColor.Cyan: 229 | return 'cyan' 230 | case PlayerColor.Lime: 231 | return 'lime' 232 | } 233 | } 234 | 235 | /** 236 | * Convert a task type to a human-readable string as seen in the task list in the game. 237 | * 238 | * @param type Task type 239 | */ 240 | export const prettyTaskType = (type: TaskType) => { 241 | switch (type) { 242 | case TaskType.SubmitScan: 243 | return 'Submit Scan' 244 | case TaskType.PrimeShields: 245 | return 'Prime Shields' 246 | case TaskType.FuelEngines: 247 | return 'Fuel Engines' 248 | case TaskType.ChartCourse: 249 | return 'Chart Course' 250 | case TaskType.StartReactor: 251 | return 'Start Reactor' 252 | case TaskType.SwipeCard: 253 | return 'Swipe Card' 254 | case TaskType.ClearAsteroids: 255 | return 'Clear Asteroids' 256 | case TaskType.UploadData: 257 | return 'Upload Data' 258 | case TaskType.InspectSample: 259 | return 'Inspect Sample' 260 | case TaskType.EmptyChute: 261 | return 'Empty Chute' 262 | case TaskType.EmptyGarbage: 263 | return 'Empty Garbage' 264 | case TaskType.AlignEngineOutput: 265 | return 'Align Engine Output' 266 | case TaskType.FixWiring: 267 | return 'Fix Wiring' 268 | case TaskType.CalibrateDistributor: 269 | return 'Calibrate Distributor' 270 | case TaskType.DivertPower: 271 | return 'Divert Power' 272 | case TaskType.UnlockManifolds: 273 | return 'Unlock Manifolds' 274 | case TaskType.ResetReactor: 275 | return 'Reset Reactor' 276 | case TaskType.FixLights: 277 | return 'Fix Lights' 278 | case TaskType.CleanO2Filter: 279 | return 'Clean O2 Filter' 280 | case TaskType.FixComms: 281 | return 'Fix Comms' 282 | case TaskType.RestoreOxygen: 283 | return 'Restore Oxygen' 284 | case TaskType.StabilizeSteering: 285 | return 'Stabilize Steering' 286 | case TaskType.AssembleArtifact: 287 | return 'Assemble Artifact' 288 | case TaskType.SortSamples: 289 | return 'Sort Samples' 290 | case TaskType.MeasureWeather: 291 | return 'Measure Weather' 292 | case TaskType.EnterIdCode: 293 | return 'Enter Id Code' 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /packages/data/src/types.ts: -------------------------------------------------------------------------------- 1 | import { Vector2 } from '@among-js/util' 2 | import { 3 | GameDataType, 4 | SceneChangeLocation, 5 | PayloadType, 6 | RPCFlag, 7 | Language, 8 | AmongUsMap, 9 | PlayerColor, 10 | GameOverReason, 11 | TaskBarUpdates 12 | } from './enums' 13 | 14 | /** 15 | * All payload packets. {@link https://wiki.weewoo.net/wiki/Protocol#Reliable_Packets} 16 | */ 17 | export type PayloadPacket = 18 | | GameDataPayloadPacket 19 | | GameDataToPayloadPacket 20 | | JoinedGamePayloadPacket 21 | | RedirectPayloadPacket 22 | | JoinGameErrorPayloadPacket 23 | | JoinGameRequestPayloadPacket 24 | | EndGamePayloadPacket 25 | | StartGamePayloadPacket 26 | 27 | /** 28 | * Game data packet. {@link https://wiki.weewoo.net/wiki/Protocol#5.2C_6_-_Game_Data_and_Game_Data_To} 29 | */ 30 | export interface GameDataPayloadPacket { 31 | type: PayloadType.GameData 32 | code: number 33 | parts: GameDataPacket[] 34 | } 35 | 36 | /** 37 | * Game data to packet. Similar to `GameDataPayloadPacket` but it has a recipient as well. 38 | * {@link https://wiki.weewoo.net/wiki/Protocol#5.2C_6_-_Game_Data_and_Game_Data_To} 39 | */ 40 | export interface GameDataToPayloadPacket { 41 | type: PayloadType.GameDataTo 42 | code: number 43 | recipient: number 44 | parts: GameDataPacket[] 45 | } 46 | 47 | /** 48 | * End game packet, for when the current game is over. 49 | * This removes the client from the room so it'll have to rejoin. 50 | */ 51 | export interface EndGamePayloadPacket { 52 | type: PayloadType.EndGame 53 | code: number 54 | endReason: GameOverReason 55 | showAd: boolean 56 | } 57 | 58 | /** 59 | * Start game packet, for when the current game is starting. 60 | */ 61 | export interface StartGamePayloadPacket { 62 | type: PayloadType.StartGame 63 | code: number 64 | } 65 | 66 | /** 67 | * Joined game packet, sent after joining is a success. 68 | */ 69 | export interface JoinedGamePayloadPacket { 70 | type: PayloadType.JoinedGame 71 | code: number 72 | playerClientId: number 73 | hostClientId: number 74 | } 75 | 76 | /** 77 | * Represents an error while joining a game, sent from the server to the client. 78 | * 79 | * Be wary that `JoinGameRequestPayloadPacket` has the same payload type but a 80 | * different format. You can use `assertJoinGameErrorPayloadPacket` to make sure 81 | * that a packet is an error and not a request. 82 | * 83 | * {@link https://wiki.weewoo.net/wiki/Protocol#Server_To_Client} 84 | */ 85 | export interface JoinGameErrorPayloadPacket { 86 | type: PayloadType.JoinGame 87 | reason: Error 88 | } 89 | 90 | /** 91 | * A request to join a game, sent from the client to the server. 92 | * 93 | * Be wary that `JoinGameErrorPayloadPacket` has the same payload type but a 94 | * different format. You can use `assertJoinGameRequestPayloadPacket` to make sure 95 | * that a packet is a request and not an error. 96 | * 97 | * {@link https://wiki.weewoo.net/wiki/Protocol#Client_To_Server} 98 | */ 99 | export interface JoinGameRequestPayloadPacket { 100 | type: PayloadType.JoinGame 101 | code: number 102 | } 103 | 104 | /** 105 | * A packet sent by the server to instruct the client to disconnect 106 | * and retry the last message on the given server. 107 | * {@link https://wiki.weewoo.net/wiki/Protocol#13_-_Redirect} 108 | */ 109 | export interface RedirectPayloadPacket { 110 | type: PayloadType.Redirect 111 | port: number 112 | ip: string 113 | } 114 | 115 | /** 116 | * Game data and game data to packets. {@link https://wiki.weewoo.net/wiki/Protocol#5.2C_6_-_Game_Data_and_Game_Data_To} 117 | */ 118 | export type GameDataPacket = 119 | | RPCGameDataPacket 120 | | SpawnGameDataPacket 121 | | DataGameDataPacket 122 | | SceneChangeGameDataPacket 123 | | ReadyGameDataPacket 124 | 125 | /** 126 | * Ready packet. Sent by clients when the game is starting. 127 | * {@link https://wiki.weewoo.net/wiki/Protocol#7_-_Ready} 128 | * 129 | * Very complex and difficult to understand. 130 | */ 131 | export interface ReadyGameDataPacket { 132 | type: GameDataType.Ready 133 | clientId: number 134 | } 135 | 136 | /** 137 | * Packet to spawn an entity with a list of components. {@link https://wiki.weewoo.net/wiki/Protocol#4_-_Spawn} 138 | */ 139 | export interface SpawnGameDataPacket { 140 | type: GameDataType.Spawn 141 | spawnId: number 142 | ownerId: number 143 | flags: number 144 | components: GameComponent[] 145 | } 146 | 147 | /** 148 | * Data packet, right now only for movement. {@link https://wiki.weewoo.net/wiki/Protocol#1_-_Data} 149 | */ 150 | export interface DataGameDataPacket { 151 | type: GameDataType.Data 152 | netId: number 153 | sequence: number 154 | position: Vector2 155 | velocity: Vector2 156 | } 157 | 158 | /** 159 | * Packet for requesting a scene change, most useful for getting a spawn point. 160 | * {@link https://wiki.weewoo.net/wiki/Protocol#6_-_Scene_Change} 161 | */ 162 | export interface SceneChangeGameDataPacket { 163 | type: GameDataType.SceneChange 164 | playerClientId: number 165 | location: SceneChangeLocation 166 | } 167 | 168 | /** 169 | * Remote procedure call packet bodies. These are actually extensions 170 | * of the regular game data packet but with more data including an RPC flag. 171 | * {@link https://wiki.weewoo.net/wiki/Protocol#2_-_RPC_Game_Data} 172 | */ 173 | export type RPCGameDataPacket = 174 | | SyncSettingsRPCGameDataPacket 175 | | CheckNameRPCGameDataPacket 176 | | CheckColorRPCGameDataPacket 177 | | SetColorRPCGameDataPacket 178 | | UnparsedRPCGameDataPacket 179 | | UpdateGameDataRPCGameDataPacket 180 | | SetNameRPCGameDataPacket 181 | | VotingCompleteRPCGameDataPacket 182 | | SetInfectedRPCGameDataPacket 183 | | MurderPlayerRPCGameDataPacket 184 | | SetStartCounterRPCGameDataPacket 185 | 186 | /** 187 | * Set the timer until the game starts. 188 | */ 189 | export interface SetStartCounterRPCGameDataPacket { 190 | type: GameDataType.RPC, 191 | flag: RPCFlag.SetStartCounter, 192 | sequence: number, 193 | seconds: number 194 | } 195 | 196 | /** 197 | * Sync game options between clients. 198 | */ 199 | export interface SyncSettingsRPCGameDataPacket { 200 | type: GameDataType.RPC 201 | flag: RPCFlag.SyncSettings 202 | netId: number 203 | gameOptions: GameOptions 204 | } 205 | 206 | /** 207 | * Sets the list of impostor player ids. 208 | */ 209 | export interface SetInfectedRPCGameDataPacket { 210 | type: GameDataType.RPC 211 | flag: RPCFlag.SetInfected 212 | infected: number[] 213 | } 214 | 215 | /** 216 | * Called when a player is killed by an impostor. 217 | */ 218 | export interface MurderPlayerRPCGameDataPacket { 219 | type: GameDataType.RPC 220 | flag: RPCFlag.MurderPlayer 221 | id: number 222 | } 223 | 224 | /** 225 | * When all votes have been placed in a meeting. 226 | */ 227 | export interface VotingCompleteRPCGameDataPacket { 228 | type: GameDataType.RPC 229 | flag: RPCFlag.VotingComplete 230 | states: VoteState[] 231 | exiled: number | null 232 | tie: boolean 233 | } 234 | 235 | /** 236 | * Check if a name is available and set it. 237 | */ 238 | export interface CheckNameRPCGameDataPacket { 239 | type: GameDataType.RPC 240 | flag: RPCFlag.CheckName 241 | netId: number 242 | name: string 243 | } 244 | 245 | /** 246 | * Set a player name. Prefer `CheckNameRPCGameDataPacket`. 247 | */ 248 | export interface SetNameRPCGameDataPacket { 249 | type: GameDataType.RPC 250 | flag: RPCFlag.SetName 251 | netId: number 252 | name: string 253 | } 254 | 255 | /** 256 | * Check if a color is available and set it. 257 | */ 258 | export interface CheckColorRPCGameDataPacket { 259 | type: GameDataType.RPC 260 | flag: RPCFlag.CheckColor 261 | netId: number 262 | color: PlayerColor 263 | } 264 | 265 | /** 266 | * Set a player color. Prefer `CheckColorRPCGameDataPacket`. 267 | */ 268 | export interface SetColorRPCGameDataPacket { 269 | type: GameDataType.RPC 270 | flag: RPCFlag.SetColor 271 | netId: number 272 | color: PlayerColor 273 | } 274 | 275 | /** 276 | * Update the game data for multiple players. See `GameData` for more information. 277 | */ 278 | export interface UpdateGameDataRPCGameDataPacket { 279 | type: GameDataType.RPC 280 | flag: RPCFlag.UpdateGameData 281 | netId: number 282 | players: GameData[] 283 | } 284 | 285 | /** 286 | * All unsupported RPC packets are represented with this type, so until support 287 | * is added you can read from the buffer in `data`. 288 | */ 289 | export interface UnparsedRPCGameDataPacket { 290 | type: GameDataType.RPC 291 | // Next line is cursed, fuck typescript 292 | flag: Exclude< 293 | RPCFlag, 294 | | RPCFlag.CheckName 295 | | RPCFlag.SyncSettings 296 | | RPCFlag.CheckColor 297 | | RPCFlag.SetName 298 | | RPCFlag.SetColor 299 | | RPCFlag.UpdateGameData 300 | | RPCFlag.VotingComplete 301 | | RPCFlag.SetInfected 302 | | RPCFlag.MurderPlayer 303 | | RPCFlag.SetStartCounter 304 | > 305 | netId: number 306 | data: ByteBuffer 307 | } 308 | 309 | /** 310 | * Component on a Unity GameObject. {@link https://wiki.weewoo.net/wiki/Components} 311 | */ 312 | export interface GameComponent { 313 | netId: number 314 | data: ByteBuffer 315 | } 316 | 317 | /** 318 | * Game options/settings. {@link https://wiki.weewoo.net/wiki/Game_Options_Data} 319 | */ 320 | export interface GameOptions { 321 | maxPlayers: number 322 | language: Language 323 | map: AmongUsMap 324 | playerSpeedModifier: number 325 | crewLightModifier: number 326 | impostorLightModifier: number 327 | killCooldown: number 328 | commonTasks: number 329 | longTasks: number 330 | shortTasks: number 331 | emergencies: number 332 | impostors: number 333 | killDistance: number 334 | discussionTime: number 335 | votingTime: number 336 | isDefault: boolean 337 | emergencyCooldown: number 338 | confirmEjects: boolean 339 | visualTasks: boolean 340 | anonymousVotes: boolean 341 | taskBarUpdates: TaskBarUpdates 342 | } 343 | 344 | /** 345 | * Game data, used for representing information about players. 346 | */ 347 | export interface GameData { 348 | playerId: number 349 | playerName: string 350 | color: PlayerColor 351 | hat: number 352 | pet: number 353 | skin: number 354 | disconnected: boolean 355 | isImpostor: boolean 356 | isDead: boolean 357 | tasks: TaskInfo[] 358 | } 359 | 360 | /** 361 | * In-game task info. 362 | */ 363 | export interface TaskInfo { 364 | type: number 365 | complete: boolean 366 | } 367 | 368 | /** 369 | * State of a player's vote board during an emergency meeting or body report. 370 | */ 371 | export interface VoteState { 372 | playerId: number 373 | votedFor: number | null 374 | didReport: boolean 375 | isDead: boolean 376 | } 377 | -------------------------------------------------------------------------------- /packages/data/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.build.json", 3 | "include": ["src", "types", "../../types"] 4 | } -------------------------------------------------------------------------------- /packages/hazel/README.md: -------------------------------------------------------------------------------- 1 | # Hazel | Among JS 2 | 3 | A library for interacting with the Hazel network protocol. This is part of Among JS, a simple and flexible library for interacting with the Among Us protocol. 4 | 5 | Currently, the only thing here is [HazelUDPSocket](https://among-js-docs.vercel.app/classes/hazel.hazeludpsocket.html), which uses UDP to transport messages. In the future things like WebSockets will be supported as well so you can run Among Us clients entirely in the browser. -------------------------------------------------------------------------------- /packages/hazel/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@among-js/hazel", 3 | "version": "0.2.0", 4 | "description": "Implementation of the Hazel protocol that powers Among Us", 5 | "author": "Felix Mattick ", 6 | "scripts": { 7 | "dev": "tsdx watch --tsconfig tsconfig.build.json --verbose --noClean", 8 | "build": "tsdx build --tsconfig tsconfig.build.json", 9 | "lint": "tsdx lint", 10 | "prepublish": "yarn build" 11 | }, 12 | "main": "dist/index.js", 13 | "module": "dist/utils.esm.js", 14 | "typings": "dist/index.d.ts", 15 | "files": [ 16 | "README.md", 17 | "dist" 18 | ], 19 | "dependencies": { 20 | "@among-js/data": "^0.2.0", 21 | "bytebuffer": "^5.0.1", 22 | "tslib": "^2.0.0" 23 | }, 24 | "devDependencies": { 25 | "@types/bytebuffer": "^5.0.41" 26 | }, 27 | "publishConfig": { 28 | "access": "public" 29 | }, 30 | "license": "AGPL-3.0-or-later", 31 | "gitHead": "141d2a1f5f6583f2bcd37bb783244e6c10007c3a" 32 | } 33 | -------------------------------------------------------------------------------- /packages/hazel/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './udp' 2 | -------------------------------------------------------------------------------- /packages/hazel/src/udp.ts: -------------------------------------------------------------------------------- 1 | import dgram from 'dgram' 2 | import ByteBuffer from 'bytebuffer' 3 | import { EventEmitter } from 'events' 4 | import { PacketType, prettyDisconnectReason } from '@among-js/data' 5 | 6 | export declare interface HazelUDPSocket { 7 | on(event: 'message', cb: (buffer: ByteBuffer) => void): this 8 | } 9 | 10 | /** 11 | * Implementation of the Hazel base protocol with a raw UDP transport. 12 | * 13 | * This handles things such as different packet types, as well as sending acknowledgements and pings. 14 | * 15 | * No parsing is done to the inner packets to maintain separation of concerns. You should be able to 16 | * use this with **any** Hazel-based backed without trouble. 17 | * 18 | * The main methods you'll be using are: 19 | * - `send` and `sendReliable` for sending messages 20 | * - `connect` and `disconnect` for, well, connecting and disconnecting 21 | * - `on` to listen for the message event 22 | * 23 | * In 99% of use cases you'll also want `@among-js/data` for packet type enums and more, 24 | * as well as `bytebuffer` for a nice buffer library. 25 | * 26 | * @example 27 | * ```typescript 28 | * import { HazelUDPSocket } from '@among-js/hazel' 29 | * import { PacketType } from '@among-js/data' 30 | * import ByteBuffer from 'bytebuffer' 31 | * 32 | * const socket = new HazelUDPSocket('udp4') 33 | * 34 | * socket.on('message', (buffer) => { 35 | * console.log(buffer.toDebug(true)) 36 | * }) 37 | * 38 | * // Send an empty hello packet 39 | * await socket.sendReliable(PacketType.Hello, new ByteBuffer(0)) 40 | * ``` 41 | */ 42 | export class HazelUDPSocket extends EventEmitter { 43 | private s: dgram.Socket 44 | private reliableId: number = 0 45 | 46 | /** 47 | * @param type Type of socket, for now this should always be `udp4` 48 | */ 49 | constructor(type: dgram.SocketType) { 50 | super() 51 | 52 | this.s = dgram.createSocket(type) 53 | 54 | this.s.on('error', err => { 55 | console.error(err) 56 | this.s.close() 57 | }) 58 | 59 | // Setup listeners for various packet types. 60 | this.s.on('message', msg => { 61 | const packetType: PacketType = msg[0] 62 | 63 | switch (packetType) { 64 | case PacketType.Acknowledgement: { 65 | // TODO: Actually check acknowledgement packets for reliability. 66 | break 67 | } 68 | 69 | case PacketType.Ping: { 70 | this.handleReliableResponse(msg) 71 | break 72 | } 73 | 74 | case PacketType.Disconnect: { 75 | console.warn( 76 | `Disconnecting by request:\n${prettyDisconnectReason(msg[1])}` 77 | ) 78 | this.s.close() 79 | this.removeAllListeners() 80 | break 81 | } 82 | 83 | case PacketType.Normal: { 84 | this.handlePayloadPacket(msg, 1) 85 | break 86 | } 87 | 88 | case PacketType.Reliable: { 89 | this.handleReliableResponse(msg) 90 | this.handlePayloadPacket(msg, 3) 91 | break 92 | } 93 | 94 | default: { 95 | if (process.env.AJ_DEBUG === 'yes') 96 | console.warn(`Unknown packet type: ${packetType}`) 97 | } 98 | } 99 | }) 100 | } 101 | 102 | /** 103 | * Reliable packets require an acknowledgement packet in response 104 | * or the server will throw a tantrum. This will send that response. 105 | * {@link https://wiki.weewoo.net/wiki/Protocol#Acknowledgement} 106 | * 107 | * @param buffer Packet buffer 108 | */ 109 | private handleReliableResponse(buffer: Buffer) { 110 | const reliableId = (buffer[1] << 8) + buffer[2] 111 | const bb = new ByteBuffer(4) 112 | bb.writeByte(PacketType.Acknowledgement) 113 | bb.writeInt16(reliableId) 114 | bb.writeByte(0xff) 115 | this.send(bb) 116 | } 117 | 118 | /** 119 | * Generic handler for packets with payloads, for both reliable 120 | * and normal packets. Calls the appropriate event listeners. 121 | * 122 | * @param buffer Packet buffer 123 | * @param offset Position the packet begins at 124 | */ 125 | private handlePayloadPacket(buffer: Buffer, offset: number) { 126 | const bb = new ByteBuffer(buffer.length - offset, true) 127 | bb.append(buffer.slice(offset)) 128 | bb.clear() 129 | this.emit('message', bb) 130 | } 131 | 132 | /** 133 | * Hacky helper to wait for an acknowledgement before continuing. 134 | * 135 | * @param reliableId Nonce of the packet sent 136 | */ 137 | private async waitForAcknowledgement(reliableId: number) { 138 | await new Promise(resolve => { 139 | const cb = (msg: Buffer) => { 140 | const packetType: PacketType = msg[0] 141 | if (packetType !== PacketType.Acknowledgement) return 142 | 143 | const ackReliableId = (msg[1] << 8) + msg[2] 144 | if (ackReliableId !== reliableId) return 145 | 146 | this.s.off('message', cb) 147 | resolve() 148 | } 149 | 150 | this.s.on('message', cb) 151 | }) 152 | } 153 | 154 | /** 155 | * Bind the socket to an ip and port. 156 | * 157 | * @param port Port 158 | * @param ip IPV4 address 159 | */ 160 | connect(port: number, ip?: string) { 161 | return new Promise(resolve => { 162 | this.s.connect(port, ip, () => resolve()) 163 | }) 164 | } 165 | 166 | /** 167 | * Helper for sending reliable packer. Automatically handles waiting for 168 | * acknowledgements and incrementing the reliable id. 169 | * {@link https://wiki.weewoo.net/wiki/Protocol#Reliable_Packets} 170 | * 171 | * @param sendOption Type of packet to send 172 | * @param data Data as a byte buffer 173 | */ 174 | async sendReliable(sendOption: PacketType, data: ByteBuffer) { 175 | const reliableId = ++this.reliableId 176 | const bb = new ByteBuffer(3 + data.capacity()) 177 | bb.writeByte(sendOption) 178 | bb.writeInt16(reliableId) 179 | bb.append(data.buffer) 180 | 181 | const ack = this.waitForAcknowledgement(reliableId) 182 | await this.send(bb) 183 | await ack 184 | } 185 | 186 | /** 187 | * Wrapper for asyncronously sending raw packets. 188 | * 189 | * @param bb Data as a byte buffer 190 | */ 191 | send(bb: ByteBuffer) { 192 | return new Promise((resolve, reject) => { 193 | this.s.send(bb.buffer, err => { 194 | if (err) { 195 | reject(err) 196 | } else { 197 | resolve() 198 | } 199 | }) 200 | }) 201 | } 202 | 203 | /** 204 | * Disconnect cleanly by sending a disconnect packet and 205 | * waiting for a response. Otherwise the next time we try 206 | * to connect the server won't respond to the hello. 207 | * 208 | * {@link https://wiki.weewoo.net/wiki/Protocol#Disconnect} 209 | */ 210 | async disconnect() { 211 | const dc = new ByteBuffer(1) 212 | dc.writeByte(9) 213 | 214 | this.s.removeAllListeners() 215 | const promise = new Promise(resolve => { 216 | this.s.on('message', msg => { 217 | if (msg[0] === PacketType.Disconnect) { 218 | this.s.close() 219 | this.s.removeAllListeners() 220 | this.removeAllListeners() 221 | resolve() 222 | } 223 | }) 224 | }) 225 | 226 | await this.send(dc) 227 | await promise 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /packages/hazel/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.build.json", 3 | "include": ["src", "types", "../../types"] 4 | } -------------------------------------------------------------------------------- /packages/packets/README.md: -------------------------------------------------------------------------------- 1 | # Packets | Among JS 2 | 3 | Rich Among Us packet parsing and serialization with a programmer-friendly API. This is part of Among JS, a simple and flexible library for interacting with the Among Us protocol. 4 | 5 | This library was designed with extreme simplicity in mind. **For most use cases, the only functions you'll need are `parsePayloads` and `generatePayloads`**, both of which can be imported directly. As you may be able to guess, the former parses a buffer into a rich manipulatable structure, and the latter does the opposite. 6 | 7 | This is meant to be used with a library like `@among-js/hazel` to strip packet headers, and `bytebuffer` for manipulating buffers. 8 | 9 | ## Basic Concepts 10 | 11 | The base of the Among Us protocol is a list of "payloads." Each payload has a type, like game data or join game, and some payloads have inner payloads. 12 | 13 | For example, say you have a payload of type game data. This has an array of parts, each one being an inner payload. One part might be of type RPC, which has further instructions inside. Etcetera. 14 | 15 | For more technical information on the protocol you may be interested in reading [the protocol wiki](https://wiki.weewoo.net/wiki/Protocol). 16 | 17 | ## Game Codes 18 | 19 | You may notice that game codes are stored as numbers. This is how Among Us internally stores them and allows for much better normalization. 20 | 21 | Specifically, version 2 (6 character) codes are represented as large negative numbers which is generated through a complex algorithm that is out of the scope of this specific package. To convert a v2 code into something this package can understand use the `v2CodeToNumber` function which is exported from `@among-js/util`. 22 | 23 | For more in-depth information, read [this wiki page](https://wiki.weewoo.net/wiki/Game_Codes). 24 | -------------------------------------------------------------------------------- /packages/packets/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@among-js/packets", 3 | "version": "0.2.0", 4 | "description": "Among JS packet parsing and serialization", 5 | "author": "Felix Mattick ", 6 | "scripts": { 7 | "dev": "tsdx watch --tsconfig tsconfig.build.json --verbose --noClean", 8 | "build": "tsdx build --tsconfig tsconfig.build.json", 9 | "lint": "tsdx lint", 10 | "prepublish": "yarn build" 11 | }, 12 | "main": "dist/index.js", 13 | "module": "dist/utils.esm.js", 14 | "typings": "dist/index.d.ts", 15 | "files": [ 16 | "README.md", 17 | "dist" 18 | ], 19 | "dependencies": { 20 | "@among-js/data": "^0.2.0", 21 | "@among-js/util": "^0.2.0", 22 | "bytebuffer": "^5.0.1", 23 | "tslib": "^2.0.0" 24 | }, 25 | "devDependencies": { 26 | "@types/bytebuffer": "^5.0.41" 27 | }, 28 | "publishConfig": { 29 | "access": "public" 30 | }, 31 | "license": "AGPL-3.0-or-later", 32 | "gitHead": "141d2a1f5f6583f2bcd37bb783244e6c10007c3a" 33 | } 34 | -------------------------------------------------------------------------------- /packages/packets/src/game-data.ts: -------------------------------------------------------------------------------- 1 | import { GameData, PlayerColor, TaskInfo, TaskType } from '@among-js/data' 2 | import { pack, readPacked } from '@among-js/util' 3 | import ByteBuffer from 'bytebuffer' 4 | 5 | /** 6 | * Read a game data object from a buffer. 7 | * 8 | * @param buffer Buffer to read from 9 | */ 10 | export const readGameData = (buffer: ByteBuffer): GameData => { 11 | buffer.readInt16() 12 | const playerId = buffer.readByte() 13 | 14 | const playerNameLength = buffer.readByte() 15 | const playerName = buffer.readString(playerNameLength) 16 | 17 | const color: PlayerColor = buffer.readByte() 18 | const hat = readPacked(buffer) 19 | const pet = readPacked(buffer) 20 | const skin = readPacked(buffer) 21 | 22 | const flags = buffer.readByte() 23 | const disconnected = (flags & 1) > 0 24 | const isImpostor = (flags & 2) > 0 25 | const isDead = (flags & 4) > 0 26 | 27 | const taskCount = buffer.readByte() 28 | const tasks: TaskInfo[] = [] 29 | 30 | for (let i = 0; i < taskCount; i++) { 31 | const type: TaskType = readPacked(buffer) 32 | const complete = buffer.readByte() > 0 33 | tasks.push({ type, complete }) 34 | } 35 | 36 | return { 37 | playerId, 38 | playerName, 39 | color, 40 | hat, 41 | pet, 42 | skin, 43 | disconnected, 44 | isImpostor, 45 | isDead, 46 | tasks 47 | } 48 | } 49 | 50 | /** 51 | * Serialize a game data object into a buffer. 52 | * 53 | * @remarks 54 | * The buffer is variable-size, meaning you should not rely on `buffer.capacity()` 55 | * to get the length. Instead, use `buffer.offset`. 56 | * 57 | * @param gameData Game data 58 | */ 59 | export const serializeGameData = (gameData: GameData): ByteBuffer => { 60 | const buffer = new ByteBuffer(undefined, true) 61 | 62 | const packedHat = pack(gameData.hat) 63 | const packedPet = pack(gameData.pet) 64 | const packedSkin = pack(gameData.pet) 65 | 66 | buffer.writeInt16( 67 | 2 + 68 | gameData.playerName.length + 69 | 1 + 70 | packedHat.length + 71 | packedPet.length + 72 | packedSkin.length + 73 | 2 74 | ) 75 | buffer.writeByte(gameData.playerId) 76 | 77 | buffer.writeByte(gameData.playerName.length) 78 | buffer.writeString(gameData.playerName) 79 | 80 | buffer.writeByte(gameData.color) 81 | buffer.append(packedHat) 82 | buffer.append(packedPet) 83 | buffer.append(packedSkin) 84 | 85 | // TODO: Refactor to bitfield util coolness 86 | const f1 = gameData.disconnected ? 1 : 0 87 | const f2 = gameData.isImpostor ? 2 : 0 88 | const f3 = gameData.isDead ? 4 : 0 89 | buffer.writeByte(f1 | f2 | f3) 90 | 91 | // TODO: Write tasks 92 | buffer.writeByte(0) 93 | 94 | return buffer 95 | } 96 | -------------------------------------------------------------------------------- /packages/packets/src/game-options.ts: -------------------------------------------------------------------------------- 1 | import { 2 | GameOptions, 3 | Language, 4 | AmongUsMap, 5 | TaskBarUpdates 6 | } from '@among-js/data' 7 | import { pack, readPacked } from '@among-js/util' 8 | import ByteBuffer from 'bytebuffer' 9 | 10 | const baseLength = 46 11 | const packedBaseLength = pack(baseLength) 12 | 13 | const supportedVersion = 4 14 | 15 | /** 16 | * Read game options data from a buffer. 17 | * 18 | * @param buffer Buffer to read from 19 | */ 20 | export const readGameOptions = (buffer: ByteBuffer): GameOptions => { 21 | readPacked(buffer) // Length 22 | const version = buffer.readByte() // Version 23 | 24 | if (supportedVersion > version) { 25 | throw new Error(`Could not parse game data of old version ${version}`) 26 | } 27 | if (version !== supportedVersion) { 28 | // Often new game options formats are vaguely backwards-compatible 29 | console.warn(`Parsing game data of unsupported version ${version}`) 30 | } 31 | 32 | const maxPlayers = buffer.readByte() 33 | const language: Language = buffer.readUint32() 34 | const map: AmongUsMap = buffer.readByte() 35 | 36 | const playerSpeedModifier = buffer.readFloat32() 37 | const crewLightModifier = buffer.readFloat32() 38 | const impostorLightModifier = buffer.readFloat32() 39 | const killCooldown = buffer.readFloat32() 40 | 41 | const commonTasks = buffer.readByte() 42 | const longTasks = buffer.readByte() 43 | const shortTasks = buffer.readByte() 44 | 45 | const emergencies = buffer.readInt32() 46 | const impostors = buffer.readByte() 47 | const killDistance = buffer.readByte() 48 | const discussionTime = buffer.readInt32() 49 | const votingTime = buffer.readInt32() 50 | const isDefault = buffer.readByte() > 0 51 | 52 | const emergencyCooldown = buffer.readByte() 53 | const confirmEjects = buffer.readByte() > 0 54 | const visualTasks = buffer.readByte() > 0 55 | 56 | const anonymousVotes = buffer.readByte() > 0 57 | const taskBarUpdates: TaskBarUpdates = buffer.readByte() 58 | 59 | return { 60 | maxPlayers, 61 | language, 62 | map, 63 | playerSpeedModifier, 64 | crewLightModifier, 65 | impostorLightModifier, 66 | killCooldown, 67 | commonTasks, 68 | longTasks, 69 | shortTasks, 70 | emergencies, 71 | impostors, 72 | killDistance, 73 | discussionTime, 74 | votingTime, 75 | isDefault, 76 | emergencyCooldown, 77 | confirmEjects, 78 | visualTasks, 79 | anonymousVotes, 80 | taskBarUpdates 81 | } 82 | } 83 | 84 | /** 85 | * Serialize game options data into a buffer. 86 | * 87 | * @remarks 88 | * The buffer is variable-size, meaning you should not rely on `buffer.capacity()` 89 | * to get the length. Instead, use `buffer.offset`. 90 | * 91 | * @param gameOptions Game options data 92 | */ 93 | export const serializeGameOptions = (gameOptions: GameOptions): ByteBuffer => { 94 | const buffer = new ByteBuffer(undefined, true) 95 | 96 | buffer.append(packedBaseLength) 97 | buffer.writeByte(supportedVersion) 98 | 99 | buffer.writeByte(gameOptions.maxPlayers) 100 | buffer.readUint32(gameOptions.language) 101 | buffer.readByte(gameOptions.map) 102 | 103 | buffer.writeFloat32(gameOptions.playerSpeedModifier) 104 | buffer.writeFloat32(gameOptions.crewLightModifier) 105 | buffer.writeFloat32(gameOptions.impostorLightModifier) 106 | buffer.writeFloat32(gameOptions.killCooldown) 107 | 108 | buffer.writeByte(gameOptions.commonTasks) 109 | buffer.writeByte(gameOptions.longTasks) 110 | buffer.writeByte(gameOptions.shortTasks) 111 | 112 | buffer.writeInt32(gameOptions.emergencies) 113 | buffer.writeByte(gameOptions.impostors) 114 | buffer.writeByte(gameOptions.killDistance) 115 | buffer.writeInt32(gameOptions.discussionTime) 116 | buffer.writeInt32(gameOptions.votingTime) 117 | buffer.readByte(gameOptions.isDefault ? 1 : 0) 118 | 119 | buffer.writeByte(gameOptions.emergencyCooldown) 120 | buffer.writeByte(gameOptions.confirmEjects ? 1 : 0) 121 | buffer.writeByte(gameOptions.visualTasks ? 1 : 0) 122 | 123 | buffer.writeByte(gameOptions.anonymousVotes ? 1 : 0) 124 | buffer.writeByte(gameOptions.taskBarUpdates) 125 | 126 | return buffer 127 | } 128 | -------------------------------------------------------------------------------- /packages/packets/src/generator.ts: -------------------------------------------------------------------------------- 1 | import ByteBuffer from 'bytebuffer' 2 | import { 3 | GameDataType, 4 | PayloadType, 5 | assertJoinGameRequestPayloadPacket, 6 | DataGameDataPacket, 7 | GameDataPacket, 8 | GameDataPayloadPacket, 9 | GameDataToPayloadPacket, 10 | PayloadPacket, 11 | RPCGameDataPacket, 12 | SceneChangeGameDataPacket, 13 | prettyGameDataType, 14 | prettyPayloadType, 15 | prettyRPCFlag, 16 | RPCFlag 17 | } from '@among-js/data' 18 | import { pack } from '@among-js/util' 19 | import { serializeGameOptions } from './game-options' 20 | import { serializeGameData } from './game-data' 21 | 22 | const generateDataGameDataPacket = (packet: DataGameDataPacket): ByteBuffer => { 23 | const packedNetId = pack(packet.netId) 24 | 25 | const buffer = new ByteBuffer(3 + packedNetId.length + 10, true) 26 | buffer.writeInt16(packedNetId.length + 10) 27 | buffer.writeByte(packet.type) 28 | 29 | buffer.append(packedNetId) 30 | buffer.writeUint16(packet.sequence) 31 | packet.position.write(buffer) 32 | packet.velocity.write(buffer) 33 | 34 | return buffer 35 | } 36 | 37 | const generateSceneChangeGameDataPacket = ( 38 | packet: SceneChangeGameDataPacket 39 | ): ByteBuffer => { 40 | const packedPlayerClientId = pack(packet.playerClientId) 41 | const size = packedPlayerClientId.length + 1 + packet.location.length 42 | 43 | const buffer = new ByteBuffer(3 + size, true) 44 | buffer.writeInt16(size) 45 | buffer.writeByte(packet.type) 46 | 47 | buffer.append(packedPlayerClientId) 48 | buffer.writeByte(packet.location.length) 49 | buffer.writeString(packet.location) 50 | 51 | return buffer 52 | } 53 | 54 | const generateRPCGameDataPacket = (packet: RPCGameDataPacket): ByteBuffer => { 55 | switch (packet.flag) { 56 | case RPCFlag.SyncSettings: { 57 | const packedNetId = pack(packet.netId) 58 | const serializedGameOptions = serializeGameOptions(packet.gameOptions) 59 | 60 | const buffer = new ByteBuffer( 61 | 3 + packedNetId.length + 1 + serializedGameOptions.offset, 62 | true 63 | ) 64 | 65 | buffer.writeInt16(packedNetId.length + 1 + serializedGameOptions.offset) 66 | buffer.writeByte(packet.type) 67 | 68 | buffer.append(packedNetId) 69 | buffer.writeByte(packet.flag) 70 | 71 | buffer.append( 72 | serializedGameOptions.buffer.slice(0, serializedGameOptions.offset) 73 | ) 74 | return buffer 75 | } 76 | 77 | case RPCFlag.CheckName: 78 | case RPCFlag.SetName: { 79 | const packedNetId = pack(packet.netId) 80 | const buffer = new ByteBuffer( 81 | 3 + packedNetId.length + 2 + packet.name.length, 82 | true 83 | ) 84 | 85 | buffer.writeInt16(packedNetId.length + 2 + packet.name.length) 86 | buffer.writeByte(packet.type) 87 | 88 | buffer.append(packedNetId) 89 | buffer.writeByte(packet.flag) 90 | 91 | buffer.writeByte(packet.name.length) 92 | buffer.writeString(packet.name) 93 | 94 | return buffer 95 | } 96 | 97 | case RPCFlag.UpdateGameData: { 98 | const dataBuffer = new ByteBuffer(undefined, true) 99 | for (const player of packet.players) { 100 | const serialized = serializeGameData(player) 101 | dataBuffer.append(serialized.buffer.slice(0, serialized.offset)) 102 | } 103 | 104 | const packedNetId = pack(packet.netId) 105 | const buffer = new ByteBuffer( 106 | 3 + packedNetId.length + 1 + dataBuffer.offset, 107 | true 108 | ) 109 | 110 | buffer.writeInt16(packedNetId.length + 1 + dataBuffer.offset) 111 | buffer.writeByte(packet.type) 112 | 113 | buffer.append(packedNetId) 114 | buffer.writeByte(packet.flag) 115 | buffer.append(dataBuffer.slice(0, dataBuffer.offset)) 116 | 117 | return buffer 118 | } 119 | 120 | case RPCFlag.CheckColor: 121 | case RPCFlag.SetColor: { 122 | const packedNetId = pack(packet.netId) 123 | const buffer = new ByteBuffer(3 + packedNetId.length + 2, true) 124 | 125 | buffer.writeInt16(packedNetId.length + 2) 126 | buffer.writeByte(packet.type) 127 | 128 | buffer.append(packedNetId) 129 | buffer.writeByte(packet.flag) 130 | 131 | buffer.writeByte(packet.color) 132 | return buffer 133 | } 134 | 135 | case RPCFlag.VotingComplete: { 136 | const buffer = new ByteBuffer(3, true) 137 | 138 | buffer.writeByte(0) 139 | buffer.writeUint8(packet.exiled ?? 0xff) 140 | buffer.writeByte(buffer.readByte() ? 1 : 0) 141 | 142 | return buffer 143 | } 144 | 145 | case RPCFlag.SetInfected: { 146 | const packedInfectedLength = pack(packet.infected.length) 147 | const buffer = new ByteBuffer( 148 | packedInfectedLength.length + packet.infected.length, 149 | true 150 | ) 151 | buffer.writeBytes(packedInfectedLength) 152 | for (const id of packet.infected) buffer.writeByte(id) 153 | return buffer 154 | } 155 | 156 | case RPCFlag.MurderPlayer: { 157 | const packedId = pack(packet.id) 158 | const buffer = new ByteBuffer(packedId.length, true) 159 | buffer.writeBytes(packedId) 160 | return buffer 161 | } 162 | 163 | case RPCFlag.SetStartCounter: { 164 | const packedSequence = pack(packet.sequence) 165 | const buffer = new ByteBuffer(packedSequence.length + 1, true) 166 | buffer.writeBytes(packedSequence) 167 | buffer.writeByte(packet.seconds) 168 | return buffer 169 | } 170 | 171 | default: { 172 | if (process.env.AJ_DEBUG === 'yes') 173 | console.warn( 174 | `Generated data-only packet of type ${prettyRPCFlag(packet.flag)}` 175 | ) 176 | 177 | const packedNetId = pack(packet.netId) 178 | const buffer = new ByteBuffer( 179 | 3 + packedNetId.length + 1 + packet.data.capacity(), 180 | true 181 | ) 182 | buffer.writeInt16(11) 183 | buffer.writeByte(packet.type) 184 | 185 | buffer.append(packedNetId) 186 | buffer.writeByte(packet.flag) 187 | buffer.append(packet.data.buffer) 188 | 189 | return buffer 190 | } 191 | } 192 | } 193 | 194 | const genericGameDataPacketSwitch = (part: GameDataPacket): ByteBuffer => { 195 | switch (part.type) { 196 | case GameDataType.Data: { 197 | return generateDataGameDataPacket(part) 198 | } 199 | 200 | case GameDataType.RPC: { 201 | return generateRPCGameDataPacket(part) 202 | } 203 | 204 | case GameDataType.SceneChange: { 205 | return generateSceneChangeGameDataPacket(part) 206 | } 207 | 208 | case GameDataType.Ready: { 209 | const packedClientId = pack(part.clientId) 210 | const buffer = new ByteBuffer(3 + packedClientId.length, true) 211 | 212 | buffer.writeInt16(packedClientId.length) 213 | buffer.writeByte(part.type) 214 | buffer.append(packedClientId) 215 | 216 | return buffer 217 | } 218 | 219 | default: { 220 | if (process.env.AJ_DEBUG === 'yes') 221 | console.warn( 222 | `Game data packet of type ${prettyGameDataType( 223 | part.type 224 | )} wasn't able to be generated` 225 | ) 226 | return new ByteBuffer(0) 227 | } 228 | } 229 | } 230 | 231 | const generateGameDataPayloadPacket = ( 232 | packet: GameDataPayloadPacket 233 | ): ByteBuffer => { 234 | const serializedParts: ByteBuffer[] = [] 235 | 236 | for (const part of packet.parts) { 237 | serializedParts.push(genericGameDataPacketSwitch(part)) 238 | } 239 | 240 | const size = serializedParts.reduce((acc, bb) => acc + bb.capacity(), 0) 241 | const buffer = new ByteBuffer(7 + size, true) 242 | 243 | buffer.writeInt16(4 + size) 244 | buffer.writeByte(packet.type) 245 | buffer.writeInt32(packet.code) 246 | 247 | for (const bb of serializedParts) { 248 | buffer.append(bb.buffer) 249 | } 250 | return buffer 251 | } 252 | 253 | const generateGameDataToPayloadPacket = ( 254 | packet: GameDataToPayloadPacket 255 | ): ByteBuffer => { 256 | const serializedParts: ByteBuffer[] = [] 257 | 258 | for (const part of packet.parts) { 259 | serializedParts.push(genericGameDataPacketSwitch(part)) 260 | } 261 | 262 | const packedRecipient = pack(packet.recipient) 263 | const size = serializedParts.reduce((acc, bb) => acc + bb.capacity(), 0) 264 | const buffer = new ByteBuffer(7 + packedRecipient.length + size, true) 265 | 266 | buffer.writeInt16(4 + packedRecipient.length + size) 267 | buffer.writeByte(packet.type) 268 | buffer.writeInt32(packet.code) 269 | buffer.append(packedRecipient) 270 | 271 | for (const bb of serializedParts) { 272 | buffer.append(bb.buffer) 273 | } 274 | return buffer 275 | } 276 | 277 | /** 278 | * Take a list of typed object packets and serialize them into a byte 279 | * buffer to send over the network. This is the main function of this 280 | * library, see the `@among-us/data` docs for all packet types. 281 | * 282 | * @param packets Packets to serialize 283 | */ 284 | export const generatePayloads = (packets: PayloadPacket[]): ByteBuffer => { 285 | const serializedPackets: ByteBuffer[] = [] 286 | 287 | for (const packet of packets) { 288 | switch (packet.type) { 289 | case PayloadType.GameData: { 290 | serializedPackets.push(generateGameDataPayloadPacket(packet)) 291 | break 292 | } 293 | 294 | case PayloadType.GameDataTo: { 295 | serializedPackets.push(generateGameDataToPayloadPacket(packet)) 296 | break 297 | } 298 | 299 | case PayloadType.Redirect: { 300 | const bb = new ByteBuffer(9, true) 301 | 302 | bb.writeInt16(6) 303 | bb.writeByte(packet.type) 304 | 305 | const ipBytes = packet.ip.split('.').map(part => parseInt(part)) 306 | bb.writeUint8(ipBytes[0]) 307 | bb.writeUint8(ipBytes[1]) 308 | bb.writeUint8(ipBytes[2]) 309 | bb.writeUint8(ipBytes[3]) 310 | 311 | bb.writeInt16(packet.port) 312 | serializedPackets.push(bb) 313 | 314 | break 315 | } 316 | 317 | case PayloadType.JoinGame: { 318 | assertJoinGameRequestPayloadPacket(packet) 319 | 320 | const bb = new ByteBuffer(8, true) 321 | bb.writeInt16(5) 322 | bb.writeByte(packet.type) 323 | bb.writeInt32(packet.code) 324 | bb.writeByte(7) 325 | serializedPackets.push(bb) 326 | 327 | break 328 | } 329 | 330 | default: { 331 | if (process.env.AJ_DEBUG === 'yes') 332 | console.warn( 333 | `Packet of type ${prettyPayloadType( 334 | packet.type 335 | )} wasn't able to be generated` 336 | ) 337 | } 338 | } 339 | } 340 | 341 | const buffer = new ByteBuffer( 342 | serializedPackets.reduce((acc, bb) => acc + bb.capacity(), 0), 343 | true 344 | ) 345 | for (const bb of serializedPackets) { 346 | buffer.append(bb.buffer) 347 | } 348 | return buffer 349 | } 350 | -------------------------------------------------------------------------------- /packages/packets/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './generator' 2 | export * from './parser' 3 | export * from './game-options' 4 | export * from './game-data' 5 | -------------------------------------------------------------------------------- /packages/packets/src/parser.ts: -------------------------------------------------------------------------------- 1 | import { 2 | RPCGameDataPacket, 3 | RPCFlag, 4 | GameDataType, 5 | SpawnGameDataPacket, 6 | GameComponent, 7 | DataGameDataPacket, 8 | GameDataPayloadPacket, 9 | GameDataPacket, 10 | prettyGameDataType, 11 | PayloadType, 12 | PayloadPacket, 13 | prettyDisconnectReason, 14 | prettyPayloadType, 15 | prettyRPCFlag, 16 | GameData, 17 | VoteState 18 | } from '@among-js/data' 19 | import { readPacked, Vector2 } from '@among-js/util' 20 | import { readGameData } from './game-data' 21 | import { readGameOptions } from './game-options' 22 | 23 | const parseRPCGameDataPacket = ( 24 | buffer: ByteBuffer, 25 | dataLength: number 26 | ): RPCGameDataPacket => { 27 | const beforeReadPacked = buffer.offset 28 | const netId = readPacked(buffer) 29 | const afterReadPacked = buffer.offset 30 | const packedSize = afterReadPacked - beforeReadPacked 31 | 32 | const flag: RPCFlag = buffer.readByte() 33 | 34 | switch (flag) { 35 | case RPCFlag.SyncSettings: { 36 | return { 37 | type: GameDataType.RPC, 38 | netId, 39 | flag, 40 | gameOptions: readGameOptions(buffer) 41 | } 42 | } 43 | 44 | case RPCFlag.CheckName: 45 | case RPCFlag.SetName: { 46 | const length = buffer.readByte() 47 | const name = buffer.readString(length) 48 | // @ts-ignore 49 | return { 50 | type: GameDataType.RPC, 51 | netId, 52 | flag, 53 | name 54 | } 55 | } 56 | 57 | case RPCFlag.CheckColor: 58 | case RPCFlag.SetColor: { 59 | return { 60 | type: GameDataType.RPC, 61 | netId, 62 | flag, 63 | color: buffer.readByte() 64 | } 65 | } 66 | 67 | case RPCFlag.UpdateGameData: { 68 | const players: GameData[] = [] 69 | while (buffer.offset < beforeReadPacked + dataLength) { 70 | players.push(readGameData(buffer)) 71 | } 72 | 73 | return { 74 | type: GameDataType.RPC, 75 | netId, 76 | flag, 77 | players 78 | } 79 | } 80 | 81 | case RPCFlag.VotingComplete: { 82 | const states: VoteState[] = [] 83 | const statesLength = buffer.readByte() 84 | 85 | for (let playerId = 0; playerId < statesLength; playerId++) { 86 | const byte = buffer.readUint8() 87 | states.push({ 88 | playerId, 89 | votedFor: 90 | (byte & 64) > 0 // Did vote 91 | ? (byte & 15) - 1 92 | : null, 93 | isDead: (byte & 128) > 0, 94 | didReport: (byte & 32) > 0 95 | }) 96 | } 97 | 98 | const exiled = buffer.readUint8() 99 | const tie = buffer.readByte() > 0 100 | 101 | return { 102 | type: GameDataType.RPC, 103 | states, 104 | flag, 105 | exiled: exiled === 0xff ? null : exiled, 106 | tie 107 | } 108 | } 109 | 110 | case RPCFlag.MurderPlayer: { 111 | return { 112 | type: GameDataType.RPC, 113 | flag, 114 | id: readPacked(buffer) 115 | } 116 | } 117 | 118 | case RPCFlag.SetInfected: { 119 | const infectedLength = readPacked(buffer) 120 | const infected = [] 121 | for (let i = 0; i < infectedLength; i++) { 122 | infected.push(buffer.readByte()) 123 | } 124 | 125 | return { 126 | type: GameDataType.RPC, 127 | flag, 128 | infected 129 | } 130 | } 131 | 132 | case RPCFlag.SetStartCounter: { 133 | const sequence = readPacked(buffer) 134 | const seconds = buffer.readByte() 135 | return { 136 | type: GameDataType.RPC, 137 | flag, 138 | sequence, 139 | seconds 140 | } 141 | } 142 | 143 | default: { 144 | if (process.env.AJ_DEBUG === 'yes') 145 | console.warn(`RPC packet of type ${prettyRPCFlag(flag)} wasn't parsed`) 146 | 147 | const data = buffer.readBytes(dataLength - (1 + packedSize)) 148 | return { 149 | type: GameDataType.RPC, 150 | netId, 151 | flag, 152 | data 153 | } 154 | } 155 | } 156 | } 157 | 158 | const parseSpawnGameDataPacket = (buffer: ByteBuffer): SpawnGameDataPacket => { 159 | const spawnId = readPacked(buffer) 160 | const ownerId = readPacked(buffer) 161 | const flags = buffer.readByte() 162 | 163 | const componentCount = readPacked(buffer) 164 | const components: GameComponent[] = [] 165 | 166 | for (let i = 0; i < componentCount; i++) { 167 | const netId = readPacked(buffer) 168 | const length = buffer.readUint16() 169 | buffer.readByte() 170 | const data = buffer.readBytes(length) 171 | 172 | components.push({ netId, data }) 173 | } 174 | 175 | return { 176 | type: GameDataType.Spawn, 177 | spawnId, 178 | ownerId, 179 | flags, 180 | components 181 | } 182 | } 183 | 184 | const parseDataGameDataPacket = ( 185 | buffer: ByteBuffer, 186 | netId: number 187 | ): DataGameDataPacket => { 188 | const sequence = buffer.readUint16() 189 | const position = Vector2.read(buffer) 190 | const velocity = Vector2.read(buffer) 191 | 192 | return { 193 | type: GameDataType.Data, 194 | netId, 195 | sequence, 196 | position, 197 | velocity 198 | } 199 | } 200 | 201 | const genericParseGameDataPayloadPacket = ( 202 | buffer: ByteBuffer, 203 | codeNumber: number 204 | ): GameDataPayloadPacket => { 205 | const parts: GameDataPacket[] = [] 206 | 207 | while (buffer.offset < buffer.capacity()) { 208 | const dataLength = buffer.readInt16() 209 | const dataType: GameDataType = buffer.readByte() 210 | 211 | const startOffset = buffer.offset 212 | switch (dataType) { 213 | case GameDataType.RPC: { 214 | parts.push(parseRPCGameDataPacket(buffer, dataLength)) 215 | break 216 | } 217 | 218 | case GameDataType.Spawn: { 219 | parts.push(parseSpawnGameDataPacket(buffer)) 220 | break 221 | } 222 | 223 | case GameDataType.Ready: { 224 | const clientId = readPacked(buffer) 225 | parts.push({ 226 | type: GameDataType.Ready, 227 | clientId 228 | }) 229 | break 230 | } 231 | 232 | case GameDataType.Data: { 233 | const beforeNetId = buffer.offset 234 | const netId = readPacked(buffer) 235 | const afterNetId = buffer.offset 236 | if (dataLength === afterNetId - beforeNetId + 10) { 237 | parts.push(parseDataGameDataPacket(buffer, netId)) 238 | } else { 239 | buffer.readBytes(dataLength - (afterNetId - beforeNetId)) 240 | } 241 | 242 | break 243 | } 244 | } 245 | const endOffset = buffer.offset 246 | 247 | if (endOffset - startOffset < dataLength) { 248 | if (endOffset - startOffset === 0) { 249 | if (process.env.AJ_DEBUG === 'yes') 250 | console.warn( 251 | `Game data packet of type ${prettyGameDataType( 252 | dataType 253 | )} wasn't handled` 254 | ) 255 | } else { 256 | console.warn( 257 | `Parsing game data packet of type ${prettyGameDataType( 258 | dataType 259 | )} did not use entire length (${endOffset - 260 | startOffset} < ${dataLength})` 261 | ) 262 | } 263 | buffer.skip(dataLength - (endOffset - startOffset)) 264 | } else if (endOffset - startOffset > dataLength) { 265 | throw new Error( 266 | `Parsing game data packet of type ${prettyGameDataType( 267 | dataType 268 | )} went over the length` 269 | ) 270 | } 271 | } 272 | 273 | return { 274 | type: PayloadType.GameData, 275 | code: codeNumber, 276 | parts 277 | } 278 | } 279 | 280 | /** 281 | * Take a buffer of bytes and parse it into a rich object structure for 282 | * consuming for code. See the `@among-us/data` docs for all packet types. 283 | * 284 | * @param packets Packets to serialize 285 | */ 286 | export const parsePayloads = (buffer: ByteBuffer): PayloadPacket[] => { 287 | const packets: PayloadPacket[] = [] 288 | 289 | while (buffer.offset < buffer.capacity()) { 290 | const payloadLength = buffer.readInt16() 291 | const payloadType: PayloadType = buffer.readByte() 292 | 293 | const startOffset = buffer.offset 294 | switch (payloadType) { 295 | case PayloadType.GameData: { 296 | const codeNumber = buffer.readInt32() 297 | packets.push(genericParseGameDataPayloadPacket(buffer, codeNumber)) 298 | break 299 | } 300 | 301 | case PayloadType.GameDataTo: { 302 | const codeNumber = buffer.readInt32() 303 | const recipient = readPacked(buffer) 304 | packets.push({ 305 | ...genericParseGameDataPayloadPacket(buffer, codeNumber), 306 | type: PayloadType.GameDataTo, 307 | recipient 308 | }) 309 | break 310 | } 311 | 312 | case PayloadType.JoinedGame: { 313 | const codeNumber = buffer.readInt32() 314 | const playerClientId = buffer.readUint32() 315 | const hostClientId = buffer.readUint32() 316 | buffer.skip(payloadLength - (buffer.offset - startOffset)) 317 | 318 | packets.push({ 319 | type: payloadType, 320 | code: codeNumber, 321 | playerClientId, 322 | hostClientId 323 | }) 324 | 325 | break 326 | } 327 | 328 | case PayloadType.Redirect: { 329 | const ip = `${buffer.readUint8()}.${buffer.readUint8()}.${buffer.readUint8()}.${buffer.readUint8()}` 330 | const port = buffer.readUint16() 331 | 332 | packets.push({ 333 | type: payloadType, 334 | ip, 335 | port 336 | }) 337 | 338 | break 339 | } 340 | 341 | case PayloadType.JoinGame: { 342 | const reason = new Error(prettyDisconnectReason(buffer.readByte())) 343 | buffer.skip(payloadLength - (buffer.offset - startOffset)) 344 | packets.push({ 345 | type: payloadType, 346 | reason 347 | }) 348 | 349 | break 350 | } 351 | 352 | case PayloadType.EndGame: { 353 | const code = buffer.readInt32() 354 | const endReason = buffer.readByte() 355 | const showAd = buffer.readByte() > 0 356 | 357 | packets.push({ 358 | type: payloadType, 359 | code, 360 | endReason, 361 | showAd 362 | }) 363 | 364 | break 365 | } 366 | 367 | case PayloadType.StartGame: { 368 | const code = buffer.readInt32() 369 | packets.push({ 370 | type: payloadType, 371 | code 372 | }) 373 | 374 | break 375 | } 376 | } 377 | const endOffset = buffer.offset 378 | 379 | if (endOffset - startOffset < payloadLength) { 380 | if (endOffset - startOffset === 0) { 381 | if (process.env.AJ_DEBUG === 'yes') 382 | console.warn( 383 | `Payload of type ${prettyPayloadType(payloadType)} wasn't handled` 384 | ) 385 | } else { 386 | console.warn( 387 | `Parsing payload of type ${prettyPayloadType( 388 | payloadType 389 | )} did not use entire length (${endOffset - 390 | startOffset} < ${payloadLength})` 391 | ) 392 | } 393 | buffer.skip(payloadLength - (endOffset - startOffset)) 394 | } else if (endOffset - startOffset > payloadLength) { 395 | throw new Error( 396 | `Parsing payload packet of type ${prettyPayloadType( 397 | payloadType 398 | )} went over the length` 399 | ) 400 | } 401 | } 402 | 403 | return packets 404 | } 405 | -------------------------------------------------------------------------------- /packages/packets/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.build.json", 3 | "include": ["src", "types", "../../types"] 4 | } -------------------------------------------------------------------------------- /packages/sus/README.md: -------------------------------------------------------------------------------- 1 | # Sus | Among JS 2 | 3 | Simple and expressive object-oriented library for easily making bots and clients. This is part of Among JS, a simple and flexible library for interacting with the Among Us protocol. 4 | 5 | Currently, the only thing here is [AmongUsSocket](https://among-js-docs.vercel.app/classes/sus.amongussocket.html), a monolithic class for interacting as a fake Among Us player. -------------------------------------------------------------------------------- /packages/sus/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@among-js/sus", 3 | "version": "0.2.0", 4 | "description": "A clean wrapper for writing Among Us bots", 5 | "author": "Felix Mattick ", 6 | "scripts": { 7 | "dev": "tsdx watch --tsconfig tsconfig.build.json --verbose --noClean", 8 | "build": "tsdx build --tsconfig tsconfig.build.json", 9 | "lint": "tsdx lint", 10 | "prepublish": "yarn build" 11 | }, 12 | "main": "dist/index.js", 13 | "module": "dist/utils.esm.js", 14 | "typings": "dist/index.d.ts", 15 | "files": [ 16 | "README.md", 17 | "dist" 18 | ], 19 | "dependencies": { 20 | "@among-js/data": "^0.2.0", 21 | "@among-js/hazel": "^0.2.0", 22 | "@among-js/packets": "^0.2.0", 23 | "@among-js/util": "^0.2.0", 24 | "bytebuffer": "^5.0.1", 25 | "tslib": "^2.0.0" 26 | }, 27 | "license": "AGPL-3.0-or-later", 28 | "devDependencies": { 29 | "@types/bytebuffer": "^5.0.41" 30 | }, 31 | "publishConfig": { 32 | "access": "public" 33 | }, 34 | "gitHead": "141d2a1f5f6583f2bcd37bb783244e6c10007c3a" 35 | } 36 | -------------------------------------------------------------------------------- /packages/sus/src/among-us.ts: -------------------------------------------------------------------------------- 1 | import { 2 | PacketType, 3 | PayloadType, 4 | assertJoinGameErrorPayloadPacket, 5 | PlayerColor, 6 | GameDataType, 7 | RPCFlag, 8 | SceneChangeLocation, 9 | GameComponent 10 | } from '@among-js/data' 11 | import { HazelUDPSocket } from '@among-js/hazel' 12 | import { parsePayloads, generatePayloads } from '@among-js/packets' 13 | import { v2CodeToNumber, Vector2 } from '@among-js/util' 14 | import ByteBuffer from 'bytebuffer' 15 | import { EventEmitter } from 'events' 16 | 17 | interface Game { 18 | code: string 19 | playerClientId: number 20 | hostClientId: number 21 | } 22 | 23 | interface JoinedJoinResult { 24 | state: 'joined' 25 | game: Game 26 | } 27 | 28 | interface ErrorJoinResult { 29 | state: 'error' 30 | error: Error 31 | } 32 | 33 | interface RedirectJoinResult { 34 | state: 'redirect' 35 | ip: string 36 | port: number 37 | } 38 | 39 | type JoinResult = JoinedJoinResult | ErrorJoinResult | RedirectJoinResult 40 | 41 | export declare interface AmongUsSocket { 42 | on( 43 | event: 'playerMove', 44 | cb: (netId: number, position: Vector2, velocity: Vector2) => void 45 | ): this 46 | 47 | on( 48 | event: 'startCounter', 49 | cb: (seconds: number) => void 50 | ): this 51 | } 52 | 53 | /** 54 | * Simple and clean wrapper for making Among Us clients and bots. 55 | * 56 | * If you're reading this through TypeDoc, I **highly** recommend unchecking "Inherited" 57 | * in the top right corner. It'll make it so you only have to see the methods and properties 58 | * that are pertinent to Among JS. 59 | * 60 | * @example 61 | * ```typescript 62 | * import { AmongUsSocket } from '@among-js/sus' 63 | * import { PlayerColor, matchmakingServers } from '@among-js/data' 64 | * 65 | * const socket = new AmongUsSocket('testing') 66 | * await socket.connect(22023, matchmakingServers.NA[1]) 67 | * await socket.joinGame('ABCDEF') 68 | * await socket.spawn(PlayerColor.Lime) 69 | * ``` 70 | */ 71 | export class AmongUsSocket extends EventEmitter { 72 | private name: string 73 | private game: Game | null = null 74 | private moveSequence: number = -1 75 | private components: GameComponent[] = [] 76 | 77 | /** 78 | * The internal Hazel socket. This is exposed in case you want to 79 | * do things like sending raw packets or disconnecting. 80 | */ 81 | s: HazelUDPSocket 82 | 83 | /** 84 | * Whether or not the client is ready to move around and perform actions. 85 | */ 86 | isReady = false 87 | 88 | /** 89 | * @param name Username to login with 90 | */ 91 | constructor(name: string) { 92 | super() 93 | this.name = name 94 | this.s = new HazelUDPSocket('udp4') 95 | } 96 | 97 | /** 98 | * Connect to a port and ip address. This also performs a handshake to properly initialize the version and username. 99 | * 100 | * If you don't know what server to connect to, get an ip from the `matchmakingServers` export from `@among-js/data` 101 | * and use 22023 as a port. You may also want to consider setting up a local {@link https://github.com/AeonLucid/Impostor | Impostor} 102 | * server for testing without putting load on the official servers. 103 | * 104 | * @param port Port 105 | * @param ip Ip address 106 | */ 107 | async connect(port: number, ip: string) { 108 | await this.s.connect(port, ip) 109 | 110 | // Send a hello with a username and wait for the response. 111 | const hello = new ByteBuffer(6 + this.name.length) 112 | hello.writeByte(0) 113 | hello.writeInt32(0x46_d2_02_03) 114 | hello.writeByte(this.name.length) 115 | hello.writeString(this.name) 116 | await this.s.sendReliable(PacketType.Hello, hello) 117 | } 118 | 119 | /** 120 | * Shitty code to attempt joining a game. This will respond with one of three states: 121 | * - Joined, meaning no further action must be taken 122 | * - Redirect, meaning the current socket should be scrapped and the join should be retried on the given ip and port 123 | * - Error, meaning it should throw an error 124 | * 125 | * @param code Game code to join, as a string 126 | */ 127 | private async tryJoin(code: string) { 128 | const promise = new Promise(resolve => { 129 | const cb = (buffer: ByteBuffer) => { 130 | const payloads = parsePayloads(buffer) 131 | 132 | for (const payload of payloads) { 133 | if (payload.type === PayloadType.JoinedGame) { 134 | this.s.off('message', cb) 135 | resolve({ 136 | state: 'joined', 137 | game: { 138 | code, 139 | playerClientId: payload.playerClientId, 140 | hostClientId: payload.hostClientId 141 | } 142 | }) 143 | } else if (payload.type === PayloadType.Redirect) { 144 | this.s.off('message', cb) 145 | resolve({ 146 | state: 'redirect', 147 | ip: payload.ip, 148 | port: payload.port 149 | }) 150 | } else if (payload.type === PayloadType.JoinGame) { 151 | assertJoinGameErrorPayloadPacket(payload) 152 | 153 | this.s.off('message', cb) 154 | resolve({ 155 | state: 'error', 156 | error: payload.reason 157 | }) 158 | } 159 | } 160 | } 161 | 162 | this.s.on('message', cb) 163 | }) 164 | 165 | // Actually send the join game packet now that the listener 166 | // is set up. 167 | await this.s.sendReliable( 168 | PacketType.Reliable, 169 | generatePayloads([ 170 | { 171 | type: PayloadType.JoinGame, 172 | code: v2CodeToNumber(code) 173 | } 174 | ]) 175 | ) 176 | 177 | return await promise 178 | } 179 | 180 | /** 181 | * Join an Among Us game, and handle join errors as well as redirects. 182 | * **This only connects! To get an avatar, receive events, and move around 183 | * you must use the `spawn` function.` 184 | * 185 | * @param code Game code to join, as a string 186 | */ 187 | async joinGame(code: string) { 188 | let joinResult: JoinResult 189 | 190 | while (true) { 191 | joinResult = await this.tryJoin(code) 192 | if (joinResult.state === 'error') throw joinResult.error 193 | 194 | if (joinResult.state === 'joined') { 195 | this.game = joinResult.game 196 | return this.game 197 | } 198 | 199 | if (joinResult.state === 'redirect') { 200 | console.info(`Redirecting to ${joinResult.ip}:${joinResult.port}`) 201 | await this.s.disconnect() 202 | this.s = new HazelUDPSocket('udp4') 203 | await this.connect(joinResult.port, joinResult.ip) 204 | } 205 | } 206 | } 207 | 208 | /** 209 | * Spawn the player with an avatar and username, and begin emitting events. 210 | * 211 | * @param color The color to spawn with, from `@among-js/data` 212 | */ 213 | async spawn(color: PlayerColor) { 214 | const promise = new Promise((resolve) => { 215 | this.s.on('message', async buffer => { 216 | const payloads = parsePayloads(buffer) 217 | 218 | for (const payload of payloads) { 219 | if (payload.type === PayloadType.GameData) { 220 | for (const part of payload.parts) { 221 | if (part.type === GameDataType.Spawn) { 222 | // When a spawn packet is received, send a two-part payload with the 223 | // desired username and color. The actual game sends these as two payloads 224 | // but this is equivalent. 225 | 226 | // Technically, I should check what it's actually spawning and add other logic 227 | // here, but I'm lazy so I'll do that when something breaks. 228 | 229 | this.components = part.components 230 | 231 | await this.s.sendReliable( 232 | PacketType.Reliable, 233 | generatePayloads([ 234 | { 235 | type: PayloadType.GameDataTo, 236 | recipient: this.game!.hostClientId, 237 | code: v2CodeToNumber(this.game!.code), 238 | parts: [ 239 | { 240 | type: GameDataType.RPC, 241 | flag: RPCFlag.CheckName, 242 | netId: part.components[0].netId, 243 | name: this.name 244 | }, 245 | { 246 | type: GameDataType.RPC, 247 | flag: RPCFlag.CheckColor, 248 | netId: part.components[0].netId, 249 | color 250 | } 251 | ] 252 | } 253 | ]) 254 | ) 255 | 256 | resolve() 257 | } else if (part.type === GameDataType.Data) { 258 | this.moveSequence = part.sequence 259 | this.emit( 260 | 'playerMove', 261 | part.netId, 262 | part.position, 263 | part.velocity 264 | ) 265 | } else if (part.type === GameDataType.RPC) { 266 | if (part.flag === RPCFlag.SetStartCounter) { 267 | // TODO: Account for sequence 268 | this.emit( 269 | 'startCounter', 270 | part.seconds 271 | ) 272 | } 273 | } 274 | } 275 | } else if (payload.type === PayloadType.StartGame) { 276 | console.log('Game starting, sending ready packet') 277 | await this.ready() 278 | } 279 | } 280 | }) 281 | }) 282 | 283 | // Listener is setup, so request a scene change to get a spawn point. 284 | await this.s.sendReliable( 285 | PacketType.Reliable, 286 | generatePayloads([ 287 | { 288 | type: PayloadType.GameData, 289 | code: v2CodeToNumber(this.game!.code), 290 | parts: [ 291 | { 292 | type: GameDataType.SceneChange, 293 | playerClientId: this.game!.playerClientId, 294 | location: SceneChangeLocation.OnlineGame 295 | } 296 | ] 297 | } 298 | ]) 299 | ) 300 | 301 | await promise 302 | this.isReady = true 303 | } 304 | 305 | /** 306 | * Move to a position with a velocity. 307 | * 308 | * @param position Position to move to 309 | * @param velocity Character controller velocity 310 | * 311 | * @beta 312 | */ 313 | async move(position: Vector2, velocity: Vector2) { 314 | await this.s.sendReliable( 315 | PacketType.Reliable, 316 | generatePayloads([ 317 | { 318 | type: PayloadType.GameData, 319 | code: v2CodeToNumber(this.game!.code), 320 | parts: [ 321 | { 322 | type: GameDataType.Data, 323 | netId: this.components[2].netId, 324 | sequence: ++this.moveSequence, 325 | position: position, 326 | velocity: velocity 327 | } 328 | ] 329 | } 330 | ]) 331 | ) 332 | } 333 | 334 | /** 335 | * Send a ready packet. This took years to implement so please use carefully. 336 | */ 337 | async ready() { 338 | await this.s.sendReliable( 339 | PacketType.Reliable, 340 | generatePayloads([ 341 | { 342 | type: PayloadType.GameData, 343 | code: v2CodeToNumber(this.game!.code), 344 | parts: [ 345 | { 346 | type: GameDataType.Ready, 347 | clientId: this.game!.playerClientId 348 | } 349 | ] 350 | } 351 | ]) 352 | ) 353 | } 354 | } 355 | -------------------------------------------------------------------------------- /packages/sus/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './among-us' 2 | -------------------------------------------------------------------------------- /packages/sus/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.build.json", 3 | "include": ["src", "types", "../../types"] 4 | } -------------------------------------------------------------------------------- /packages/util/README.md: -------------------------------------------------------------------------------- 1 | # Sus | Among JS 2 | 3 | General utilities for reading bytes and more. This is part of Among JS, a simple and flexible library for interacting with the Among Us protocol. -------------------------------------------------------------------------------- /packages/util/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@among-js/util", 3 | "version": "0.2.0", 4 | "description": "Among JS helper functions", 5 | "author": "Felix Mattick ", 6 | "scripts": { 7 | "dev": "tsdx watch --tsconfig tsconfig.build.json --verbose --noClean", 8 | "build": "tsdx build --tsconfig tsconfig.build.json", 9 | "lint": "tsdx lint", 10 | "test": "tsdx test", 11 | "prepublish": "yarn build" 12 | }, 13 | "main": "dist/index.js", 14 | "module": "dist/utils.esm.js", 15 | "typings": "dist/index.d.ts", 16 | "files": [ 17 | "README.md", 18 | "dist" 19 | ], 20 | "dependencies": { 21 | "bytebuffer": "^5.0.1", 22 | "tslib": "^2.0.0" 23 | }, 24 | "devDependencies": { 25 | "@types/bytebuffer": "^5.0.41" 26 | }, 27 | "publishConfig": { 28 | "access": "public" 29 | }, 30 | "license": "AGPL-3.0-or-later", 31 | "gitHead": "b479f5582a7e36a1d5dc20a10dcd746f89559c65" 32 | } 33 | -------------------------------------------------------------------------------- /packages/util/src/codes.test.ts: -------------------------------------------------------------------------------- 1 | import { v2CodeToNumber, v2NumberToCode } from './codes' 2 | 3 | test('v2 codes convert to numbers correctly', () => { 4 | expect(v2CodeToNumber('AAAAAA')).toBe(-1679540573) 5 | expect(v2CodeToNumber('ABCDEF')).toBe(-1943683525) 6 | expect(v2CodeToNumber('UVWXYZ')).toBe(-1838004714) 7 | expect(v2CodeToNumber('EIVKQQ')).toBe(-2147036604) 8 | }) 9 | 10 | test('v2 numbers convert to codes correctly', () => { 11 | expect(v2NumberToCode(-1679540573)).toBe('AAAAAA') 12 | expect(v2NumberToCode(-1943683525)).toBe('ABCDEF') 13 | expect(v2NumberToCode(-1838004714)).toBe('UVWXYZ') 14 | expect(v2NumberToCode(-2147036604)).toBe('EIVKQQ') 15 | }) 16 | -------------------------------------------------------------------------------- /packages/util/src/codes.ts: -------------------------------------------------------------------------------- 1 | // https://wiki.weewoo.net/wiki/Game_Codes 2 | 3 | const v2Characters = 'QWXRTYLPESDFGHUJKZOCVBINMA' 4 | const v2LookupTable = [ 5 | 25, 6 | 21, 7 | 19, 8 | 10, 9 | 8, 10 | 11, 11 | 12, 12 | 13, 13 | 22, 14 | 15, 15 | 16, 16 | 6, 17 | 24, 18 | 23, 19 | 18, 20 | 7, 21 | 0, 22 | 3, 23 | 9, 24 | 4, 25 | 14, 26 | 20, 27 | 1, 28 | 2, 29 | 5, 30 | 17 31 | ] 32 | 33 | /** 34 | * Converts a V2 game code into its number form. 35 | * 36 | * @param code Game code as a string 37 | */ 38 | export const v2CodeToNumber = (code: string) => { 39 | code = code.toUpperCase() 40 | 41 | const a = v2LookupTable[code[0].charCodeAt(0) - 65] 42 | const b = v2LookupTable[code[1].charCodeAt(0) - 65] 43 | const c = v2LookupTable[code[2].charCodeAt(0) - 65] 44 | const d = v2LookupTable[code[3].charCodeAt(0) - 65] 45 | const e = v2LookupTable[code[4].charCodeAt(0) - 65] 46 | const f = v2LookupTable[code[5].charCodeAt(0) - 65] 47 | 48 | const one = (a + 26 * b) & 0x3ff 49 | const two = c + 26 * (d + 26 * (e + 26 * f)) 50 | return one | ((two << 10) & 0x3ffffc00) | 0x80000000 51 | } 52 | 53 | /** 54 | * Converts a V2 game code as a number into a human-readable string 55 | * 56 | * @param code Game code as a number 57 | */ 58 | export const v2NumberToCode = (code: number) => { 59 | const a = code & 0x3ff 60 | const b = (code >> 10) & 0xfffff 61 | 62 | return [ 63 | v2Characters[a % 26], 64 | v2Characters[Math.trunc(a / 26)], 65 | v2Characters[b % 26], 66 | v2Characters[Math.trunc((b / 26) % 26)], 67 | v2Characters[Math.trunc((b / (26 * 26)) % 26)], 68 | v2Characters[Math.trunc((b / (26 * 26 * 26)) % 26)] 69 | ].join('') 70 | } 71 | -------------------------------------------------------------------------------- /packages/util/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './codes' 2 | export * from './manipulation' 3 | export * from './vector' 4 | -------------------------------------------------------------------------------- /packages/util/src/manipulation.test.ts: -------------------------------------------------------------------------------- 1 | import ByteBuffer from 'bytebuffer' 2 | import { pack, lerp, unlerp, readPacked } from './manipulation' 3 | 4 | test('lerp works', () => { 5 | expect(lerp(-10, 10, 0.5)).toBe(0) 6 | }) 7 | 8 | test('lerp snaps', () => { 9 | expect(lerp(-30, -20, -69)).toBe(-30) 10 | }) 11 | 12 | test('unlerp works', () => { 13 | expect(unlerp(-10, 10, 0)).toBe(0.5) 14 | }) 15 | 16 | test('pack works', () => { 17 | expect(pack(0)).toMatchInlineSnapshot(` 18 | Object { 19 | "data": Array [ 20 | 0, 21 | ], 22 | "type": "Buffer", 23 | } 24 | `) 25 | 26 | expect(pack(782137612983)).toMatchInlineSnapshot(` 27 | Object { 28 | "data": Array [ 29 | 183, 30 | 181, 31 | 163, 32 | 216, 33 | 1, 34 | ], 35 | "type": "Buffer", 36 | } 37 | `) 38 | }) 39 | 40 | test('can read packed numbers', () => { 41 | const bb = new ByteBuffer(1) 42 | bb.writeByte(0) 43 | bb.clear() 44 | expect(readPacked(bb)).toBe(0) 45 | expect(bb.offset).toBe(1) 46 | }) 47 | -------------------------------------------------------------------------------- /packages/util/src/manipulation.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Pack a number into the smallest number of bytes possible. 3 | * 4 | * @remarks 5 | * See {@link https://wiki.weewoo.net/wiki/Packing | the wiki page on packing} for more information on this process. 6 | * 7 | * @param value Number to pack 8 | */ 9 | export const pack = (value: number) => { 10 | const array = [] 11 | 12 | do { 13 | let b = value & 0xff 14 | if (value >= 0x80) { 15 | b |= 0x80 16 | } 17 | 18 | array.push(b) 19 | value >>= 7 20 | } while (value > 0) 21 | 22 | return Buffer.from(array) 23 | } 24 | 25 | /** 26 | * Read and return a packed number from a buffer, incrementing the offset by the number of bytes. 27 | * 28 | * @remarks 29 | * See {@link https://wiki.weewoo.net/wiki/Packing | the wiki page on packing} for more information on this process. 30 | * 31 | * @param bb Buffer to read from 32 | */ 33 | export const readPacked = (bb: ByteBuffer) => { 34 | let readMore = true 35 | let shift = 0 36 | let output = 0 37 | 38 | while (readMore) { 39 | let b = bb.readUint8() 40 | if (b >= 0x80) { 41 | readMore = true 42 | b ^= 0x80 43 | } else { 44 | readMore = false 45 | } 46 | 47 | output |= b << shift 48 | shift += 7 49 | } 50 | 51 | return output 52 | } 53 | 54 | /** 55 | * Linearly interpolate a number between 0 and 1 to be between the lower and upper bound. 56 | * See `unlerp` for the opposite of this. 57 | * 58 | * @param min Lower bound 59 | * @param max Upper bound 60 | * @param value Value to lerp 61 | */ 62 | export const lerp = (min: number, max: number, value: number) => { 63 | if (value < 0) { 64 | value = 0 65 | } else if (value > 1) { 66 | value = 1 67 | } 68 | 69 | return min + (max - min) * value 70 | } 71 | 72 | /** 73 | * Reverse of `lerp`. Takes a value between the lower and upper bound and maps it to a number between 0 and 1. 74 | * 75 | * @param min Lower bound 76 | * @param max Upper bound 77 | * @param value Value to unlerp 78 | */ 79 | export const unlerp = (min: number, max: number, value: number) => { 80 | return (value - min) / (max - min) 81 | } 82 | -------------------------------------------------------------------------------- /packages/util/src/vector.test.ts: -------------------------------------------------------------------------------- 1 | import ByteBuffer from 'bytebuffer' 2 | import { Vector2 } from './vector' 3 | 4 | test('can create vector2', () => { 5 | const vector2 = new Vector2(1, -3) 6 | expect(vector2.x).toBe(1) 7 | expect(vector2.y).toBe(-3) 8 | }) 9 | 10 | test('can read vector2', () => { 11 | const buffer = new ByteBuffer(4) 12 | buffer.append(Buffer.from([0xbf, 0xff, 0x20, 0x00])) 13 | buffer.clear() 14 | 15 | const vector2 = Vector2.read(buffer) 16 | expect(buffer.offset).toBe(4) 17 | expect(Math.round(vector2.x)).toBe(20) 18 | expect(Math.round(vector2.y)).toBe(-30) 19 | }) 20 | 21 | test('can write vector2', () => { 22 | const vector2 = new Vector2(20, -30) 23 | const buffer = new ByteBuffer(4) 24 | 25 | vector2.write(buffer) 26 | expect(buffer.offset).toBe(4) 27 | expect(buffer.buffer[0]).toBe(0xbf) 28 | expect(buffer.buffer[1]).toBe(0xff) 29 | expect(buffer.buffer[2]).toBe(0x20) 30 | expect(buffer.buffer[3]).toBe(0x00) 31 | }) 32 | -------------------------------------------------------------------------------- /packages/util/src/vector.ts: -------------------------------------------------------------------------------- 1 | import { lerp, unlerp } from './manipulation' 2 | 3 | /** 4 | * A Unity Vector2 helper class with serialization and deserialization methods. 5 | */ 6 | export class Vector2 { 7 | x: number 8 | y: number 9 | 10 | constructor(x: number, y: number) { 11 | this.x = x 12 | this.y = y 13 | } 14 | 15 | /** 16 | * Read a Vector2 from a buffer and correctly linearly interpolate the values. 17 | * 18 | * @param bb Buffer to read from 19 | */ 20 | static read(bb: ByteBuffer): Vector2 { 21 | const x = bb.readUint16() / 65535 22 | const y = bb.readUint16() / 65535 23 | return new Vector2(lerp(-40, 40, x), lerp(-40, 40, y)) 24 | } 25 | 26 | /** 27 | * Write the Vector2 to a buffer and correctly linearly interpolate the values. 28 | * 29 | * @param bb Buffer to write to 30 | */ 31 | write(bb: ByteBuffer) { 32 | const x = unlerp(-40, 40, this.x) * 65535 33 | const y = unlerp(-40, 40, this.y) * 65535 34 | bb.writeUint16(Math.round(x)) 35 | bb.writeUint16(Math.round(y)) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /packages/util/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.build.json", 3 | "include": ["src", "types", "../../types"] 4 | } -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "esnext", 4 | "lib": ["dom", "esnext"], 5 | "importHelpers": true, 6 | "declaration": true, 7 | "sourceMap": true, 8 | "strict": true, 9 | "noUnusedLocals": true, 10 | "noUnusedParameters": true, 11 | "noImplicitReturns": true, 12 | "noFallthroughCasesInSwitch": true, 13 | "moduleResolution": "node", 14 | "jsx": "react", 15 | "esModuleInterop": true 16 | } 17 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.build.json", 3 | "include": ["packages", "types"], 4 | "compilerOptions": { 5 | "allowJs": false, 6 | "baseUrl": ".", 7 | "typeRoots": ["./node_modules/@types", "./types"], 8 | "paths": { 9 | "@among-js/util": ["packages/util/src"], 10 | "@among-js/data": ["packages/data/src"], 11 | "@among-js/packets": ["packages/packets/src"], 12 | "@among-js/sus": ["packages/sus/src"], 13 | "@among-js/hazel": ["packages/hazel/src"] 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /typedoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Among JS", 3 | "inputFiles": [], 4 | "readme": "./README.md", 5 | "out": "docs", 6 | "mode": "modules", 7 | "external-modulemap": ".*packages\/([^\/]+)", 8 | "excludePrivate": true, 9 | "excludeNotExported": true 10 | } --------------------------------------------------------------------------------