Add files via upload

This commit is contained in:
DeBros 2025-04-02 13:37:54 +03:00 committed by GitHub
commit aac9a38ca1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 16252 additions and 0 deletions

595
LICENSE Normal file
View File

@ -0,0 +1,595 @@
GNU General Public License
==========================
_Version 3, 29 June 2007_
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: **(1)** assert
copyright on the software, and **(2)** offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a “modified version” of the earlier work or a
work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on
the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the
extent that it includes a convenient and prominently visible feature that **(1)**
displays an appropriate copyright notice, and **(2)** tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code
The “source code” for a work means the preferred form of the work for
making modifications to it. “Object code” means any non-source form of a
work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.
The “System Libraries” of an executable work include anything, other than
the work as a whole, that **(a)** is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and **(b)** serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A “Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.
### 4. Conveying Verbatim Copies
You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
### 5. Conveying Modified Source Versions
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to “keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an “aggregate” if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.
### 6. Conveying Non-Source Forms
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either **(1)** a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or **(2)** access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A “User Product” is either **(1)** a “consumer product”, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or **(2)** anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, “normally used” refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.
### 7. Additional Terms
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.
### 8. Termination
You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated **(a)** provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and **(b)** permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.
### 11. Patents
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To “grant” such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either **(1)** cause the Corresponding
Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. “Knowingly relying” means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.
A patent license is “discriminatory” if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license **(a)** in connection with
copies of the covered work conveyed by you (or copies made from those copies), or **(b)**
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License “or any later
version” applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16
If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.
_END OF TERMS AND CONDITIONS_
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the “copyright” line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands `show w` and `show c` should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a “copyright disclaimer” for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.

370
README.md Normal file
View File

@ -0,0 +1,370 @@
# DeBros CLI
Command-line interface for managing applications on the DeBros decentralized network. This CLI runs on your local development machine, allowing you to build, upload, and deploy applications to the DeBros network from your local environment.
## Overview
DeBros CLI allows you to:
- Build and upload applications to the DeBros network
- Deploy applications to your local node
- Configure domains with IPNS for your applications
- Manage .sol domains for easy access to your applications
- Set up K3s with Nginx for container orchestration
## Installation
### Quick Install Script
The easiest way to install the DeBros CLI on your local machine is using our install script:
```bash
curl -sL https://raw.githubusercontent.com/DeBrosOfficial/node/main/packages/@debros/cli/install-cli.sh | bash
```
This script will:
1. Check for Node.js, Docker, and IPFS dependencies
2. Install IPFS if needed (with your permission)
3. Install the DeBros CLI globally
4. Set up the necessary configuration directories
### Manual Installation
Alternatively, you can install manually:
```bash
# Global installation with npm
npm install -g @debros/cli
# Or with pnpm
pnpm install -g @debros/cli
# Or with yarn
yarn global add @debros/cli
```
## Prerequisites
- Node.js 18+
- Docker
- IPFS (for some commands)
- K3s (optional, for container orchestration)
## Getting Started
Initialize the CLI and environment:
```bash
debros init
```
This will guide you through setting up your environment, including K3s and Nginx if desired.
## Commands
### Upload an Application (and Update)
```bash
debros upload <folder> [options]
```
Options:
- `-t, --tag <tag>`: Docker image tag (default: "latest")
- `-n, --name <name>`: Application name (defaults to folder name)
- `-d, --domain <subdomain>`: Custom subdomain (only specify the part before .debros.sol)
Example:
```bash
# Using default subdomain (awesome-app.debros.sol)
debros upload ./my-app -n awesome-app -t v1.0.0
# Using custom subdomain (api-myproject.debros.sol)
debros upload ./my-app -n awesome-app -d api-myproject
# Update an existing application
# (uploading with the same name will update the existing deployment)
debros upload ./my-app -n awesome-app -t v1.1.0
```
The upload command is used both for initial deployment and for updates. When you upload a new version of an existing application, the network automatically updates the deployment.
### Deploy Locally
```bash
debros deploy <image-path> [options]
```
Options:
- `-n, --name <name>`: Application name (if not provided, derived from image name)
Note: All applications run on port 8787 internally and are automatically deployed with 2 replicas for redundancy in the 'debros-apps' namespace. External access is standardized through port 80 via Nginx using K3s.
Example:
```bash
debros deploy awesome-app.tar -n awesome-app
```
### List Deployments and Network
```bash
debros list [options]
```
Options:
- `-a, --apps`: List deployed applications
- `-n, --nodes`: List network nodes
- `-i, --images`: List local Docker images
- `-d, --detailed`: Show detailed information
### List Application Versions
```bash
debros versions <app-name>
```
Example:
```bash
debros versions awesome-app
```
This will show all available versions of the application along with their upload timestamps and deployment status.
### Rollback Application
```bash
debros rollback <app-name> [version-tag]
```
Options:
- `-f, --force`: Force rollback without confirmation
Example:
```bash
# Rollback to a specific version
debros rollback awesome-app v1.0.0
# Rollback to the previous version
debros rollback awesome-app
```
### Stop Application
```bash
debros stop <app-name>
```
Options:
- `-f, --force`: Force stop without confirmation
Example:
```bash
debros stop awesome-app
```
### Start Application
```bash
debros start <app-name>
```
Options:
- `-v, --version <version>`: Version tag to start (defaults to latest)
Example:
```bash
# Start with latest version
debros start awesome-app
# Start with specific version
debros start awesome-app -v v1.0.0
```
### Delete Application
```bash
debros delete <app-name>
```
Options:
- `-f, --force`: Force delete without confirmation
Example:
```bash
debros delete awesome-app
```
### Configure IPNS
```bash
debros configure-ipns <name> <cid>
```
Example:
```bash
debros configure-ipns awesome-app QmXYZ123...
```
### Domain Management
Check domain availability:
```bash
debros domain check <domain>
```
Register a domain:
```bash
debros domain register <domain>
```
Link a domain to IPNS:
```bash
debros domain link <domain> <ipns-address>
```
Set up a domain with application and IPNS in one step:
```bash
debros domain setup <domain> <cid>
```
## Docker Deployment vs K3s
The CLI supports two deployment strategies:
1. **Docker**: Simple container deployment on a single node
2. **K3s**: Kubernetes-based orchestration with Nginx for routing
K3s is recommended for production deployments as it provides better scaling, failover, and routing capabilities.
## Example Workflow
Here's a typical workflow for deploying an application to the DeBros network:
```bash
# 1. Initialize the CLI on your local machine
debros init
# 2. Upload your application to the network
# IMPORTANT: Your application should listen on port 8787 internally
debros upload ./my-app
# Or with a custom subdomain
debros upload ./my-app -d api-myservice
# This will:
# - Build a Docker image from your application folder
# - Save the image to a tar file
# - Upload the tar file to IPFS, getting a CID
# - Announce the deployment to the network
# - DeBros nodes will automatically pull and deploy your application with 2 replicas
# - Your application gets the subdomain: my-app.debros.sol (or api-myservice.debros.sol)
# - External traffic is managed via Nginx routing based on domain name
# 3. List your deployments and network nodes
debros list
# 4. Update your application (when you make changes)
debros upload ./my-app -t v1.1.0
# 5. View version history and manage versions
debros versions my-app
# 6. Rollback to a previous version if needed
debros rollback my-app v1.0.0
# 7. Stop, start, and delete applications
debros stop my-app
debros start my-app
debros delete my-app
debros domain setup my-app.debros.sol QmXYZ123...
# 5. Check if your application is deployed on the network
debros list -a
```
## Deployment Process Overview
When you use the DeBros CLI to deploy an application to the network:
1. Your application is dockerized and should listen on port 8787
2. The CLI builds, uploads and announces the app to the network
3. You specify a subdomain (e.g., "anchat-api") that will be used to access your app
4. The CLI automatically appends ".debros.sol" to your subdomain
5. DeBros nodes automatically pull and deploy your application with K3s and Nginx
6. Your app becomes accessible at the specified domain (e.g., anchat-api.debros.sol)
7. All routing between domains and apps is handled transparently by the network
## Standardized Application Configuration
For consistency and reliability across the DeBros network, all applications follow these standardized rules:
**Port Standardization**:
- All applications **MUST** listen on port 8787 internally
- External traffic is routed through port 80 via Nginx
- Domain-based routing (app-name.debros.sol) handles multiple applications on the same nodes
- Port configuration is handled automatically by the CLI and node infrastructure
**Replica Management**:
- All applications are automatically deployed with 2 replicas for redundancy
- Replicas are distributed across different nodes when possible
- If a node fails, traffic is automatically routed to healthy replicas
- Scaling is handled transparently by the network
**Environment Variables**:
- The following environment variables are automatically set:
- `PORT=8787`: Tells your application which port to listen on
- `DEBROS_APP_NAME`: Your application's name on the network
## Remote vs Local Operations
The DeBros CLI distinguishes between operations on your local machine and operations that interact with the DeBros network:
**Local Operations**:
- Building Docker images
- Uploading files to IPFS
- Managing local K3s deployments
**Network Operations**:
- Discovering network nodes
- Announcing deployments to the network
- Managing node lists and application distribution
- Setting up domains and IPNS
## IPFS and IPNS
The CLI integrates with IPFS and IPNS to provide decentralized content addressing and name resolution. This allows you to:
- Store application images and data on IPFS
- Use IPNS for stable naming despite content changes
- Link .sol domains to your IPNS addresses
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
[GNU GPL v3.0](LICENSE)

82
eslint.config.js Normal file
View File

