├── COPYING.txt ├── README.md ├── client ├── .env.example ├── Dockerfile ├── README.md ├── async_ffi │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── mixnet_client.rs ├── build.sh ├── docs │ └── MessageFormat.md ├── requirements.txt ├── src │ ├── __init__.py │ ├── connectionUtils.py │ ├── cryptographyUtils.py │ ├── dbUtils.py │ ├── logUtils.py │ ├── messageHandler.py │ ├── mixnetMessages.py │ ├── runClient.py │ └── tests │ │ ├── test_crypto.py │ │ ├── test_db.py │ │ └── test_messageHandling.py └── storage │ └── .gitkeep ├── docker-compose.yml ├── docs ├── Build.md └── Protocol.md ├── images ├── architecture.png ├── messageSending.png ├── userLookup.png └── userRegistration.png └── server ├── .env.example ├── COPYING.txt ├── Dockerfile ├── README.md ├── docs └── Overview.md ├── requirements.txt ├── scripts ├── entrypoint.sh └── install.sh ├── src ├── cryptographyUtils.py ├── dbUtils.py ├── envLoader.py ├── logConfig.py ├── mainApp.py ├── messageUtils.py └── websocketUtils.py └── storage └── .gitkeep /COPYING.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nymCHAT 2 | 3 | A security focused messaging app powered by the Nym Mixnet. The repo is divided into two parts: the **Chat Client** (in the _client_ folder) and the **Discovery Node** (in the server folder). Together they enable pseudonymous, end-to-end encrypted messaging. 4 | 5 | ## Overview 6 | 7 | Users register a `public key` and `username` with a discovery node. The discovery node provides user lookups & message relaying. Nodes maintain a database mapping each `username` to its corresponding `public key` and a `senderTag`. 8 | 9 | A `senderTag` is a random UUID string derived from received SURBs. This is used to track which received messages correspond to SURBs. Single Use Reply Blocks (SURBs) allow the server to forward messages to clients without ever knowing the destination of the message. 10 | 11 | Initially, messages are routed through the discovery node; however, clients can exchange an encrypted handshake to enable direct client-to-client communication for an extra layer of privacy. 12 | 13 | ## Security Properties 14 | **I. Transport Privacy** 15 | 16 | All traffic routed through Nym mixnet via sphinx packet format 17 | 18 | **II. Message Privacy** 19 | 20 | End-to-end encryption using ECDH with ephemeral keys + AES-GCM 21 | 22 | **III. Authentication** 23 | 24 | Signature verification using long-term EC keys (SECP256R1) 25 | 26 | **IV. Pseudonymity** 27 | 28 | Username registration with no linkage to real identity 29 | 30 | **V. Direct Communication** 31 | 32 | Optional p2p mode bypasses discovery node after initial contact 33 | 34 | ## Quickstart 35 | For ease of use, we recommend running the app via Docker. 36 | 37 | Detailed documentation on building, running, and troubleshooting: 38 | 39 | - [Client README](client/README.md) 40 | 41 | - [Server README](server/README.md) 42 | 43 | - [Build Docs](docs/Build.md) 44 | 45 | For those interested in the system design, we recommend starting here: 46 | 47 | - [Protocol Docs](docs/Protocol.md) 48 | 49 | - [Discovery Node Overview](server/docs/Overview.md) 50 | 51 | 52 | 53 | ## Future Work 54 | - Rust backend 55 | - Group chats 56 | - MLS Cryptography 57 | - Federated network of discovery nodes -------------------------------------------------------------------------------- /client/.env.example: -------------------------------------------------------------------------------- 1 | SERVER_ADDRESS=42rxQ9Vra6QdXrzi9YphHiBB6tfMydiv3597fvMvhs2o.5B8GWQxPAPW9f4gfWhnM4b7th4UyMnd2hJpiy1PzxZJZ@9AHi1PfuFEH2XAM4czMpB7DbD389QQ4eCxTV87YeKZ2t -------------------------------------------------------------------------------- /client/Dockerfile: -------------------------------------------------------------------------------- 1 | # Stage 1: Build Stage 2 | FROM python:3.11-slim AS builder 3 | 4 | # Install build dependencies 5 | RUN apt-get update && apt-get install -y \ 6 | build-essential \ 7 | libssl-dev \ 8 | pkg-config \ 9 | curl \ 10 | && rm -rf /var/lib/apt/lists/* 11 | 12 | WORKDIR /app 13 | 14 | # Copy the build script and Rust project files 15 | COPY build.sh . 16 | COPY async_ffi/ async_ffi/ 17 | COPY requirements.txt . 18 | 19 | # Make sure build.sh is executable 20 | RUN chmod +x build.sh 21 | 22 | # Run the build script to install Rust (if needed) and build the wheel 23 | RUN ./build.sh 24 | 25 | # Copy the built wheel to a dedicated folder for later retrieval 26 | RUN mkdir /wheel && cp async_ffi/target/wheels/*.whl /wheel/ 27 | 28 | # Stage 2: Final (runtime) Stage 29 | FROM python:3.11-slim 30 | 31 | WORKDIR /app 32 | 33 | # Copy only the files needed at runtime 34 | COPY requirements.txt . 35 | COPY src/ src/ 36 | COPY storage/ storage/ 37 | COPY .env.example .env 38 | 39 | # Copy the pre-built wheel from the builder stage 40 | COPY --from=builder /wheel/ /wheel/ 41 | 42 | # Install runtime Python dependencies and the built wheel 43 | RUN pip install --no-cache-dir -r requirements.txt && \ 44 | pip install --no-cache-dir /wheel/*.whl 45 | 46 | # Expose the port your application uses 47 | EXPOSE 8080 48 | 49 | # Launch the application 50 | CMD ["python", "src/runClient.py"] -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | ## Docker Build 2 | Make sure to set your .env first (.env.example for an example) 3 | ``` 4 | echo "SERVER_ADDRESS=" >> .env 5 | ``` 6 | 7 | Build: 8 | ``` 9 | docker build -t nymchat:latest . 10 | ``` 11 | 12 | Run: 13 | ``` 14 | docker run -d -p 8080 -v $(pwd)/storage:/app/storage --name nymchat-client nymchat:latest 15 | ``` 16 | 17 | Navigate to `localhost:8080` in your browser! 18 | 19 | Check logs: 20 | ``` 21 | docker logs -f nymchat-client 22 | ``` 23 | 24 | 25 | --- 26 | ## Build from Source 27 | 28 | Prerequisites 29 | - Python 3.11 30 | - Rust 31 | --- 32 | ## Set Up 33 | 34 | 1. Clone this repository and navigate to the directory: 35 | ``` 36 | git clone https://github.com/code-zm/nymCHAT.git 37 | cd client 38 | ``` 39 | 40 | 2. Create & activate python virtual environment 41 | ``` 42 | python3 -m venv .venv 43 | source .venv/bin/activate # Windows: .venv\Scripts\activate 44 | ``` 45 | 46 | 3. Install requirements 47 | ``` 48 | pip install -r requirements.txt 49 | ``` 50 | 51 | 4. Build the python-rust bindings 52 | ``` 53 | cd async_ffi # change to the rust ffi directory 54 | maturin build --release # build the .whl 55 | ``` 56 | *Take note of where the .whl file is built, usually `/target/wheels/`* 57 | 58 | 5. Install the FFI library 59 | ``` 60 | pip install target/wheels/*.whl 61 | ``` 62 | 6. Setup your .env (see .env.example for an example) 63 | ``` 64 | echo "SERVER_ADDRESS=" >> .env 65 | ``` 66 | 67 | --- 68 | ## Running the App 69 | 70 | ``` 71 | cd .. # go back to the client home directory 72 | python src/runClient.py # launch the client 73 | ``` 74 | 75 | --- 76 | ## Usage 77 | **Connect to the mixnet** 78 | - Start the app 79 | - Connect to the mixnet 80 | 81 | **Register a new user**: 82 | - Navigate to the **Register** page, enter your username, and click **Register**. 83 | - The system will generate a key pair and send a registration request to the NymDirectory server. 84 | 85 | **Login**: 86 | - After registration, log in using your username to access the messaging features. 87 | 88 | **Search** 89 | - To start a chat with a new user, click the search button at the top. 90 | - Enter the username and click search. *Note: Usernames are CASE SENSITIVE* 91 | 92 | **Send Messages**: 93 | - Once logged in, you can select a contact and send secure, encrypted messages. 94 | 95 | **Send Handshake**: 96 | - Send a handshake to allow the recipient to route their messages directly to you instead of through the discovery node. 97 | 98 | **Database Storage**: 99 | - All messages are stored locally in a SQLite database. The app loads your messages upon login and stores new ones after each communication. 100 | 101 | --- 102 | ## Script Overview 103 | 104 | - `connectionUtils.py`: Manages Mixnet operations using Rust-Python FFI library. 105 | - `cryptographyUtils.py`: Handles cryptographic operations like key generation, signing, encryption, and decryption. 106 | - `dbUtils.py`: Manages the local SQLite database for contacts and messages. 107 | - `messageHandler.py`: Handles the logic for registering, logging in, and managing messages. 108 | - `mixnetMessages.py`: Constructs messages for communication with `nym-client`. 109 | - `runClient.py`: Runs the user interface using NiceGUI. 110 | - `storage/`: Directory where keys and databases are stored. 111 | - `src/`: Directory where the scripts are stored. 112 | -------------------------------------------------------------------------------- /client/async_ffi/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async_ffi" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | [dependencies] 7 | pyo3 = { version = "0.20.0", features = ["extension-module"] } 8 | pyo3-asyncio = { version = "0.20.0", features = ["tokio-runtime"] } 9 | tokio = { version = "1", features = ["full"] } 10 | anyhow = "1.0" 11 | futures = "0.3" 12 | nym-sdk = { git = "https://github.com/nymtech/nym", branch = "master" } 13 | 14 | [lib] 15 | crate-type = ["cdylib"] 16 | 17 | 18 | -------------------------------------------------------------------------------- /client/async_ffi/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod mixnet_client; 2 | use mixnet_client::MixnetHandler; 3 | use pyo3::prelude::*; 4 | use pyo3_asyncio::tokio::future_into_py; 5 | use std::sync::Arc; 6 | 7 | #[pyclass] 8 | struct PyMixnetClient { 9 | inner: Arc, 10 | } 11 | 12 | #[pymethods] 13 | impl PyMixnetClient { 14 | #[staticmethod] 15 | fn create(py: Python) -> PyResult<&PyAny> { 16 | future_into_py(py, async { 17 | let client = MixnetHandler::new().await.map_err(|e| { 18 | pyo3::exceptions::PyRuntimeError::new_err(format!("Client init failed: {:?}", e)) 19 | })?; 20 | Ok(PyMixnetClient { inner: Arc::new(client) }) 21 | }) 22 | } 23 | 24 | #[pyo3(name = "get_nym_address")] 25 | fn get_nym_address<'a>(&self, py: Python<'a>) -> PyResult<&'a PyAny> { 26 | let client = self.inner.clone(); 27 | future_into_py(py, async move { 28 | Ok(client.get_nym_address().await.unwrap_or_else(|| "Client disconnected".to_string())) 29 | }) 30 | } 31 | 32 | #[pyo3(name = "send_message")] 33 | fn send_message<'a>( 34 | &self, 35 | py: Python<'a>, 36 | recipient: String, 37 | message: String, 38 | ) -> PyResult<&'a PyAny> { 39 | let client = self.inner.clone(); 40 | future_into_py(py, async move { 41 | client.send_message(&recipient, &message).await.map_err(|e| { 42 | pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to send message: {:?}", e)) 43 | })?; 44 | Ok(()) 45 | }) 46 | } 47 | 48 | #[pyo3(name = "receive_messages")] 49 | fn receive_messages<'a>(&self, py: Python<'a>) -> PyResult<&'a PyAny> { 50 | let client = self.inner.clone(); 51 | future_into_py(py, async move { 52 | client.receive_messages().await; 53 | Ok(()) 54 | }) 55 | } 56 | 57 | #[pyo3(name = "set_message_callback")] 58 | fn set_message_callback<'a>(&self, py: Python<'a>, py_callback: PyObject) -> PyResult<&'a PyAny> { 59 | let client = self.inner.clone(); 60 | future_into_py(py, async move { 61 | client.set_callback(py_callback).await; 62 | Ok(()) 63 | }) 64 | } 65 | 66 | #[pyo3(name = "shutdown")] 67 | fn shutdown<'a>(&self, py: Python<'a>) -> PyResult<&'a PyAny> { 68 | let client = self.inner.clone(); 69 | future_into_py(py, async move { 70 | client.disconnect().await; 71 | Ok(()) 72 | }) 73 | } 74 | } 75 | 76 | #[pymodule] 77 | fn async_ffi(_py: Python, m: &PyModule) -> PyResult<()> { 78 | m.add_class::()?; 79 | Ok(()) 80 | } 81 | 82 | -------------------------------------------------------------------------------- /client/async_ffi/src/mixnet_client.rs: -------------------------------------------------------------------------------- 1 | use futures::StreamExt; 2 | use nym_sdk::mixnet::{MixnetClient, MixnetClientSender, MixnetMessageSender, Recipient}; 3 | use std::sync::Arc; 4 | use tokio::sync::{Mutex, Notify}; 5 | use pyo3::prelude::*; 6 | use anyhow::Context; 7 | 8 | pub struct MixnetHandler { 9 | client: Arc>>, 10 | sender: MixnetClientSender, 11 | message_callback: Arc>>, 12 | listening: Arc>, 13 | shutdown_signal: Arc, 14 | } 15 | 16 | impl MixnetHandler { 17 | /// Creates a new Mixnet client. 18 | pub async fn new() -> anyhow::Result { 19 | let client = nym_sdk::mixnet::MixnetClientBuilder::new_ephemeral() 20 | .build() 21 | .context("Failed to build ephemeral client")? 22 | .connect_to_mixnet() 23 | .await 24 | .context("Failed to connect to mixnet")?; 25 | 26 | let sender = client.split_sender(); 27 | Ok(Self { 28 | client: Arc::new(Mutex::new(Some(client))), 29 | sender, 30 | message_callback: Arc::new(Mutex::new(None)), 31 | listening: Arc::new(Mutex::new(false)), 32 | shutdown_signal: Arc::new(Notify::new()), 33 | }) 34 | } 35 | 36 | pub async fn set_callback(&self, callback: PyObject) { 37 | let mut cb = self.message_callback.lock().await; 38 | *cb = Some(callback); 39 | } 40 | 41 | pub async fn get_nym_address(&self) -> Option { 42 | let lock = self.client.lock().await; 43 | lock.as_ref().map(|c| c.nym_address().to_string()) 44 | } 45 | 46 | pub async fn send_message(&self, recipient: &str, message: &str) -> anyhow::Result<()> { 47 | let parsed_recipient = recipient 48 | .parse::() 49 | .context("Failed to parse recipient address")?; 50 | 51 | println!("🚀 Sending message to: {}", recipient); 52 | 53 | self.sender 54 | .send_message( 55 | parsed_recipient, 56 | message.as_bytes().to_vec(), 57 | nym_sdk::mixnet::IncludedSurbs::Amount(10), // 👈 Corrected here 58 | ) 59 | .await 60 | .context("Failed to send message with SURBs")?; 61 | 62 | println!("✅ Message sent successfully with 10 SURBs included!"); 63 | Ok(()) 64 | } 65 | 66 | 67 | 68 | pub async fn receive_messages(&self) { 69 | let mut listening = self.listening.lock().await; 70 | if *listening { 71 | println!("⚠️ Listener already running, skipping..."); 72 | return; 73 | } 74 | *listening = true; 75 | drop(listening); 76 | 77 | let client_ref = Arc::clone(&self.client); 78 | let callback_ref = Arc::clone(&self.message_callback); 79 | let shutdown_signal = Arc::clone(&self.shutdown_signal); 80 | 81 | tokio::spawn(async move { 82 | let mut lock = client_ref.lock().await; 83 | if let Some(client) = lock.as_mut() { 84 | println!("📡 Listening for incoming messages..."); 85 | loop { 86 | tokio::select! { 87 | _ = shutdown_signal.notified() => { 88 | println!("🛑 Listener stopping..."); 89 | break; 90 | } 91 | received = client.next() => { 92 | if let Some(received) = received { 93 | if !received.message.is_empty() { 94 | let msg_str = String::from_utf8_lossy(&received.message).to_string(); 95 | let callback = callback_ref.lock().await; 96 | pyo3::Python::with_gil(|py| { 97 | if let Some(ref callback) = *callback { 98 | if let Err(e) = callback.call1(py, (&msg_str,)) { 99 | e.print(py); 100 | } 101 | } else { 102 | println!("📩 Received: {}", msg_str); 103 | } 104 | }); 105 | } 106 | } 107 | } 108 | } 109 | } 110 | } 111 | }); 112 | } 113 | 114 | pub async fn disconnect(&self) { 115 | println!("🚪 Stopping background tasks..."); 116 | self.shutdown_signal.notify_waiters(); 117 | 118 | let mut lock = self.client.lock().await; 119 | if let Some(client) = lock.take() { 120 | println!("🔌 Disconnecting Mixnet client..."); 121 | client.disconnect().await; 122 | println!("✅ Client disconnected."); 123 | } 124 | } 125 | } 126 | 127 | -------------------------------------------------------------------------------- /client/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Function to log messages 5 | log() { 6 | echo "[$1] $2" 7 | } 8 | 9 | # Install Rust if it's not already available 10 | if ! command -v rustc >/dev/null 2>&1; then 11 | log "INFO" "Rust not found. Installing Rust toolchain..." 12 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y 13 | source "$HOME/.cargo/env" 14 | log "INFO" "Rust installed successfully!" 15 | else 16 | log "INFO" "Rust is already installed: $(rustc --version)" 17 | fi 18 | 19 | log "INFO" "Installing maturin" 20 | pip install --no-cache-dir maturin 21 | # Build the Rust extension using maturin 22 | log "INFO" "Building Rust extension..." 23 | cd async_ffi 24 | maturin build --release 25 | -------------------------------------------------------------------------------- /client/docs/MessageFormat.md: -------------------------------------------------------------------------------- 1 | 2 | **General Message Format** 3 | ```json 4 | { 5 | "a": "action_code", 6 | "c": "context_code", 7 | "p": "{payload}" 8 | } 9 | ``` 10 | 11 | This is then encapsulated for the nym-client to send, resulting in this nested structure: 12 | ```json 13 | { 14 | "message": "{\"a\":5,\"p\":{\"f\":\"alice\",\"to\":\"bob\",\"e\":{\"epk\":\"\",\"iv\":\"\",\"ct\":\"\",\"tag\":\"\"},\"s\":\"\"}}", 15 | "recipient": "recipient_nym_address", 16 | "senderTag": "sender_tag" 17 | } 18 | ``` 19 | 20 | 21 | ## Client -> Server Messages 22 | 23 | #### 🔍 Query User (Action = 0) 24 | Query the server for user information (public key). 25 | 26 | ``` 27 | # Inner Payload 28 | { 29 | "u": "" 30 | } 31 | 32 | # Full Message 33 | { 34 | "message": "{ 35 | \"a\": 0, 36 | \"p\": { 37 | \"u\": \"bob\" 38 | } 39 | }", 40 | "recipient": "server_address_here", 41 | "senderTag": "client_sender_tag" 42 | } 43 | ``` 44 | 45 | #### 🔑 Register (Action = 1) 46 | Registers a new user account. 47 | 48 | ``` 49 | # Inner Payload 50 | { 51 | "u": "", 52 | "k": "" 53 | } 54 | 55 | # Full Message 56 | { 57 | "message": "{ 58 | \"a\": 1, 59 | \"p\": { 60 | \"u\": \"alice\", 61 | \"k\": \"\" 62 | } 63 | }", 64 | "recipient": "server_address_here", 65 | "senderTag": "client_sender_tag" 66 | } 67 | ``` 68 | 69 | #### 📤 Registration Response (Action = 2) 70 | Client responds to registration challenge. 71 | 72 | ``` 73 | # Inner Payload 74 | { 75 | "u": "", 76 | "s": "" 77 | } 78 | 79 | # Full Message 80 | { 81 | "message": "{ 82 | \"a\": 2, 83 | \"p\": { 84 | \"u\": \"alice\", 85 | \"s\": \"\" 86 | } 87 | }", 88 | "recipient": "server_address_here", 89 | "senderTag": "client_sender_tag" 90 | } 91 | ``` 92 | 93 | #### 🔐 Login (Action = 3) 94 | Request to authenticate an existing user. 95 | 96 | 97 | ``` 98 | # Inner Payload 99 | { 100 | "u": "" 101 | } 102 | 103 | # Full Message 104 | { 105 | "message": "{ 106 | \"a\": 3, 107 | \"p\": { 108 | \"u\": \"alice\" 109 | } 110 | }", 111 | "recipient": "server_address_here", 112 | "senderTag": "client_sender_tag" 113 | } 114 | 115 | 116 | ``` 117 | 118 | #### ✅ Login Response (Action = 4) 119 | Client responds to a login challenge. 120 | 121 | 122 | ``` 123 | # Inner Payload 124 | { 125 | "u": "", 126 | "s": "" 127 | } 128 | 129 | # Full Message: 130 | { 131 | "message": "{ 132 | \"a\": 4, 133 | \"p\": { 134 | \"u\": \"alice\", 135 | \"s\": \"\" 136 | } 137 | }", 138 | "recipient": "server_address_here", 139 | "senderTag": "client_sender_tag" 140 | } 141 | 142 | ``` 143 | 144 | #### 📧 Send Direct Message (Action = 5) 145 | Sends an encrypted direct message to another user. 146 | 147 | ``` 148 | # Inner Payload 149 | { 150 | "f": "", 151 | "to": "", 152 | "e": { 153 | "epk": "", 154 | "iv": "", 155 | "ct": "", 156 | "tag": "" 157 | }, 158 | "s": "" 159 | } 160 | 161 | # Full Message 162 | { 163 | "message": "{ 164 | \"a\": 5, 165 | \"p\": { 166 | \"f\": \"alice\", 167 | \"to\": \"bob\", 168 | \"e\": { 169 | \"epk\": \"\", 170 | \"iv\": \"\", 171 | \"ct\": \"\", 172 | \"tag\": \"\" 173 | }, 174 | \"s\": \"\" 175 | } 176 | }", 177 | "recipient": "server_address_here", 178 | "senderTag": "client_sender_tag" 179 | } 180 | ``` 181 | 182 | 183 | ## Server -> Client Messages 184 | 185 | #### 🔍 Query Response (Action = 0) 186 | Server response to a user's query request. 187 | 188 | Context required: 189 | - `c: 3` (Query) 190 | 191 | If user found: 192 | ``` 193 | 194 | # Inner Payload 195 | { 196 | "u": "", 197 | "k": "" 198 | } 199 | 200 | # Full Message 201 | { 202 | "message": "{ 203 | \"a\": 0, 204 | \"c\": 3, 205 | \"p\": { 206 | \"u\": \"bob\", 207 | \"k\": \"\" 208 | } 209 | }", 210 | "recipient": "client_ephemeral_address", 211 | "senderTag": "server_sender_tag" 212 | } 213 | ``` 214 | 215 | If user not found: 216 | ``` 217 | # Inner Payload 218 | "No user found" 219 | 220 | # Full Message 221 | { 222 | "message": "{ 223 | \"a\": 0, 224 | \"c\": 3, 225 | \"p\": \"No user found\" 226 | }", 227 | "recipient": "client_ephemeral_address", 228 | "senderTag": "server_sender_tag" 229 | } 230 | ``` 231 | 232 | #### 📥 Incoming Message (Action = 6) 233 | Encrypted direct message forwarded from another client via server. 234 | 235 | Context required: 236 | - `c: 2` (Chat) 237 | 238 | Payload: 239 | ``` 240 | 241 | # Inner Payload 242 | { 243 | "f": "", 244 | "e": { 245 | "epk": "", 246 | "iv": "", 247 | "ct": "", 248 | "tag": "" 249 | }, 250 | "s": "", 251 | "pk": "" 252 | } 253 | 254 | # Full Message 255 | { 256 | "message": "{ 257 | \"a\": 6, 258 | \"c\": 2, 259 | \"p\": { 260 | \"f\": \"alice\", 261 | \"e\": { 262 | \"epk\": \"\", 263 | \"iv\": \"\", 264 | \"ct\": \"\", 265 | \"tag\": \"\" 266 | }, 267 | \"s\": \"\", 268 | \"pk\": \"\" 269 | } 270 | }", 271 | "recipient": "bob_ephemeral_address", 272 | "senderTag": "sender_ephemeral_tag" 273 | } 274 | ``` 275 | 276 | #### 📦 Send Response (Action = 7) 277 | Server acknowledges the delivery status of a client's sent message. 278 | 279 | Context required: 280 | - `c: 2` (Chat) 281 | 282 | - on success: 283 | ``` 284 | # Inner Payload 285 | "success" 286 | 287 | # Full Message 288 | { 289 | "message": "{ 290 | \"a\": 7, 291 | \"c\": 2, 292 | \"p\": \"success\" 293 | }", 294 | "recipient": "client_ephemeral_address", 295 | "senderTag": "server_sender_tag" 296 | } 297 | ``` 298 | 299 | - on fail: 300 | ``` 301 | # Inner Payload 302 | "error:" 303 | 304 | # Full Message 305 | { 306 | "message": "{ 307 | \"a\": 7, 308 | \"c\": 2, 309 | \"p\": \"error:recipient not found\" 310 | }", 311 | "recipient": "client_ephemeral_address", 312 | "senderTag": "server_sender_tag" 313 | } 314 | ``` 315 | 316 | #### 🛡️ Challenge (Action = 8) 317 | Sends a cryptographic nonce challenge to verify identity. 318 | 319 | Contexts required: 320 | - `c: 0` (Registration) 321 | - `c: 1` (Login) 322 | 323 | Payload: 324 | ``` 325 | { 326 | "n": "" 327 | } 328 | ``` 329 | 330 | #### ✅ Challenge Response (Action = 9) 331 | Server confirms client's response to a challenge. 332 | 333 | Contexts required: 334 | - `c: 0` (Registration) 335 | - `c: 1` (Login) 336 | 337 | Payload: 338 | - on success: 339 | ``` 340 | "success" 341 | ``` 342 | 343 | - on fail: 344 | ``` 345 | "error:" 346 | ``` 347 | 348 | 349 | ## Client -> Client Direct Messages 350 | #### 📬 Incoming Direct Message (Action = 6) 351 | Direct encrypted messages sent between clients via ephemeral routing. The recipient client receives this format directly: 352 | 353 | Context required: 354 | - `c: 2` (Chat) 355 | 356 | ``` 357 | # Inner Payload 358 | { 359 | "f": "", 360 | "e": { 361 | "epk": "", 362 | "iv": "", 363 | "ct": "", 364 | "tag": "" 365 | }, 366 | "s": "", 367 | "pk": "" 368 | } 369 | 370 | # Full Message 371 | { 372 | "message": "{ 373 | \"a\": 6, 374 | \"c\": 2, 375 | \"p\": { 376 | \"f\": \"alice\", 377 | \"e\": { 378 | \"epk\": \"\", 379 | \"iv\": \"\", 380 | \"ct\": \"\", 381 | \"tag\": \"\" 382 | }, 383 | \"s\": \"\", 384 | \"pk\": \"\" 385 | } 386 | }", 387 | "recipient": "bob_ephemeral_address", 388 | "senderTag": "sender_ephemeral_tag" 389 | } 390 | ``` 391 | 392 | # 📖 References: 393 | 394 | **Field Legend** 395 | 396 | | Field | Description | 397 | | ----- | ----------------------------------------------- | 398 | | `a` | Action code | 399 | | `c` | Context code | 400 | | `p` | Payload | 401 | | `u` | Username | 402 | | `k` | Public key (PEM format) | 403 | | `s` | Signature | 404 | | `n` | Nonce | 405 | | `f` | Sender username ("from") | 406 | | `to` | Recipient username | 407 | | `e` | Encrypted payload | 408 | | `epk` | Ephemeral public key | 409 | | `iv` | Initialization vector (base64) | 410 | | `ct` | Ciphertext (base64) | 411 | | `tag` | AES-GCM authentication tag (base64) | 412 | | `pk` | Sender's public key (optional, initial contact) | 413 | 414 | **🗂️ Action Codes Reference Table** 415 | 416 | | Action Name | Code | 417 | | --------------------- | ---- | 418 | | Query User | 0 | 419 | | Register | 1 | 420 | | Registration Response | 2 | 421 | | Login | 3 | 422 | | Login Response | 4 | 423 | | Send Direct Message | 5 | 424 | | Incoming Message | 6 | 425 | | Send Response | 7 | 426 | | Challenge | 8 | 427 | | Chellenge Response | 9 | 428 | 429 | **🏷️ Context Codes Reference Table** 430 | 431 | |Context Name|Code| 432 | |---|---| 433 | |Registration|0| 434 | |Login|1| 435 | |Chat|2| 436 | |Query|3| 437 | -------------------------------------------------------------------------------- /client/requirements.txt: -------------------------------------------------------------------------------- 1 | nicegui 2 | cryptography 3 | maturin 4 | -------------------------------------------------------------------------------- /client/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/code-zm/nymCHAT/f41b74f0b02d5c3ba4a779d9759a5260a7cf7021/client/src/__init__.py -------------------------------------------------------------------------------- /client/src/connectionUtils.py: -------------------------------------------------------------------------------- 1 | import json 2 | from async_ffi import PyMixnetClient 3 | from logUtils import logger 4 | 5 | class MixnetConnectionClient: 6 | def __init__(self): 7 | self.client = None # Will be initialized asynchronously 8 | 9 | async def init(self): 10 | """ 11 | Asynchronously initialize the mixnet client. 12 | """ 13 | self.client = await PyMixnetClient.create() 14 | 15 | async def get_nym_address(self): 16 | """ 17 | Asynchronously retrieve the client's Nym address. 18 | """ 19 | return await self.client.get_nym_address() 20 | 21 | async def send_message(self, message): 22 | """ 23 | Send a message using the async mixnet FFI. 24 | Expects `message` to be a dict with at least 'recipient' and 'message' keys. 25 | """ 26 | recipient = message.get("recipient") 27 | msg = message.get("message") 28 | if not recipient or not msg: 29 | raise ValueError("Both 'recipient' and 'message' must be provided.") 30 | await self.client.send_message(recipient, msg) 31 | 32 | async def set_message_callback(self, callback): 33 | """ 34 | Set a callback function for incoming messages. 35 | """ 36 | await self.client.set_message_callback(callback) 37 | 38 | async def receive_messages(self): 39 | """ 40 | Start receiving messages from the Mixnet. 41 | """ 42 | logger.info("STARTED MESSAGE RECEIVING LOOP") 43 | await self.client.receive_messages() # Ensure this is awaited properly 44 | 45 | async def shutdown(self): 46 | """ 47 | Asynchronously shut down the mixnet client. 48 | """ 49 | await self.client.shutdown() 50 | -------------------------------------------------------------------------------- /client/src/cryptographyUtils.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.asymmetric import ec 2 | from cryptography.hazmat.primitives.kdf.hkdf import HKDF 3 | from cryptography.hazmat.primitives import hashes, serialization 4 | from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature, decode_dss_signature 5 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 6 | import os 7 | import json 8 | 9 | class CryptoUtils: 10 | def __init__(self, storage_dir="storage"): 11 | """Initialize the CryptoUtils with a base storage directory.""" 12 | self.storage_dir = storage_dir 13 | if not os.path.exists(storage_dir): 14 | os.makedirs(storage_dir) 15 | 16 | # ---------------------------------------------- 17 | # 🔑 KEY MANAGEMENT 18 | # ---------------------------------------------- 19 | def generate_key_pair(self, username): 20 | """Generate a private/public key pair.""" 21 | private_key = ec.generate_private_key(ec.SECP256R1()) 22 | public_key = private_key.public_key() 23 | public_key_pem = public_key.public_bytes( 24 | encoding=serialization.Encoding.PEM, 25 | format=serialization.PublicFormat.SubjectPublicKeyInfo, 26 | ).decode() 27 | return private_key, public_key_pem 28 | 29 | def save_keys(self, username, private_key, public_key_pem): 30 | """Save the private and public keys to files.""" 31 | user_dir = os.path.join(self.storage_dir, username) 32 | if not os.path.exists(user_dir): 33 | os.makedirs(user_dir) 34 | 35 | # Save private key 36 | private_key_path = os.path.join(user_dir, f"{username}_private_key.pem") 37 | with open(private_key_path, "wb") as f: 38 | f.write( 39 | private_key.private_bytes( 40 | encoding=serialization.Encoding.PEM, 41 | format=serialization.PrivateFormat.PKCS8, 42 | encryption_algorithm=serialization.NoEncryption(), 43 | ) 44 | ) 45 | 46 | # Save public key 47 | public_key_path = os.path.join(user_dir, f"{username}_public_key.pem") 48 | with open(public_key_path, "wb") as f: 49 | f.write(public_key_pem.encode()) 50 | 51 | def load_private_key(self, username): 52 | """Load the private key from the user's folder.""" 53 | private_key_path = os.path.join(self.storage_dir, username, f"{username}_private_key.pem") 54 | with open(private_key_path, "rb") as f: 55 | private_key = serialization.load_pem_private_key( 56 | f.read(), 57 | password=None, 58 | ) 59 | return private_key 60 | 61 | def load_public_key(self, username): 62 | """Load the public key from the user's folder.""" 63 | public_key_path = os.path.join(self.storage_dir, username, f"{username}_public_key.pem") 64 | with open(public_key_path, "rb") as f: 65 | public_key = serialization.load_pem_public_key(f.read()) 66 | return public_key 67 | 68 | # ---------------------------------------------- 69 | # 🔒 SIGNING & VERIFICATION 70 | # ---------------------------------------------- 71 | def sign_message(self, private_key, message): 72 | """Sign a message using ECDSA.""" 73 | if not isinstance(message, str): 74 | raise ValueError("sign_message expects a raw string, not a dictionary.") 75 | 76 | signature = private_key.sign( 77 | message.encode(), 78 | ec.ECDSA(hashes.SHA256()) 79 | ) 80 | return signature.hex() 81 | 82 | def verify_signature(self, public_key, message, signature): 83 | """Verify the authenticity of a signed message.""" 84 | try: 85 | r, s = decode_dss_signature(bytes.fromhex(signature)) 86 | public_key.verify( 87 | encode_dss_signature(r, s), 88 | message.encode(), 89 | ec.ECDSA(hashes.SHA256()) 90 | ) 91 | return True 92 | except Exception: 93 | return False 94 | 95 | # ---------------------------------------------- 96 | # 🔑 ENCRYPTION & DECRYPTION WITH ECDH 97 | # ---------------------------------------------- 98 | def encrypt_message(self, recipient_public_key_pem, message): 99 | """Encrypts a message using ECDH key exchange + AES-GCM.""" 100 | 101 | # ✅ Automatically convert a string public key to a PEM-encoded object 102 | if isinstance(recipient_public_key_pem, str): 103 | try: 104 | recipient_public_key = serialization.load_pem_public_key(recipient_public_key_pem.encode()) 105 | except ValueError: 106 | raise ValueError("❌ Invalid PEM format for recipient public key.") 107 | else: 108 | recipient_public_key = recipient_public_key_pem # Assume it's already a key object 109 | 110 | # ✅ Generate an ephemeral key pair 111 | ephemeral_private_key = ec.generate_private_key(ec.SECP256R1()) 112 | ephemeral_public_key = ephemeral_private_key.public_key() 113 | 114 | # ✅ Compute shared secret using ephemeral private key and recipient's public key 115 | shared_secret = ephemeral_private_key.exchange(ec.ECDH(), recipient_public_key) 116 | salt = os.urandom(16) # 128 bits of salt 117 | # ✅ Derive AES key using HKDF 118 | derived_key = HKDF( 119 | algorithm=hashes.SHA256(), 120 | length=32, 121 | salt=salt, 122 | info=b'ECDH session key' 123 | ).derive(shared_secret) 124 | 125 | # ✅ Encrypt message using AES-GCM 126 | encrypted_payload = self._aes_encrypt(message, derived_key) 127 | 128 | # ✅ Serialize ephemeral public key 129 | ephemeral_public_key_pem = ephemeral_public_key.public_bytes( 130 | encoding=serialization.Encoding.PEM, 131 | format=serialization.PublicFormat.SubjectPublicKeyInfo 132 | ).decode() 133 | 134 | return { 135 | "ephemeralPublicKey": ephemeral_public_key_pem, 136 | "salt": salt.hex(), 137 | "encryptedBody": encrypted_payload 138 | } 139 | 140 | def decrypt_message(self, recipient_private_key, encrypted_message): 141 | """Decrypt an encrypted message using ECDH key exchange and AES-GCM.""" 142 | 143 | try: 144 | # ✅ Extract ephemeral public key and encrypted body 145 | ephemeral_public_key_pem = encrypted_message["ephemeralPublicKey"] 146 | encrypted_body = encrypted_message["encryptedBody"] 147 | salt = bytes.fromhex(encrypted_message["salt"]) 148 | 149 | ephemeral_public_key = serialization.load_pem_public_key(ephemeral_public_key_pem.encode()) 150 | 151 | # ✅ Compute shared secret using recipient’s private key & sender’s ephemeral public key 152 | shared_key = recipient_private_key.exchange(ec.ECDH(), ephemeral_public_key) 153 | 154 | # ✅ Derive AES key using HKDF 155 | derived_key = HKDF( 156 | algorithm=hashes.SHA256(), 157 | length=32, 158 | salt=salt, 159 | info=b'ECDH session key' 160 | ).derive(shared_key) 161 | 162 | # ✅ Decrypt the message 163 | decrypted_message = self._aes_decrypt(encrypted_body, derived_key) 164 | 165 | return decrypted_message # ✅ Return the plaintext message directly 166 | 167 | except Exception as e: 168 | print(f"❌ Error during decryption: {e}") 169 | return None 170 | 171 | 172 | # ---------------------------------------------- 173 | # 🛡 AES-GCM ENCRYPTION HELPERS 174 | # ---------------------------------------------- 175 | def _aes_encrypt(self, plaintext, derived_key): 176 | """Encrypt a message using AES-GCM.""" 177 | iv = os.urandom(12) 178 | encryptor = Cipher(algorithms.AES(derived_key), modes.GCM(iv)).encryptor() 179 | ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize() 180 | return { 181 | "iv": iv.hex(), 182 | "ciphertext": ciphertext.hex(), 183 | "tag": encryptor.tag.hex() 184 | } 185 | 186 | def _aes_decrypt(self, enc_dict, derived_key): 187 | """Decrypt an encrypted message using AES-GCM.""" 188 | iv = bytes.fromhex(enc_dict["iv"]) 189 | ciphertext = bytes.fromhex(enc_dict["ciphertext"]) 190 | tag = bytes.fromhex(enc_dict["tag"]) 191 | decryptor = Cipher(algorithms.AES(derived_key), modes.GCM(iv, tag)).decryptor() 192 | plaintext = decryptor.update(ciphertext) + decryptor.finalize() 193 | return plaintext.decode() 194 | -------------------------------------------------------------------------------- /client/src/dbUtils.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import json 3 | import os 4 | from datetime import datetime 5 | 6 | class SQLiteManager: 7 | def __init__(self, username, storage_dir="storage"): 8 | """ 9 | Initialize the database connection and create necessary tables. 10 | :param username: The username of the client. 11 | :param storage_dir: The base directory for storage. 12 | """ 13 | user_dir = os.path.join(storage_dir, username) 14 | if not os.path.exists(user_dir): 15 | os.makedirs(user_dir) 16 | 17 | db_path = os.path.join(user_dir, f"{username}_client.db") 18 | self.conn = sqlite3.connect(db_path) 19 | self.create_global_tables() 20 | 21 | def create_global_tables(self): 22 | """ 23 | Create global tables to track users. 24 | """ 25 | with self.conn: 26 | # Global users table now stores only username and public_key 27 | self.conn.execute(""" 28 | CREATE TABLE IF NOT EXISTS users ( 29 | username TEXT PRIMARY KEY, 30 | public_key TEXT NOT NULL 31 | ) 32 | """) 33 | 34 | def create_user_tables(self, username): 35 | """ 36 | Create user-specific tables for contacts and messages. 37 | """ 38 | with self.conn: 39 | # Contacts table for the specific user now stores username and public_key 40 | self.conn.execute(f""" 41 | CREATE TABLE IF NOT EXISTS contacts_{username} ( 42 | username TEXT PRIMARY KEY, 43 | public_key TEXT NOT NULL 44 | ) 45 | """) 46 | # Messages table for the specific user remains unchanged 47 | self.conn.execute(f""" 48 | CREATE TABLE IF NOT EXISTS messages_{username} ( 49 | id INTEGER PRIMARY KEY AUTOINCREMENT, 50 | username TEXT NOT NULL, 51 | type TEXT CHECK(type IN ('to', 'from')) NOT NULL, 52 | message TEXT NOT NULL, 53 | timestamp DATETIME DEFAULT CURRENT_TIMESTAMP 54 | ) 55 | """) 56 | 57 | def register_user(self, username, public_key): 58 | """ 59 | Register a new user and create their specific tables. 60 | """ 61 | with self.conn: 62 | # Add user to the global users table (store the public key) 63 | self.conn.execute(""" 64 | INSERT OR REPLACE INTO users (username, public_key) 65 | VALUES (?, ?) 66 | """, (username, public_key)) 67 | # Create user-specific tables 68 | self.create_user_tables(username) 69 | 70 | def add_contact(self, active_user, contact_username, public_key): 71 | """ 72 | Add or update a contact for the specified active user. 73 | """ 74 | with self.conn: 75 | self.conn.execute(f""" 76 | INSERT OR REPLACE INTO contacts_{active_user} (username, public_key) 77 | VALUES (?, ?) 78 | """, (contact_username, public_key)) 79 | 80 | def get_contact(self, active_user, contact_username): 81 | """ 82 | Retrieve a contact's information for the specified active user. 83 | Returns (username, public_key) if found. 84 | """ 85 | with self.conn: 86 | return self.conn.execute(f""" 87 | SELECT username, public_key 88 | FROM contacts_{active_user} 89 | WHERE username = ? 90 | """, (contact_username,)).fetchone() 91 | 92 | def get_all_contacts(self, active_user): 93 | """ 94 | Retrieve all contacts for the specified active user. 95 | """ 96 | with self.conn: 97 | return self.conn.execute(f"SELECT * FROM contacts_{active_user}").fetchall() 98 | 99 | def save_message(self, active_user, contact_username, msg_type, message): 100 | """ 101 | Save a message for the specified active user. 102 | """ 103 | with self.conn: 104 | self.conn.execute(f""" 105 | INSERT INTO messages_{active_user} (username, type, message) 106 | VALUES (?, ?, ?) 107 | """, (contact_username, msg_type, message)) 108 | 109 | def get_messages_by_contact(self, active_user, contact_username): 110 | """ 111 | Retrieve all messages exchanged with a specific contact for the active user. 112 | """ 113 | with self.conn: 114 | return self.conn.execute(f""" 115 | SELECT type, message, timestamp 116 | FROM messages_{active_user} 117 | WHERE username = ? 118 | ORDER BY timestamp ASC 119 | """, (contact_username,)).fetchall() 120 | 121 | def get_all_messages(self, active_user): 122 | """ 123 | Retrieve all messages for the specified active user. 124 | """ 125 | with self.conn: 126 | return self.conn.execute(f""" 127 | SELECT username, type, message, timestamp 128 | FROM messages_{active_user} 129 | ORDER BY username, timestamp ASC 130 | """).fetchall() 131 | 132 | def delete_contact(self, active_user, contact_username): 133 | """ 134 | Delete a contact for the specified active user. 135 | """ 136 | with self.conn: 137 | self.conn.execute(f""" 138 | DELETE FROM contacts_{active_user} WHERE username = ? 139 | """, (contact_username,)) 140 | 141 | def delete_all_messages(self, active_user): 142 | """ 143 | Delete all messages for the specified active user. 144 | """ 145 | with self.conn: 146 | self.conn.execute(f"DELETE FROM messages_{active_user}") 147 | 148 | def get_all_users(self): 149 | """ 150 | Retrieve all registered users. 151 | """ 152 | with self.conn: 153 | return self.conn.execute("SELECT * FROM users").fetchall() 154 | 155 | def close(self): 156 | """ 157 | Close the database connection. 158 | """ 159 | self.conn.close() 160 | -------------------------------------------------------------------------------- /client/src/logUtils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | # Configure logging 5 | LOG_FILE = os.path.join(os.getcwd(), "storage", "app.log") 6 | 7 | logging.basicConfig( 8 | level=logging.INFO, 9 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 10 | handlers=[ 11 | logging.FileHandler(LOG_FILE), # Log to file 12 | logging.StreamHandler() # Log to console 13 | ] 14 | ) 15 | 16 | logger = logging.getLogger("AppLogger") 17 | 18 | logging.getLogger("watchfiles").setLevel(logging.WARNING) 19 | -------------------------------------------------------------------------------- /client/src/messageHandler.py: -------------------------------------------------------------------------------- 1 | import json 2 | import asyncio 3 | from nicegui import ui 4 | from datetime import datetime 5 | from cryptography.hazmat.primitives import serialization 6 | from mixnetMessages import MixnetMessage 7 | from cryptographyUtils import CryptoUtils 8 | from connectionUtils import MixnetConnectionClient 9 | from dbUtils import SQLiteManager 10 | from logUtils import logger 11 | 12 | class MessageHandler: 13 | def __init__(self, crypto_utils: CryptoUtils, connection_client: MixnetConnectionClient): 14 | self.crypto_utils = crypto_utils 15 | self.connection_client = connection_client 16 | self.current_user = {"username": None} 17 | self.temporary_keys = {"private_key": None, "public_key": None} 18 | self.db_manager = None # Will be set after login/registration 19 | 20 | # Wait-for-completion events 21 | self.registration_complete = asyncio.Event() 22 | self.login_complete = asyncio.Event() 23 | 24 | # Registration / login status (success or failure) 25 | self.registration_successful = None 26 | self.login_successful = None 27 | 28 | # Query flow 29 | self.query_result_event = asyncio.Event() 30 | self.query_result = None 31 | 32 | # [OPTIONAL] references to UI or chat state 33 | self.chat_messages = None 34 | self.chat_list = None 35 | self.active_chat = None 36 | self.render_chat_fn = None 37 | self.chat_list_sidebar_fn = None # For refreshing the chat list sidebar 38 | self.chat_container = None 39 | self.new_message_callback = None # To notify UI of new messages 40 | 41 | # Ephemeral mapping of usernames to nym addresses for p2p routing 42 | self.nym_addresses = {} # {username: nym_address} 43 | 44 | # Store our own nym address (to be set externally after mixnet initialization) 45 | self.nym_address = None 46 | 47 | def update_nym_address(self, nym_address): 48 | """Update the client's own nym address in MessageHandler.""" 49 | self.nym_address = nym_address 50 | logger.info(f"Updated own nym address in MessageHandler: {nym_address}") 51 | 52 | def set_ui_state(self, messages, chat_list, get_active_chat, render_chat, chat_container, chat_list_sidebar_fn=None): 53 | """ 54 | Optionally call this from runClient.py if you want to update UI state 55 | directly from handle_incoming_message. 56 | 'get_active_chat' can be a function or a reference to the global variable. 57 | """ 58 | self.chat_messages = messages 59 | self.chat_list = chat_list 60 | self._get_active_chat = get_active_chat 61 | self.render_chat_fn = render_chat 62 | self.chat_container = chat_container 63 | self.chat_list_sidebar_fn = chat_list_sidebar_fn # Store reference for sidebar refresh 64 | 65 | # -------------------------------------------------------------------------- 66 | # Registration & Login 67 | # -------------------------------------------------------------------------- 68 | 69 | async def register_user(self, username, first_name="", last_name=""): 70 | try: 71 | self.current_user["username"] = username 72 | self.registration_complete.clear() 73 | 74 | private_key, public_key = self.crypto_utils.generate_key_pair(username) 75 | self.temporary_keys["private_key"] = private_key 76 | self.temporary_keys["public_key"] = public_key 77 | logger.info(f"Keypair generated for user: {username}") 78 | 79 | # Send a 'register' message (only username and public key are used) 80 | register_msg = MixnetMessage.register(usernym=username, publicKey=public_key) 81 | await self.connection_client.send_message(register_msg) 82 | logger.info("Registration message sent; waiting for challenge...") 83 | 84 | await self.registration_complete.wait() 85 | 86 | except Exception as e: 87 | logger.error(f"Registration error: {e}") 88 | 89 | async def login_user(self, username): 90 | try: 91 | self.current_user["username"] = username 92 | self.login_complete.clear() 93 | 94 | private_key = self.crypto_utils.load_private_key(username) 95 | if not private_key: 96 | logger.error(f"No private key for {username}") 97 | return 98 | 99 | self.temporary_keys["private_key"] = private_key 100 | logger.info(f"Loaded private key for {username}") 101 | 102 | msg = MixnetMessage.login(username) 103 | await self.connection_client.send_message(msg) 104 | logger.info("Login message sent; waiting for challenge...") 105 | 106 | await self.login_complete.wait() 107 | 108 | except Exception as e: 109 | logger.error(f"Login error: {e}") 110 | 111 | async def handle_registration_challenge(self, content): 112 | nonce = content.get("nonce") 113 | if not nonce: 114 | logger.error("No nonce in registration challenge.") 115 | return 116 | private_key = self.temporary_keys.get("private_key") 117 | if not private_key: 118 | logger.error("No private key for registration.") 119 | return 120 | 121 | try: 122 | signature = self.crypto_utils.sign_message(private_key, nonce) 123 | resp = MixnetMessage.registrationResponse(self.current_user["username"], signature) 124 | await self.connection_client.send_message(resp) 125 | logger.info("Registration challenge response sent.") 126 | except Exception as e: 127 | logger.error(f"Signing registration nonce: {e}") 128 | 129 | async def handle_login_challenge(self, content): 130 | nonce = content.get("nonce") 131 | if not nonce: 132 | logger.error("No nonce in login challenge.") 133 | return 134 | private_key = self.temporary_keys.get("private_key") 135 | if not private_key: 136 | logger.error("No private key for login.") 137 | return 138 | 139 | try: 140 | signature = self.crypto_utils.sign_message(private_key, nonce) 141 | resp = MixnetMessage.loginResponse(self.current_user["username"], signature) 142 | await self.connection_client.send_message(resp) 143 | logger.info("Login challenge response sent.") 144 | except Exception as e: 145 | logger.error(f"Signing login nonce: {e}") 146 | 147 | async def handle_registration_response(self, content): 148 | """ 149 | Handles the response after the registration challenge has been completed. 150 | """ 151 | if content == "success": 152 | logger.info("Registration successful!") 153 | username = self.current_user["username"] 154 | priv_k = self.temporary_keys["private_key"] 155 | pub_k = self.temporary_keys["public_key"] 156 | 157 | try: 158 | self.crypto_utils.save_keys(username, priv_k, pub_k) 159 | logger.info("Keys saved.") 160 | except Exception as e: 161 | logger.error(f"Saving keys: {e}") 162 | self.registration_successful = False 163 | self.registration_complete.set() # Ensure the event is set 164 | return 165 | 166 | try: 167 | self.db_manager = SQLiteManager(username) 168 | logger.info("DB initialized for user: %s", username) 169 | except Exception as e: 170 | logger.error(f"DB init: {e}") 171 | self.registration_successful = False 172 | self.registration_complete.set() # Ensure the event is set 173 | return 174 | 175 | self.registration_successful = True # Registration is successful 176 | self.registration_complete.set() # Signal that registration is complete 177 | 178 | else: 179 | logger.error(f"Registration failed: {content}") 180 | self.registration_successful = False 181 | self.registration_complete.set() 182 | 183 | async def handle_login_response(self, content): 184 | """ 185 | Handles the response after the login challenge has been completed. 186 | """ 187 | if content == "success": 188 | logger.info("Login successful!") 189 | username = self.current_user["username"] 190 | try: 191 | self.db_manager = SQLiteManager(username) 192 | logger.info("DB manager created.") 193 | self.db_manager.create_user_tables(username) 194 | except Exception as e: 195 | logger.error(f"DB init: {e}") 196 | self.login_successful = False 197 | self.login_complete.set() 198 | return 199 | 200 | self.login_successful = True 201 | self.login_complete.set() 202 | 203 | else: 204 | logger.error(f"Login failed: {content}") 205 | self.login_successful = False 206 | self.login_complete.set() 207 | 208 | # -------------------------------------------------------------------------- 209 | # Sending Direct Messages (All messages encrypted) 210 | # -------------------------------------------------------------------------- 211 | async def send_direct_message(self, recipient_username, message_content): 212 | if not recipient_username or not message_content.strip(): 213 | return 214 | 215 | sender_private_key = self.crypto_utils.load_private_key(self.current_user["username"]) 216 | if not sender_private_key: 217 | logger.error("No private key to send message.") 218 | return 219 | 220 | if not self.db_manager: 221 | logger.error("DB manager not initialized.") 222 | return 223 | 224 | contact = self.db_manager.get_contact(self.current_user["username"], recipient_username) 225 | if not contact: 226 | logger.error(f"No contact record found for {recipient_username}. Cannot send message.") 227 | return 228 | 229 | existing_msgs = self.db_manager.get_messages_by_contact(self.current_user["username"], recipient_username) 230 | initial_message = not existing_msgs 231 | 232 | recipient_public_key_pem = contact[1] 233 | 234 | # Maintain original message format 235 | wrapped_message = json.dumps({"type": 0, "message": message_content}) 236 | 237 | # Encrypt using ECDH + AES-GCM 238 | encrypted_payload = self.crypto_utils.encrypt_message(recipient_public_key_pem, wrapped_message) 239 | 240 | # Sign only the encryptedPayload 241 | encrypted_payload_str = json.dumps(encrypted_payload) # Convert to string for signing 242 | payload_signature = self.crypto_utils.sign_message(sender_private_key, encrypted_payload_str) 243 | 244 | # Construct the body field (ENCAPSULATING SIGNATURE INSIDE `body`) 245 | body = { 246 | "encryptedPayload": encrypted_payload, 247 | "payloadSignature": payload_signature # Inner signature inside `body` 248 | } 249 | 250 | # Construct final message payload 251 | payload = { 252 | "sender": self.current_user["username"], 253 | "recipient": recipient_username, 254 | "body": body, # contains both encryptedPayload + signature 255 | "encrypted": True 256 | } 257 | 258 | # If it's an initial message, include sender's public key 259 | if initial_message: 260 | sender_public_key_obj = self.crypto_utils.load_public_key(self.current_user["username"]) 261 | sender_public_key_pem = sender_public_key_obj.public_bytes( 262 | encoding=serialization.Encoding.PEM, 263 | format=serialization.PublicFormat.SubjectPublicKeyInfo 264 | ).decode() 265 | payload["senderPublicKey"] = sender_public_key_pem 266 | 267 | # Sign the full message (for the server) 268 | payload_str = json.dumps(payload) 269 | outer_signature = self.crypto_utils.sign_message(sender_private_key, payload_str) 270 | 271 | # Encapsulate as per existing protocol 272 | if recipient_username in self.nym_addresses: 273 | msg = MixnetMessage.directMessage(content=payload_str, signature=outer_signature) 274 | msg["recipient"] = self.nym_addresses[recipient_username] 275 | else: 276 | msg = MixnetMessage.send(content=payload_str, signature=outer_signature) 277 | 278 | await self.connection_client.send_message(msg) 279 | logger.info(f"Sent direct message to {recipient_username}") 280 | 281 | self.db_manager.save_message( 282 | self.current_user["username"], 283 | contact_username=recipient_username, 284 | msg_type='to', 285 | message=message_content 286 | ) 287 | 288 | 289 | async def send_handshake(self, recipient_username): 290 | """ 291 | Sends a handshake (type 1 message) containing this client's nym address. 292 | """ 293 | if self.nym_address is None: 294 | logger.error("Nym address not set in MessageHandler.") 295 | return 296 | 297 | sender_private_key = self.crypto_utils.load_private_key(self.current_user["username"]) 298 | if not sender_private_key: 299 | logger.error("No private key available for handshake.") 300 | return 301 | 302 | if not self.db_manager: 303 | logger.error("DB manager not initialized.") 304 | return 305 | 306 | contact = self.db_manager.get_contact(self.current_user["username"], recipient_username) 307 | if not contact: 308 | logger.error(f"No contact record found for {recipient_username}. Cannot send handshake.") 309 | return 310 | 311 | recipient_public_key_pem = contact[1] 312 | 313 | # inner message format 314 | handshake_payload = json.dumps({"type": 1, "message": self.nym_address}) 315 | 316 | # Encrypt and sign 317 | enc_result = self.crypto_utils.encrypt_message(recipient_public_key_pem, handshake_payload) 318 | encrypted_payload_str = json.dumps(enc_result) 319 | payload_signature = self.crypto_utils.sign_message(sender_private_key, encrypted_payload_str) 320 | 321 | payload = { 322 | "sender": self.current_user["username"], 323 | "recipient": recipient_username, 324 | "body": { 325 | "encryptedPayload": enc_result, 326 | "payloadSignature": payload_signature 327 | }, 328 | "encrypted": True 329 | } 330 | 331 | # Sign the entire payload (for server to verify) 332 | payload_str = json.dumps(payload) 333 | signature = self.crypto_utils.sign_message(sender_private_key, payload_str) 334 | 335 | # If we have an ephemeral nym_address for a given user, format as directMessage & send to nym_address, else normal send to server 336 | if recipient_username in self.nym_addresses: 337 | msg = MixnetMessage.directMessage(content=payload_str, signature=signature) 338 | msg["recipient"] = self.nym_addresses[recipient_username] 339 | else: 340 | msg = MixnetMessage.send(content=payload_str, signature=signature) 341 | 342 | await self.connection_client.send_message(msg) 343 | logger.info(f"Sent handshake to {recipient_username}") 344 | 345 | async def handle_send_response(self, content): 346 | pass 347 | 348 | # -------------------------------------------------------------------------- 349 | # Query 350 | # -------------------------------------------------------------------------- 351 | async def query_user(self, target_username): 352 | try: 353 | self.query_result_event.clear() 354 | self.query_result = None 355 | 356 | msg = MixnetMessage.query(target_username) 357 | await self.connection_client.send_message(msg) 358 | logger.info(f"Sent query for user: {target_username}") 359 | 360 | await self.query_result_event.wait() 361 | return self.query_result 362 | except Exception as e: 363 | logger.error(f"query_user: {e}") 364 | return None 365 | 366 | async def handle_query_response(self, content): 367 | self.query_result = content 368 | self.query_result_event.set() 369 | logger.info("queryResponse received") 370 | if self.db_manager and isinstance(content, dict): 371 | username = content.get("username") 372 | public_key = content.get("publicKey") 373 | if username and public_key: 374 | self.db_manager.add_contact(self.current_user["username"], username, public_key) 375 | 376 | # -------------------------------------------------------------------------- 377 | # Handling Incoming Messages (SINGLE CALLBACK) 378 | # -------------------------------------------------------------------------- 379 | async def handle_incoming_message(self, message): 380 | """ Main dispatcher for handling messages """ 381 | try: 382 | encapsulated_data = json.loads(message) 383 | action = encapsulated_data.get("action") 384 | context = encapsulated_data.get("context") 385 | content = self._parse_content(encapsulated_data.get("content")) 386 | 387 | handler = self.get_handler(action, context) 388 | if handler: 389 | await handler(content) 390 | else: 391 | logger.warning(f"Unknown or unhandled action '{action}', context='{context}'") 392 | except json.JSONDecodeError: 393 | logger.error("Could not decode the message content.") 394 | 395 | def _parse_content(self, content): 396 | """ Ensure content is a dictionary, converting if necessary """ 397 | if isinstance(content, str): 398 | try: 399 | return json.loads(content) 400 | except json.JSONDecodeError: 401 | pass 402 | return content 403 | 404 | 405 | def get_handler(self, action, context): 406 | """ Returns the appropriate handler function based on action and context """ 407 | handlers = { 408 | ("challenge", "registration"): self.handle_registration_challenge, 409 | ("challenge", "login"): self.handle_login_challenge, 410 | ("challengeResponse", "registration"): self.handle_registration_response, 411 | ("challengeResponse", "login"): self.handle_login_response, 412 | ("incomingMessage", "chat"): self.handle_incoming_message_content, 413 | ("queryResponse", "query"): self.handle_query_response, 414 | ("sendResponse", "chat"): self.handle_send_response, 415 | } 416 | return handlers.get((action, context)) or handlers.get((action, None)) 417 | 418 | async def handle_incoming_message_content(self, content): 419 | """Handles incoming messages, including decryption, verification, and storage.""" 420 | logger.info("Processing incoming message") 421 | 422 | if not isinstance(content, dict): 423 | logger.error("Parsed content is not a valid dictionary after JSON decoding.") 424 | return 425 | 426 | from_user = content.get("sender") 427 | body = content.get("body") 428 | sender_pub_from_msg = content.get("senderPublicKey") # Extract sender's long-term public key 429 | if not from_user or not body: 430 | logger.error("Malformed incoming message. Missing sender or body.") 431 | return 432 | 433 | encrypted_payload = body.get("encryptedPayload") 434 | payload_signature = body.get("payloadSignature") 435 | 436 | if not encrypted_payload or not payload_signature: 437 | logger.error("Malformed body. Missing encryptedPayload or payloadSignature.") 438 | return 439 | 440 | ephemeral_public_key_pem = encrypted_payload.get("ephemeralPublicKey") 441 | if not ephemeral_public_key_pem: 442 | logger.error("No ephemeral public key attached. Cannot derive shared secret.") 443 | return 444 | 445 | logger.info(f"Received message from {from_user}") 446 | 447 | # Retrieve sender's stored long-term public key (for signature verification) 448 | contact = self.db_manager.get_contact(self.current_user["username"], from_user) if self.db_manager else None 449 | sender_public_key_pem = contact[1] if contact else None 450 | 451 | # If this is the first contact, store the sender's public key 452 | if sender_pub_from_msg: 453 | if not sender_public_key_pem: # First-time contact 454 | logger.info(f"Storing new sender public key for {from_user}") 455 | self.db_manager.add_contact(self.current_user["username"], from_user, sender_pub_from_msg) 456 | sender_public_key_pem = sender_pub_from_msg # Use this for signature verification 457 | 458 | # If we still don't have a long-term public key, we cannot verify the signature 459 | if not sender_public_key_pem: 460 | logger.error(f"No sender public key available for {from_user}. Cannot verify message signature.") 461 | return None 462 | 463 | sender_public_key = serialization.load_pem_public_key(sender_public_key_pem.encode()) 464 | 465 | # Step 1: Verify the `payloadSignature` using sender's long-term key 466 | encrypted_payload_str = json.dumps(encrypted_payload) 467 | 468 | if not self.crypto_utils.verify_signature(sender_public_key, encrypted_payload_str, payload_signature): 469 | logger.error(f"Signature verification failed for {from_user}. Dropping message.") 470 | return None 471 | logger.info("Payload signature verified successfully!") 472 | 473 | # Step 2: Load recipient's private key 474 | recipient_private_key = self.crypto_utils.load_private_key(self.current_user["username"]) 475 | if not recipient_private_key: 476 | logger.error(f"No private key available for recipient: {self.current_user['username']}.") 477 | return None 478 | 479 | # Step 3: Decrypt using the ephemeral key 480 | try: 481 | decrypted_message = self.crypto_utils.decrypt_message( 482 | recipient_private_key, encrypted_payload 483 | ) 484 | 485 | if decrypted_message: 486 | logger.info(f" Decrypted message from {from_user}") 487 | else: 488 | logger.error(f"Failed to decrypt message from {from_user}.") 489 | 490 | except Exception as e: 491 | logger.error(f"Decryption failed: {e}") 492 | return None 493 | 494 | # Step 4: Parse JSON 495 | try: 496 | message_obj = json.loads(decrypted_message) 497 | except json.JSONDecodeError: 498 | logger.error("Decrypted message not valid JSON") 499 | return None 500 | 501 | # Step 5 Check type 502 | message_type = message_obj.get("type") 503 | actual_message = message_obj.get("message") 504 | 505 | if message_type == 1: 506 | logger.info(f"Storing handshake nym_address from {from_user}") 507 | self.nym_addresses[from_user] = actual_message 508 | return 509 | 510 | # Step 6 Handle normal message storage 511 | if from_user and actual_message and self.db_manager: 512 | self._store_message(from_user, actual_message) 513 | logger.info(f"Stored incoming message from {from_user} in DB.") 514 | 515 | # Update the chat UI 516 | self._update_chat_ui(from_user, actual_message) 517 | 518 | 519 | def _verify_and_decrypt_message(self, encrypted_payload, signature, from_user): 520 | """ Calls CryptoUtils to verify the signature and then decrypt the message """ 521 | 522 | # Retrieve sender's stored public key 523 | contact = self.db_manager.get_contact(self.current_user["username"], from_user) if self.db_manager else None 524 | sender_public_key_pem = contact[1] if contact else None 525 | 526 | if not sender_public_key_pem: 527 | logger.error(f"No sender public key available for {from_user}. Cannot verify message.") 528 | return None 529 | 530 | sender_public_key = serialization.load_pem_public_key(sender_public_key_pem.encode()) 531 | 532 | # Step 1: Verify Signature Before Decryption 533 | encrypted_payload_str = json.dumps(encrypted_payload) # Convert dict to string for signature verification 534 | if not self.crypto_utils.verify_signature(sender_public_key, encrypted_payload_str, signature): 535 | logger.error(f"Signature verification failed for {from_user}. Dropping message.") 536 | return None 537 | 538 | # Load recipient's private key 539 | recipient_private_key = self.crypto_utils.load_private_key(self.current_user["username"]) 540 | 541 | if not recipient_private_key: 542 | logger.error(f"No private key available for recipient {self.current_user['username']}.") 543 | return None 544 | 545 | try: 546 | # Step 2: Decrypt Message 547 | decrypted_message = self.crypto_utils.decrypt_message( 548 | recipient_private_key, encrypted_payload 549 | ) 550 | 551 | if decrypted_message: 552 | logger.info(f"Successfully decrypted message from {from_user}: {decrypted_message}") 553 | else: 554 | logger.error(f"Failed to decrypt message from {from_user}.") 555 | 556 | return decrypted_message 557 | 558 | except Exception as e: 559 | logger.error(f"Decryption or verification failed: {e}") 560 | return None 561 | 562 | def _parse_message(self, decrypted_msg): 563 | """ 564 | Ensures the message content is in the correct format. 565 | - If it's JSON, return as a dict. 566 | - If it's plaintext, wrap it in {"type": 0, "message": decrypted_msg}. 567 | """ 568 | try: 569 | parsed_message = json.loads(decrypted_msg) # Try parsing JSON 570 | if isinstance(parsed_message, dict): 571 | return parsed_message 572 | except json.JSONDecodeError: 573 | logger.error(" _parse_message: Decrypted message is not valid JSON") 574 | return None 575 | 576 | # def _handle_handshake(self, from_user, message_obj): 577 | # """ Handles handshake messages and updates contact list """ 578 | # nym_addr = message_obj.get("message") 579 | # if nym_addr: 580 | # self.nym_addresses[from_user] = nym_addr 581 | # logger.info(f"Received handshake from {from_user}. Updated nym address: {nym_addr}") 582 | # else: 583 | # logger.warning(f"Handshake message from {from_user} missing nym address.") 584 | 585 | def _store_message(self, from_user, actual_message): 586 | """ Stores message in the database """ 587 | self.db_manager.save_message(self.current_user["username"], from_user, 'from', actual_message) 588 | logger.info(f"Stored incoming message from {from_user} in DB.") 589 | 590 | def _update_chat_ui(self, from_user, actual_message): 591 | """ Updates chat messages and UI elements """ 592 | if self.chat_messages is None: 593 | logger.warning("chat_messages is None; UI might not be initialized.") 594 | return 595 | 596 | if from_user not in self.chat_messages: 597 | self.chat_messages[from_user] = [] 598 | 599 | stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') 600 | self.chat_messages[from_user].append((from_user, actual_message, stamp)) 601 | 602 | if not any(chat["id"] == from_user for chat in self.chat_list): 603 | self.chat_list.append({"id": from_user, "name": from_user}) 604 | if self.chat_list_sidebar_fn: 605 | self.chat_list_sidebar_fn.refresh() 606 | logger.info(f"Added {from_user} to chat list.") 607 | 608 | currently_active_chat = self._get_active_chat() 609 | if from_user == currently_active_chat and self.render_chat_fn: 610 | try: 611 | self.render_chat_fn.refresh(self.current_user["username"], currently_active_chat, self.chat_messages) 612 | logger.info("Chat UI refreshed successfully.") 613 | except Exception as e: 614 | logger.error(f"Failed to refresh chat UI: {e}") 615 | elif self.new_message_callback: 616 | self.new_message_callback(from_user, actual_message) 617 | -------------------------------------------------------------------------------- /client/src/mixnetMessages.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | 5 | def load_env(filepath=".env"): 6 | """Load environment variables from a .env file into os.environ.""" 7 | if os.path.exists(filepath): 8 | with open(filepath) as f: 9 | for line in f: 10 | # Ignore empty lines and comments 11 | if line.strip() and not line.startswith("#"): 12 | key, value = line.strip().split("=", 1) 13 | os.environ[key] = value 14 | 15 | load_env() 16 | 17 | SERVER_ADDRESS = os.getenv("SERVER_ADDRESS") 18 | 19 | class MixnetMessage: 20 | @staticmethod 21 | def query(usernym): 22 | encapsulatedMessage = json.dumps({"action": "query", "username": usernym}) 23 | return { 24 | "message": encapsulatedMessage, 25 | "recipient": SERVER_ADDRESS, 26 | } 27 | 28 | @staticmethod 29 | def register(usernym, publicKey): 30 | encapsulatedMessage = json.dumps({"action": "register", "usernym": usernym, "publicKey": publicKey}) 31 | return { 32 | "message": encapsulatedMessage, 33 | "recipient": SERVER_ADDRESS, 34 | } 35 | 36 | @staticmethod 37 | def login(usernym): 38 | encapsulatedMessage = json.dumps({"action": "login", "usernym": usernym}) 39 | return { 40 | "message": encapsulatedMessage, 41 | "recipient": SERVER_ADDRESS, 42 | } 43 | 44 | @staticmethod 45 | def update(field, value, signature): 46 | encapsulatedMessage = json.dumps({"action": "update", "field": field, "value": value, "signature": signature}) 47 | return { 48 | "message": encapsulatedMessage, 49 | "recipient": SERVER_ADDRESS, 50 | } 51 | 52 | @staticmethod 53 | def send(content, signature): 54 | """ 55 | Encapsulates a message for sending via the centralized server. 56 | This is used for handshake messages (to hide it from the server) and is not appropriate for p2p direct messaging. 57 | """ 58 | encapsulatedMessage = json.dumps({"action": "send", "content": content, "signature": signature}) 59 | return { 60 | "message": encapsulatedMessage, 61 | "recipient": SERVER_ADDRESS, 62 | } 63 | 64 | @staticmethod 65 | def directMessage(content, signature): 66 | """ 67 | Encapsulates a p2p direct message in the format expected by the receiving client. 68 | The resulting JSON has an action of 'incomingMessage' and a context of 'chat'. 69 | """ 70 | encapsulatedMessage = json.dumps({ 71 | "action": "incomingMessage", 72 | "content": content, 73 | "context": "chat", 74 | "signature": signature 75 | }) 76 | # The recipient field can be overridden if a direct p2p address is available. 77 | return { 78 | "message": encapsulatedMessage, 79 | "recipient": "" # This field can be set externally 80 | } 81 | 82 | @staticmethod 83 | def sendGroup(groupID, content, signature): 84 | encapsulatedMessage = json.dumps({"action": "sendGroup", "target": groupID, "content": content, "signature": signature}) 85 | return { 86 | "message": encapsulatedMessage, 87 | "recipient": SERVER_ADDRESS, 88 | } 89 | 90 | @staticmethod 91 | def createGroup(signature): 92 | encapsulatedMessage = json.dumps({"action": "createGroup", "signature": signature}) 93 | return { 94 | "message": encapsulatedMessage, 95 | "recipient": SERVER_ADDRESS, 96 | } 97 | 98 | @staticmethod 99 | def inviteGroup(usernym, groupID, signature): 100 | encapsulatedMessage = json.dumps({"action": "inviteGroup", "target": usernym, "groupID": groupID, "signature": signature}) 101 | return { 102 | "message": encapsulatedMessage, 103 | "recipient": SERVER_ADDRESS, 104 | } 105 | 106 | @staticmethod 107 | def registrationResponse(username, signature): 108 | encapsulatedMessage = json.dumps({ 109 | "action": "registrationResponse", 110 | "username": username, 111 | "signature": signature, 112 | }) 113 | return { 114 | "message": encapsulatedMessage, 115 | "recipient": SERVER_ADDRESS, 116 | } 117 | 118 | @staticmethod 119 | def loginResponse(username, signature): 120 | encapsulatedMessage = json.dumps({ 121 | "action": "loginResponse", 122 | "username": username, 123 | "signature": signature, 124 | }) 125 | return { 126 | "message": encapsulatedMessage, 127 | "recipient": SERVER_ADDRESS, 128 | } 129 | 130 | -------------------------------------------------------------------------------- /client/src/runClient.py: -------------------------------------------------------------------------------- 1 | # runClient.py 2 | import threading 3 | import os 4 | import asyncio 5 | from nicegui import ui, app 6 | from uuid import uuid4 7 | from datetime import datetime 8 | 9 | from dbUtils import SQLiteManager 10 | from cryptographyUtils import CryptoUtils 11 | from connectionUtils import MixnetConnectionClient 12 | from messageHandler import MessageHandler 13 | from logUtils import logger 14 | 15 | ############################################################################### 16 | # GLOBAL / IN-MEMORY STATE 17 | ############################################################################### 18 | DB_DIR = os.path.join(os.getcwd(), "storage") 19 | usernames = [] 20 | 21 | chat_list = [] # [{"id": , "name": }] 22 | active_chat = None # currently active chat user ID 23 | active_chat_user = None 24 | messages = {} # {username: [(sender_id, msg_text, timestamp), ...]} 25 | 26 | chat_messages_container = None # assigned in chat_page() 27 | 28 | # Global variable for storing our nym address 29 | global_nym_address = None 30 | 31 | def set_active_chat(value): 32 | global active_chat 33 | active_chat = value 34 | 35 | def get_active_chat(): 36 | """Helper so we can pass this function to MessageHandler for checking which chat is active.""" 37 | return active_chat 38 | 39 | def set_active_chat_user(value): 40 | global active_chat_user 41 | active_chat_user = value 42 | 43 | ############################################################################### 44 | # REFRESHABLE UI FOR CHAT 45 | ############################################################################### 46 | @ui.refreshable 47 | def render_chat_messages(current_user, target_chat, msg_dict): 48 | """ 49 | Refresh the chat area to display messages properly, inside a structured column. 50 | """ 51 | # Ensure chat_messages_container is defined 52 | if chat_messages_container is not None: 53 | chat_messages_container.clear() # Clear old messages before re-rendering 54 | 55 | ui.label(f"Chat with {target_chat or ''}").classes('text-lg font-bold') 56 | 57 | if not target_chat or target_chat not in msg_dict or not msg_dict[target_chat]: 58 | ui.label('No messages yet.').classes('mx-auto my-4') 59 | else: 60 | with ui.column().classes('w-full max-w-6xl mx-auto items-stretch flex-grow gap-2'): 61 | for sender_id, text, stamp in msg_dict[target_chat]: 62 | is_sent = sender_id == current_user # Check if the message is sent by the user 63 | 64 | # Handle multi-line messages 65 | text_content = text.split("\n") if "\n" in text else text 66 | 67 | ui.chat_message( 68 | text=text_content, 69 | stamp=stamp, 70 | sent=is_sent 71 | ).classes('p-3 rounded-lg') 72 | 73 | ui.run_javascript('window.scrollTo(0, document.body.scrollHeight)') # Auto-scroll to latest message 74 | 75 | ############################################################################### 76 | # CREATE CORE OBJECTS 77 | ############################################################################### 78 | crypto_utils = CryptoUtils() 79 | connection_client = MixnetConnectionClient() 80 | message_handler = MessageHandler(crypto_utils, connection_client) 81 | 82 | ############################################################################### 83 | # UTILITY: SCAN FOR USERS, LOAD CHATS FROM DB, CONNECT TO MIXNET 84 | ############################################################################### 85 | def scan_for_users(): 86 | global usernames 87 | if not os.path.exists(DB_DIR): 88 | os.makedirs(DB_DIR) 89 | logger.info("Created 'storage' directory for user data.") 90 | return 91 | 92 | dirs = [ 93 | d for d in os.listdir(DB_DIR) 94 | if os.path.isdir(os.path.join(DB_DIR, d)) 95 | ] 96 | usernames = dirs 97 | 98 | def load_chats_from_db(): 99 | """Load the chat_list and messages from DB for the current user.""" 100 | global chat_list, messages 101 | chat_list.clear() 102 | messages.clear() 103 | 104 | active_username = message_handler.current_user["username"] 105 | if not message_handler.db_manager: 106 | logger.warning("DB manager not found; maybe not logged in yet.") 107 | return 108 | 109 | rows = message_handler.db_manager.conn.execute( 110 | f"SELECT DISTINCT username FROM messages_{active_username}" 111 | ).fetchall() 112 | 113 | # build chat_list 114 | for (contact_username,) in rows: 115 | chat_list.append({"id": contact_username, "name": contact_username}) 116 | 117 | # load messages 118 | for info in chat_list: 119 | contact_username = info["id"] 120 | chat_msgs = message_handler.db_manager.get_messages_by_contact( 121 | active_username, contact_username 122 | ) 123 | 124 | msg_list = [] 125 | for (msg_type, msg_content, stamp) in chat_msgs: 126 | sender_id = active_username if msg_type == 'to' else contact_username 127 | msg_list.append((sender_id, msg_content, stamp)) 128 | 129 | messages[contact_username] = msg_list 130 | 131 | logger.info("Chat list and messages loaded from DB.") 132 | 133 | async def connect_mixnet(): 134 | global global_nym_address 135 | logger.info("Initializing Mixnet client...") 136 | await connection_client.init() 137 | logger.info("Mixnet client initialized.") 138 | nym_address = await connection_client.get_nym_address() 139 | global_nym_address = nym_address 140 | # Update MessageHandler with our nym address 141 | message_handler.update_nym_address(nym_address) 142 | logger.info(f"My Nym Address: {nym_address}") 143 | main_loop = asyncio.get_running_loop() 144 | def message_callback(msg): 145 | logger.debug(f"Received raw message from server: {msg}") 146 | asyncio.run_coroutine_threadsafe(message_handler.handle_incoming_message(msg), main_loop) 147 | await connection_client.set_message_callback(message_callback) 148 | logger.info("Message callback set.") 149 | asyncio.create_task(connection_client.receive_messages()) 150 | logger.info("Started message receiving loop.") 151 | ui.navigate.to("/welcome") # Redirect to welcome page 152 | 153 | ############################################################################### 154 | # OUTGOING MESSAGES 155 | ############################################################################### 156 | async def send_message(text_input): 157 | if not active_chat or not text_input.value.strip(): 158 | return 159 | 160 | msg_text = text_input.value.strip() 161 | text_input.value = '' 162 | current_user = message_handler.current_user["username"] 163 | 164 | # 1) Send direct message 165 | await message_handler.send_direct_message(active_chat_user, msg_text) 166 | 167 | # 2) Store in local memory 168 | stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') 169 | if active_chat not in messages: 170 | messages[active_chat] = [] 171 | messages[active_chat].append((current_user, msg_text, stamp)) 172 | 173 | # 3) Re-render chat UI 174 | render_chat_messages.refresh(current_user, active_chat, messages) 175 | 176 | async def send_handshake(): 177 | """ 178 | Native function to send a handshake (type 1 message) to the active chat user. 179 | """ 180 | if not active_chat or not active_chat_user or not global_nym_address: 181 | return 182 | await message_handler.send_handshake(active_chat_user) 183 | 184 | ############################################################################### 185 | # PAGE DEFINITIONS 186 | ############################################################################### 187 | @ui.page('/') 188 | def connect_page(): 189 | with ui.column().classes('max-w-4xl mx-auto items-center flex flex-col justify-center h-screen'): 190 | ui.label("NymCHAT").classes("text-3xl font-bold mb-8") 191 | with ui.row().classes('justify-center w-full'): 192 | spin = ui.spinner(size='lg').props('hidden').classes("mb-4") 193 | 194 | async def do_connect(): 195 | spin.props(remove='hidden') # Show spinner 196 | await connect_mixnet() # Connect to mixnet 197 | spin.props('hidden') # Hide spinner 198 | ui.navigate.to("/welcome") # Navigate to welcome page 199 | 200 | ui.button("Connect to Mixnet", color="green-6", on_click=do_connect, icon="wifi") 201 | 202 | @ui.page('/welcome') 203 | def welcome_page(): 204 | with ui.column().classes('max-w-2xl mx-auto items-stretch flex-grow gap-1 flex justify-center items-center h-screen w-full'): 205 | ui.label("Welcome to NymCHAT").classes("text-3xl text-center font-bold mb-8") 206 | ui.button("Login", color="green-6", on_click=lambda: ui.navigate.to("/login"), icon="login").classes("mb-2") 207 | ui.button("Register", color="green-6", on_click=lambda: ui.navigate.to("/register"), icon="how_to_reg").classes("mb-2") 208 | 209 | @ui.page('/login') 210 | def login_page(): 211 | with ui.column().classes('max-w-2xl mx-auto items-stretch flex-grow gap-1 flex justify-center items-center h-screen w-full'): 212 | ui.label("Login").classes("text-2xl text-center font-bold mb-4") 213 | 214 | scan_for_users() # Load list of usernames 215 | 216 | if usernames: 217 | user_select = ui.select(usernames, label="Select a User").props("outlined").classes("mb-2") 218 | 219 | with ui.row().classes('justify-center w-full'): 220 | spin = ui.spinner(size='lg').props('hidden').classes("mb-4") 221 | 222 | async def do_login(): 223 | if not user_select.value: 224 | ui.notify("Please select a user.") 225 | return 226 | spin.props(remove='hidden') # Show spinner 227 | 228 | # Begin login process 229 | await message_handler.login_user(user_select.value) 230 | await message_handler.login_complete.wait() 231 | 232 | # Set up UI state and load chat data 233 | message_handler.set_ui_state(messages, chat_list, get_active_chat, render_chat_messages, chat_messages_container) 234 | load_chats_from_db() 235 | 236 | spin.props('hidden') # Hide spinner 237 | 238 | if message_handler.login_successful: 239 | ui.notify("Login successful! Welcome.") 240 | ui.navigate.to("/app") 241 | else: 242 | ui.notify("Login Failed: Did you delete your key file?") 243 | 244 | ui.button("Login", color="green-6", on_click=do_login, icon="login").classes("mb-2") 245 | else: 246 | ui.label("No users found. Please register first.") 247 | 248 | ui.button("Back", color="green-6", on_click=lambda: ui.navigate.to("/welcome"), icon="arrow_back_ios_new").classes("mb-2") 249 | 250 | @ui.page('/register') 251 | def register_page(): 252 | with ui.column().classes('max-w-2xl mx-auto items-stretch flex-grow gap-1 flex justify-center items-center h-screen w-full'): 253 | ui.label("Register a New User").classes("text-2xl text-center font-bold mb-4") 254 | user_in = ui.input(label="Username").props("outlined").classes("mb-2") 255 | 256 | with ui.row().classes('justify-center w-full'): 257 | spin = ui.spinner(size='lg').props('hidden').classes("mb-4") 258 | 259 | async def do_register(): 260 | username = user_in.value.strip() 261 | if not username: 262 | ui.notify("Username is required!") 263 | return 264 | 265 | spin.props(remove='hidden') 266 | await message_handler.register_user(username) 267 | await message_handler.registration_complete.wait() 268 | spin.props('hidden') 269 | 270 | if message_handler.registration_successful: 271 | ui.notify("Registration completed! Please login.") 272 | ui.navigate.to("/login") 273 | else: 274 | user_in.value = "" 275 | 276 | ui.button("Register", color="green-6", on_click=do_register, icon="how_to_reg").classes("mb-2") 277 | ui.button("Back", color="green-6", on_click=lambda: ui.navigate.to("/welcome"), icon="arrow_back_ios_new").classes("mb-2") 278 | 279 | @ui.page('/app') 280 | def chat_page(): 281 | """ 282 | Main chat page: toggleable chat list (sidebar), chat container, and message input. 283 | """ 284 | user_id = message_handler.current_user["username"] or str(uuid4()) 285 | 286 | global chat_messages_container # Ensure accessibility 287 | 288 | chat_messages_container = ui.column().classes('flex-grow gap-2 overflow-auto') 289 | 290 | def show_new_message_notification(sender, message): 291 | with chat_messages_container: 292 | ui.notify(f"New message from {sender}: {message}") 293 | 294 | message_handler.new_message_callback = show_new_message_notification 295 | 296 | 297 | @ui.refreshable 298 | def chat_list_sidebar(): 299 | with ui.column(): 300 | ui.label('Chats').classes('text-xl font-bold') 301 | if not chat_list: 302 | ui.label('No chats yet').classes('text-gray-400') 303 | for info in chat_list: 304 | with ui.row().classes('p-2 hover:bg-gray-800 cursor-pointer') \ 305 | .on('click', lambda _, u=info: open_chat(u)): 306 | ui.label(info["name"]).classes('font-bold text-white') 307 | ui.label('Click to open chat').classes('text-gray-400 text-sm') 308 | 309 | def open_chat(u): 310 | set_active_chat(u["id"]) 311 | set_active_chat_user(u["name"]) 312 | chat_drawer.toggle() 313 | if chat_messages_container: 314 | render_chat_messages.refresh(user_id, active_chat, messages) 315 | 316 | with ui.left_drawer().classes('w-64 bg-zinc-700 text-white p-4') as chat_drawer: 317 | chat_list_sidebar() 318 | 319 | with ui.header().classes('w-full bg-zinc-800 text-white p-4 items-center justify-between'): 320 | with ui.row().classes('items-center gap-2'): 321 | ui.button(icon='menu', color="", on_click=lambda: chat_drawer.toggle()) 322 | ui.label('NymCHAT').classes('text-xl font-bold') 323 | ui.button("Send Handshake", color="green-6", on_click=lambda: asyncio.create_task(send_handshake())).classes("ml-2") 324 | ui.button('Search', color="green-6", on_click=lambda: ui.navigate.to('/search'), icon="search") \ 325 | .classes('bg-blue-500 text-white p-2 rounded') \ 326 | .style('margin-left: auto; margin-right: auto;') 327 | with ui.element('q-fab').props('square icon=settings color=green-6 direction=left'): 328 | ui.element('q-fab-action').props('icon=logout color=green-6 label=LOGOUT') \ 329 | .on('click', lambda: ui.navigate.to('/')) 330 | ui.element('q-fab-action').props('icon=power_settings_new color=green-6 label=SHUTDOWN') \ 331 | .on('click', lambda: (app.shutdown(), ui.notify("Shutting down the app..."))) 332 | 333 | message_handler.set_ui_state(messages, chat_list, get_active_chat, render_chat_messages, chat_messages_container, chat_list_sidebar) 334 | render_chat_messages(user_id, active_chat, messages) 335 | 336 | with ui.footer().classes('w-full bg-zinc-800 text-white p-4'): 337 | with ui.row().classes('w-full items-center'): 338 | text_in = ui.input(placeholder='Type a message...') \ 339 | .props('rounded outlined input-class=mx-3') \ 340 | .classes('flex-grow bg-zinc-700 text-white p-2 rounded-lg') \ 341 | .on('keydown.enter', lambda: asyncio.create_task(send_message(text_in))) 342 | ui.button('Send', color="green-6", icon="send", on_click=lambda: asyncio.create_task(send_message(text_in))) \ 343 | .classes('text-white p-2 rounded') 344 | 345 | @ui.page('/search') 346 | def search_page(): 347 | with ui.header().classes('w-full bg-zinc-950 text-white p-4 justify-between'): 348 | ui.button('Back', color="green-6", icon="arrow_back_ios_new", on_click=lambda: ui.navigate.to('/app')).classes('text-white p-2 rounded') 349 | 350 | with ui.column().classes('w-full max-w-6xl mx-auto items-stretch flex-grow gap-1 w-full items-start p-4'): 351 | with ui.row().classes('gap-2 bg-zinc-800 p-4 rounded-lg shadow-lg w-full items-center justify-center'): 352 | search_in = ui.input(placeholder='Enter a username: *CASE SENSITIVE*') \ 353 | .props('rounded outlined input-class=mx-3') \ 354 | .classes('flex-grow bg-zinc-700 text-white p-2 rounded-lg') \ 355 | .on('keydown.enter', lambda: asyncio.create_task(do_search())) 356 | ui.button('Search', color="green-6", icon="search", on_click=lambda: asyncio.create_task(do_search())).classes('text-white p-2 rounded') 357 | 358 | global profile_container 359 | profile_container = ui.column().classes('mt-4') 360 | 361 | async def do_search(): 362 | username = search_in.value.strip() 363 | with profile_container: 364 | profile_container.clear() 365 | if not username: 366 | ui.notify("Enter a username to search.") 367 | return 368 | ui.notify(f"Searching for '{username}'...") 369 | result = await message_handler.query_user(username) 370 | with profile_container: 371 | if result is None: 372 | ui.notify("Error or no response from server.") 373 | return 374 | if isinstance(result, str): 375 | ui.notify(result) 376 | elif isinstance(result, dict): 377 | user_data = result 378 | with ui.card().classes('p-4 bg-zinc-700 text-white rounded-lg shadow-lg w-80'): 379 | ui.label(f"Username: {user_data.get('username') or 'N/A'}").classes('text-xl font-bold') 380 | partial_key = (user_data.get('publicKey') or '')[:50] 381 | ui.label(f"Public Key (partial): {partial_key}...") 382 | def start_chat(): 383 | new_chat = {"id": user_data["username"], "name": user_data["username"]} 384 | if new_chat not in chat_list: 385 | chat_list.append(new_chat) 386 | ui.navigate.to('/app') 387 | ui.button('Start Chat', color='green-6', icon="chat", on_click=start_chat).classes('text-white p-2 mt-2 rounded') 388 | else: 389 | ui.notify("Unexpected response format from server.") 390 | 391 | ############################################################################### 392 | # APP STARTUP 393 | ############################################################################### 394 | @app.on_startup 395 | async def startup_sequence(): 396 | # UI Setup 397 | message_handler.set_ui_state( 398 | messages, # in-memory messages dict 399 | chat_list, # in-memory chat_list 400 | get_active_chat, # function to retrieve 'active_chat' 401 | render_chat_messages, # our refreshable function 402 | chat_messages_container # container (if needed) 403 | ) 404 | 405 | def shutdown_client(): 406 | # Create a new event loop in this thread and run the shutdown coroutine 407 | asyncio.run(connection_client.shutdown()) 408 | 409 | @app.on_shutdown 410 | def on_shutdown(): 411 | if connection_client.client is not None: 412 | logger.info("Shutting down Mixnet client...") 413 | t = threading.Thread(target=shutdown_client) 414 | t.start() 415 | t.join() # Wait for shutdown to complete 416 | logger.info("Mixnet client shutdown complete.") 417 | 418 | ui.run(dark=True, host='0.0.0.0', title="NymCHAT") 419 | -------------------------------------------------------------------------------- /client/src/tests/test_crypto.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | import json 4 | from cryptography.hazmat.primitives import serialization 5 | from cryptographyUtils import CryptoUtils 6 | 7 | class TestCryptoUtils(unittest.TestCase): 8 | def setUp(self): 9 | self.crypto = CryptoUtils(storage_dir="test_storage") 10 | self.username = "test_user" 11 | self.recipient = "recipient" 12 | 13 | # Generate and save keys for both sender and recipient 14 | self.private_key, self.public_key_pem = self.crypto.generate_key_pair(self.username) 15 | self.recipient_private_key, self.recipient_public_key_pem = self.crypto.generate_key_pair(self.recipient) 16 | 17 | self.crypto.save_keys(self.username, self.private_key, self.public_key_pem) 18 | self.crypto.save_keys(self.recipient, self.recipient_private_key, self.recipient_public_key_pem) 19 | 20 | def tearDown(self): 21 | # Cleanup test storage directory 22 | if os.path.exists("test_storage"): 23 | for root, dirs, files in os.walk("test_storage", topdown=False): 24 | for file in files: 25 | os.remove(os.path.join(root, file)) 26 | for dir in dirs: 27 | os.rmdir(os.path.join(root, dir)) 28 | os.rmdir("test_storage") 29 | 30 | def test_generate_key_pair(self): 31 | private_key, public_key_pem = self.crypto.generate_key_pair("new_user") 32 | self.assertIsNotNone(private_key) 33 | self.assertTrue(public_key_pem.startswith("-----BEGIN PUBLIC KEY-----")) 34 | 35 | def test_save_key_pair(self): 36 | self.assertTrue(os.path.exists(f"test_storage/{self.username}/{self.username}_private_key.pem")) 37 | self.assertTrue(os.path.exists(f"test_storage/{self.username}/{self.username}_public_key.pem")) 38 | 39 | def test_load_public_key(self): 40 | loaded_public_key = self.crypto.load_public_key(self.username) 41 | self.assertIsNotNone(loaded_public_key) 42 | 43 | def test_load_private_key(self): 44 | loaded_private_key = self.crypto.load_private_key(self.username) 45 | self.assertIsNotNone(loaded_private_key) 46 | 47 | def test_sign_and_verify_message(self): 48 | message = "Hello, World!" 49 | signature = self.crypto.sign_message(self.private_key, message) 50 | public_key = self.crypto.load_public_key(self.username) 51 | self.assertTrue(self.crypto.verify_signature(public_key, message, signature)) 52 | 53 | def test_invalid_signature(self): 54 | message = "Hello, World!" 55 | invalid_signature = self.crypto.sign_message(self.recipient_private_key, message) 56 | public_key = self.crypto.load_public_key(self.username) # Load test_user's public key 57 | self.assertFalse(self.crypto.verify_signature(public_key, message, invalid_signature)) 58 | 59 | def test_encrypt_and_decrypt_message(self): 60 | recipient_public_key_pem = self.crypto.load_public_key(self.recipient).public_bytes( 61 | encoding=serialization.Encoding.PEM, 62 | format=serialization.PublicFormat.SubjectPublicKeyInfo 63 | ).decode() 64 | 65 | # ✅ Step 1: Encrypt the message 66 | encrypted_message = self.crypto.encrypt_message(recipient_public_key_pem, "Secret Message") 67 | 68 | # ✅ Ensure salt is stored as a string 69 | self.assertIsInstance(encrypted_message["salt"], str, "Salt should be a hex string.") 70 | 71 | # ✅ Ensure salt can be converted back to bytes 72 | salt_bytes = bytes.fromhex(encrypted_message["salt"]) 73 | self.assertEqual(len(salt_bytes), 16, "Salt should be 16 bytes long.") 74 | 75 | # ✅ Step 2: Sign the encrypted payload 76 | encrypted_message_str = json.dumps(encrypted_message) # Convert encrypted message to string for signing 77 | signature = self.crypto.sign_message(self.private_key, encrypted_message_str) 78 | 79 | # ✅ Step 3: Verify the signature before decryption 80 | sender_public_key = self.crypto.load_public_key(self.username) 81 | self.assertTrue(self.crypto.verify_signature(sender_public_key, encrypted_message_str, signature)) 82 | 83 | # ✅ Step 4: Decrypt using both recipient's private key & sender's public key 84 | decrypted_message = self.crypto.decrypt_message(self.recipient_private_key, encrypted_message) 85 | self.assertEqual(decrypted_message, "Secret Message") 86 | 87 | if __name__ == "__main__": 88 | unittest.main() 89 | -------------------------------------------------------------------------------- /client/src/tests/test_db.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | from dbUtils import SQLiteManager # Assuming the class is in a file named sqlite_manager.py 4 | 5 | class TestSQLiteManager(unittest.TestCase): 6 | def setUp(self): 7 | self.username = "testuser" 8 | self.storage_dir = "test_storage" 9 | self.db_manager = SQLiteManager(self.username, self.storage_dir) 10 | 11 | # Populate the database with test data 12 | self.db_manager.register_user(self.username, "public_key_testuser") 13 | self.db_manager.create_user_tables(self.username) 14 | self.db_manager.add_contact(self.username, "alice", "public_key_alice") 15 | self.db_manager.add_contact(self.username, "bob", "public_key_bob") 16 | self.db_manager.save_message(self.username, "alice", "to", "Hello Alice!") 17 | self.db_manager.save_message(self.username, "bob", "from", "Hello Bob!") 18 | 19 | def tearDown(self): 20 | self.db_manager.close() 21 | db_path = os.path.join(self.storage_dir, self.username, f"{self.username}_client.db") 22 | if os.path.exists(db_path): 23 | os.remove(db_path) 24 | os.rmdir(os.path.join(self.storage_dir, self.username)) 25 | os.rmdir(self.storage_dir) 26 | 27 | def test_create_global_tables(self): 28 | tables = self.db_manager.get_all_users() 29 | self.assertIsInstance(tables, list) 30 | 31 | def test_register_user(self): 32 | self.db_manager.register_user("charlie", "public_key_123") 33 | user = self.db_manager.get_all_users() 34 | self.assertIn(("charlie", "public_key_123"), user) 35 | 36 | def test_create_user_tables(self): 37 | self.db_manager.create_user_tables("charlie") 38 | contacts = self.db_manager.get_all_contacts("charlie") 39 | messages = self.db_manager.get_all_messages("charlie") 40 | self.assertIsInstance(contacts, list) 41 | self.assertIsInstance(messages, list) 42 | 43 | def test_add_contact(self): 44 | self.db_manager.add_contact(self.username, "dave", "public_key_dave") 45 | contact = self.db_manager.get_contact(self.username, "dave") 46 | self.assertEqual(contact, ("dave", "public_key_dave")) 47 | 48 | def test_get_all_contacts(self): 49 | contacts = self.db_manager.get_all_contacts(self.username) 50 | self.assertGreater(len(contacts), 0) 51 | 52 | def test_save_message(self): 53 | self.db_manager.save_message(self.username, "dave", "to", "Hey Dave!") 54 | messages = self.db_manager.get_messages_by_contact(self.username, "dave") 55 | self.assertEqual(len(messages), 1) 56 | self.assertEqual(messages[0][1], "Hey Dave!") 57 | 58 | def test_get_all_messages(self): 59 | messages = self.db_manager.get_all_messages(self.username) 60 | self.assertGreater(len(messages), 1) 61 | 62 | def test_delete_contact(self): 63 | self.db_manager.delete_contact(self.username, "alice") 64 | contact = self.db_manager.get_contact(self.username, "alice") 65 | self.assertIsNone(contact) 66 | 67 | def test_delete_all_messages(self): 68 | self.db_manager.delete_all_messages(self.username) 69 | messages = self.db_manager.get_all_messages(self.username) 70 | self.assertEqual(len(messages), 0) 71 | 72 | def test_get_all_users(self): 73 | users = self.db_manager.get_all_users() 74 | self.assertIn((self.username, "public_key_testuser"), users) 75 | 76 | if __name__ == "__main__": 77 | unittest.main() 78 | -------------------------------------------------------------------------------- /client/src/tests/test_messageHandling.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import json 3 | import os 4 | import secrets 5 | import asyncio 6 | from cryptography.hazmat.primitives import serialization 7 | from messageHandler import MessageHandler 8 | from cryptographyUtils import CryptoUtils 9 | from dbUtils import SQLiteManager 10 | from connectionUtils import MixnetConnectionClient 11 | from mixnetMessages import MixnetMessage 12 | 13 | class MockServer: 14 | def __init__(self): 15 | self.users = {} 16 | self.nonces = {} 17 | self.pending_users = {} 18 | 19 | async def handle_message(self, message_json): 20 | """Simulates processing a message from a client and returning a response.""" 21 | try: 22 | if isinstance(message_json, str): 23 | message = json.loads(message_json) # Ensure message is properly parsed 24 | else: 25 | message = message_json 26 | 27 | if "message" in message: # Extract encapsulated message 28 | message = json.loads(message["message"]) 29 | 30 | action = message.get("action") 31 | senderTag = message.get("senderTag", "mockTag") 32 | 33 | # print(f"[MockServer] Received action: {action}") 34 | 35 | if action == "query": 36 | return await self.handle_query(message, senderTag) 37 | elif action == "register": 38 | return await self.handle_register(message, senderTag) 39 | elif action == "registrationResponse": 40 | return await self.handle_registration_response(message, senderTag) 41 | elif action == "login": 42 | return await self.handle_login(message, senderTag) 43 | elif action == "loginResponse": 44 | return await self.handle_login_response(message, senderTag) 45 | elif action == "send": 46 | return await self.handle_send(message, senderTag) 47 | return json.dumps({"error": f"Unknown action: {action}"}) 48 | except json.JSONDecodeError: 49 | return json.dumps({"error": "Invalid JSON"}) 50 | 51 | async def handle_query(self, message, senderTag): 52 | """Handles user queries.""" 53 | username = message.get("username") 54 | if username in self.users: 55 | return json.dumps({ 56 | "action": "queryResponse", 57 | "content": {"username": username, "publicKey": self.users[username]}, 58 | "context": "query" 59 | }) 60 | return json.dumps({ 61 | "action": "queryResponse", 62 | "content": "No user found", 63 | "context": "query" 64 | }) 65 | 66 | async def handle_register(self, message, senderTag): 67 | """Handles user registration (returns a nonce).""" 68 | username = message.get("usernym") 69 | publicKey = message.get("publicKey") 70 | 71 | if username in self.users: 72 | return json.dumps({"action": "challengeResponse", "content": "error: username already in use", "context": "registration"}) 73 | 74 | nonce = secrets.token_hex(16) 75 | self.pending_users[senderTag] = (username, publicKey, nonce) 76 | return json.dumps({"action": "challenge", "content": {"nonce": nonce}, "context": "registration"}) 77 | 78 | async def handle_registration_response(self, message, senderTag): 79 | """Handles user registration challenge response.""" 80 | signature = message.get("signature") 81 | if senderTag not in self.pending_users: 82 | return json.dumps({"action": "challengeResponse", "content": "error: no pending registration", "context": "registration"}) 83 | 84 | username, publicKey, nonce = self.pending_users[senderTag] 85 | 86 | # Simulate successful signature verification 87 | if signature == "valid_signature": 88 | self.users[username] = publicKey 89 | del self.pending_users[senderTag] 90 | return json.dumps({"action": "challengeResponse", "content": "success", "context": "registration"}) 91 | 92 | return json.dumps({"action": "challengeResponse", "content": "error: invalid signature", "context": "registration"}) 93 | 94 | async def handle_login(self, message, senderTag): 95 | """Handles user login request (returns a nonce).""" 96 | username = message.get("usernym") 97 | 98 | if username not in self.users: 99 | return json.dumps({"action": "challengeResponse", "content": "error: user not found", "context": "login"}) 100 | 101 | nonce = secrets.token_hex(16) 102 | self.nonces[senderTag] = (username, self.users[username], nonce) 103 | return json.dumps({"action": "challenge", "content": {"nonce": nonce}, "context": "login"}) 104 | 105 | async def handle_login_response(self, message, senderTag): 106 | """Handles user login challenge response.""" 107 | signature = message.get("signature") 108 | if senderTag not in self.nonces: 109 | return json.dumps({"action": "challengeResponse", "content": "error: no pending login", "context": "login"}) 110 | 111 | username, publicKey, nonce = self.nonces[senderTag] 112 | 113 | # Simulate successful signature verification 114 | if signature == "valid_signature": 115 | del self.nonces[senderTag] 116 | return json.dumps({"action": "challengeResponse", "content": "success", "context": "login"}) 117 | 118 | return json.dumps({"action": "challengeResponse", "content": "error: invalid signature", "context": "login"}) 119 | 120 | async def handle_send(self, message, senderTag): 121 | """Handles direct message sending.""" 122 | content = message.get("content") 123 | signature = message.get("signature") 124 | 125 | try: 126 | content_data = json.loads(content) 127 | except json.JSONDecodeError: 128 | return json.dumps({"action": "sendResponse", "content": "error: invalid JSON", "context": "chat"}) 129 | 130 | sender = content_data.get("sender") 131 | recipient = content_data.get("recipient") 132 | 133 | if sender not in self.users or recipient not in self.users: 134 | return json.dumps({"action": "sendResponse", "content": "error: sender or recipient not found", "context": "chat"}) 135 | 136 | # Simulate successful signature verification 137 | if signature != "valid_signature": 138 | return json.dumps({"action": "sendResponse", "content": "error: invalid signature", "context": "chat"}) 139 | 140 | return json.dumps({"action": "sendResponse", "content": "success", "context": "chat"}) 141 | 142 | 143 | class TestMessageHandler(unittest.TestCase): 144 | def setUp(self): 145 | """Setup real dependencies and mock the server.""" 146 | 147 | # self.logger = logging.getLogger("AppLogger") 148 | # self.logger.setLevel(logging.CRITICAL) # Suppress logs except critical 149 | 150 | self.username = "testuser" 151 | self.friend_username = "friend" # ✅ Add friend user 152 | self.storage_dir = "test_storage" 153 | self.crypto_utils = CryptoUtils() 154 | self.connection_client = MixnetConnectionClient() 155 | self.db_manager = SQLiteManager(self.username, self.storage_dir) 156 | 157 | # ✅ Generate keys for testuser 158 | self.private_key, self.public_key_pem = self.crypto_utils.generate_key_pair(self.username) 159 | self.crypto_utils.save_keys(self.username, self.private_key, self.public_key_pem) 160 | 161 | # ✅ Generate keys for friend (sender) 162 | self.friend_private_key, self.friend_public_key_pem = self.crypto_utils.generate_key_pair(self.friend_username) 163 | self.crypto_utils.save_keys(self.friend_username, self.friend_private_key, self.friend_public_key_pem) 164 | 165 | # Populate the database with test data 166 | self.db_manager.register_user(self.username, self.public_key_pem) 167 | self.db_manager.create_user_tables(self.username) 168 | self.db_manager.add_contact(self.username, "alice", "public_key_alice") 169 | self.db_manager.add_contact(self.username, "bob", "public_key_bob") 170 | self.db_manager.add_contact(self.username, self.friend_username, self.friend_public_key_pem) # ✅ Ensure friend is a contact 171 | # self.db_manager.save_message(self.username, "alice", "to", "Hello Alice!") 172 | # self.db_manager.save_message(self.username, "bob", "from", "Hello Bob!") 173 | 174 | self.mock_server = MockServer() 175 | self.message_handler = MessageHandler( 176 | crypto_utils=self.crypto_utils, 177 | connection_client=self.connection_client 178 | ) 179 | 180 | # Set the active user 181 | self.message_handler.current_user["username"] = self.username 182 | self.message_handler.db_manager = self.db_manager # Ensure DB is set 183 | 184 | self.message_handler.set_ui_state( 185 | messages={}, # Empty dictionary to prevent 'None' errors 186 | chat_list=[], 187 | get_active_chat=lambda: None, 188 | render_chat=lambda u, c, m: None, 189 | chat_container=None, 190 | chat_list_sidebar_fn=None 191 | ) 192 | 193 | 194 | def tearDown(self): 195 | # self.logger.setLevel(logging.NOTSET) 196 | self.db_manager.close() 197 | db_path = os.path.join(self.storage_dir, self.username, f"{self.username}_client.db") 198 | if os.path.exists(db_path): 199 | os.remove(db_path) 200 | os.rmdir(os.path.join(self.storage_dir, self.username)) 201 | os.rmdir(self.storage_dir) 202 | 203 | def test_register_user(self): 204 | asyncio.run(self.async_test_register_user()) 205 | 206 | async def async_test_register_user(self): 207 | username = "testuser" 208 | private_key, public_key = self.crypto_utils.generate_key_pair(username) 209 | register_msg = MixnetMessage.register(username, public_key) 210 | register_msg_json = json.dumps(register_msg) 211 | server_response = await self.mock_server.handle_message(register_msg_json) 212 | # print(f"[TEST] Register response: {server_response}") 213 | self.assertIn("challenge", server_response) 214 | 215 | def test_login_user(self): 216 | asyncio.run(self.async_test_login_user()) 217 | 218 | async def async_test_login_user(self): 219 | username = "testuser" 220 | self.mock_server.users[username] = "mock_public_key" 221 | login_msg = MixnetMessage.login(username) 222 | login_msg_json = json.dumps(login_msg) 223 | server_response = await self.mock_server.handle_message(login_msg_json) 224 | # print(f"[TEST] Login response: {server_response}") 225 | self.assertIn("challenge", server_response) 226 | 227 | def test_query_user(self): 228 | asyncio.run(self.async_test_query_user()) 229 | 230 | async def async_test_query_user(self): 231 | username = "friend" 232 | self.mock_server.users[username] = "mock_public_key" 233 | query_msg = MixnetMessage.query(username) 234 | query_msg_json = json.dumps(query_msg) 235 | server_response = await self.mock_server.handle_message(query_msg_json) 236 | # print(f"[TEST] Query response: {server_response}") 237 | self.assertIn("queryResponse", server_response) 238 | 239 | def test_send_message(self): 240 | asyncio.run(self.async_test_send_message()) 241 | 242 | async def async_test_send_message(self): 243 | sender = "testuser" 244 | recipient = "friend" 245 | self.mock_server.users[sender] = "mock_public_key" 246 | self.mock_server.users[recipient] = "mock_public_key" 247 | send_msg = MixnetMessage.send(json.dumps({"sender": sender, "recipient": recipient, "body": "Hello"}), "valid_signature") 248 | send_msg_json = json.dumps(send_msg) 249 | # print(send_msg) 250 | server_response = await self.mock_server.handle_message(send_msg_json) 251 | # print(f"[TEST] Send response: {server_response}") 252 | self.assertIn("success", server_response) 253 | 254 | def test_handle_incoming_message(self): 255 | asyncio.run(self.async_test_handle_incoming_message()) 256 | 257 | async def async_test_handle_incoming_message(self): 258 | sender = self.friend_username 259 | recipient = self.username 260 | message_content = "Hello!" 261 | 262 | # ✅ Ensure message format matches original encapsulation 263 | wrapped_message = json.dumps({"type": 0, "message": message_content}) 264 | 265 | # ✅ Encrypt message using ECDH + AES-GCM 266 | encrypted_payload = self.crypto_utils.encrypt_message( 267 | self.public_key_pem, wrapped_message 268 | ) 269 | 270 | # ✅ Sign the encrypted payload separately 271 | sender_private_key = self.crypto_utils.load_private_key(sender) 272 | encrypted_payload_str = json.dumps(encrypted_payload) # Convert dict to string for signing 273 | payload_signature = self.crypto_utils.sign_message(sender_private_key, encrypted_payload_str) 274 | 275 | # ✅ Construct payload to match updated format 276 | payload = { 277 | "sender": sender, 278 | "recipient": recipient, 279 | "body": { 280 | "encryptedPayload": encrypted_payload, 281 | "payloadSignature": payload_signature 282 | }, 283 | "encrypted": True 284 | } 285 | 286 | # ✅ Sign the full payload (outer signature) 287 | payload_str = json.dumps(payload) 288 | outer_signature = self.crypto_utils.sign_message(sender_private_key, payload_str) 289 | 290 | # ✅ Construct final incoming message 291 | incoming_message = json.dumps({ 292 | "action": "incomingMessage", 293 | "context": "chat", 294 | "content": payload, 295 | "signature": outer_signature 296 | }) 297 | 298 | # print(f"simulating incoming message: {incoming_message}") 299 | 300 | # ✅ Process the incoming message 301 | await self.message_handler.handle_incoming_message(incoming_message) 302 | 303 | # ✅ Allow time for async processing 304 | await asyncio.sleep(0.5) 305 | 306 | # ✅ Verify that message was stored 307 | chat_messages = self.db_manager.get_messages_by_contact(recipient, sender) 308 | self.assertGreater(len(chat_messages), 0) 309 | 310 | 311 | if __name__ == "__main__": 312 | unittest.main() 313 | -------------------------------------------------------------------------------- /client/storage/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/code-zm/nymCHAT/f41b74f0b02d5c3ba4a779d9759a5260a7cf7021/client/storage/.gitkeep -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | x-logging: &logging 2 | driver: "json-file" 3 | options: 4 | max-size: "10m" 5 | max-file: "3" 6 | 7 | services: 8 | server-init: 9 | image: alpine:latest 10 | networks: 11 | - nym_network 12 | volumes: 13 | - server_data:/app/storage 14 | command: | 15 | sh -c ' 16 | mkdir -p /app/storage 17 | echo "your_secure_password" > /app/storage/encryption_password.txt && 18 | chmod 600 /app/storage/encryption_password.txt 19 | ' 20 | 21 | server: 22 | build: 23 | context: ./server 24 | restart: unless-stopped 25 | depends_on: 26 | - server-init 27 | networks: 28 | - nym_network 29 | volumes: 30 | - address_data:/app/shared # Single shared volume for communication 31 | - server_data:/app/storage 32 | - server_nym_data:/root/.nym # Renamed for consistency 33 | environment: 34 | - SECRET_PATH=/app/storage/encryption_password.txt 35 | - NYM_CLIENT_ID=nym_server 36 | ports: 37 | - "1977:1977" 38 | logging: *logging 39 | healthcheck: 40 | test: "cat /app/shared/nym_address.txt | grep '@' || exit 1" # Ensure the file is not just empty 41 | interval: 10s 42 | timeout: 5s 43 | retries: 12 44 | start_period: 40s 45 | 46 | client: 47 | build: ./client 48 | restart: unless-stopped 49 | depends_on: 50 | server: 51 | condition: service_healthy 52 | networks: 53 | - nym_network 54 | volumes: 55 | - address_data:/app/shared:ro # Use the same shared volume 56 | - client_data:/app/storage 57 | - client_nym_data:/root/.nym 58 | ports: 59 | - "8080:8080" 60 | command: > 61 | sh -c ' 62 | echo "Waiting for the server to fully initialize..." 63 | while [ ! -s /app/shared/nym_address.txt ] || ! grep -q "@" /app/shared/nym_address.txt; do 64 | echo "Server is not fully ready, waiting..." 65 | sleep 2 66 | done 67 | 68 | # Ensure .env is properly updated 69 | rm -f /app/.env # Remove old .env 70 | cp /app/shared/nym_address.txt /app/.env 71 | sed -i 's/^/SERVER_ADDRESS=/' /app/.env 72 | echo "Updated .env file content:" 73 | cat /app/.env # Print for debugging 74 | 75 | # Run the client application 76 | exec python src/runClient.py 77 | ' 78 | logging: *logging 79 | 80 | networks: 81 | nym_network: 82 | driver: bridge 83 | 84 | volumes: 85 | server_data: 86 | server_nym_data: # Updated to match client format 87 | client_data: 88 | client_nym_data: 89 | address_data: # Single shared volume 90 | -------------------------------------------------------------------------------- /docs/Build.md: -------------------------------------------------------------------------------- 1 | ## Quickstart 2 | 3 | ### Docker Compose Deployment 4 | 5 | The fastest way to deploy both the discovery node & client is with Docker Compose: 6 | 7 | ```bash 8 | # Clone the repository 9 | git clone https://github.com/code-zm/nymCHAT.git 10 | cd nymCHAT 11 | 12 | # Create server configuration 13 | cp server/.env.example server/.env 14 | echo "your-secure-password" > server/password.txt 15 | chmod 600 server/password.txt 16 | 17 | # Deploy with docker-compose 18 | docker compose up --build -d 19 | ``` 20 | 21 | This deploys the discovery node server and client, with the client automatically configured to use your discovery node. The docker-compose configuration: 22 | - Builds the server container with the required dependencies 23 | - Mounts persistent volumes for Nym identity and database 24 | - Runs the `install.sh` script to set up the Nym client 25 | - Executes the server application that handles message routing 26 | 27 | ### Building from Source 28 | 29 | #### Server Setup 30 | 31 | Note: need the `nym-client` binary installed, if you're on linux based os this can be installed directly from https://github.com/nymtech/nym/releases/ 32 | 33 | If running on mac, try this installation script. 34 | You will need to have Brew installed. 35 | 36 | ``` 37 | curl -fsSL https://raw.githubusercontent.com/dial0ut/nym-build/main/nym_build.sh | bash 38 | ``` 39 | 40 | 41 | ```bash 42 | # 1. Set up a virtual environment 43 | python -m venv venv 44 | source venv/bin/activate # On Windows: venv\Scripts\activate 45 | 46 | # 2. Install server dependencies 47 | cd server 48 | pip install -r requirements.txt # Or: uv pip install -r requirements.txt 49 | 50 | # 3. Configure the server 51 | cp .env.example .env 52 | echo "your-secure-password" >> password.txt 53 | chmod 600 password.txt 54 | 55 | # 4. Set up the Nym client binary 56 | 57 | 58 | # 5. Initialize Nym client 59 | ~/.local/bin/nym-client init --id nym_server 60 | # 6. Run the server 61 | python src/mainApp.py 62 | ``` 63 | 64 | #### Client Setup 65 | 66 | ```bash 67 | # 1. Set up a virtual environment if not already done 68 | cd client 69 | python -m venv venv 70 | source venv/bin/activate # On Windows: venv\Scripts\activate 71 | 72 | # 2. Install Python dependencies 73 | pip install -r requirements.txt # Or: uv pip install nicegui cryptography 74 | # 3. Build the Rust FFI component 75 | cd async_ffi 76 | maturin build --release 77 | # 4. Set the discovery node address 78 | cp .env.example .env # Note: the address in the .env.example is the official nymCHAT discovery node 79 | 80 | # 5. Run the client 81 | cd .. 82 | python src/runClient.py 83 | ``` 84 | 85 | --- 86 | 87 | ## Docker Compose Deployment Architecture 88 | 89 | In this section we will cover the containerization of our current application. 90 | Prepare for a deep-dive into the world of 1337. 91 | 92 | It should also cover the some issues you might encounter during the setup, so we also added a Troubleshooting section. 93 | 94 | 95 | ### High-level overview 96 | 97 | Our Docker Compose configuration establishes a seamless deployment of both the server and client components with appropriate isolation and communication channels. 98 | 99 | ### Network and Service Communication 100 | 101 | The deployment uses a bridge network (`nym_network`) to isolate the application's internal communication. The critical connection flow works as follows: 102 | 103 | 1. The server initializes a Nym client and writes its address to `/app/shared/nym_address.txt` 104 | 2. The client container waits for this file to appear, then reads the server's address 105 | 3. This address is used by the client to establish a connection to the discovery node 106 | 107 | ### Volume Structure and Data Sharing 108 | 109 | The architecture leverages Docker volumes for persistence and inter-service communication: 110 | 111 | - `server_data`: Stores server-specific data (SQLite DB and encryption keys) 112 | - `server_nym_data`/`client_nym_data`: Separate Nym identities for server and client 113 | - `client_data`: Client-specific storage for local databases 114 | - `address_data`: Critical shared volume mounted at `/app/shared` in both containers 115 | 116 | The shared address volume creates a simple yet effective communication channel between containers without exposing sensitive information through environment variables or command-line arguments. 117 | 118 | ### Troubleshooting Container Networking 119 | 120 | If you experience networking issues between containers: 121 | 122 | 1. Test basic connectivity using Netcat: 123 | ```bash 124 | # Test if ports are reachable on your host machine (old h4x0r way) 125 | ncat localhost 1977 -v # this should show you some open socket, if you see connx timed out, something is wrong. 126 | ncat localhost 8080 -v # if the webUI is working, you should get the same result. 127 | HEAD / HTTP/1.1 # smash enter until server responds 128 | # Install netcat in a container if needed 129 | docker compose exec server apk add --no-cache netcat-openbsd 130 | 131 | # From server, verify client is reachable (replace PORT with the internal port) 132 | docker compose exec server nc -zv client PORT 133 | 134 | # From client, verify server is reachable 135 | docker compose exec client nc -zv server 2000 136 | ``` 137 | 138 | 2. Verify the shared address file exists: 139 | ```bash 140 | docker-compose exec server cat /app/shared/nym_address.txt 141 | docker-compose exec client cat /app/shared/nym_address.txt 142 | ``` 143 | 144 | 3. Check container logs for specific errors: 145 | ```bash 146 | docker compose logs server 147 | docker compose logs client 148 | ``` 149 | 150 | 4. Verify volume mounts are working correctly: 151 | ```bash 152 | docker compose exec server ls -la /app/shared 153 | docker compose exec client ls -la /app/shared 154 | ``` 155 | 156 | ### Container Startup Sequence 157 | 158 | The containers follow a specific startup sequence: 159 | 160 | 1. `server-init` creates the necessary storage structure and encryption password 161 | 2. `server` starts and initializes its Nym client, writing the address to the shared volume 162 | 3. The `client` container waits until the server health check passes (address file exists) 163 | 4. The client reads the server address and establishes connection to the mixnet 164 | 165 | **This orchestrated startup ensures the client always has the correct server address before attempting connection.** 166 | 167 | Hopefully, this explanation can explain everything you need to know about the details on how the networking architecture works, why volumes are shared between containers, and how to troubleshoot common issues. 168 | 169 | -------------------------------------------------------------------------------- /docs/Protocol.md: -------------------------------------------------------------------------------- 1 | 2 | **TLDR:** 3 | - Implements a “discovery node” service that stores `(username → (public_key, senderTag))`. 4 | - Discovery nodes challenge any new registration with a random nonce. The prospective user signs that nonce with their “username key.” 5 | - For lookups, the discovery node queries its DB for a given `username`, if found it returns `username_pk`, else `e`. 6 | - The contacting user obtains `username_pk` and uses it to encrypt their messages. 7 | - All messages are forwarded through the discovery node until users decide to exchange `handshake` messages, which reveal their nym-client address. From then on, all messages for that session will be routed directly to the recipient. This is useful if you want an extra layer of privacy, as the discovery node will never know about these messages. 8 | - It should be noted that revealing your nym-client address reveals which gateway your client is connected to. Handshake with caution. 9 | 10 | ## 1. Overview 11 | Provide a privacy focused way for one user (Alice) to discover another user (Bob) using only a short username (e.g. `bob99`), rather than an email address / other real world ID. 12 | - **Core Requirements**: 13 | 14 | **I. User Registration** 15 | 16 | Bob registers a username and binds it to his long‑term `SECP256R1` keypair. 17 | 18 | **II. Authentication** 19 | 20 | Bob proves ownership of that username by signing a random server‑provided nonce with his private key. 21 | 22 | **III. Lookups** 23 | 24 | When Alice looks up Bob’s username, she gets back Bob's associated public key. 25 | 26 | **IV. SURBs** 27 | 28 | Clients send single use reply block's (SURBs) along with their `registration`, `login`, and `send` messages. The server organizes these SURBs via `senderTag`. The discovery node never needs to know the client's nym-address, and automatically updates `senderTags` as it receives new SURBs. 29 | 30 | **V. Mutual Key Authentication** 31 | 32 | All client payloads are encrypted and signed to ensure other clients and the server can validate a user is who they claim to be. 33 | 34 | **VI. E2E Enryption** 35 | 36 | All messages are end to end encrypted between clients using ECDH with ephemeral keys and AES-GCM. The Discovery Node can never learn the contents of user messages. 37 | 38 | **VII. Mixnet Transport** 39 | 40 | All requests and responses are carried as Sphinx packets in the Nym mixnet, preserving sender–receiver unlinkability and preventing the network from learning who’s contacting whom. 41 | 42 | 43 | ## 2. Architecture Components 44 | ![architecture diagram](../images/architecture.png) 45 | 46 | **I. Clients** 47 | - An application using the Nym SDK (`nym_sdk::mixnet`) via PyO3 bindings for sending and receiving mixnet messages. 48 | - Maintains user’s long-term keypair (`username_keypair`), stored in a local on‑disk directory. 49 | - Maintains messages and contacts locally. 50 | - Registers a username via the discovery nodes. 51 | - Chat UI for easy messaging. 52 | 53 | **II. Discovery Nodes** 54 | - Nym clients running as special-purpose application servers, each storing user registration data. 55 | - Each node holds: 56 | - A database of `(username → contact info)`. (“contact info” includes user’s public key and senderTag) 57 | - On registration, a node demands proof of ownership. 58 | - On lookup, the node either: 59 | - Returns the associated `username_pk` 60 | - Returns an `error` message 61 | 62 | **III. Nym Mixnet** 63 | - Provides packet routing via the mix nodes & gateway nodes, using the standard Sphinx packet layering. 64 | - Mixnet traffic is fully asynchronous; the user device can be offline, and the associated gateway will buffer messages. 65 | 66 | 67 | ## Protocol 68 | 69 | `alice` wants to send a message to her friend `bob`. 70 | 71 | **Client Registration**: 72 | 73 | - Alice sends a registration request containing `(alice, pk_alice, SURB)` to a server. 74 | - The server responds with a nonce. 75 | - Alice signs the nonce and sends it back to the server. 76 | - The server verifies the signature, if successful adds `alice -> pk_alice, senderTag` to the DB and responds with a success message. 77 | 78 | ![User Registration](../images/userLookup.png) 79 | 80 | **User Lookup** 81 | 82 | - Alice sends a query to the server, containing `(bob, SURB)`. 83 | - The server receives the message and checks it's DB for `bob`. 84 | - If it has an entry, it forwards `PK_bob` to alice via `SURB`. 85 | - Alice stores `bob -> PK_bob` in her local contacts table. 86 | 87 | ![User Lookup](../images/userRegistration.png) 88 | 89 | **Message Sending**: 90 | 91 | - Alice uses `PK_bob` and an ephemeral keypair `(SK_tmp, PK_tmp)` to derive a shared secret, then encrypts the message and encapsulates it into a payload. 92 | - She attaches `PK_tmp` for bob to derive the same shared secret. Since this is her first message to Bob, she also attaches `PK_alice`. Alice signs the payload for Bob to verify. 93 | - Alice then encapsulated this payload into the proper format, and signs the entire outer payload for the server to verify. 94 | - This message is sent to the server, addressed to Bob. 95 | - The server verifies the outer signature against Alice's stored public key and the message payload. If successful, the server queries it's local db for Bob and retrieves the associated `senderTag`. 96 | - The server forwards the encrypted message to Bob via `SURB`. 97 | - Bob receives the encrypted message and parses `PK_alice` and `PK_tmp` from it. Bob verifies the signature using `PK_Alice`. If successful, he uses `PK_tmp` to derive the same shared secret and decrypts the message. 98 | 99 | ![Message Sending](../images/messageSending.png) 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /images/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/code-zm/nymCHAT/f41b74f0b02d5c3ba4a779d9759a5260a7cf7021/images/architecture.png -------------------------------------------------------------------------------- /images/messageSending.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/code-zm/nymCHAT/f41b74f0b02d5c3ba4a779d9759a5260a7cf7021/images/messageSending.png -------------------------------------------------------------------------------- /images/userLookup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/code-zm/nymCHAT/f41b74f0b02d5c3ba4a779d9759a5260a7cf7021/images/userLookup.png -------------------------------------------------------------------------------- /images/userRegistration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/code-zm/nymCHAT/f41b74f0b02d5c3ba4a779d9759a5260a7cf7021/images/userRegistration.png -------------------------------------------------------------------------------- /server/.env.example: -------------------------------------------------------------------------------- 1 | NYM_CLIENT_ID=nym_server 2 | DATABASE_PATH=storage/$NYM_CLIENT_ID.db 3 | LOG_FILE_PATH=storage/app.log 4 | KEYS_DIR=storage/keys 5 | WEBSOCKET_URL=ws://127.0.0.1:1977 6 | SECRET_PATH=secrets/encryption_password 7 | -------------------------------------------------------------------------------- /server/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.11-slim 2 | 3 | # Set the working directory 4 | WORKDIR /app 5 | 6 | # Install system dependencies 7 | RUN apt-get update && apt-get install -y curl gettext 8 | 9 | # Copy the requirements file and install dependencies 10 | COPY requirements.txt . 11 | 12 | RUN pip install --no-cache-dir -r requirements.txt 13 | 14 | # Copy the required directories in one command 15 | COPY src/*.py server/ 16 | 17 | COPY scripts/* scripts/ 18 | 19 | COPY .env.example .env.example 20 | 21 | COPY password.txt password.txt 22 | 23 | # Ensure the shell scripts are executable 24 | RUN chmod +x scripts/*.sh 25 | 26 | # Run the installation script 27 | RUN scripts/install.sh 28 | 29 | EXPOSE 1977 30 | # Set entrypoint to run the Nym client 31 | ENTRYPOINT ["scripts/entrypoint.sh"] 32 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 | ## Discovery Node 2 | A discovery / message relay service used by nymCHAT clients. 3 | 4 | ## Installation 5 | 6 | **Prerequisities** 7 | 1. Git - to clone the repo 8 | 2. Docker - to run in everything in container 9 | 10 | #### Step 1: Clone the Repo 11 | Download the project to your local machine: 12 | ```sh 13 | git clone https://github.com/code-zm/nymCHAT.git 14 | cd nymCHAT/server 15 | ``` 16 | 17 | #### Step 2: Configuration 18 | Before we build the Docker image, we have to do some setup. 19 | First, create the `.env` file: 20 | ```sh 21 | cp .env.example .env 22 | ``` 23 | 24 | *Note: no changes are necessary, simply copying is fine. If you want your nym-client itself to have a custom name, set NYM_CLIENT_ID* 25 | 26 | Next, setup your encryption password. This will be used to unlock your keys. 27 | ```sh 28 | echo "your-secure-password" > password.txt 29 | ``` 30 | 31 | #### Step 3. Build the Docker Image 32 | This installs dependencies and sets up the nym-client. 33 | ```sh 34 | docker build -t nymserver:latest . 35 | ``` 36 | 37 | #### Step 4: Run the Docker Container 38 | Since we are running a discovery service, we want persistent storage across runs. The following command achieves this: 39 | ```sh 40 | docker run -d \ 41 | -v $(pwd)/nym-data:/root/.nym:rw \ 42 | -v $(pwd)/storage:/app/storage \ 43 | --name nymchat-server \ 44 | nymserver:latest 45 | ``` 46 | 47 | **Command Arguments** 48 | - `d` -> Runs the container in the background 49 | - `--name nymdir` -> Container name 50 | - `-v $(pwd)/nym-data:/root/.nym:rw` -> Nym-Client identity persistance 51 | - `-v $(pwd)/storage:/app/storage` -> Logs and DB persistance 52 | 53 | #### Step 5: Manage the Container 54 | Here are some common docker commands you may find useful: 55 | *Note: To allow docker to run without sudo, add your user to the docker group. `sudo usermod -aG docker $USER`* 56 | **Check Running Containers** 57 | ```sh 58 | docker ps 59 | ``` 60 | 61 | **View Logs** 62 | ```sh 63 | docker logs -f nymchat-server 64 | ``` 65 | 66 | **Stop the Container** 67 | ```sh 68 | docker stop nymchat-server 69 | ``` 70 | 71 | **Start the Container** 72 | ```sh 73 | docker start nymchat-server 74 | ``` 75 | 76 | **Remove the Container** 77 | ```sh 78 | docker rm -f nymchat-server 79 | ``` -------------------------------------------------------------------------------- /server/docs/Overview.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | The nymDirectory is a discovery / remailer service provider used by nymCHAT clients on the Nym Mixnet. The directory stores `username -> (pubkey, senderTag)` in a local sqlite db. 4 | 5 | Sender tags correspond with single use reply blocks (SURB), which are received from incoming messages. SURBs allow nym-clients to reply to incoming messages without ever learning the destination of the message. 6 | 7 | I chose to rely strictly on SURBs because your nym-client address reveals which gateway you are connected to. 8 | Nym Addresses are formatted as follows: 9 | 10 | ``` 11 | .@ 12 | ``` 13 | 14 | Anyone with a list of gateway's can determine your gateway from the `GatewayIdKey` part of the nym address. This does not fully deanonymize you thanks to Nym's cover traffic and mixing, but it is reducing your anonymity set. An easy way around this is to use an ephemeral client (nymCHAT does by default) or manually rotate gateways often. 15 | 16 | By routing messages via SURB instead of nym client address, the nymDirectory enables fully pseudonymous user discovery and message forwarding. All messages are end to end encrypted by the clients to ensure the directory cannot read any message content. 17 | 18 | Users have the ability to route their messages directly to one another, skipping the directory entirely. To enable this, clients exchange `handshake` messages which reveal their nym addresses. All further messages can be sent directly from `client -> client`, instead of `client -> nymDirectory -> client`. The handshake data is encrypted and formatted exactly like a normal encrypted message to prevent the server from learning your nym address. 19 | 20 | ## Components 21 | 22 | **cryptographyUtils.py** 23 | Contains utility functions for cryptographic operations such as key generation, signing, and verifying messages. 24 | 25 | **dbUtils.py** 26 | Handles interactions with the SQLite database, including user registration and group management. 27 | 28 | **logConfig.py** 29 | Configures logging for the server, logging errors, info, and debug messages. 30 | 31 | **messageUtils.py** 32 | Handles incoming messages, verifies signatures, processes user registration, login, sending/receiving messages. 33 | 34 | **websocketUtils.py** 35 | Manages WebSocket communication with the Nym client binary and facilitates sending/receiving messages from the mixnet. -------------------------------------------------------------------------------- /server/requirements.txt: -------------------------------------------------------------------------------- 1 | cryptography 2 | websockets 3 | -------------------------------------------------------------------------------- /server/scripts/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Ensure correct storage location 5 | export NYM_CONFIG_DIR="/root/.nym" 6 | 7 | # Check for encryption password 8 | if [ ! -f "/app/secrets/encryption_password" ]; then 9 | echo "[ERROR] Encryption password secret not found!" 10 | exit 1 11 | fi 12 | chmod 600 /app/secrets/encryption_password 13 | echo "[INFO] Encryption password loaded successfully." 14 | 15 | # Run the main Python application **as the main process** 16 | exec python server/mainApp.py 17 | -------------------------------------------------------------------------------- /server/scripts/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Define URLs and directories 5 | ENV_EXAMPLE="/app/.env.example" 6 | PASSWORD_FILE="/app/secrets/encryption_password" 7 | STORAGE_DIR="/app/storage" 8 | NYM_CONFIG_DIR="/root/.nym" 9 | BUILD_DIR="/tmp/nym-build" 10 | INSTALL_DIR="/app" 11 | 12 | # Logging function 13 | log() { 14 | local level="$1" 15 | local message="$2" 16 | local color_start="" 17 | local color_end="" 18 | 19 | if [[ -t 1 ]]; then 20 | case "$level" in 21 | "INFO") color_start="\033[0;32m" ;; # Green 22 | "WARN") color_start="\033[0;33m" ;; # Yellow 23 | "ERROR") color_start="\033[0;31m" ;; # Red 24 | "DEBUG") color_start="\033[0;36m" ;; # Cyan 25 | esac 26 | color_end="\033[0m" 27 | fi 28 | 29 | echo -e "${color_start}[$level] $message${color_end}" 30 | } 31 | 32 | # Detect OS and architecture 33 | detect_os() { 34 | case "$(uname -s)" in 35 | Linux*) OS="linux";; 36 | Darwin*) OS="macos";; 37 | CYGWIN*|MINGW*|MSYS*) OS="windows";; 38 | *) OS="unknown";; 39 | esac 40 | 41 | case "$(uname -m)" in 42 | x86_64) ARCH="x86_64";; 43 | i386|i686) ARCH="x86";; 44 | arm64|aarch64) ARCH="aarch64";; 45 | armv7*) ARCH="arm";; 46 | *) ARCH="unknown";; 47 | esac 48 | 49 | log "INFO" "Detected system: $OS ($ARCH)" 50 | } 51 | 52 | # Install system dependencies 53 | install_dependencies() { 54 | log "INFO" "[PHASE] Installing required system packages..." 55 | 56 | apt-get update # Always update package lists first 57 | 58 | if [[ "$ARCH" == "x86_64" || "$ARCH" == "x86" ]]; then 59 | log "INFO" "Detected $ARCH, installing only curl (prebuilt binary will be used)" 60 | apt-get install -y curl 61 | else 62 | log "INFO" "Detected $ARCH, installing full build dependencies for Rust" 63 | apt-get install -y git build-essential cmake pkg-config libssl-dev curl 64 | fi 65 | 66 | log "INFO" "System dependencies installed successfully!" 67 | } 68 | 69 | 70 | # Fetch the latest version of from nymtech/nym repo 71 | fetch_latest_version() { 72 | log "INFO" "Fetching latest Nym release version from GitHub..." 73 | LATEST_VERSION=$(curl -fsSL "https://api.github.com/repos/nymtech/nym/releases/latest" | grep '"tag_name":' | cut -d '"' -f 4) 74 | 75 | if [[ -z "$LATEST_VERSION" ]]; then 76 | log "ERROR" "Failed to fetch latest version. Exiting." 77 | exit 1 78 | fi 79 | 80 | NYM_BINARY_URL="https://github.com/nymtech/nym/releases/download/${LATEST_VERSION}/nym-client" 81 | HASH_URL="https://github.com/nymtech/nym/releases/download/${LATEST_VERSION}/hashes.json" 82 | 83 | log "INFO" "Latest Nym version: $LATEST_VERSION" 84 | } 85 | 86 | # Install the Nym client binary in /app/ 87 | install_binary() { 88 | log "INFO" "[PHASE] Installing Nym client binary..." 89 | local install_path="$INSTALL_DIR/nym-client" 90 | 91 | mkdir -p "$INSTALL_DIR" 92 | 93 | log "INFO" "Downloading Nym client from $NYM_BINARY_URL" 94 | curl -L "$NYM_BINARY_URL" -o "$install_path" 95 | chmod +x "$install_path" 96 | 97 | # Verify the binary 98 | verify_binary "$install_path" 99 | } 100 | 101 | # Ensure our download hash matches Nym's 102 | verify_binary() { 103 | local binary="$1" 104 | local hash_file="/tmp/hashes.json" 105 | 106 | log "INFO" "Fetching latest hash file from: $HASH_URL" 107 | if ! curl -fsSL "$HASH_URL" -o "$hash_file"; then 108 | log "ERROR" "Failed to download hash file! Aborting." 109 | exit 1 110 | fi 111 | 112 | # Calculate the binary's SHA-256 hash 113 | local hash 114 | if command -v sha256sum >/dev/null; then 115 | hash=$(sha256sum "$binary" | cut -d ' ' -f 1) 116 | elif command -v shasum >/dev/null; then 117 | hash=$(shasum -a 256 "$binary" | cut -d ' ' -f 1) 118 | else 119 | log "ERROR" "No SHA-256 utility found! Cannot verify binary." 120 | exit 1 121 | fi 122 | 123 | log "INFO" "Calculated SHA-256: $hash" 124 | 125 | # Extract expected hash from JSON using grep 126 | local expected_hash 127 | expected_hash=$(grep -A 1 '"nym-client"' "$hash_file" | grep -o '"sha256": "[^"]*' | cut -d '"' -f 4) 128 | 129 | log "INFO" "Expected SHA-256: $expected_hash" 130 | 131 | # Compare hashes 132 | if [[ "$hash" == "$expected_hash" ]]; then 133 | log "INFO" "✅ Hash verification successful!" 134 | return 0 135 | else 136 | log "ERROR" "❌ Hash verification failed! Binary may be compromised." 137 | exit 1 138 | fi 139 | } 140 | 141 | # Ensure storage directories exist and have correct permissions 142 | setup_storage() { 143 | log "INFO" "[PHASE] Setting up storage directories..." 144 | 145 | mkdir -p "$STORAGE_DIR" 146 | chmod -R 777 "$STORAGE_DIR" # Ensure all users can write logs 147 | 148 | mkdir -p /app/secrets 149 | chmod -R 700 /app/secrets # Only allow root to read secrets 150 | 151 | mkdir -p "$NYM_CONFIG_DIR" 152 | chmod -R 700 "$NYM_CONFIG_DIR" 153 | 154 | log "INFO" "Storage directories are set up." 155 | } 156 | 157 | # Copy encryption password 158 | setup_encryption_password() { 159 | log "INFO" "[PHASE] Setting up encryption password..." 160 | 161 | mkdir -p /app/secrets 162 | chmod 700 /app/secrets # Restrict access to secrets directory 163 | 164 | if [ ! -f "/app/password.txt" ]; then 165 | log "ERROR" "password.txt is missing! Please create it before running the install script." 166 | exit 1 167 | fi 168 | 169 | log "INFO" "Copying provided password to secrets directory." 170 | cp "/app/password.txt" "/app/secrets/encryption_password" 171 | chmod 600 "/app/secrets/encryption_password" 172 | 173 | log "INFO" "Encryption password setup complete." 174 | } 175 | 176 | # Generate .env file from .env.example 177 | generate_env_file() { 178 | log "INFO" "[PHASE] Generating .env file..." 179 | 180 | ENV_EXAMPLE=".env.example" 181 | ENV_FILE=".env" 182 | 183 | if [ ! -f "$ENV_EXAMPLE" ]; then 184 | log "ERROR" ".env.example not found!" 185 | exit 1 186 | fi 187 | 188 | log "INFO" "Copying .env.example to .env" 189 | cp "$ENV_EXAMPLE" "$ENV_FILE" 190 | 191 | # Extract NYM_CLIENT_ID first 192 | NYM_CLIENT_ID=$(grep '^NYM_CLIENT_ID=' "$ENV_EXAMPLE" | cut -d '=' -f 2-) 193 | export NYM_CLIENT_ID 194 | 195 | log "INFO" "Using NYM_CLIENT_ID: $NYM_CLIENT_ID" 196 | 197 | # Replace environment variables using envsubst 198 | envsubst < "$ENV_EXAMPLE" > "$ENV_FILE" 199 | 200 | chmod 600 "$ENV_FILE" 201 | log "INFO" ".env file generated successfully." 202 | } 203 | 204 | 205 | 206 | # Install Rust if needed 207 | install_rust() { 208 | if ! command -v rustc >/dev/null 2>&1; then 209 | log "INFO" "Rust not found. Installing Rust toolchain..." 210 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y 211 | source "$HOME/.cargo/env" 212 | log "INFO" "Rust installed successfully!" 213 | else 214 | log "INFO" "Rust is already installed: $(rustc --version)" 215 | fi 216 | } 217 | 218 | # Build nym-client from source 219 | build_nym_client() { 220 | log "INFO" "Cloning Nym repository from GitHub..." 221 | rm -rf "$BUILD_DIR" 222 | git clone --depth 1 "https://github.com/nymtech/nym.git" "$BUILD_DIR" 223 | 224 | cd "$BUILD_DIR" 225 | 226 | log "INFO" "Building `nym-client` for architecture: $ARCH..." 227 | cargo build --release --bin nym-client 228 | 229 | if [[ -f "target/release/nym-client" ]]; then 230 | log "INFO" "Build successful! Moving binary to installation directory..." 231 | mv "target/release/nym-client" "$INSTALL_DIR/nym-client" 232 | chmod +x "$INSTALL_DIR/nym-client" 233 | log "INFO" "nym-client installed at $INSTALL_DIR/nym-client" 234 | else 235 | log "ERROR" "Build failed! Check logs for details." 236 | exit 1 237 | fi 238 | 239 | # Clean up build files to save space 240 | log "INFO" "Cleaning up build directory..." 241 | rm -rf "$BUILD_DIR" 242 | } 243 | 244 | # Main execution flow 245 | log "INFO" "=============================================================" 246 | log "INFO" "NYM CLIENT INSTALLATION AND CONFIGURATION" 247 | log "INFO" "Client ID: $NYM_CLIENT_ID" 248 | log "INFO" "=============================================================" 249 | 250 | detect_os 251 | install_dependencies 252 | fetch_latest_version 253 | setup_storage 254 | setup_encryption_password 255 | generate_env_file 256 | 257 | # Determine whether to use prebuilt binary or build from source 258 | if [[ "$ARCH" != "x86_64" && "$ARCH" != "x86" ]]; then 259 | log "INFO" "Forcing build from source due to architecture: $ARCH" 260 | install_rust 261 | build_nym_client 262 | # initialize_nym_client 263 | else 264 | log "INFO" "Using prebuilt binary for Linux ($ARCH)" 265 | install_binary 266 | # initialize_nym_client 267 | fi 268 | 269 | log "INFO" "[COMPLETE] Nym client installation & config successful" -------------------------------------------------------------------------------- /server/src/cryptographyUtils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import base64 3 | import secrets 4 | from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC 5 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 6 | from cryptography.hazmat.primitives import hashes, serialization 7 | from cryptography.hazmat.backends import default_backend 8 | from cryptography.hazmat.primitives.asymmetric import ec 9 | from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature, decode_dss_signature 10 | from logConfig import logger 11 | from envLoader import load_env 12 | 13 | load_env() 14 | 15 | class CryptoUtils: 16 | def __init__(self, key_dir, password): 17 | """Initialize the CryptoUtils with a directory for storing keys and a password for encryption.""" 18 | self.key_dir = os.getenv("KEYS_DIR", "storage/keys") 19 | self.password = password # Store password in memory 20 | if not os.path.exists(self.key_dir): 21 | os.makedirs(self.key_dir) 22 | 23 | def _derive_key(self, salt): 24 | """Derive a 256-bit AES key using PBKDF2 with 100,000 iterations.""" 25 | kdf = PBKDF2HMAC( 26 | algorithm=hashes.SHA256(), 27 | length=32, 28 | salt=salt, 29 | iterations=100_000, 30 | backend=default_backend(), 31 | ) 32 | return kdf.derive(self.password.encode()) 33 | 34 | def _encrypt_private_key(self, private_key_pem): 35 | """Encrypt the private key using AES-256-GCM.""" 36 | salt = secrets.token_bytes(16) 37 | key = self._derive_key(salt) 38 | iv = secrets.token_bytes(12) 39 | cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()) 40 | encryptor = cipher.encryptor() 41 | ciphertext = encryptor.update(private_key_pem) + encryptor.finalize() 42 | 43 | return base64.b64encode(salt + iv + encryptor.tag + ciphertext).decode() 44 | 45 | def _decrypt_private_key(self, encrypted_data): 46 | """Decrypt the AES-256-GCM encrypted private key.""" 47 | encrypted_data = base64.b64decode(encrypted_data) 48 | salt, iv, tag, ciphertext = encrypted_data[:16], encrypted_data[16:28], encrypted_data[28:44], encrypted_data[44:] 49 | key = self._derive_key(salt) 50 | cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()) 51 | decryptor = cipher.decryptor() 52 | return decryptor.update(ciphertext) + decryptor.finalize() 53 | 54 | def generate_key_pair(self, username): 55 | """Generate and securely save a private/public key pair.""" 56 | private_key = ec.generate_private_key(ec.SECP256R1()) 57 | public_key = private_key.public_key() 58 | private_key_pem = private_key.private_bytes( 59 | encoding=serialization.Encoding.PEM, 60 | format=serialization.PrivateFormat.PKCS8, 61 | encryption_algorithm=serialization.NoEncryption(), 62 | ) 63 | 64 | encrypted_private_key = self._encrypt_private_key(private_key_pem) 65 | 66 | private_key_path = os.path.join(self.key_dir, f"{username}_private_key.enc") 67 | public_key_path = os.path.join(self.key_dir, f"{username}_public_key.pem") 68 | 69 | with open(private_key_path, "w") as f: 70 | f.write(encrypted_private_key) 71 | 72 | with open(public_key_path, "wb") as f: 73 | f.write( 74 | public_key.public_bytes( 75 | encoding=serialization.Encoding.PEM, 76 | format=serialization.PublicFormat.SubjectPublicKeyInfo, 77 | ) 78 | ) 79 | 80 | logger.info(f"generateKeyPair - success!") 81 | return private_key, public_key.public_bytes( 82 | encoding=serialization.Encoding.PEM, 83 | format=serialization.PublicFormat.SubjectPublicKeyInfo, 84 | ).decode() 85 | 86 | def load_private_key(self, username): 87 | """Load and decrypt the private key from storage.""" 88 | private_key_path = os.path.join(self.key_dir, f"{username}_private_key.enc") 89 | 90 | if not os.path.exists(private_key_path): 91 | return None 92 | 93 | with open(private_key_path, "r") as f: 94 | encrypted_data = f.read() 95 | 96 | try: 97 | decrypted_pem = self._decrypt_private_key(encrypted_data) 98 | private_key = serialization.load_pem_private_key(decrypted_pem, password=None, backend=default_backend()) 99 | return private_key 100 | except Exception as e: 101 | logger.error(f"loadPrivateKey - error :( |{e}") 102 | return None 103 | 104 | def load_public_key(self, username): 105 | """Load the public key from file.""" 106 | try: 107 | public_key_path = os.path.join(self.key_dir, f"{username}_public_key.pem") 108 | with open(public_key_path, "rb") as f: 109 | public_key = serialization.load_pem_public_key(f.read()) 110 | return public_key 111 | except Exception as e: 112 | logger.error(f"loadPublicKey - error :( | {e}") 113 | return None 114 | 115 | def sign_message(self, username, message): 116 | """Sign a message using the user's private key.""" 117 | private_key = self.load_private_key(username) 118 | if not private_key: 119 | return None 120 | 121 | try: 122 | signature = private_key.sign( 123 | message.encode(), 124 | ec.ECDSA(hashes.SHA256()) 125 | ) 126 | r, s = decode_dss_signature(signature) 127 | logger.info(f"signMessage - success!") 128 | return encode_dss_signature(r, s).hex() 129 | except Exception as e: 130 | logger.error(f"signMessage - error :( | {e}") 131 | return None 132 | 133 | def verify_signature(self, publicKeyPem, message, signature): 134 | """Verify a message signature using the provided public key in PEM format.""" 135 | try: 136 | public_key = serialization.load_pem_public_key(publicKeyPem.encode()) 137 | r, s = decode_dss_signature(bytes.fromhex(signature)) 138 | public_key.verify( 139 | encode_dss_signature(r, s), 140 | message.encode(), 141 | ec.ECDSA(hashes.SHA256()) 142 | ) 143 | logger.info("verifySignature - success!") 144 | return True 145 | except Exception as e: 146 | logger.error(f"verifySignature - error :( | {e}") 147 | return False 148 | -------------------------------------------------------------------------------- /server/src/dbUtils.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import json 3 | import os 4 | from logConfig import logger 5 | from envLoader import load_env 6 | 7 | load_env() 8 | 9 | class DbUtils: 10 | def __init__(self, dbPath): 11 | self.dbPath = os.getenv("DATABASE_PATH") 12 | 13 | if not os.path.exists(dbPath): 14 | logger.info(f"Initializing new database at {dbPath}.") 15 | else: 16 | logger.info(f"Using existing database at {dbPath}.") 17 | 18 | self.connection = sqlite3.connect(dbPath, check_same_thread=False) 19 | self.cursor = self.connection.cursor() 20 | self._initializeTables() 21 | 22 | def _initializeTables(self): 23 | logger.info("Ensuring necessary database tables exist...") 24 | self.cursor.execute(""" 25 | CREATE TABLE IF NOT EXISTS users ( 26 | username TEXT PRIMARY KEY, 27 | publicKey TEXT NOT NULL, 28 | senderTag TEXT NOT NULL 29 | ) 30 | """) 31 | self.cursor.execute(""" 32 | CREATE TABLE IF NOT EXISTS groups ( 33 | groupID TEXT PRIMARY KEY, 34 | userList TEXT NOT NULL 35 | ) 36 | """) 37 | self.connection.commit() 38 | 39 | def addUser(self, username, publicKey, senderTag): 40 | try: 41 | self.cursor.execute( 42 | "INSERT INTO users (username, publicKey, senderTag) VALUES (?, ?, ?)", 43 | (username, publicKey, senderTag), 44 | ) 45 | self.connection.commit() 46 | logger.info(f"User {username} added successfully.") 47 | except sqlite3.IntegrityError as e: 48 | logger.error(f"Error adding user {username}: {e}") 49 | return False 50 | return True 51 | 52 | def getUserByUsername(self, username): 53 | self.cursor.execute("SELECT * FROM users WHERE username = ?", (username,)) 54 | return self.cursor.fetchone() 55 | 56 | def getUserBySenderTag(self, senderTag): 57 | self.cursor.execute("SELECT * FROM users WHERE senderTag = ?", (senderTag,)) 58 | return self.cursor.fetchone() 59 | 60 | def updateUserField(self, username, field, value): 61 | try: 62 | self.cursor.execute(f"UPDATE users SET {field} = ? WHERE username = ?", (value, username)) 63 | self.connection.commit() 64 | logger.info(f"User {username} field {field} updated") 65 | return True 66 | except sqlite3.Error as e: 67 | logger.error(f"Error updating user {username} field {field}: {e}") 68 | return False 69 | 70 | def addGroup(self, groupId, initialUsers): 71 | try: 72 | self.cursor.execute( 73 | "INSERT INTO groups (groupID, userList) VALUES (?, ?)", 74 | (groupId, json.dumps(initialUsers)), 75 | ) 76 | self.connection.commit() 77 | logger.info(f"Group {groupId} added successfully.") 78 | except sqlite3.IntegrityError as e: 79 | logger.error(f"Error adding group {groupId}: {e}") 80 | return False 81 | return True 82 | 83 | def getGroup(self, groupId): 84 | self.cursor.execute("SELECT * FROM groups WHERE groupID = ?", (groupId,)) 85 | return self.cursor.fetchone() 86 | 87 | def close(self): 88 | logger.info("Closing database connection.") 89 | self.connection.close() -------------------------------------------------------------------------------- /server/src/envLoader.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def load_env(filepath=".env"): 4 | """Load environment variables from a .env file into os.environ.""" 5 | if os.path.exists(filepath): 6 | with open(filepath) as f: 7 | for line in f: 8 | # Ignore empty lines and comments 9 | if line.strip() and not line.startswith("#"): 10 | key, value = line.strip().split("=", 1) 11 | os.environ[key] = value 12 | -------------------------------------------------------------------------------- /server/src/logConfig.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from envLoader import load_env 4 | 5 | load_env() 6 | 7 | # Configure logging 8 | LOG_FILE = os.getenv("LOG_FILE_PATH", "storage/app.log") 9 | 10 | logging.basicConfig( 11 | level=logging.INFO, 12 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 13 | handlers=[ 14 | logging.FileHandler(LOG_FILE), # Log to file 15 | logging.StreamHandler() # Log to console 16 | ] 17 | ) 18 | 19 | logger = logging.getLogger("AppLogger") 20 | 21 | 22 | -------------------------------------------------------------------------------- /server/src/mainApp.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | import sys 4 | import time 5 | import signal 6 | import subprocess 7 | import threading 8 | from websocketUtils import WebsocketUtils 9 | from dbUtils import DbUtils 10 | from messageUtils import MessageUtils 11 | from cryptographyUtils import CryptoUtils 12 | from logConfig import logger 13 | from envLoader import load_env 14 | 15 | load_env() 16 | 17 | # Ensure all required directories exist 18 | storage_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "storage") 19 | os.makedirs(storage_dir, exist_ok=True) 20 | keys_dir = os.getenv("KEYS_DIR", "storage/keys") 21 | os.makedirs(keys_dir, exist_ok=True) 22 | logs_dir = os.path.dirname(os.getenv("LOG_FILE", "storage/app.log")) 23 | os.makedirs(logs_dir, exist_ok=True) 24 | 25 | # Global variables 26 | client_process = None 27 | shutdown_event = threading.Event() # Used for clean shutdown 28 | 29 | 30 | def get_encryption_password(): 31 | secret_path = os.getenv("SECRET_PATH") 32 | if os.path.exists(secret_path): 33 | with open(secret_path, "r") as f: 34 | return f.read().strip() 35 | logger.error("Encryption password secret not found.") 36 | sys.exit(1) 37 | 38 | def initialize_nym_client(): 39 | """Checks if Nym client is already initialized, and initializes if necessary.""" 40 | nym_client_id = os.getenv("NYM_CLIENT_ID") 41 | nym_client_dir = f"/root/.nym/clients/{nym_client_id}" 42 | 43 | if os.path.exists(nym_client_dir): 44 | logger.info("Existing Nym config found. Skipping init.") 45 | else: 46 | logger.info("No existing Nym config found. Initializing...") 47 | command = ["./nym-client", "init", "--id", nym_client_id] 48 | try: 49 | subprocess.run(command, check=True) 50 | logger.info("Nym client initialized successfully.") 51 | except subprocess.CalledProcessError as e: 52 | logger.error(f"Failed to initialize Nym client: {e}") 53 | sys.exit(1) 54 | 55 | def start_client(): 56 | """Starts the `nym-client` process without using a shell.""" 57 | global client_process 58 | try: 59 | command = ["./nym-client", "run", "--id", os.getenv("NYM_CLIENT_ID")] 60 | client_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 61 | logger.info("Nym client started successfully.") 62 | 63 | # Wait for the client to initialize 64 | time.sleep(5) # Allow the client time to start up before proceeding 65 | 66 | except Exception as e: 67 | logger.error(f"Failed to start Nym client: {e}") 68 | client_process = None 69 | 70 | 71 | def monitor_client(): 72 | """Monitors the Nym client output for errors and restarts if necessary.""" 73 | global client_process 74 | while True: 75 | if client_process is None or client_process.poll() is not None: 76 | logger.error("Nym client crashed. Restarting in 10 seconds...") 77 | time.sleep(10) 78 | start_client() 79 | continue 80 | 81 | try: 82 | # Read output from stdout and stderr 83 | stdout, stderr = client_process.communicate(timeout=60) 84 | output = (stdout + stderr).decode() 85 | 86 | # Check if there's any error (any occurrence of "ERROR") 87 | if "ERROR" in output: 88 | logger.error(f"Error detected in client output: {output}") 89 | client_process.terminate() # Restart on error 90 | time.sleep(2) # Short wait before restarting 91 | except subprocess.TimeoutExpired: 92 | logger.info("Nym client is still running, no issues detected.") 93 | except Exception as e: 94 | logger.error(f"Unhandled error while monitoring Nym client: {e}") 95 | 96 | 97 | 98 | def graceful_shutdown(signal_received, frame): 99 | """Handles shutdown signals (SIGINT & SIGTERM) to terminate processes cleanly.""" 100 | logger.info("Graceful shutdown initiated. Sending Ctrl+C to Nym client...") 101 | shutdown_event.set() # Signal the monitoring thread to stop 102 | 103 | if client_process is not None: 104 | client_process.send_signal(signal.SIGINT) # Send SIGINT (Ctrl+C) 105 | logger.info("Waiting 5 seconds for Nym client to shut down gracefully...") 106 | time.sleep(5) # Give it time to handle cleanup 107 | logger.info("Nym client shutdown complete.") 108 | 109 | sys.exit(0) 110 | 111 | 112 | async def main(): 113 | """Main asynchronous function handling WebSocket communication.""" 114 | password = get_encryption_password() 115 | 116 | websocket_url = os.getenv("WEBSOCKET_URL") 117 | db_path = os.getenv("DATABASE_PATH", "storage/nym_server.db") 118 | key_dir = os.getenv("KEYS_DIR", "storage/keys") 119 | 120 | cryptography_utils = CryptoUtils(key_dir, password) 121 | database_manager = DbUtils(db_path) 122 | 123 | websocket_manager = WebsocketUtils(websocket_url) 124 | message_handler = MessageUtils(websocket_manager, database_manager, cryptography_utils, password) 125 | 126 | websocket_manager.set_message_callback(message_handler.processMessage) 127 | 128 | try: 129 | logger.info("Connecting to WebSocket...") 130 | await websocket_manager.connect() 131 | logger.info("Waiting for incoming messages...") 132 | 133 | while not shutdown_event.is_set(): 134 | await asyncio.sleep(1) # Prevent busy-waiting 135 | 136 | except asyncio.CancelledError: 137 | logger.info("Main coroutine was cancelled.") 138 | except KeyboardInterrupt: 139 | logger.info("Received KeyboardInterrupt. Closing gracefully...") 140 | except Exception as e: 141 | logger.error(f"Error occurred: {e}") 142 | finally: 143 | logger.info("Closing connections...") 144 | await websocket_manager.close() 145 | database_manager.close() 146 | 147 | 148 | if __name__ == "__main__": 149 | # Register SIGTERM and SIGINT handlers for clean shutdown 150 | signal.signal(signal.SIGTERM, graceful_shutdown) 151 | signal.signal(signal.SIGINT, graceful_shutdown) 152 | 153 | initialize_nym_client() 154 | 155 | # Start Nym client first 156 | start_client() 157 | 158 | # Start monitoring the Nym client in a separate thread 159 | monitoring_thread = threading.Thread(target=monitor_client, daemon=True).start() 160 | 161 | # Start the async WebSocket server 162 | try: 163 | asyncio.run(main()) # Run the main async function 164 | except KeyboardInterrupt: 165 | logger.info("Application interrupted by user.") 166 | except asyncio.CancelledError: 167 | logger.info("Application shutdown gracefully.") -------------------------------------------------------------------------------- /server/src/messageUtils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import secrets 3 | import os 4 | import re 5 | from cryptography.hazmat.primitives.asymmetric import ec 6 | from cryptography.hazmat.primitives import hashes 7 | from cryptography.hazmat.primitives.serialization import load_pem_private_key 8 | from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature, decode_dss_signature 9 | from cryptographyUtils import CryptoUtils 10 | from envLoader import load_env 11 | from logConfig import logger 12 | 13 | load_env() 14 | 15 | class MessageUtils: 16 | NONCES = {} # Temporary storage for nonces 17 | PENDING_USERS = {} # Temporary storage for user details during registration 18 | 19 | def __init__(self, websocketManager, databaseManager, crypto_utils, password): 20 | NYM_CLIENT_ID = os.getenv("NYM_CLIENT_ID") 21 | SERVER_KEY_PATH = os.getenv("KEYS_DIR") 22 | 23 | self.websocketManager = websocketManager 24 | self.databaseManager = databaseManager 25 | self.cryptoUtils = CryptoUtils(SERVER_KEY_PATH, password) 26 | 27 | private_key_path = os.path.join(os.getenv("KEYS_DIR"), f"{NYM_CLIENT_ID}_private_key.enc") 28 | 29 | # Ensure the server's key pair exists 30 | if not os.path.exists(private_key_path): 31 | self.cryptoUtils.generate_key_pair(NYM_CLIENT_ID) 32 | logger.info("Init - Server key pair generated.") 33 | 34 | @staticmethod 35 | def is_valid_username(username): 36 | """Validates that the username contains only letters, numbers, '-', or '_'""" 37 | return bool(re.fullmatch(r"[A-Za-z0-9_-]+", username)) 38 | 39 | async def processMessage(self, messageData): 40 | messageType = messageData.get("type") 41 | 42 | if messageType == "received": 43 | await self.processReceivedMessage(messageData) 44 | else: 45 | logger.error(f"processMessaage - Unknown message type :( | {messageType}") 46 | 47 | async def processReceivedMessage(self, messageData): 48 | encapsulatedJson = messageData.get("message") 49 | senderTag = messageData.get("senderTag") 50 | 51 | try: 52 | encapsulatedData = json.loads(encapsulatedJson) 53 | action = encapsulatedData.get("action") 54 | 55 | if action == "query": 56 | await self.handleQuery(encapsulatedData, senderTag) 57 | elif action == "register": 58 | await self.handleRegister(encapsulatedData, senderTag) 59 | elif action == "login": 60 | await self.handleLogin(encapsulatedData, senderTag) 61 | elif action == "registrationResponse": 62 | await self.handleRegistrationResponse(encapsulatedData, senderTag) 63 | elif action == "update": 64 | await self.handleUpdate(encapsulatedData, senderTag) 65 | elif action == "send": 66 | await self.handleSend(encapsulatedData, senderTag) 67 | elif action == "sendGroup": 68 | await self.handleSendGroup(encapsulatedData, senderTag) 69 | elif action == "createGroup": 70 | await self.handleCreateGroup(encapsulatedData, senderTag) 71 | elif action == "inviteGroup": 72 | await self.handleSendInvite(encapsulatedData, senderTag) 73 | elif action == "loginResponse": 74 | await self.handleLoginResponse(encapsulatedData, senderTag) 75 | else: 76 | logger.error(f"processReceivedMessage - Unknown encapsulated action :( | {action}") 77 | except json.JSONDecodeError as e: 78 | logger.error(f"processReceivedMessage - Decoding JSON :( | {e}") 79 | 80 | async def handleSend(self, messageData, senderTag): 81 | """ 82 | Handle a direct 'send' message request from a client. 83 | """ 84 | 85 | content_str = messageData.get("content") 86 | signature = messageData.get("signature") 87 | 88 | # Basic validation 89 | if not content_str or not signature: 90 | await self.sendEncapsulatedReply( 91 | senderTag, 92 | "error: missing 'content' or 'signature'", 93 | action="sendResponse", 94 | context="chat" 95 | ) 96 | logger.warning("handleSend - missing content or signature :(") 97 | return 98 | 99 | # Parse the inner JSON for actual message details. 100 | try: 101 | content_dict = json.loads(content_str) 102 | except json.JSONDecodeError: 103 | await self.sendEncapsulatedReply( 104 | senderTag, 105 | "error: invalid JSON in content", 106 | action="sendResponse", 107 | context="chat" 108 | ) 109 | logger.warning("handleSend - invalid JSON :(") 110 | return 111 | 112 | # Extract sender and recipient usernames. 113 | sender_username = content_dict.get("sender") 114 | recipient_username = content_dict.get("recipient") 115 | if not sender_username or not recipient_username: 116 | await self.sendEncapsulatedReply( 117 | senderTag, 118 | "error: missing 'sender' or 'recipient' field in message content", 119 | action="sendResponse", 120 | context="chat" 121 | ) 122 | logger.warning("handleSend - missing sender/recipient :(") 123 | return 124 | 125 | # Look up the sender by username. 126 | senderRecord = self.databaseManager.getUserByUsername(sender_username) 127 | if not senderRecord: 128 | await self.sendEncapsulatedReply( 129 | senderTag, 130 | "error: unrecognized sender username", 131 | action="sendResponse", 132 | context="chat" 133 | ) 134 | logger.warning("handleSend - could not find sender in DB :(") 135 | return 136 | 137 | # Extract sender details from the database. 138 | dbSenderTag = senderRecord[2] 139 | dbPublicKey = senderRecord[1] 140 | 141 | # Verify the signature using the sender's public key. 142 | if not self.cryptoUtils.verify_signature(dbPublicKey, content_str, signature): 143 | await self.sendEncapsulatedReply( 144 | senderTag, 145 | "error: invalid signature", 146 | action="sendResponse", 147 | context="chat" 148 | ) 149 | logger.warning("handleSend - invalid signature :(") 150 | return 151 | 152 | # Check if the senderTag has changed. 153 | if dbSenderTag != senderTag: 154 | self.databaseManager.updateUserField(sender_username, "senderTag", senderTag) 155 | 156 | # Look up the recipient by username. 157 | targetUser = self.databaseManager.getUserByUsername(recipient_username) 158 | if not targetUser: 159 | await self.sendEncapsulatedReply( 160 | senderTag, 161 | "error: recipient not found", 162 | action="sendResponse", 163 | context="chat" 164 | ) 165 | logger.warning("handleSend - could not find recipient in DB :(") 166 | return 167 | 168 | # Extract recipient senderTag. 169 | targetSenderTag = targetUser[2] 170 | 171 | # Build the forward payload. 172 | forwardPayload = { 173 | "sender": sender_username, 174 | "body": content_dict.get("body") 175 | } 176 | # Include sender's public key if present. 177 | if "senderPublicKey" in content_dict: 178 | forwardPayload["senderPublicKey"] = content_dict["senderPublicKey"] 179 | 180 | # Forward the message to the recipient. 181 | await self.sendEncapsulatedReply( 182 | targetSenderTag, 183 | json.dumps(forwardPayload), 184 | action="incomingMessage", 185 | context="chat" 186 | ) 187 | 188 | # Confirm success to the sender. 189 | await self.sendEncapsulatedReply( 190 | senderTag, 191 | "success", 192 | action="sendResponse", 193 | context="chat" 194 | ) 195 | 196 | async def handleQuery(self, messageData, senderTag): 197 | """ 198 | Handle a user discovery query: 199 | - The client sends a 'username' field to look up. 200 | - We return either the user details (username and publicKey) 201 | or "No user found". 202 | Example incoming data: 203 | { 204 | "action": "query", 205 | "username": "" 206 | } 207 | """ 208 | target_username = messageData.get("username") 209 | if not target_username: 210 | # If 'username' is missing, let the client know 211 | await self.sendEncapsulatedReply( 212 | senderTag, 213 | "error: missing 'username' field", 214 | action="queryResponse", 215 | context="query" 216 | ) 217 | logger.warning("handleQuery - missing username field :(") 218 | return 219 | 220 | # Look up the user record in the DB 221 | user = self.databaseManager.getUserByUsername(target_username) 222 | if user: 223 | # Depending on your schema, user might be (username, publicKey, senderTag, ...) 224 | # We'll just extract the first two. 225 | username, publicKey = user[0], user[1] 226 | 227 | # Only return the username and publicKey 228 | user_data = { 229 | "username": username, 230 | "publicKey": publicKey 231 | } 232 | 233 | await self.sendEncapsulatedReply( 234 | senderTag, 235 | json.dumps(user_data), 236 | action="queryResponse", 237 | context="query" 238 | ) 239 | else: 240 | # No user found 241 | await self.sendEncapsulatedReply( 242 | senderTag, 243 | "No user found", 244 | action="queryResponse", 245 | context="query" 246 | ) 247 | 248 | async def handleRegister(self, messageData, senderTag): 249 | username = messageData.get("usernym") 250 | publicKey = messageData.get("publicKey") 251 | 252 | if not username or not publicKey: 253 | await self.sendEncapsulatedReply(senderTag, "error: missing username or public key", action="challengeResponse", context="registration") 254 | return 255 | 256 | if not MessageUtils.is_valid_username(username): 257 | await self.sendEncapsulatedReply(senderTag, "error: invalid username format", action="challengeResponse", context="registration") 258 | return 259 | 260 | if self.databaseManager.getUserByUsername(username): 261 | await self.sendEncapsulatedReply(senderTag, "error: username already in use", action="challengeResponse", context="registration") 262 | return 263 | 264 | # Generate a nonce and store it in PENDING_USERS 265 | nonce = secrets.token_hex(16) 266 | self.PENDING_USERS[senderTag] = (username, publicKey, nonce) 267 | logger.info("handleRegister - sending challenge") 268 | # Send the challenge to the client 269 | await self.sendEncapsulatedReply(senderTag, json.dumps({"nonce": nonce}), action="challenge", context="registration") 270 | 271 | async def handleRegistrationResponse(self, messageData, senderTag): 272 | signature = messageData.get("signature") 273 | user_details = self.PENDING_USERS.get(senderTag) 274 | 275 | if not user_details: 276 | await self.sendEncapsulatedReply(senderTag, "error: no pending registration for sender", action="challengeResponse", context="registration") 277 | logger.warning("handleRegistrationResponse - no pending registration for sender :(") 278 | return 279 | 280 | username, publicKey, nonce = user_details 281 | 282 | # Verify the signature 283 | if self.cryptoUtils.verify_signature(publicKey, nonce, signature): 284 | if self.databaseManager.addUser(username, publicKey, senderTag): 285 | await self.sendEncapsulatedReply(senderTag, "success", action="challengeResponse", context="registration") 286 | del self.PENDING_USERS[senderTag] # Clean up after successful registration 287 | logger.info("handleRegistrationResponse - registration successful") 288 | else: 289 | await self.sendEncapsulatedReply(senderTag, "error: database failure", action="challengeResponse", context="registration") 290 | else: 291 | await self.sendEncapsulatedReply(senderTag, "error: signature verification failed", action="challengeResponse", context="registration") 292 | del self.PENDING_USERS[senderTag] # Clean up after failed verification 293 | logger.warning("handleRegistrationResponse - registration failed :(") 294 | 295 | async def handleLogin(self, messageData, senderTag): 296 | """ 297 | Handle the login request from the client. 298 | """ 299 | username = messageData.get("usernym") 300 | 301 | if not username: 302 | await self.sendEncapsulatedReply(senderTag, "error: missing username", action="challengeResponse", context="login") 303 | logger.warning("handleLogin - missing username :(") 304 | return 305 | 306 | user = self.databaseManager.getUserByUsername(username) 307 | if not user: 308 | await self.sendEncapsulatedReply(senderTag, "error: user not found", action="challengeResponse", context="login") 309 | logger.warning("handleLogin - user not found in DB :(") 310 | return 311 | 312 | # Generate a nonce and store it 313 | nonce = secrets.token_hex(16) 314 | self.NONCES[senderTag] = (username, user[1], nonce) # user[1] is the public key 315 | 316 | # Send the challenge to the client 317 | await self.sendEncapsulatedReply(senderTag, json.dumps({"nonce": nonce}), action="challenge", context="login") 318 | logger.info("handleLogin - sending challenge") 319 | 320 | async def handleLoginResponse(self, messageData, senderTag): 321 | """ 322 | Handle the login response from the client. 323 | """ 324 | signature = messageData.get("signature") 325 | user_details = self.NONCES.get(senderTag) 326 | 327 | if not user_details: 328 | await self.sendEncapsulatedReply( 329 | senderTag, 330 | "error: no pending login for sender", 331 | action="challengeResponse", 332 | context="login" 333 | ) 334 | logger.warning("handleLoginResponse - no pending login for sender :(") 335 | return 336 | 337 | username, publicKey, nonce = user_details 338 | 339 | # Verify the signature 340 | if self.cryptoUtils.verify_signature(publicKey, nonce, signature): 341 | # Look up the user in the database 342 | userRecord = self.databaseManager.getUserByUsername(username) 343 | if userRecord: 344 | dbSenderTag = userRecord[2] # Stored senderTag 345 | 346 | # If the senderTag has changed, update it in the database 347 | if dbSenderTag != senderTag: 348 | self.databaseManager.updateUserField(username, "senderTag", senderTag) 349 | 350 | await self.sendEncapsulatedReply( 351 | senderTag, 352 | "success", 353 | action="challengeResponse", 354 | context="login" 355 | ) 356 | del self.NONCES[senderTag] # Clean up after successful login 357 | logger.info("handleLoginResponse - success!") 358 | else: 359 | await self.sendEncapsulatedReply( 360 | senderTag, 361 | "error: invalid signature", 362 | action="challengeResponse", 363 | context="login" 364 | ) 365 | del self.NONCES[senderTag] 366 | logger.warning("handleLoginResponse - invalid signature :(") 367 | 368 | async def sendEncapsulatedReply(self, recipientTag, content, action="challengeResponse", context=None): 369 | """ 370 | Send an encapsulated reply message. 371 | :param recipientTag: The recipient's sender tag. 372 | :param content: The content to send back. 373 | :param action: The action type of the reply (default is "challengeResponse"). 374 | :param context: Additional context for the reply (e.g., 'registration'). 375 | """ 376 | # Load the server's private key 377 | private_key = self.cryptoUtils.load_private_key(os.getenv("NYM_CLIENT_ID")) 378 | if private_key is None: 379 | logger.error("sendEncapsulatedReply - server priv key not found :(") 380 | return 381 | 382 | signature = self.cryptoUtils.sign_message(os.getenv("NYM_CLIENT_ID"), content) 383 | if signature is None: 384 | logger.error("sendEncapsulatedReply - failed to sign message :(") 385 | return 386 | 387 | replyMessage = { 388 | "type": "reply", 389 | "message": json.dumps({ 390 | "action": action, 391 | "content": content, 392 | "context": context, 393 | "signature": signature 394 | }), 395 | "senderTag": recipientTag 396 | } 397 | await self.websocketManager.send(replyMessage) 398 | -------------------------------------------------------------------------------- /server/src/websocketUtils.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | import os 4 | import websockets 5 | from logConfig import logger 6 | from envLoader import load_env 7 | 8 | load_env() 9 | 10 | class WebsocketUtils: 11 | def __init__(self, server_url=None): 12 | self.server_url = server_url or os.getenv("WEBSOCKET_URL") 13 | self.websocket = None 14 | self.message_callback = None # Callback for processing messages 15 | self.address = None # store the address 16 | 17 | async def connect(self): 18 | """Establish a WebSocket connection with the Nym client.""" 19 | try: 20 | self.websocket = await websockets.connect(self.server_url) 21 | await self.websocket.send(json.dumps({"type": "selfAddress"})) 22 | response = await self.websocket.recv() 23 | data = json.loads(response) 24 | 25 | # Store address and validate 26 | self.address = data.get("address") 27 | if not self.address: 28 | logger.error("Failed to retrieve valid Nym address") 29 | raise ValueError("Empty or invalid Nym address received") 30 | 31 | logger.info(f"Connected to WebSocket. Your Nym Address: {self.address}") 32 | 33 | # Save to file with proper error handling 34 | try: 35 | # project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) 36 | 37 | ### DIRTY HACKS 38 | ### SEE COMMENT BELOW 39 | 40 | shared_dir = "/app/shared" 41 | os.makedirs(shared_dir, exist_ok=True) 42 | file_path = os.path.join(shared_dir, "nym_address.txt") 43 | # @gyrusdentatus 44 | #file_path = os.path.join(project_root, "nym_address.txt") 45 | # 46 | # Save that fucker to shared mount for developer QoL improvement 47 | # might wanna change this back to the above later if it's 48 | # not really needed. Not that it's a security issue but 49 | # The lesser space to fuck up the better, AMIRITE??? ;d 50 | # file_path = os.path.join(project_root, "shared", "nym_address.txt") 51 | 52 | # Ensure directory exists 53 | os.makedirs(os.path.dirname(file_path), exist_ok=True) 54 | 55 | with open(file_path, "w") as f: 56 | f.write(self.address) 57 | 58 | logger.info(f"Nym address saved to {file_path}") 59 | except IOError as e: 60 | logger.error(f"Failed to write address to file: {e}") 61 | # Continue execution - failure to write file shouldn't crash the server 62 | 63 | # Start listening for incoming messages 64 | await self.receive_messages() 65 | except Exception as e: 66 | logger.error(f"Connection error: {e}") 67 | raise # Re-raise to signal failure up the stack 68 | 69 | async def receive_messages(self): 70 | """Listen for incoming messages and forward them to the callback.""" 71 | try: 72 | while True: 73 | raw_message = await self.websocket.recv() 74 | logger.info("Message received") 75 | message_data = json.loads(raw_message) 76 | 77 | # Call the callback for further processing 78 | if self.message_callback: 79 | await self.message_callback(message_data) 80 | else: 81 | logger.warning("No callback set for processing messages.") 82 | except websockets.exceptions.ConnectionClosed: 83 | logger.warning("Connection closed by the server.") 84 | except Exception as e: 85 | logger.error(f"Error while receiving messages: {e}") 86 | 87 | async def send(self, message): 88 | """Send a message through the WebSocket.""" 89 | try: 90 | if isinstance(message, dict): 91 | message = json.dumps(message) 92 | await self.websocket.send(message) 93 | logger.info("Message sent") 94 | except Exception as e: 95 | logger.error(f"Error sending message: {e}") 96 | 97 | async def close(self): 98 | """Close the websocket connection.""" 99 | if self.websocket: 100 | try: 101 | await self.websocket.close() 102 | logger.info("Websocket connection closed") 103 | except Exception as e: 104 | logger.error(f"Error closing connection: {e}") 105 | else: 106 | logger.warning("Websocket connection is not established") 107 | 108 | def set_message_callback(self, callback): 109 | """Set the callback function for processing received messages.""" 110 | self.message_callback = callback 111 | -------------------------------------------------------------------------------- /server/storage/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/code-zm/nymCHAT/f41b74f0b02d5c3ba4a779d9759a5260a7cf7021/server/storage/.gitkeep --------------------------------------------------------------------------------