@ -0,0 +1,82 @@
import globals from 'globals';
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import prettier from 'eslint-plugin-prettier';
export default [
// Base configuration for all files
{
files: ['**/*.{ts}'],
ignores: ['dist/**', 'docs/**', 'src/components/bot/templates/**'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: {
...globals.node,
NodeJS: 'readonly', // Add NodeJS as a global
Express: 'readonly', // Add Express as a global
},
},
plugins: {
prettier: prettier,
},
rules: {
...js.configs.recommended.rules,
...prettier.configs.recommended.rules,
camelcase: 'off',
'no-invalid-this': 'off',
'prettier/prettier': 'error',
'require-jsdoc': 'off',
'valid-jsdoc': 'off',
'new-cap': ['error', { capIsNew: false }],
'no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
// TypeScript-specific configuration
{
files: ['**/*.ts', '**/*.tsx'],
languageOptions: {
parser: tseslint.parser,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: './tsconfig.json',
},
},
plugins: {
'@typescript-eslint': tseslint.plugin,
},
rules: {
...tseslint.configs.recommended.rules,
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'default',
format: ['camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE'],
leadingUnderscore: 'allow',
trailingUnderscore: 'allow',
},
{
selector: 'property',
format: null,
},
],
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
];

148
install-cli.sh Normal file
View File

@ -0,0 +1,148 @@
#!/bin/bash
set -e # Exit on any error
trap 'echo -e "\033[0;31mAn error occurred. Installation aborted.\033[0m"; exit 1' ERR
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
BLUE='\033[38;2;2;128;175m'
YELLOW='\033[1;33m'
NOCOLOR='\033[0m'
log() {
echo -e "${CYAN}[$(date '+%Y-%m-%d %H:%M:%S')]${NOCOLOR} $1"
}
log "${BLUE}==================================================${NOCOLOR}"
log "${GREEN} DeBros CLI Installer ${NOCOLOR}"
log "${BLUE}==================================================${NOCOLOR}"
# Check Node.js installation
if ! command -v node &> /dev/null; then
log "${RED}Node.js is not installed. Please install Node.js 18 or later.${NOCOLOR}"
exit 1
fi
NODE_VERSION=$(node -v | cut -d 'v' -f 2 | cut -d '.' -f 1)
if [[ $NODE_VERSION -lt 18 ]]; then
log "${RED}Node.js version $NODE_VERSION is too old. Please install Node.js 18 or later.${NOCOLOR}"
exit 1
fi
log "${GREEN}Using Node.js $(node -v)${NOCOLOR}"
# Check if Docker is installed
if ! command -v docker &> /dev/null; then
log "${YELLOW}Warning: Docker is not installed. Some DeBros CLI features require Docker.${NOCOLOR}"
log "${YELLOW}Please install Docker to use all CLI features: https://docs.docker.com/get-docker/${NOCOLOR}"
else
log "${GREEN}Docker is installed: $(docker --version)${NOCOLOR}"
fi
# Check if IPFS is installed
if ! command -v ipfs &> /dev/null; then
log "${YELLOW}Warning: IPFS is not installed. Some DeBros CLI features require IPFS.${NOCOLOR}"
log "${YELLOW}Would you like to install IPFS now?${NOCOLOR}"
read -rp "Install IPFS? (yes/no) [Default: yes]: " INSTALL_IPFS
INSTALL_IPFS="${INSTALL_IPFS:-yes}"
if [[ "$INSTALL_IPFS" == "yes" ]]; then
log "${CYAN}Installing IPFS...${NOCOLOR}"
# Detect platform
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
PLATFORM="linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
PLATFORM="darwin"
else
log "${RED}Unsupported platform: $OSTYPE${NOCOLOR}"
exit 1
fi
# Detect architecture
ARCH=$(uname -m)
if [[ "$ARCH" == "x86_64" ]]; then
ARCH="amd64"
elif [[ "$ARCH" == "arm64" || "$ARCH" == "aarch64" ]]; then
ARCH="arm64"
else
log "${RED}Unsupported architecture: $ARCH${NOCOLOR}"
exit 1
fi
# Download and install IPFS
TMP_DIR=$(mktemp -d)
IPFS_VERSION="0.27.0"
IPFS_ARCHIVE="kubo_v${IPFS_VERSION}_${PLATFORM}-${ARCH}.tar.gz"
IPFS_URL="https://dist.ipfs.tech/kubo/v${IPFS_VERSION}/${IPFS_ARCHIVE}"
log "${CYAN}Downloading IPFS from $IPFS_URL${NOCOLOR}"
curl -L -o "$TMP_DIR/$IPFS_ARCHIVE" "$IPFS_URL"
log "${CYAN}Extracting IPFS...${NOCOLOR}"
tar -xzf "$TMP_DIR/$IPFS_ARCHIVE" -C "$TMP_DIR"
log "${CYAN}Installing IPFS to /usr/local/bin${NOCOLOR}"
sudo mv "$TMP_DIR/kubo/ipfs" /usr/local/bin/
# Clean up
rm -rf "$TMP_DIR"
# Initialize IPFS
log "${CYAN}Initializing IPFS...${NOCOLOR}"
ipfs init
log "${GREEN}IPFS installed successfully!${NOCOLOR}"
fi
else
log "${GREEN}IPFS is installed: $(ipfs --version)${NOCOLOR}"
fi
# Install DeBros CLI
log "${CYAN}Installing DeBros CLI...${NOCOLOR}"
# Check for package manager preference
if command -v pnpm &> /dev/null; then
PM="pnpm"
elif command -v yarn &> /dev/null; then
PM="yarn"
else
PM="npm"
fi
log "${CYAN}Using package manager: $PM${NOCOLOR}"
# Install the CLI
if [[ "$PM" == "pnpm" ]]; then
pnpm install -g @debros/cli
elif [[ "$PM" == "yarn" ]]; then
yarn global add @debros/cli
else
npm install -g @debros/cli
fi
# Verify installation
if command -v debros &> /dev/null; then
CLI_VERSION=$(debros --version)
log "${GREEN}DeBros CLI installed successfully: $CLI_VERSION${NOCOLOR}"
# Create config directory
mkdir -p "$HOME/.debros"
log "${BLUE}==================================================${NOCOLOR}"
log "${GREEN} DeBros CLI Installation Complete ${NOCOLOR}"
log "${BLUE}==================================================${NOCOLOR}"
log "${GREEN}To start using the CLI, run:${NOCOLOR}"
log "${CYAN}debros init${NOCOLOR}"
log "${BLUE}==================================================${NOCOLOR}"
log "${GREEN}Common commands:${NOCOLOR}"
log "${CYAN} debros upload <folder>${NOCOLOR} - Upload an app to the network"
log "${CYAN} debros list${NOCOLOR} - List network nodes and deployments"
log "${CYAN} debros domain check <name>${NOCOLOR} - Check domain availability"
log "${BLUE}==================================================${NOCOLOR}"
else
log "${RED}Failed to install DeBros CLI. Please try installing manually:${NOCOLOR}"
log "${CYAN}npm install -g @debros/cli${NOCOLOR}"
exit 1
fi

54
package.json Normal file
View File

@ -0,0 +1,54 @@
{
"name": "@debros/cli",
"version": "0.0.10-alpha",
"description": "DeBros CLI tool for managing deployments to the DeBros network",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"debros": "./dist/cli.js"
},
"files": [
"dist",
"types.d.ts"
],
"scripts": {
"build": "tsc",
"dev": "tsc -w",
"clean": "rimraf dist",
"prepublishOnly": "npm run clean && npm run build",
"lint": "npx eslint src"
},
"keywords": [
"debros",
"cli",
"ipfs",
"libp2p",
"decentralized",
"p2p"
],
"author": "Debros",
"license": "gnu-gpl-v3.0",
"dependencies": {
"@debros/network": "^0.0.14-alpha",
"@ipshipyard/node-datachannel": "0.26.5",
"@solana/web3.js": "^1.87.6",
"chalk": "^5.3.0",
"commander": "^11.1.0",
"dockerode": "^4.0.0",
"dotenv": "^16.4.1",
"helia": "^5.3.0",
"inquirer": "^9.2.12",
"ipfs-core": "^0.18.1",
"libp2p": "^2.8.2",
"ora": "^7.0.1"
},
"devDependencies": {
"@types/dockerode": "^3.3.37",
"@types/inquirer": "^9.0.7",
"@types/node": "^22.13.10",
"eslint": "^8.56.0",
"rimraf": "^5.0.5",
"typescript": "^5.8.2"
}
}

12338
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

12
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,12 @@
packages:
- packages/**
onlyBuiltDependencies:
- '@ipshipyard/node-datachannel'
- bigint-buffer
- bufferutil
- classic-level
- cpu-features
- iso-constants
- protobufjs
- ssh2
- utf-8-validate

37
src/cli.ts Normal file
View File

@ -0,0 +1,37 @@
#!/usr/bin/env node
import { program } from "commander";
import { uploadCommand } from "./commands/upload.js";
import { deployCommand } from "./commands/deploy.js";
import { listCommand } from "./commands/list.js";
import { initCommand } from "./commands/init.js";
import { configureIPNSCommand } from "./commands/configure-ipns.js";
import { domainCommand } from "./commands/domain.js";
import { versionsCommand } from "./commands/versions.js";
import { rollbackCommand } from "./commands/rollback.js";
import { stopCommand } from "./commands/stop.js";
import { startCommand } from "./commands/start.js";
import { deleteCommand } from "./commands/delete.js";
// Main CLI setup
program
.name("debros")
.description(
"DeBros CLI - Deploy and manage applications on the DeBros network"
)
.version("0.0.10-alpha");
// Register commands
uploadCommand(program);
deployCommand(program);
listCommand(program);
initCommand(program);
configureIPNSCommand(program);
domainCommand(program);
versionsCommand(program);
rollbackCommand(program);
stopCommand(program);
startCommand(program);
deleteCommand(program);
// Execute the CLI with the provided arguments
program.parse(process.argv);

View File

@ -0,0 +1,39 @@
import { Command } from 'commander';
import { ensureIPNSKey, publishToIPNS } from '../services/ipfs.js';
import { logger } from '../utils/logger.js';
export function configureIPNSCommand(program: Command) {
program
.command('configure-ipns')
.description('Configure IPNS for an application')
.argument('<name>', 'Application or service name')
.argument('<cid>', 'IPFS CID to publish')
.action(async (name, cid) => {
try {
logger.info(`Configuring IPNS for ${name} with CID ${cid}`);
// Ensure IPNS key exists
const keyId = await ensureIPNSKey(name);
// Publish to IPNS
const ipnsAddress = await publishToIPNS(cid, name);
logger.success(`
IPNS configuration successful!
Application: ${name}
IPFS CID: ${cid}
IPNS key: ${keyId}
IPNS address: ${ipnsAddress}
This IPNS address can now be used to access your application.
You can link a .sol domain to this IPNS address using:
debros domain link ${name}.debros.sol ${ipnsAddress}
`);
} catch (error) {
logger.error(`Failed to configure IPNS: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

38
src/commands/delete.ts Normal file
View File

@ -0,0 +1,38 @@
import { Command } from 'commander';
import { deleteApplication } from '../services/network.js';
import { logger } from '../utils/logger.js';
export function deleteCommand(program: Command) {
program
.command('delete')
.description('Delete an application from the network')
.argument('<app-name>', 'Application name')
.option('-f, --force', 'Force delete without confirmation')
.action(async (appName, options) => {
try {
if (!options.force) {
// If not forcing, we'd typically prompt for confirmation here
logger.warn(`
WARNING: This will completely remove ${appName} from the network!
All versions will be deleted and cannot be recovered.`);
logger.info(`Deleting application ${appName}...`);
} else {
logger.info(`Force deleting application ${appName}...`);
}
// Delete the application
const result = await deleteApplication(appName, options.force);
if (result.success) {
logger.success(`
Application ${appName} has been completely removed from the network.
`);
} else {
logger.error(`Failed to delete application: ${result.message}`);
}
} catch (error) {
logger.error(`Failed to delete application: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

61
src/commands/deploy.ts Normal file
View File

@ -0,0 +1,61 @@
import { Command } from 'commander';
import { loadDockerImage, runContainer } from '../services/docker.js';
import { installK3s, installNginxIngress, deployToK3s } from '../services/k3s.js';
import { logger } from '../utils/logger.js';
import { config } from '../utils/config.js';
export function deployCommand(program: Command) {
program
.command('deploy')
.description('Deploy a Docker image to a local K3s node')
.argument('<image-path>', 'Path to the Docker image tar file')
.option('-n, --name <name>', 'Application name')
// Port is fixed at 8787 for standardization
// Replicas fixed at 2 for redundancy
// Strategy and namespace handled automatically
.action(async (imagePath, options) => {
try {
// Load the Docker image
const { loadedImage } = await loadDockerImage(imagePath);
if (!loadedImage) {
logger.error('Failed to load Docker image');
process.exit(1);
}
const appName = options.name || loadedImage.split('/').pop()?.split(':')[0] || 'app';
// Fixed standardized port and replica count
const port = 8787;
const replicas = 2; // Always deploy with redundancy
const namespace = 'debros-apps'; // Standard namespace for all applications
// Always use K3s for standardized deployments
// Install K3s if not already installed
await installK3s();
// Install Nginx Ingress Controller
await installNginxIngress();
// Deploy the application to K3s
const result = await deployToK3s(
appName,
loadedImage,
namespace,
port,
replicas
);
logger.success(`
Application ${appName} deployed successfully!
Access URL: http://${appName}.${config.defaultDomain}
Your application is now running on the DeBros network.
Internal port: 8787
External domain: ${appName}.${config.defaultDomain}
`);
} catch (error) {
logger.error(`Failed to deploy application: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

175
src/commands/domain.ts Normal file
View File

@ -0,0 +1,175 @@
import { Command } from 'commander';
import { checkDomainAvailability, guideDomainRegistration, configureDomainIPNS } from '../services/solana.js';
import { ensureIPNSKey } from '../services/ipfs.js';
import { logger } from '../utils/logger.js';
export function domainCommand(program: Command) {
const domain = program
.command('domain')
.description('Manage .sol domains for your applications');
domain
.command('check')
.description('Check if a .sol domain is available')
.argument('<domain>', 'Domain name to check (e.g., myapp.debros.sol)')
.action(async (domainName) => {
try {
// Ensure domain has .sol suffix
if (!domainName.endsWith('.sol')) {
domainName = `${domainName}.sol`;
}
logger.info(`Checking availability of ${domainName}...`);
const isAvailable = await checkDomainAvailability(domainName);
if (isAvailable) {
logger.success(`
Domain ${domainName} is available for registration!
${guideDomainRegistration(domainName)}
`);
} else {
logger.warn(`
Domain ${domainName} is already registered.
Try another domain name or contact the current owner.
`);
}
} catch (error) {
logger.error(`Failed to check domain: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
domain
.command('register')
.description('Guide you through registering a .sol domain')
.argument('<domain>', 'Domain name to register (e.g., myapp.debros.sol)')
.action(async (domainName) => {
try {
// Ensure domain has .sol suffix
if (!domainName.endsWith('.sol')) {
domainName = `${domainName}.sol`;
}
logger.info(`Preparing to register ${domainName}...`);
// Check availability first
const isAvailable = await checkDomainAvailability(domainName);
if (isAvailable) {
const guide = guideDomainRegistration(domainName);
logger.success(`
${guide}
After registration, link the domain to your IPNS address using:
debros domain link ${domainName} <ipns-address>
`);
} else {
logger.warn(`
Domain ${domainName} is already registered.
Try another domain name or contact the current owner.
`);
}
} catch (error) {
logger.error(`Failed to register domain: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
domain
.command('link')
.description('Link a .sol domain to an IPNS address')
.argument('<domain>', 'Domain name (e.g., myapp.debros.sol)')
.argument('<ipns-address>', 'IPNS address to link to (or application name)')
.action(async (domainName, ipnsAddr) => {
try {
// Ensure domain has .sol suffix
if (!domainName.endsWith('.sol')) {
domainName = `${domainName}.sol`;
}
// Check if ipnsAddr is an IPNS address or an application name
if (!ipnsAddr.startsWith('/ipns/')) {
logger.info(`${ipnsAddr} appears to be an application name, looking up IPNS key...`);
// Treat as an application name and get the IPNS key
const keyName = ipnsAddr;
const keyId = await ensureIPNSKey(keyName);
// If we found a key, create an IPNS address
ipnsAddr = `/ipns/${keyId}`;
logger.info(`Using IPNS address: ${ipnsAddr}`);
}
logger.info(`Linking domain ${domainName} to ${ipnsAddr}...`);
// Create a DNS TXT record for the domain
const dnsLink = `dnslink=${ipnsAddr}`;
logger.success(`
To link ${domainName} to ${ipnsAddr}, set the following DNS records:
1. TXT record:
Name: _dnslink.${domainName}
Value: ${dnsLink}
2. (Optional) A record:
Name: ${domainName}
Value: <Your public IPFS gateway IP>
For the Solana Name Service, update your domain's resolver to point to:
${ipnsAddr}
Once DNS propagates (up to 24 hours), your application will be accessible at:
http://${domainName}/
`);
} catch (error) {
logger.error(`Failed to link domain: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
domain
.command('setup')
.description('Set up a domain with application and IPNS in one step')
.argument('<domain>', 'Domain name (e.g., myapp.debros.sol)')
.argument('<cid>', 'IPFS CID of the application content')
.action(async (domainName, cid) => {
try {
// Ensure domain has .sol suffix
if (!domainName.endsWith('.sol')) {
domainName = `${domainName}.sol`;
}
logger.info(`Setting up ${domainName} for CID ${cid}...`);
// Extract application name from domain
const appName = domainName.split('.')[0];
// Configure domain with IPNS
const result = await configureDomainIPNS(domainName, appName, cid);
logger.success(`
Domain ${domainName} set up successfully!
IPFS CID: ${cid}
IPNS address: ${result.ipnsPath}
To complete the setup, set the following DNS record:
TXT record:
Name: _dnslink.${domainName}
Value: ${result.dnsLinkValue}
Once DNS propagates (up to 24 hours), your application will be accessible at:
http://${domainName}/
`);
} catch (error) {
logger.error(`Failed to set up domain: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
return domain;
}

146
src/commands/init.ts Normal file
View File

@ -0,0 +1,146 @@
import { Command } from 'commander';
import inquirer from 'inquirer';
import fs from 'fs';
import path from 'path';
import { installK3s, installNginxIngress, isK3sInstalled } from '../services/k3s.js';
import { config, updateConfig } from '../utils/config.js';
import { logger, startSpinner, stopSpinner } from '../utils/logger.js';
export function initCommand(program: Command) {
program
.command('init')
.description('Initialize DeBros CLI and set up the environment')
.option('--non-interactive', 'Run in non-interactive mode with default values')
.action(async (options) => {
try {
logger.info('Initializing DeBros CLI...');
let answers = {
defaultDomain: config.defaultDomain,
dockerRegistry: config.dockerRegistry,
defaultDeploymentStrategy: config.defaultDeploymentStrategy,
solanaEndpoint: config.solanaEndpoint,
installK3s: true
};
// If interactive mode, ask questions
if (!options.nonInteractive) {
answers = await inquirer.prompt([
{
type: 'input',
name: 'defaultDomain',
message: 'Default domain suffix for applications:',
default: config.defaultDomain
},
{
type: 'input',
name: 'dockerRegistry',
message: 'Docker registry prefix for images:',
default: config.dockerRegistry
},
{
type: 'list',
name: 'defaultDeploymentStrategy',
message: 'Default deployment strategy:',
choices: ['k3s', 'docker'],
default: config.defaultDeploymentStrategy
},
{
type: 'input',
name: 'solanaEndpoint',
message: 'Solana RPC endpoint:',
default: config.solanaEndpoint
},
{
type: 'confirm',
name: 'installK3s',
message: 'Install K3s now?',
default: true,
when: () => !isK3sInstalled()
}
]);
}
// Update configuration
updateConfig('defaultDomain', answers.defaultDomain);
updateConfig('dockerRegistry', answers.dockerRegistry);
updateConfig('defaultDeploymentStrategy', answers.defaultDeploymentStrategy);
updateConfig('solanaEndpoint', answers.solanaEndpoint);
logger.success('Configuration updated successfully');
// Install K3s if requested
if (answers.installK3s && !isK3sInstalled()) {
await installK3s();
await installNginxIngress();
}
// Create example Dockerfile if it doesn't exist
const exampleDir = path.join(process.cwd(), 'example-app');
if (!fs.existsSync(exampleDir)) {
const spinner = startSpinner('Creating example application...');
try {
fs.mkdirSync(exampleDir, { recursive: true });
// Create example Dockerfile
const dockerfilePath = path.join(exampleDir, 'Dockerfile');
const dockerfileContent = `FROM node:18-alpine
WORKDIR /app
COPY . .
RUN echo '#!/bin/sh\\necho "DeBros Example App running on port 3000"\\nwhile true; do echo \\'{"status":"ok", "timestamp":"\\'$(date -u +"%Y-%m-%dT%H:%M:%SZ")\\'"}\\' | nc -l -p 3000; done' > server.sh
RUN chmod +x server.sh
EXPOSE 3000
CMD ["./server.sh"]
`;
fs.writeFileSync(dockerfilePath, dockerfileContent);
// Create README
const readmePath = path.join(exampleDir, 'README.md');
const readmeContent = `# DeBros Example App
This is a simple example application to demonstrate the DeBros deployment process.
## Deployment
To deploy this application to the DeBros network, run:
\`\`\`bash
debros upload example-app
\`\`\`
## Local Testing
You can test the application locally with:
\`\`\`bash
docker build -t debros/example-app example-app
docker run -p 3000:3000 debros/example-app
\`\`\`
Then access http://localhost:3000 in your browser.
`;
fs.writeFileSync(readmePath, readmeContent);
stopSpinner('Example application created in ./example-app', true);
} catch (error) {
stopSpinner(`Failed to create example application: ${error instanceof Error ? error.message : String(error)}`, false);
}
}
logger.success(`
DeBros CLI initialized successfully!
Quick Start:
1. Upload an application: debros upload <folder>
2. List your deployments: debros list
3. Configure a domain: debros domain <name>
For more information, use: debros --help
`);
} catch (error) {
logger.error(`Failed to initialize DeBros CLI: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

105
src/commands/list.ts Normal file
View File

@ -0,0 +1,105 @@
import { Command } from 'commander';
import { listDebrosImages } from '../services/docker.js';
import { listK3sDeployments } from '../services/k3s.js';
import { getPeersAsNodeInfo } from '../services/network.js';
import { logger } from '../utils/logger.js';
export function listCommand(program: Command) {
program
.command('list')
.description('List DeBros deployments and network information')
.option('-a, --apps', 'List deployed applications')
.option('-n, --nodes', 'List network nodes')
.option('-i, --images', 'List local Docker images')
.option('-d, --detailed', 'Show detailed information')
.action(async (options) => {
try {
// Default to listing all if no specific option is provided
const listAll = !options.apps && !options.nodes && !options.images;
// List applications
if (listAll || options.apps) {
logger.info('=== DeBros Applications ===');
try {
const deployments = await listK3sDeployments();
if (deployments && deployments.length > 0) {
deployments.forEach((dep: any) => {
const name = dep.metadata.name;
const status = dep.status.availableReplicas > 0 ? 'Running' : 'Pending';
const replicas = `${dep.status.availableReplicas || 0}/${dep.spec.replicas}`;
logger.raw(`${name} (${status}) - Replicas: ${replicas}`);
if (options.detailed) {
const containers = dep.spec.template.spec.containers;
containers.forEach((container: any) => {
logger.raw(` - Image: ${container.image}`);
logger.raw(` - Ports: ${container.ports?.map((p: any) => p.containerPort).join(', ') || 'none'}`);
});
}
});
} else {
logger.warn('No applications deployed on K3s');
}
} catch (error) {
logger.warn('Failed to list K3s deployments, they may not be installed');
}
logger.raw('');
}
// List nodes
if (listAll || options.nodes) {
logger.info('=== DeBros Network Nodes ===');
try {
const nodes = await getPeersAsNodeInfo();
if (nodes.length > 0) {
nodes.forEach(node => {
logger.raw(`${node.id.slice(0, 12)}... (${node.type}) - ${node.address}:${node.port} - Load: ${node.load}`);
});
} else {
logger.warn('No network nodes found');
}
} catch (error) {
logger.error(`Failed to list network nodes: ${error instanceof Error ? error.message : String(error)}`);
}
logger.raw('');
}
// List images
if (listAll || options.images) {
logger.info('=== DeBros Docker Images ===');
try {
const images = await listDebrosImages();
if (images.length > 0) {
images.forEach(image => {
const tags = image.RepoTags ? image.RepoTags.join(', ') : 'none';
const size = Math.round(image.Size / (1024 * 1024) * 10) / 10; // Convert to MB with 1 decimal
logger.raw(`${tags} - ${size} MB`);
if (options.detailed) {
logger.raw(` - ID: ${image.Id}`);
logger.raw(` - Created: ${new Date(image.Created * 1000).toISOString()}`);
}
});
} else {
logger.warn('No DeBros Docker images found');
}
} catch (error) {
logger.error(`Failed to list Docker images: ${error instanceof Error ? error.message : String(error)}`);
}
}
} catch (error) {
logger.error(`Failed to list DeBros deployments: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

43
src/commands/rollback.ts Normal file
View File

@ -0,0 +1,43 @@
import { Command } from 'commander';
import { rollbackToVersion } from '../services/network.js';
import { logger } from '../utils/logger.js';
import { config } from '../utils/config.js';
export function rollbackCommand(program: Command) {
program
.command('rollback')
.description('Rollback an application to a specific version')
.argument('<app-name>', 'Application name')
.argument('[version-tag]', 'Version tag to rollback to (defaults to previous version)')
.option('-f, --force', 'Force rollback without confirmation')
.action(async (appName, versionTag, options) => {
try {
if (!versionTag) {
logger.info('No version specified, rolling back to previous deployed version');
} else {
logger.info(`Rolling back ${appName} to version ${versionTag}`);
}
// Get domain
const domain = `${appName}.${config.defaultDomain}`;
// Perform the rollback
const result = await rollbackToVersion(appName, versionTag, domain, options.force);
if (result.success) {
logger.success(`
Application ${appName} successfully rolled back to version ${result.version}!
CID: ${result.cid}
The rolled back version is now being redeployed to the network.
It will be accessible at: http://${domain}
`);
} else {
logger.error(`Rollback failed: ${result.message}`);
}
} catch (error) {
logger.error(`Failed to rollback: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

36
src/commands/start.ts Normal file
View File

@ -0,0 +1,36 @@
import { Command } from 'commander';
import { startApplication } from '../services/network.js';
import { logger } from '../utils/logger.js';
import { config } from '../utils/config.js';
export function startCommand(program: Command) {
program
.command('start')
.description('Start a stopped application')
.argument('<app-name>', 'Application name')
.option('-v, --version <version>', 'Version tag to start (defaults to latest)')
.action(async (appName, options) => {
try {
const versionTag = options.version || 'latest';
logger.info(`Starting application ${appName} with version ${versionTag}...`);
// Get domain
const domain = `${appName}.${config.defaultDomain}`;
// Start the application
const result = await startApplication(appName, versionTag);
if (result.success) {
logger.success(`
Application ${appName} has been started with version ${versionTag}.
It will be accessible at: http://${domain}
`);
} else {
logger.error(`Failed to start application: ${result.message}`);
}
} catch (error) {
logger.error(`Failed to start application: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

37
src/commands/stop.ts Normal file
View File

@ -0,0 +1,37 @@
import { Command } from 'commander';
import { stopApplication } from '../services/network.js';
import { logger } from '../utils/logger.js';
export function stopCommand(program: Command) {
program
.command('stop')
.description('Stop a running application')
.argument('<app-name>', 'Application name')
.option('-f, --force', 'Force stop without confirmation')
.action(async (appName, options) => {
try {
if (!options.force) {
// If not forcing, we'd typically prompt for confirmation here
logger.info(`Stopping application ${appName}...`);
} else {
logger.info(`Force stopping application ${appName}...`);
}
// Stop the application
const result = await stopApplication(appName, options.force);
if (result.success) {
logger.success(`
Application ${appName} has been stopped.
To restart it, use:
debros start ${appName}
`);
} else {
logger.error(`Failed to stop application: ${result.message}`);
}
} catch (error) {
logger.error(`Failed to stop application: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

76
src/commands/upload.ts Normal file
View File

@ -0,0 +1,76 @@
import path from 'path';
import fs from 'fs';
import { Command } from 'commander';
import { buildDockerImage, saveDockerImage } from '../services/docker.js';
import { uploadToIPFS, publishNodeList } from '../services/ipfs.js';
import { announceDeployment } from '../services/network.js';
import { logger } from '../utils/logger.js';
import { config } from '../utils/config.js';
export function uploadCommand(program: Command) {
program
.command('upload')
.description('Build, upload and announce a project to the DeBros network')
.argument('<folder>', 'Project folder to upload')
.option('-t, --tag <tag>', 'Docker image tag', 'latest')
.option('-n, --name <name>', 'Application name (defaults to folder name)')
.option('-d, --domain <subdomain>', 'Custom subdomain - will be appended with .debros.sol')
.action(async (folder, options) => {
try {
// Resolve folder path
const folderPath = path.resolve(process.cwd(), folder);
// Make sure the folder exists
if (!fs.existsSync(folderPath)) {
logger.error(`Folder not found: ${folderPath}`);
process.exit(1);
}
// Get the application name from options or folder name
const appName = options.name || path.basename(folderPath);
const tag = options.tag || 'latest';
// Get the subdomain from options or use the app name
const subdomain = options.domain || appName;
// Ensure we only use the subdomain part and force .debros.sol domain
const cleanSubdomain = subdomain.replace(/\.debros\.sol$/i, ''); // Remove .debros.sol if user included it
const domain = `${cleanSubdomain}.${config.defaultDomain}`;
// Step 1: Build Docker image
const { imageName } = await buildDockerImage(folderPath, appName, tag);
// Step 2: Save Docker image to tar file
const tarPath = path.join(process.cwd(), `${appName}.tar`);
await saveDockerImage(imageName, tarPath);
// Step 3: Upload tar file to IPFS
const cid = await uploadToIPFS(tarPath);
// Step 4: Create initial node list (empty for now, nodes will pick it up)
await publishNodeList([], appName);
// Step 5: Announce deployment to the network
await announceDeployment(cid, appName, tag, domain);
// Clean up temporary tar file
fs.unlinkSync(tarPath);
logger.success(`
Application ${appName}:${tag} uploaded successfully!
IPFS CID: ${cid}
The application will now be deployed to available nodes in the DeBros network.
It will be accessible at: http://${domain}
IMPORTANT: Your application should listen on port 8787 internally.
Environment variables PORT=8787 and DEBROS_APP_NAME=${appName} will be set automatically.
Use 'debros list' to check the status of your deployment.
`);
} catch (error) {
logger.error(`Failed to upload project: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

35
src/commands/versions.ts Normal file
View File

@ -0,0 +1,35 @@
import { Command } from 'commander';
import { getAppVersions } from '../services/network.js';
import { logger } from '../utils/logger.js';
export function versionsCommand(program: Command) {
program
.command('versions')
.description('List all available versions of an application')
.argument('<app-name>', 'Application name')
.action(async (appName) => {
try {
const versions = await getAppVersions(appName);
if (versions.length === 0) {
logger.warn(`No versions found for application ${appName}`);
return;
}
logger.info(`Versions for ${appName}:`);
versions.forEach((version, index) => {
const isLatest = version.tag === 'latest' ? ' (latest)' : '';
const isCurrent = version.deployed ? ' (deployed)' : '';
logger.raw(`${index + 1}. ${version.tag}${isLatest}${isCurrent} - Uploaded: ${version.timestamp}, CID: ${version.cid}`);
});
logger.success(`
To rollback to a specific version, use:
debros rollback ${appName} <version-tag>
`);
} catch (error) {
logger.error(`Failed to get versions: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
});
}

18
src/index.ts Normal file
View File

@ -0,0 +1,18 @@
// Core services
export * from './services/ipfs.js';
export * from './services/docker.js';
export * from './services/network.js';
export * from './services/solana.js';
export * from './services/k3s.js';
// Utilities
export * from './utils/logger.js';
export * from './utils/config.js';
// Commands
export * from './commands/upload.js';
export * from './commands/deploy.js';
export * from './commands/list.js';
export * from './commands/init.js';
export * from './commands/configure-ipns.js';
export * from './commands/domain.js';

207
src/services/docker.ts Normal file
View File

@ -0,0 +1,207 @@
import { execSync } from "child_process";
import fs from "fs";
import path from "path";
import Dockerode from "dockerode";
import { logger, startSpinner, stopSpinner } from "../utils/logger.js";
import { config } from "../utils/config.js";
// Docker client instance
const docker = new Dockerode();
/**
* Build a Docker image from a folder
*/
export async function buildDockerImage(
folderPath: string,
imageName: string,
tag: string = "latest",
additionalArgs: string[] = []
) {
const fullImageName = `${config.dockerRegistry}/${imageName}:${tag}`;
const spinner = startSpinner(`Building Docker image: ${fullImageName}`);
try {
// Verify directory exists
if (!fs.existsSync(folderPath)) {
throw new Error(`Folder does not exist: ${folderPath}`);
}
// Check for Dockerfile
const dockerfilePath = path.join(folderPath, "Dockerfile");
if (!fs.existsSync(dockerfilePath)) {
throw new Error("Dockerfile not found in the specified folder");
}
// Prepare build command
let buildCommand = `docker build -t ${fullImageName} ${additionalArgs.join(
" "
)} ${folderPath}`;
logger.debug(`Executing build command: ${buildCommand}`);
// Execute the build
const output = execSync(buildCommand, { stdio: "pipe" }).toString();
stopSpinner(`Docker image built: ${fullImageName}`, true);
return {
imageName: fullImageName,
output,
};
} catch (error) {
stopSpinner(
`Failed to build Docker image: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Save a Docker image to a tar file
*/
export async function saveDockerImage(imageName: string, outputPath: string) {
const spinner = startSpinner(
`Saving Docker image ${imageName} to ${outputPath}`
);
try {
const command = `docker save -o ${outputPath} ${imageName}`;
execSync(command);
stopSpinner(`Docker image saved to ${outputPath}`, true);
return outputPath;
} catch (error) {
stopSpinner(
`Failed to save Docker image: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Load a Docker image from a tar file
*/
export async function loadDockerImage(tarPath: string) {
const spinner = startSpinner(`Loading Docker image from ${tarPath}`);
try {
const command = `docker load -i ${tarPath}`;
const output = execSync(command).toString();
// Extract the image name from the output
const loadedImage = output.match(/Loaded image: (.+)/)?.[1];
stopSpinner(`Docker image loaded: ${loadedImage || "unknown"}`, true);
return {
imagePath: tarPath,
loadedImage,
};
} catch (error) {
stopSpinner(
`Failed to load Docker image: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* List all Docker images with the debros registry
*/
export async function listDebrosImages() {
const spinner = startSpinner("Listing DeBros Docker images");
try {
const images = await docker.listImages();
const debrosImages = images.filter((image) => {
return (
image.RepoTags &&
image.RepoTags.some((tag) =>
tag.startsWith(`${config.dockerRegistry}/`)
)
);
});
stopSpinner(`Found ${debrosImages.length} DeBros images`, true);
return debrosImages;
} catch (error) {
stopSpinner(
`Failed to list Docker images: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Run a Docker container
*/
export async function runContainer(
imageName: string,
containerName: string,
ports: { [key: string]: string } = {},
envVars: { [key: string]: string } = {},
volumes: { [key: string]: string } = {}
) {
const spinner = startSpinner(
`Starting container ${containerName} from image ${imageName}`
);
try {
// Prepare port bindings
const portBindings: any = {};
const exposedPorts: any = {};
Object.entries(ports).forEach(([containerPort, hostPort]) => {
const portKey = `${containerPort}/tcp`;
exposedPorts[portKey] = {};
portBindings[portKey] = [{ HostPort: hostPort }];
});
// Prepare environment variables
const env = Object.entries(envVars).map(
([key, value]) => `${key}=${value}`
);
// Prepare volumes
const volumeBinds = Object.entries(volumes).map(
([hostPath, containerPath]) => `${hostPath}:${containerPath}`
);
// Create container
const container = await docker.createContainer({
Image: imageName,
name: containerName,
ExposedPorts: exposedPorts,
HostConfig: {
PortBindings: portBindings,
Binds: volumeBinds,
RestartPolicy: {
Name: "unless-stopped",
},
},
Env: env,
});
// Start the container
await container.start();
stopSpinner(`Container ${containerName} started successfully`, true);
return container;
} catch (error) {
stopSpinner(
`Failed to start container: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}

237
src/services/ipfs.ts Normal file
View File

@ -0,0 +1,237 @@
import fs from "fs";
import path from "path";
import { execSync } from "child_process";
import { logger, startSpinner, stopSpinner } from "../utils/logger.js";
import { config } from "../utils/config.js";
import { initIpfs, getHelia, getLibp2p, stopIpfs } from "@debros/network";
// Interface to represent a Node in the network
export interface NodeInfo {
id: string;
address: string;
port: number;
load: number;
type: "k3s" | "docker";
}
// Interface for node list JSON
export interface NodeList {
nodes: NodeInfo[];
updatedAt: string;
}
/**
* Initialize IPFS instance using the @debros/network configuration
*/
export async function initializeIpfs() {
const spinner = startSpinner("Initializing IPFS with DeBros Network...");
try {
// Use the initIpfs function from @debros/network
await initIpfs();
const ipfs = getHelia();
const libp2p = getLibp2p();
if (!ipfs || !libp2p) {
throw new Error("Failed to initialize IPFS or libp2p");
}
// Get the peer ID
const peerId = libp2p.peerId.toString();
stopSpinner(`IPFS initialized with ID: ${peerId}`, true);
return { ipfs, libp2p };
} catch (error) {
stopSpinner(
`Failed to initialize IPFS: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Upload a file to IPFS
*/
export async function uploadToIPFS(filePath: string) {
const spinner = startSpinner(`Uploading ${filePath} to IPFS...`);
try {
// Initialize IPFS
const { ipfs } = await initializeIpfs();
// Read the file
const fileContent = fs.readFileSync(filePath);
// Create a block for the file content
const encoder = new TextEncoder();
const bytes = encoder.encode(fileContent.toString());
// Add the content to IPFS
const { cid } = await ipfs.blockstore.put(bytes);
// Stop IPFS to clean up
await stopIpfs();
stopSpinner(`File uploaded with CID: ${cid.toString()}`, true);
return cid.toString();
} catch (error) {
stopSpinner(
`Failed to upload file: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Generate IPNS key if it doesn't exist
*/
export async function ensureIPNSKey(name: string) {
const spinner = startSpinner(`Ensuring IPNS key exists for ${name}...`);
try {
// We'll use the ipfs CLI for this since the JS library doesn't expose key management well
const keyListOutput = execSync("ipfs key list -l").toString();
const keyExists = keyListOutput.includes(name);
if (!keyExists) {
logger.info(`Creating new IPNS key: ${name}`);
execSync(`ipfs key gen --type=rsa --size=2048 ${name}`);
spinner.text = `Created new IPNS key: ${name}`;
} else {
spinner.text = `IPNS key ${name} already exists`;
}
// Get the key ID
const keyInfo = execSync("ipfs key list -l")
.toString()
.split("\n")
.find((line) => line.includes(name));
if (!keyInfo) {
throw new Error(`Failed to find key info for ${name}`);
}
const keyId = keyInfo.split(" ")[0].trim();
stopSpinner(`IPNS key ready: ${keyId}`, true);
return keyId;
} catch (error) {
stopSpinner(
`Failed to ensure IPNS key: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Publish content to IPNS
*/
export async function publishToIPNS(cid: string, keyName: string) {
const spinner = startSpinner(
`Publishing ${cid} to IPNS with key ${keyName}...`
);
try {
const output = execSync(
`ipfs name publish --key=${keyName} /ipfs/${cid}`
).toString();
const ipnsAddress = output.match(/to (.+)/)?.[1]?.trim() || "";
stopSpinner(`Published to IPNS: ${ipnsAddress}`, true);
return ipnsAddress;
} catch (error) {
stopSpinner(
`Failed to publish to IPNS: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Create and publish node list JSON
*/
export async function publishNodeList(nodes: NodeInfo[], appName: string) {
const spinner = startSpinner(`Publishing node list for ${appName}...`);
try {
const nodeList: NodeList = {
nodes,
updatedAt: new Date().toISOString(),
};
const tempFile = path.join(config.ipfsDataPath, `${appName}-nodes.json`);
fs.writeFileSync(tempFile, JSON.stringify(nodeList, null, 2));
const cid = await uploadToIPFS(tempFile);
const keyName = `${appName}-nodes`;
await ensureIPNSKey(keyName);
const ipnsAddress = await publishToIPNS(cid, keyName);
fs.unlinkSync(tempFile);
stopSpinner(`Node list published to ${ipnsAddress}`, true);
return { cid, ipnsAddress };
} catch (error) {
stopSpinner(
`Failed to publish node list: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Fetch node list from IPNS
*/
export async function fetchNodeList(ipnsPath: string): Promise<NodeList> {
const spinner = startSpinner(`Fetching node list from ${ipnsPath}...`);
try {
// Resolve IPNS to CID
const ipfsCid = execSync(`ipfs name resolve ${ipnsPath}`)
.toString()
.trim()
.replace("/ipfs/", "");
spinner.text = `Resolved IPNS to CID: ${ipfsCid}`;
// Get file from IPFS
const tempOutputPath = path.join(config.ipfsDataPath, "nodelist-temp.json");
execSync(`ipfs get ${ipfsCid} -o ${tempOutputPath}`);
// Read and parse the file
const nodeListContent = fs.readFileSync(tempOutputPath, "utf8");
const nodeList = JSON.parse(nodeListContent) as NodeList;
// Clean up temp file
fs.unlinkSync(tempOutputPath);
stopSpinner(`Fetched node list with ${nodeList.nodes.length} nodes`, true);
return nodeList;
} catch (error) {
stopSpinner(
`Failed to fetch node list: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw new Error(
`Failed to fetch node list: ${
error instanceof Error ? error.message : String(error)
}`
);
}
}

312
src/services/k3s.ts Normal file
View File

@ -0,0 +1,312 @@
import { execSync } from "child_process";
import fs from "fs";
import path from "path";
import { logger, startSpinner, stopSpinner } from "../utils/logger.js";
import { config } from "../utils/config.js";
/**
* Check if K3s is installed
*/
export function isK3sInstalled(): boolean {
try {
execSync("which k3s", { stdio: "ignore" });
return true;
} catch (error) {
return false;
}
}
/**
* Install K3s if not already installed
*/
export async function installK3s() {
const spinner = startSpinner("Installing K3s...");
try {
if (isK3sInstalled()) {
stopSpinner("K3s is already installed", true);
return true;
}
logger.info("Installing K3s...");
// Use the official K3s install script
execSync("curl -sfL https://get.k3s.io | sh -");
// Wait a moment for K3s to initialize
await new Promise((resolve) => setTimeout(resolve, 5000));
// Verify installation
if (!isK3sInstalled()) {
throw new Error("K3s installation failed");
}
// Set permissions for the current user to access kubectl
execSync("sudo chmod 644 /etc/rancher/k3s/k3s.yaml");
execSync("mkdir -p $HOME/.kube");
execSync("sudo cp /etc/rancher/k3s/k3s.yaml $HOME/.kube/config");
execSync("sudo chown $(id -u):$(id -g) $HOME/.kube/config");
// Set the KUBECONFIG environment variable
process.env.KUBECONFIG = `${process.env.HOME}/.kube/config`;
stopSpinner("K3s installed successfully", true);
return true;
} catch (error) {
stopSpinner(
`Failed to install K3s: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Deploy an application to K3s
*
* All applications run on standardized port 8787 internally, which is mapped to port 80
* on the host via Nginx. Each application is deployed with 2 replicas by default for redundancy.
*/
export async function deployToK3s(
appName: string,
imageName: string,
namespace: string = "debros-apps", // Standard namespace for all DeBros applications
port: number = 8787, // Standard port for all DeBros applications
replicas: number = 2, // Default to 2 replicas for redundancy
envVars: { [key: string]: string } = {}
) {
const spinner = startSpinner(`Deploying ${appName} to K3s...`);
try {
// Ensure K3s is installed
if (!isK3sInstalled()) {
await installK3s();
}
// Create namespace if it doesn't exist
try {
execSync(`kubectl get namespace ${namespace}`);
} catch (error) {
execSync(`kubectl create namespace ${namespace}`);
logger.info(`Created namespace: ${namespace}`);
}
// Create a temporary directory for Kubernetes manifests
const tempDir = path.join(config.ipfsDataPath, "k3s-manifests");
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
// Merge with standard environment variables
const standardEnvVars = {
PORT: port.toString(),
DEBROS_APP_NAME: appName,
...envVars,
};
// Create a deployment YAML
const deploymentYaml = `
apiVersion: apps/v1
kind: Deployment
metadata:
name: ${appName}
namespace: ${namespace}
spec:
replicas: ${replicas}
selector:
matchLabels:
app: ${appName}
template:
metadata:
labels:
app: ${appName}
spec:
containers:
- name: ${appName}
image: ${imageName}
ports:
- containerPort: ${port}
env:
${Object.entries(standardEnvVars)
.map(([key, value]) => ` - name: ${key}\n value: "${value}"`)
.join("\n")}
`;
// Create a service YAML
const serviceYaml = `
apiVersion: v1
kind: Service
metadata:
name: ${appName}-service
namespace: ${namespace}
spec:
selector:
app: ${appName}
ports:
- port: 80 # Standard external port
targetPort: ${port} # Maps to the app's internal port (8787)
type: ClusterIP
`;
// Create an Ingress YAML for Nginx
const ingressYaml = `
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ${appName}-ingress
namespace: ${namespace}
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: ${appName.replace(/\.debros\.sol$/i, "")}.${config.defaultDomain}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: ${appName}-service
port:
number: 80 # Standard port 80 for all ingress traffic
`;
// Write the manifests to files
const deploymentFile = path.join(tempDir, `${appName}-deployment.yaml`);
const serviceFile = path.join(tempDir, `${appName}-service.yaml`);
const ingressFile = path.join(tempDir, `${appName}-ingress.yaml`);
fs.writeFileSync(deploymentFile, deploymentYaml);
fs.writeFileSync(serviceFile, serviceYaml);
fs.writeFileSync(ingressFile, ingressYaml);
// Apply the manifests
execSync(`kubectl apply -f ${deploymentFile}`);
execSync(`kubectl apply -f ${serviceFile}`);
execSync(`kubectl apply -f ${ingressFile}`);
stopSpinner(`${appName} deployed to K3s successfully`, true);
// Clean up the temporary files
fs.unlinkSync(deploymentFile);
fs.unlinkSync(serviceFile);
fs.unlinkSync(ingressFile);
return {
appName,
namespace,
url: `http://${appName}.${config.defaultDomain}`,
};
} catch (error) {
stopSpinner(
`Failed to deploy to K3s: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Install Nginx Ingress Controller for K3s
*/
export async function installNginxIngress() {
const spinner = startSpinner("Installing Nginx Ingress Controller...");
try {
// Ensure K3s is installed
if (!isK3sInstalled()) {
await installK3s();
}
// Apply the Nginx Ingress Controller manifest
execSync(
"kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.1/deploy/static/provider/cloud/deploy.yaml"
);
// Wait for the controller to be ready
execSync(
"kubectl wait --namespace ingress-nginx --for=condition=ready pod --selector=app.kubernetes.io/component=controller --timeout=120s"
);
stopSpinner("Nginx Ingress Controller installed successfully", true);
return true;
} catch (error) {
stopSpinner(
`Failed to install Nginx Ingress Controller: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* List all applications deployed on K3s
*/
export async function listK3sDeployments(namespace: string = "default") {
const spinner = startSpinner(
`Listing deployments in namespace ${namespace}...`
);
try {
// Ensure K3s is installed
if (!isK3sInstalled()) {
await installK3s();
}
const output = execSync(
`kubectl get deployments -n ${namespace} -o json`
).toString();
const deployments = JSON.parse(output);
stopSpinner(`Found ${deployments.items.length} deployments`, true);
return deployments.items;
} catch (error) {
stopSpinner(
`Failed to list deployments: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Delete an application from K3s
*/
export async function deleteK3sDeployment(
appName: string,
namespace: string = "default"
) {
const spinner = startSpinner(`Deleting ${appName} from K3s...`);
try {
// Ensure K3s is installed
if (!isK3sInstalled()) {
await installK3s();
}
// Delete the deployment, service, and ingress
execSync(`kubectl delete deployment ${appName} -n ${namespace}`);
execSync(`kubectl delete service ${appName}-service -n ${namespace}`);
execSync(`kubectl delete ingress ${appName}-ingress -n ${namespace}`);
stopSpinner(`${appName} deleted from K3s successfully`, true);
return true;
} catch (error) {
stopSpinner(
`Failed to delete deployment: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}

612
src/services/network.ts Normal file
View File

@ -0,0 +1,612 @@
import {
getLibp2p,
getConnectedPeers,
initIpfs,
stopIpfs,
} from "@debros/network";
import { logger, startSpinner, stopSpinner } from "../utils/logger.js";
import { config } from "../utils/config.js";
import { NodeInfo } from "./ipfs.js";
// This service handles communication with remote DeBros network nodes
// It does not manage local node deployment, but rather allows the CLI
// to discover, communicate with, and deploy to remote nodes in the network
/**
* Get all currently connected peers
*/
export async function getPeers(): Promise<any> {
const spinner = startSpinner("Getting connected peers...");
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the connected peers
const peers = getConnectedPeers();
stopSpinner(`Found ${peers.length} connected peers`, true);
return peers;
} catch (error) {
stopSpinner(
`Failed to get peers: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Convert connected peers to NodeInfo format
*/
export async function getPeersAsNodeInfo(): Promise<NodeInfo[]> {
const peers = await getPeers();
const nodeInfos: NodeInfo[] = [];
peers.forEach((data: any, peerId: any) => {
const { load, publicAddress } = data;
try {
// Extract address and port from publicAddress
const url = new URL(publicAddress);
const address = url.hostname;
const port = parseInt(url.port) || (url.protocol === "https:" ? 443 : 80);
nodeInfos.push({
id: peerId,
address,
port,
load,
type: "k3s", // Default to k3s, could be dynamically determined in the future
});
} catch (error) {
logger.warn(
`Invalid public address for peer ${peerId}: ${publicAddress}`
);
}
});
return nodeInfos;
}
/**
* Announce a deployment to the network
*/
export async function announceDeployment(
cid: string,
appName: string,
version: string = "latest",
domain: string = ""
) {
const spinner = startSpinner(
`Announcing deployment of ${appName}:${version} to the network...`
);
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
throw new Error("LibP2P is not initialized");
}
// Use default domain if not provided
let appDomain = domain || `${appName}.${config.defaultDomain}`;
// Ensure the domain ends with .debros.sol
if (!appDomain.endsWith(`.${config.defaultDomain}`)) {
// Remove any domain suffix if present
const cleanSubdomain = appDomain.split(".")[0];
appDomain = `${cleanSubdomain}.${config.defaultDomain}`;
}
// Create the deployment announcement message
const message = {
type: "deployment",
cid,
appName,
version,
domain: appDomain,
timestamp: Date.now(),
};
// Publish to the debros-deploy topic
await libp2p.services.pubsub.publish(
"debros-deploy",
new TextEncoder().encode(JSON.stringify(message))
);
stopSpinner(`Deployment announced to the network`, true);
// Clean up IPFS
await stopIpfs();
return true;
} catch (error) {
stopSpinner(
`Failed to announce deployment: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Listen for deployment announcements
*/
export async function listenForDeployments(
callback: (message: {
cid: string;
appName: string;
version: string;
domain: string;
}) => void
) {
const spinner = startSpinner("Listening for deployment announcements...");
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
throw new Error("LibP2P is not initialized");
}
// Subscribe to the debros-deploy topic
await libp2p.services.pubsub.subscribe("debros-deploy");
// Set up the message handler
libp2p.services.pubsub.addEventListener("message", (event: any) => {
try {
if (event.detail.topic === "debros-deploy") {
const msgData = new TextDecoder().decode(event.detail.data);
const message = JSON.parse(msgData);
if (message.type === "deployment") {
callback({
cid: message.cid,
appName: message.appName,
version: message.version,
domain:
message.domain || `${message.appName}.${config.defaultDomain}`,
});
}
}
} catch (error) {
logger.error(
`Failed to process deployment message: ${
error instanceof Error ? error.message : String(error)
}`
);
}
});
stopSpinner("Listening for deployment announcements", true);
return true;
} catch (error) {
stopSpinner(
`Failed to listen for deployments: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Get versions of an application
*/
export async function getAppVersions(appName: string): Promise<
Array<{
tag: string;
cid: string;
timestamp: string;
deployed: boolean;
}>
> {
const spinner = startSpinner(`Fetching versions for ${appName}...`);
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
throw new Error("LibP2P is not initialized");
}
// Get application versions from network
// In a real implementation, this would query OrbitDB or another storage mechanism
// Simulate fetching version info from network
// This would typically come from querying the network or local database
const versions = [
{
tag: "latest",
cid: "QmVersion1",
timestamp: new Date().toISOString(),
deployed: true,
},
{
tag: "v1.0.0",
cid: "QmVersion2",
timestamp: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), // 1 day ago
deployed: false,
},
{
tag: "v0.9.0",
cid: "QmVersion3",
timestamp: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(), // 1 week ago
deployed: false,
},
];
stopSpinner(`Found ${versions.length} versions for ${appName}`, true);
// Clean up IPFS
await stopIpfs();
return versions;
} catch (error) {
stopSpinner(
`Failed to fetch versions: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}
/**
* Rollback an application to a specific version
*/
export async function rollbackToVersion(
appName: string,
versionTag?: string,
domain?: string,
force: boolean = false
): Promise<{
success: boolean;
message?: string;
version?: string;
cid?: string;
}> {
const spinner = startSpinner(
`Rolling back ${appName} to ${versionTag || "previous version"}...`
);
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
throw new Error("LibP2P is not initialized");
}
// Get versions to find the right one
const versions = await getAppVersions(appName);
if (versions.length === 0) {
stopSpinner(`No versions found for ${appName}`, false);
return { success: false, message: `No versions found for ${appName}` };
}
// Find the requested version or previous version
let targetVersion;
if (versionTag) {
// Find specific version
targetVersion = versions.find((v) => v.tag === versionTag);
if (!targetVersion) {
stopSpinner(`Version ${versionTag} not found for ${appName}`, false);
return { success: false, message: `Version ${versionTag} not found` };
}
} else {
// Find previous version (not current)
const currentVersion = versions.find((v) => v.deployed);
const otherVersions = versions
.filter((v) => !v.deployed)
.sort(
(a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
);
if (otherVersions.length === 0) {
stopSpinner(`No previous versions found for ${appName}`, false);
return {
success: false,
message: "No previous versions found to rollback to",
};
}
targetVersion = otherVersions[0];
}
// Announce the rollback deployment with the CID of the target version
const appDomain = domain || `${appName}.${config.defaultDomain}`;
// Create the deployment announcement message
const message = {
type: "deployment",
cid: targetVersion.cid,
appName,
version: targetVersion.tag,
domain: appDomain,
isRollback: true,
timestamp: Date.now(),
};
// Publish to the debros-deploy topic
await libp2p.services.pubsub.publish(
"debros-deploy",
new TextEncoder().encode(JSON.stringify(message))
);
stopSpinner(`Rolled back ${appName} to version ${targetVersion.tag}`, true);
// Clean up IPFS
await stopIpfs();
return {
success: true,
version: targetVersion.tag,
cid: targetVersion.cid,
};
} catch (error) {
stopSpinner(
`Failed to rollback: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
return {
success: false,
message: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Stop an application
*/
export async function stopApplication(
appName: string,
force: boolean = false
): Promise<{
success: boolean;
message?: string;
}> {
const spinner = startSpinner(`Stopping application ${appName}...`);
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
throw new Error("LibP2P is not initialized");
}
// Create the stop message
const message = {
type: "application-action",
action: "stop",
appName,
force,
timestamp: Date.now(),
};
// Publish to the debros-app-actions topic
await libp2p.services.pubsub.publish(
"debros-app-actions",
new TextEncoder().encode(JSON.stringify(message))
);
stopSpinner(
`Stop command for ${appName} has been sent to the network`,
true
);
// Clean up IPFS
await stopIpfs();
return { success: true };
} catch (error) {
stopSpinner(
`Failed to stop application: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
return {
success: false,
message: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Start an application
*/
export async function startApplication(
appName: string,
versionTag: string = "latest"
): Promise<{
success: boolean;
message?: string;
}> {
const spinner = startSpinner(
`Starting application ${appName} with version ${versionTag}...`
);
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
throw new Error("LibP2P is not initialized");
}
// Get versions to find the right CID
const versions = await getAppVersions(appName);
if (versions.length === 0) {
stopSpinner(`No versions found for ${appName}`, false);
return { success: false, message: `No versions found for ${appName}` };
}
// Find the requested version
const targetVersion = versions.find((v) => v.tag === versionTag);
if (!targetVersion) {
stopSpinner(`Version ${versionTag} not found for ${appName}`, false);
return { success: false, message: `Version ${versionTag} not found` };
}
// Create the start message
const message = {
type: "application-action",
action: "start",
appName,
version: versionTag,
cid: targetVersion.cid,
timestamp: Date.now(),
};
// Publish to the debros-app-actions topic
await libp2p.services.pubsub.publish(
"debros-app-actions",
new TextEncoder().encode(JSON.stringify(message))
);
stopSpinner(
`Start command for ${appName} with version ${versionTag} has been sent to the network`,
true
);
// Clean up IPFS
await stopIpfs();
return { success: true };
} catch (error) {
stopSpinner(
`Failed to start application: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
return {
success: false,
message: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Delete an application
*/
export async function deleteApplication(
appName: string,
force: boolean = false
): Promise<{
success: boolean;
message?: string;
}> {
const spinner = startSpinner(`Deleting application ${appName}...`);
try {
// Initialize IPFS if it's not already running
await initIpfs();
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
throw new Error("LibP2P is not initialized");
}
// Create the delete message
const message = {
type: "application-action",
action: "delete",
appName,
force,
timestamp: Date.now(),
};
// Publish to the debros-app-actions topic
await libp2p.services.pubsub.publish(
"debros-app-actions",
new TextEncoder().encode(JSON.stringify(message))
);
stopSpinner(
`Delete command for ${appName} has been sent to the network`,
true
);
// Clean up IPFS
await stopIpfs();
return { success: true };
} catch (error) {
stopSpinner(
`Failed to delete application: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
return {
success: false,
message: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Stop listening for deployment announcements
*/
export async function stopListeningForDeployments() {
const spinner = startSpinner("Stopping deployment listener...");
try {
// Get the libp2p instance
const libp2p = getLibp2p();
if (!libp2p) {
spinner.text = "LibP2P is not initialized, nothing to stop";
stopSpinner("Stopped deployment listener", true);
return true;
}
// Unsubscribe from the debros-deploy topic
await libp2p.services.pubsub.unsubscribe("debros-deploy");
// Stop IPFS
await stopIpfs();
stopSpinner("Stopped deployment listener", true);
return true;
} catch (error) {
stopSpinner(
`Failed to stop deployment listener: ${
error instanceof Error ? error.message : String(error)
}`,
false
);
throw error;
}
}

123
src/services/solana.ts Normal file
View File

@ -0,0 +1,123 @@
import { Connection, PublicKey } from '@solana/web3.js';
import { execSync } from 'child_process';
import { logger, startSpinner, stopSpinner } from '../utils/logger.js';
import { config } from '../utils/config.js';
// Create Solana connection
const connection = new Connection(config.solanaEndpoint);
/**
* Check if a .sol domain is available
*/
export async function checkDomainAvailability(domain: string): Promise<boolean> {
const spinner = startSpinner(`Checking availability of ${domain}...`);
try {
// This is a simplified approach. In reality, you'd interact with the Solana Name Service
// For now, we'll simulate this interaction
// Simulate a domain lookup by creating a deterministic "domain address"
const domainKey = new PublicKey(
Buffer.from(`domains:${domain.toLowerCase().replace('.sol', '')}`, 'utf-8')
);
// Check if an account exists at this address
const accountInfo = await connection.getAccountInfo(domainKey);
const isAvailable = accountInfo === null;
if (isAvailable) {
stopSpinner(`Domain ${domain} is available!`, true);
} else {
stopSpinner(`Domain ${domain} is already registered`, false);
}
return isAvailable;
} catch (error) {
stopSpinner(`Failed to check domain availability: ${error instanceof Error ? error.message : String(error)}`, false);
throw error;
}
}
/**
* Create DNS link for a domain
*/
export function createDNSLink(domain: string, ipnsPath: string): string {
const spinner = startSpinner(`Creating DNS link for ${domain} pointing to ${ipnsPath}...`);
try {
// Guidance message for user - actual DNS TXT record creation would need to be done
// through a registrar that supports Solana Name Service domains
const dnsLinkValue = `dnslink=${ipnsPath}`;
spinner.text = 'DNS link creation requires a supporting registrar';
stopSpinner(`To create a DNS link for ${domain}, add a TXT record with key _dnslink and value: ${dnsLinkValue}`, true);
return dnsLinkValue;
} catch (error) {
stopSpinner(`Failed to create DNS link: ${error instanceof Error ? error.message : String(error)}`, false);
throw error;
}
}
/**
* Guide the user to register a .sol domain
*/
export function guideDomainRegistration(domain: string): string {
const spinner = startSpinner(`Preparing guide for registering ${domain}...`);
try {
// Create a guide for the user
const guide = `
To register the "${domain}" domain:
1. Visit a Solana Name Service provider like:
- Solana Name Service: https://naming.service
- Bonfida: https://naming.bonfida.org
2. Connect your Solana wallet (like Phantom, Solflare, etc.)
3. Search for "${domain.replace('.sol', '')}"
4. Complete the registration process and pay the registration fee (~$5/year + network fees)
5. Once registered, return to the DeBros CLI to configure your domain
`;
stopSpinner('Domain registration guide prepared', true);
return guide;
} catch (error) {
stopSpinner(`Failed to create guide: ${error instanceof Error ? error.message : String(error)}`, false);
throw error;
}
}
/**
* Configure IPNS with a domain
*/
export async function configureDomainIPNS(domain: string, keyName: string, ipfsCid: string) {
const spinner = startSpinner(`Configuring ${domain} with IPNS...`);
try {
// First publish the CID to IPNS with the key
const publishOutput = execSync(`ipfs name publish --key=${keyName} /ipfs/${ipfsCid}`).toString();
const ipnsPath = publishOutput.match(/to (.+)/)?.[1]?.trim() || '';
if (!ipnsPath) {
throw new Error('Failed to get IPNS path from publish operation');
}
// Create guidance for DNS Link
const dnsLinkValue = createDNSLink(domain, ipnsPath);
stopSpinner(`${domain} configured with IPNS address: ${ipnsPath}`, true);
return {
domain,
ipnsPath,
dnsLinkValue
};
} catch (error) {
stopSpinner(`Failed to configure domain IPNS: ${error instanceof Error ? error.message : String(error)}`, false);
throw error;
}
}

107
src/utils/config.ts Normal file
View File

@ -0,0 +1,107 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import os from 'os';
import { logger } from './logger.js';
import dotenv from 'dotenv';
// Load environment variables
dotenv.config();
// Calculate config file path
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CONFIG_DIR = path.join(os.homedir(), '.debros');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
// Default configuration
export interface DebrosCliConfig {
ipfsDataPath: string;
ipnsKeysPath: string;
dockerRegistry: string;
bootstrapNodes: string[];
defaultDomain: string;
solanaEndpoint: string;
defaultDeploymentStrategy: 'k3s' | 'docker';
}
const defaultConfig: DebrosCliConfig = {
ipfsDataPath: path.join(os.homedir(), '.debros', 'ipfs'),
ipnsKeysPath: path.join(os.homedir(), '.debros', 'ipns'),
dockerRegistry: 'debros',
bootstrapNodes: [
'/ip4/188.166.113.190/tcp/7778/p2p/12D3KooWNWgs4WAUmE4CsxrL6uuyv1yuTzcRReMe5r7Psemsg2Z9',
'/ip4/82.208.21.140/tcp/7778/p2p/12D3KooWPUdpNX5N6dsuFAvgwfBMXUoFK2QS5sh8NpjxbfGpkSCi'
],
defaultDomain: 'debros.sol',
solanaEndpoint: 'https://api.mainnet-beta.solana.com',
defaultDeploymentStrategy: 'k3s'
};
// Ensure config directory exists
if (!fs.existsSync(CONFIG_DIR)) {
try {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
logger.debug(`Created config directory at ${CONFIG_DIR}`);
} catch (error) {
logger.error(`Failed to create config directory: ${error instanceof Error ? error.message : String(error)}`);
}
}
// Create IPFS and IPNS directories if they don't exist
if (!fs.existsSync(defaultConfig.ipfsDataPath)) {
try {
fs.mkdirSync(defaultConfig.ipfsDataPath, { recursive: true });
logger.debug(`Created IPFS data directory at ${defaultConfig.ipfsDataPath}`);
} catch (error) {
logger.error(`Failed to create IPFS data directory: ${error instanceof Error ? error.message : String(error)}`);
}
}
if (!fs.existsSync(defaultConfig.ipnsKeysPath)) {
try {
fs.mkdirSync(defaultConfig.ipnsKeysPath, { recursive: true });
logger.debug(`Created IPNS keys directory at ${defaultConfig.ipnsKeysPath}`);
} catch (error) {
logger.error(`Failed to create IPNS keys directory: ${error instanceof Error ? error.message : String(error)}`);
}
}
// Load config or create default
export function loadConfig(): DebrosCliConfig {
if (!fs.existsSync(CONFIG_FILE)) {
saveConfig(defaultConfig);
return defaultConfig;
}
try {
const configData = fs.readFileSync(CONFIG_FILE, 'utf8');
const loadedConfig = JSON.parse(configData) as DebrosCliConfig;
// Merge with defaults in case there are new fields
return { ...defaultConfig, ...loadedConfig };
} catch (error) {
logger.error(`Failed to load config: ${error instanceof Error ? error.message : String(error)}`);
return defaultConfig;
}
}
// Save config
export function saveConfig(config: DebrosCliConfig): void {
try {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
logger.debug('Configuration saved successfully');
} catch (error) {
logger.error(`Failed to save config: ${error instanceof Error ? error.message : String(error)}`);
}
}
// Update a specific config setting
export function updateConfig(key: keyof DebrosCliConfig, value: any): DebrosCliConfig {
const currentConfig = loadConfig();
const updatedConfig = { ...currentConfig, [key]: value };
saveConfig(updatedConfig);
return updatedConfig;
}
export const config = loadConfig();
export default config;

105
src/utils/logger.ts Normal file
View File

@ -0,0 +1,105 @@
import chalk from 'chalk';
import ora from 'ora';
export enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
}
// Current log level - can be set via environment variable
let currentLogLevel = LogLevel.INFO;
export function setLogLevel(level: LogLevel) {
currentLogLevel = level;
}
export function getLogLevel(): LogLevel {
const envLevel = process.env.DEBROS_LOG_LEVEL?.toLowerCase();
if (envLevel === 'debug') return LogLevel.DEBUG;
if (envLevel === 'info') return LogLevel.INFO;
if (envLevel === 'warn') return LogLevel.WARN;
if (envLevel === 'error') return LogLevel.ERROR;
return currentLogLevel;
}
// Spinner for loading states
let spinner: ReturnType<typeof ora> | null = null;
export function startSpinner(text: string) {
if (spinner) spinner.stop();
spinner = ora(text).start();
return spinner;
}
export function updateSpinner(text: string) {
if (spinner) spinner.text = text;
}
export function stopSpinner(text?: string, success = true) {
if (!spinner) return;
if (success && text) {
spinner.succeed(text);
} else if (!success && text) {
spinner.fail(text);
} else {
spinner.stop();
}
spinner = null;
}
// Logger functions
export const logger = {
debug: (message: string, ...args: any[]) => {
if (getLogLevel() <= LogLevel.DEBUG) {
if (spinner) spinner.stop();
console.log(chalk.gray(`[DEBUG] ${message}`), ...args);
if (spinner) spinner.start();
}
},
info: (message: string, ...args: any[]) => {
if (getLogLevel() <= LogLevel.INFO) {
if (spinner) spinner.stop();
console.log(chalk.blue(`[INFO] ${message}`), ...args);
if (spinner) spinner.start();
}
},
success: (message: string, ...args: any[]) => {
if (getLogLevel() <= LogLevel.INFO) {
if (spinner) spinner.stop();
console.log(chalk.green(`[SUCCESS] ${message}`), ...args);
if (spinner) spinner.start();
}
},
warn: (message: string, ...args: any[]) => {
if (getLogLevel() <= LogLevel.WARN) {
if (spinner) spinner.stop();
console.log(chalk.yellow(`[WARN] ${message}`), ...args);
if (spinner) spinner.start();
}
},
error: (message: string, ...args: any[]) => {
if (getLogLevel() <= LogLevel.ERROR) {
if (spinner) spinner.stop();
console.error(chalk.red(`[ERROR] ${message}`), ...args);
if (spinner) spinner.start();
}
},
raw: (message: string) => {
if (spinner) spinner.stop();
console.log(message);
if (spinner) spinner.start();
}
};
export default logger;

16
tsconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"declaration": true,
"outDir": "./dist",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

88
types.d.ts vendored Normal file
View File

@ -0,0 +1,88 @@
declare module '@debros/cli' {
// Core interfaces for node and network information
export interface NodeInfo {
id: string;
address: string;
port: number;
load: number;
type: "k3s" | "docker";
}
export interface NodeList {
nodes: NodeInfo[];
updatedAt: string;
}
// Configuration interface
export interface DebrosCliConfig {
ipfsDataPath: string;
ipnsKeysPath: string;
dockerRegistry: string;
bootstrapNodes: string[];
defaultDomain: string;
solanaEndpoint: string;
defaultDeploymentStrategy: "k3s" | "docker";
}
// IPFS services
export function initializeIpfs(): Promise<{ ipfs: any; libp2p: any }>;
export function uploadToIPFS(filePath: string): Promise<string>;
export function ensureIPNSKey(name: string): Promise<string>;
export function publishToIPNS(cid: string, keyName: string): Promise<string>;
export function publishNodeList(nodes: NodeInfo[], appName: string): Promise<{ cid: string; ipnsAddress: string }>;
export function fetchNodeList(ipnsPath: string): Promise<NodeList>;
// Docker services
export function buildDockerImage(
folderPath: string,
imageName: string,
tag?: string,
additionalArgs?: string[]
): Promise<{ imageName: string; output: string }>;
export function saveDockerImage(imageName: string, outputPath: string): Promise<string>;
export function loadDockerImage(tarPath: string): Promise<{ imagePath: string; loadedImage: string | undefined }>;
export function runContainer(
imageName: string,
containerName: string,
ports?: { [key: string]: string },
envVars?: { [key: string]: string },
volumes?: { [key: string]: string }
): Promise<any>;
// Network services
export function getPeers(): Promise<any>;
export function getPeersAsNodeInfo(): Promise<NodeInfo[]>;
export function announceDeployment(
cid: string,
appName: string,
version?: string,
domain?: string
): Promise<boolean>;
export function listenForDeployments(
callback: (message: { cid: string; appName: string; version: string; domain: string }) => void
): Promise<boolean>;
export function getAppVersions(appName: string): Promise<Array<{
tag: string;
cid: string;
timestamp: string;
deployed: boolean;
}>>;
export function rollbackToVersion(
appName: string,
versionTag?: string,
domain?: string,
force?: boolean
): Promise<{ success: boolean; message?: string; version?: string; cid?: string }>;
export function startApplication(
appName: string,
versionTag?: string
): Promise<{ success: boolean; message?: string }>;
export function stopApplication(
appName: string,
force?: boolean
): Promise<{ success: boolean; message?: string }>;
export function deleteApplication(
appName: string,
force?: boolean
): Promise<{ success: boolean; message?: string }>;
}