feat(server): initial release v1.0 with mesh VPN, custom DNS, drive and android APK
This commit is contained in:
commit
bf8481157e
14
.gitignore
vendored
Normal file
14
.gitignore
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
# Binaries
|
||||
benzcloud-server
|
||||
benzcloud-server.exe
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
|
||||
# Data and Build outputs
|
||||
data/
|
||||
benzcloud-data/
|
||||
android/build/
|
||||
android/gen/
|
||||
android/bin/
|
||||
android/compiled_res/
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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 <https://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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
45
README.md
Normal file
45
README.md
Normal file
@ -0,0 +1,45 @@
|
||||
# ☁️ BenzCloud Server
|
||||
|
||||
> **Notice:** BenzCloud is in **active development / pre-release status** (`v1.0`). APIs, protocols, and interfaces are actively evolving.
|
||||
|
||||
BenzCloud Server is a privacy-first, local enterprise suite and open-source alternative to Microsoft 365 and Nextcloud written in pure Go. It features automatic zero-configuration Mesh-VPN networking (Slack Nebula), an authoritative Custom DNS server (RFC 1035), encrypted document storage, virtual host routing, and an extensible modular plugin architecture.
|
||||
|
||||
## 🚀 Key Features
|
||||
|
||||
- **One-Click Setup Wizard:** Enter your desired base domain (e.g. `benzjeremy.de` or `intern`) and admin password. The mesh VPN, custom DNS server, and routing configure themselves automatically without manual router port forwardings.
|
||||
- **Zero-Config Mesh-VPN (Slack Nebula):** Seamless P2P overlay network across strict NATs and firewalls with out-of-the-box UDP hole-punching.
|
||||
- **Authoritative Custom DNS Server:** Built-in lightweight RFC 1035 DNS server resolving system subdomains (`vpn.`, `drive.`, `mail.`, `chat.`) and custom web subdomains with fallback upstream forwarding.
|
||||
- **Permanent VPN & DNS Privileges:** By architectural decree, network connectivity (VPN & DNS) is unconditionally active for all authenticated user accounts and cannot be revoked.
|
||||
- **Encrypted Drive at Rest:** AES-256-GCM encrypted document vault with PBKDF2 (100,000 rounds) key derivation.
|
||||
- **Modular Plugin Gateway:** Supervises and reverse-proxies modular enterprise micro-services (`benzcloud-plugin-web`, `benzcloud-plugin-mail`, `benzcloud-plugin-chat`).
|
||||
- **Multi-Platform Support:** Native binaries for PC (Linux x86_64, Windows x86_64) and native Android APK.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Installation & Usage
|
||||
|
||||
### Linux (x86_64)
|
||||
```bash
|
||||
# Run server daemon
|
||||
./benzcloud-server -daemon -port 8080 -dns-port 53
|
||||
|
||||
# Or install via Go
|
||||
go install github.com/benzjeremy/benzcloud-server@latest
|
||||
```
|
||||
|
||||
### Windows (x86_64)
|
||||
Launch `benzcloud-server.exe` to run the server daemon and open the management cockpit.
|
||||
|
||||
### Android
|
||||
Install `benzcloud-server-v1.0.apk` to run BenzCloud as a mobile node or micro-server on Android.
|
||||
|
||||
---
|
||||
|
||||
## 👥 Authors & Credits
|
||||
- **Jeremy Benz** ([@benzjeremy](https://github.com/benzjeremy)) – Lead Engineer & Project Creator
|
||||
- Pair-programmed with AI Assistant (Google Antigravity)
|
||||
- © 2026 Jeremy Benz
|
||||
|
||||
## 📄 License & Third-Party Notices
|
||||
- **Main Project:** Released under the [GNU General Public License v3.0 (GPL-3.0)](LICENSE).
|
||||
- **Slack Nebula:** Mesh-VPN networking is powered by Slack Nebula, licensed under the [MIT License](https://github.com/slackhq/nebula/blob/master/LICENSE).
|
||||
29
android/app/src/main/AndroidManifest.xml
Normal file
29
android/app/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.benzjeremy.benzcloud.server"
|
||||
android:versionCode="1"
|
||||
android:versionName="1.0">
|
||||
|
||||
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:label="BenzCloud Server"
|
||||
android:theme="@style/AppTheme"
|
||||
android:networkSecurityConfig="@xml/network_security_config">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|keyboardHidden">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@ -0,0 +1,46 @@
|
||||
package com.benzjeremy.benzcloud.server;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.Bundle;
|
||||
import android.webkit.WebSettings;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
|
||||
public class MainActivity extends Activity {
|
||||
private WebView webView;
|
||||
|
||||
public static class AppWebViewClient extends WebViewClient {
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView view, String url) {
|
||||
view.loadUrl(url);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
webView = (WebView) findViewById(R.id.webView);
|
||||
WebSettings settings = webView.getSettings();
|
||||
settings.setJavaScriptEnabled(true);
|
||||
settings.setDomStorageEnabled(true);
|
||||
settings.setDatabaseEnabled(true);
|
||||
settings.setAllowFileAccess(true);
|
||||
|
||||
webView.setWebViewClient(new AppWebViewClient());
|
||||
|
||||
// Points to local BenzCloud server daemon endpoint
|
||||
webView.loadUrl("http://127.0.0.1:8080");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (webView != null && webView.canGoBack()) {
|
||||
webView.goBack();
|
||||
} else {
|
||||
super.onBackPressed();
|
||||
}
|
||||
}
|
||||
}
|
||||
12
android/app/src/main/res/layout/activity_main.xml
Normal file
12
android/app/src/main/res/layout/activity_main.xml
Normal file
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:background="@color/bg_page">
|
||||
|
||||
<WebView
|
||||
android:id="@+id/webView"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
</LinearLayout>
|
||||
7
android/app/src/main/res/values/colors.xml
Normal file
7
android/app/src/main/res/values/colors.xml
Normal file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="bg_page">#0A0E17</color>
|
||||
<color name="bg_surface">#121826</color>
|
||||
<color name="accent_blue">#38BDF8</color>
|
||||
<color name="text_main">#F1F5F9</color>
|
||||
</resources>
|
||||
6
android/app/src/main/res/values/strings.xml
Normal file
6
android/app/src/main/res/values/strings.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">BenzCloud Server</string>
|
||||
<string name="server_running">BenzCloud Server Daemon aktiv</string>
|
||||
<string name="server_desc">Mesh-VPN (Nebula) & Custom-DNS Server laufen im Hintergrund</string>
|
||||
</resources>
|
||||
8
android/app/src/main/res/values/styles.xml
Normal file
8
android/app/src/main/res/values/styles.xml
Normal file
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="AppTheme" parent="android:Theme.Material.NoActionBar">
|
||||
<item name="android:windowBackground">@color/bg_page</item>
|
||||
<item name="android:colorPrimary">@color/bg_surface</item>
|
||||
<item name="android:colorAccent">@color/accent_blue</item>
|
||||
</style>
|
||||
</resources>
|
||||
4
android/app/src/main/res/xml/network_security_config.xml
Normal file
4
android/app/src/main/res/xml/network_security_config.xml
Normal file
@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="true" />
|
||||
</network-security-config>
|
||||
BIN
android/benzcloud-server-v1.0.apk
Normal file
BIN
android/benzcloud-server-v1.0.apk
Normal file
Binary file not shown.
BIN
android/benzcloud-server-v1.0.apk.idsig
Normal file
BIN
android/benzcloud-server-v1.0.apk.idsig
Normal file
Binary file not shown.
54
android/build_apk.sh
Executable file
54
android/build_apk.sh
Executable file
@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
WORK="$DIR/build"
|
||||
SDK="/home/benzj/Android/Sdk"
|
||||
BUILD_TOOLS="$SDK/build-tools/34.0.0"
|
||||
ANDROID_JAR="$SDK/platforms/android-34/android.jar"
|
||||
KEYSTORE="/home/benzj/Projekte/benzjeremy.github.io/myfdroid/myfdroid.keystore"
|
||||
KEYPASS="myfdroid_secret_key_2026"
|
||||
|
||||
rm -rf "$WORK"
|
||||
mkdir -p "$WORK/bin" "$WORK/gen" "$WORK/compiled_res"
|
||||
|
||||
echo "==> 1. Compiling resources with aapt2..."
|
||||
"$BUILD_TOOLS/aapt2" compile --dir "$DIR/app/src/main/res" -o "$WORK/compiled_res.zip"
|
||||
|
||||
echo "==> 2. Linking resources and generating R.java..."
|
||||
"$BUILD_TOOLS/aapt2" link \
|
||||
-I "$ANDROID_JAR" \
|
||||
--manifest "$DIR/app/src/main/AndroidManifest.xml" \
|
||||
--java "$WORK/gen" \
|
||||
-o "$WORK/unaligned.apk" \
|
||||
--auto-add-overlay \
|
||||
"$WORK/compiled_res.zip"
|
||||
|
||||
echo "==> 3. Compiling Java sources..."
|
||||
find "$DIR/app/src/main/java" "$WORK/gen" -name "*.java" > "$WORK/sources.txt"
|
||||
javac --release 8 -cp "$ANDROID_JAR" -d "$WORK/bin" @"$WORK/sources.txt"
|
||||
|
||||
echo "==> 4. Converting bytecode to DEX with d8..."
|
||||
find "$WORK/bin" -name "*.class" > "$WORK/classes.txt"
|
||||
"$BUILD_TOOLS/d8" --output "$WORK" --lib "$ANDROID_JAR" @"$WORK/classes.txt"
|
||||
|
||||
echo "==> 5. Adding classes.dex to APK..."
|
||||
cd "$WORK"
|
||||
python3 -c "import zipfile; z = zipfile.ZipFile('unaligned.apk', 'a'); z.write('classes.dex', 'classes.dex'); z.close()"
|
||||
cd "$DIR"
|
||||
|
||||
echo "==> 6. Aligning APK with zipalign..."
|
||||
"$BUILD_TOOLS/zipalign" -p -f 4 "$WORK/unaligned.apk" "$WORK/aligned.apk"
|
||||
|
||||
echo "==> 7. Signing APK with apksigner..."
|
||||
"$BUILD_TOOLS/apksigner" sign \
|
||||
--ks "$KEYSTORE" \
|
||||
--ks-pass "pass:$KEYPASS" \
|
||||
--key-pass "pass:$KEYPASS" \
|
||||
--out "$DIR/benzcloud-server-v1.0.apk" \
|
||||
"$WORK/aligned.apk"
|
||||
|
||||
echo "==> 8. Verifying APK signature..."
|
||||
"$BUILD_TOOLS/apksigner" verify --verbose "$DIR/benzcloud-server-v1.0.apk"
|
||||
|
||||
echo "✅ SUCCESS! Native BenzCloud Server APK built at: $DIR/benzcloud-server-v1.0.apk"
|
||||
11
go.mod
Normal file
11
go.mod
Normal file
@ -0,0 +1,11 @@
|
||||
module github.com/benzjeremy/benzcloud-server
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require golang.org/x/crypto v0.57.0
|
||||
|
||||
require (
|
||||
github.com/miekg/dns v1.1.73 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
)
|
||||
8
go.sum
Normal file
8
go.sum
Normal file
@ -0,0 +1,8 @@
|
||||
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
||||
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
40
gui_linux.go
Normal file
40
gui_linux.go
Normal file
@ -0,0 +1,40 @@
|
||||
//go:build linux && cgo
|
||||
|
||||
package main
|
||||
|
||||
/*
|
||||
#cgo pkg-config: gtk+-3.0 webkit2gtk-4.1
|
||||
#include <gtk/gtk.h>
|
||||
#include <webkit2/webkit2.h>
|
||||
|
||||
static void activate_gtk_app(const char* title, const char* url, int width, int height) {
|
||||
gtk_init(NULL, NULL);
|
||||
|
||||
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
gtk_window_set_title(GTK_WINDOW(window), title);
|
||||
gtk_window_set_default_size(GTK_WINDOW(window), width, height);
|
||||
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
|
||||
|
||||
GtkWidget *web_view = webkit_web_view_new();
|
||||
gtk_container_add(GTK_CONTAINER(window), web_view);
|
||||
|
||||
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
|
||||
|
||||
webkit_web_view_load_uri(WEBKIT_WEB_VIEW(web_view), url);
|
||||
gtk_widget_show_all(window);
|
||||
|
||||
gtk_main();
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
import "unsafe"
|
||||
|
||||
// LaunchGUI launches native WebKitGTK desktop shell on Linux.
|
||||
func LaunchGUI(title, url string, width, height int) {
|
||||
cTitle := C.CString(title)
|
||||
cURL := C.CString(url)
|
||||
defer C.free(unsafe.Pointer(cTitle))
|
||||
defer C.free(unsafe.Pointer(cURL))
|
||||
|
||||
C.activate_gtk_app(cTitle, cURL, C.int(width), C.int(height))
|
||||
}
|
||||
22
gui_other.go
Normal file
22
gui_other.go
Normal file
@ -0,0 +1,22 @@
|
||||
//go:build (!linux && !windows) || (linux && !cgo)
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// LaunchGUI opens the browser as fallback.
|
||||
func LaunchGUI(title, url string, width, height int) {
|
||||
log.Printf("[BenzCloud GUI] Opening application interface at %s\n", url)
|
||||
var cmd *exec.Cmd
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
cmd = exec.Command("open", url)
|
||||
default:
|
||||
cmd = exec.Command("xdg-open", url)
|
||||
}
|
||||
_ = cmd.Start()
|
||||
}
|
||||
33
gui_windows.go
Normal file
33
gui_windows.go
Normal file
@ -0,0 +1,33 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// LaunchGUI launches Windows app mode using Edge or Chrome without CGO.
|
||||
func LaunchGUI(title, url string, width, height int) {
|
||||
appArg := fmt.Sprintf("--app=%s", url)
|
||||
windowSizeArg := fmt.Sprintf("--window-size=%d,%d", width, height)
|
||||
|
||||
// Try Microsoft Edge
|
||||
cmd := exec.Command("msedge.exe", appArg, windowSizeArg)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: false}
|
||||
if err := cmd.Start(); err == nil {
|
||||
_ = cmd.Wait()
|
||||
return
|
||||
}
|
||||
|
||||
// Try Chrome
|
||||
cmdChrome := exec.Command("chrome.exe", appArg, windowSizeArg)
|
||||
if err := cmdChrome.Start(); err == nil {
|
||||
_ = cmdChrome.Wait()
|
||||
return
|
||||
}
|
||||
|
||||
// Fallback to default browser
|
||||
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
||||
}
|
||||
474
internal/core/api/api.go
Normal file
474
internal/core/api/api.go
Normal file
@ -0,0 +1,474 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/auth"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/config"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/dns"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/drive"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/nebula"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/plugins"
|
||||
)
|
||||
|
||||
// Server encapsulates the REST API and state references.
|
||||
type Server struct {
|
||||
cfg *config.Config
|
||||
authMgr *auth.Manager
|
||||
dnsSrv *dns.Server
|
||||
nebulaMgr *nebula.Manager
|
||||
driveMgr *drive.DriveManager
|
||||
pluginMgr *plugins.Manager
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
// NewServer creates a new API controller.
|
||||
func NewServer(
|
||||
cfg *config.Config,
|
||||
authMgr *auth.Manager,
|
||||
dnsSrv *dns.Server,
|
||||
nebulaMgr *nebula.Manager,
|
||||
driveMgr *drive.DriveManager,
|
||||
pluginMgr *plugins.Manager,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
cfg: cfg,
|
||||
authMgr: authMgr,
|
||||
dnsSrv: dnsSrv,
|
||||
nebulaMgr: nebulaMgr,
|
||||
driveMgr: driveMgr,
|
||||
pluginMgr: pluginMgr,
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
s.registerRoutes()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.mux
|
||||
}
|
||||
|
||||
func (s *Server) registerRoutes() {
|
||||
s.mux.HandleFunc("/api/status", s.handleStatus)
|
||||
s.mux.HandleFunc("/api/setup", s.handleSetup)
|
||||
s.mux.HandleFunc("/api/login", s.handleLogin)
|
||||
s.mux.HandleFunc("/api/pair", s.handlePair)
|
||||
s.mux.HandleFunc("/api/users", s.handleUsers)
|
||||
s.mux.HandleFunc("/api/plugins", s.handlePlugins)
|
||||
s.mux.HandleFunc("/api/plugins/toggle", s.handlePluginToggle)
|
||||
s.mux.HandleFunc("/api/drive/files", s.handleDriveList)
|
||||
s.mux.HandleFunc("/api/drive/upload", s.handleDriveUpload)
|
||||
s.mux.HandleFunc("/api/drive/download", s.handleDriveDownload)
|
||||
s.mux.HandleFunc("/api/drive/folder", s.handleDriveFolder)
|
||||
s.mux.HandleFunc("/api/drive/delete", s.handleDriveDelete)
|
||||
s.mux.HandleFunc("/api/dns/logs", s.handleDNSLogs)
|
||||
}
|
||||
|
||||
func (s *Server) jsonResponse(w http.ResponseWriter, status int, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func (s *Server) jsonError(w http.ResponseWriter, status int, msg string) {
|
||||
s.jsonResponse(w, status, map[string]string{"error": msg})
|
||||
}
|
||||
|
||||
func (s *Server) authenticate(r *http.Request) (*auth.User, error) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
if token == "" {
|
||||
token = r.URL.Query().Get("token")
|
||||
}
|
||||
return s.authMgr.ValidateSession(token)
|
||||
}
|
||||
|
||||
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
var peers []*nebula.PeerInfo
|
||||
if s.nebulaMgr != nil {
|
||||
peers = s.nebulaMgr.GetPeers()
|
||||
}
|
||||
|
||||
var pluginList []*plugins.PluginStatus
|
||||
if s.pluginMgr != nil {
|
||||
pluginList = s.pluginMgr.ListPlugins()
|
||||
}
|
||||
|
||||
res := map[string]interface{}{
|
||||
"system": "benzcloud-server",
|
||||
"version": "v1.0",
|
||||
"setup_completed": s.cfg.SetupCompleted,
|
||||
"base_domain": s.cfg.BaseDomain,
|
||||
"server_local_ip": s.cfg.ServerLocalIP,
|
||||
"server_vpn_ip": s.cfg.ServerVPNIP,
|
||||
"http_port": s.cfg.HTTPPort,
|
||||
"dns_port": s.cfg.DNSPort,
|
||||
"vpn_port": s.cfg.VPNPort,
|
||||
"nebula_running": s.nebulaMgr != nil && s.nebulaMgr.IsRunning(),
|
||||
"mesh_peers": len(peers),
|
||||
"users_count": s.authMgr.UserCount(),
|
||||
"plugins": pluginList,
|
||||
"timestamp": time.Now().UTC(),
|
||||
}
|
||||
s.jsonResponse(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
s.jsonError(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
if s.cfg.SetupCompleted {
|
||||
s.jsonError(w, http.StatusBadRequest, "Setup is already completed")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
BaseDomain string `json:"base_domain"`
|
||||
AdminUsername string `json:"admin_username"`
|
||||
AdminPassword string `json:"admin_password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, "Invalid request payload")
|
||||
return
|
||||
}
|
||||
|
||||
if strings.TrimSpace(req.BaseDomain) == "" || strings.TrimSpace(req.AdminUsername) == "" || len(req.AdminPassword) < 8 {
|
||||
s.jsonError(w, http.StatusBadRequest, "Base domain, admin username and password (>= 8 chars) required")
|
||||
return
|
||||
}
|
||||
|
||||
cleanDomain := strings.ToLower(strings.Trim(req.BaseDomain, "."))
|
||||
s.cfg.BaseDomain = cleanDomain
|
||||
|
||||
// 1. Create Admin user
|
||||
adminPerms := auth.Permissions{
|
||||
Admin: true,
|
||||
Drive: true,
|
||||
Mail: true,
|
||||
Chat: true,
|
||||
Web: true,
|
||||
VPN: true,
|
||||
DNS: true,
|
||||
}
|
||||
adminUser, err := s.authMgr.CreateUser(req.AdminUsername, req.AdminPassword, adminPerms)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to create admin: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Initialize Nebula PKI
|
||||
if err := s.nebulaMgr.InitPKI(s.cfg.ServerVPNIP, s.cfg.ServerLocalIP, s.cfg.VPNPort); err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to initialize Nebula PKI: %v", err))
|
||||
return
|
||||
}
|
||||
_ = s.nebulaMgr.StartController()
|
||||
|
||||
// 3. Mark setup complete and save config
|
||||
s.cfg.SetupCompleted = true
|
||||
if err := s.cfg.Save(); err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to save config: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// 4. Log admin in
|
||||
session, err := s.authMgr.Authenticate(req.AdminUsername, req.AdminPassword)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, "Failed to authenticate new admin")
|
||||
return
|
||||
}
|
||||
|
||||
s.jsonResponse(w, http.StatusOK, map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "Setup completed successfully",
|
||||
"base_domain": cleanDomain,
|
||||
"admin_user": adminUser.Username,
|
||||
"session_token": session.Token,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
s.jsonError(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, "Invalid payload")
|
||||
return
|
||||
}
|
||||
|
||||
session, err := s.authMgr.Authenticate(req.Username, req.Password)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusUnauthorized, "Invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
user, _ := s.authMgr.ValidateSession(session.Token)
|
||||
|
||||
s.jsonResponse(w, http.StatusOK, map[string]interface{}{
|
||||
"token": session.Token,
|
||||
"user": user.Username,
|
||||
"permissions": user.Permissions,
|
||||
"overlay_ip": user.OverlayIP,
|
||||
"expires_at": session.ExpiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
s.jsonError(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, "Invalid payload")
|
||||
return
|
||||
}
|
||||
|
||||
session, err := s.authMgr.Authenticate(req.Username, req.Password)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusUnauthorized, "Pairing failed: Invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := s.authMgr.ValidateSession(session.Token)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, "User lookup failed")
|
||||
return
|
||||
}
|
||||
|
||||
certPEM, keyPEM, configYAML, err := s.nebulaMgr.IssueClientCert(
|
||||
user.Username,
|
||||
user.OverlayIP,
|
||||
s.cfg.ServerLocalIP,
|
||||
s.cfg.VPNPort,
|
||||
)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to issue client mesh certificate: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Pre-register peer in DNS if needed
|
||||
s.dnsSrv.RegisterSubdomain("peer-"+user.Username, user.OverlayIP)
|
||||
|
||||
s.jsonResponse(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "paired",
|
||||
"username": user.Username,
|
||||
"base_domain": s.cfg.BaseDomain,
|
||||
"overlay_ip": user.OverlayIP,
|
||||
"server_vpn_ip": s.cfg.ServerVPNIP,
|
||||
"cert_pem": string(certPEM),
|
||||
"key_pem": string(keyPEM),
|
||||
"client_config_yaml": string(configYAML),
|
||||
"session_token": session.Token,
|
||||
"permissions": user.Permissions,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleUsers(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Admin {
|
||||
s.jsonError(w, http.StatusForbidden, "Admin privileges required")
|
||||
return
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
users := s.authMgr.ListUsers()
|
||||
s.jsonResponse(w, http.StatusOK, map[string]interface{}{"users": users})
|
||||
case http.MethodPost:
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Permissions auth.Permissions `json:"permissions"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, "Invalid payload")
|
||||
return
|
||||
}
|
||||
user, err := s.authMgr.CreateUser(req.Username, req.Password, req.Permissions)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
s.jsonResponse(w, http.StatusCreated, user)
|
||||
case http.MethodPut:
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Permissions auth.Permissions `json:"permissions"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, "Invalid payload")
|
||||
return
|
||||
}
|
||||
if err := s.authMgr.UpdatePermissions(req.Username, req.Permissions); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
s.jsonResponse(w, http.StatusOK, map[string]bool{"success": true})
|
||||
default:
|
||||
s.jsonError(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handlePlugins(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusUnauthorized, "Unauthorized")
|
||||
return
|
||||
}
|
||||
_ = currentUser
|
||||
s.jsonResponse(w, http.StatusOK, map[string]interface{}{
|
||||
"plugins": s.pluginMgr.ListPlugins(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePluginToggle(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Admin {
|
||||
s.jsonError(w, http.StatusForbidden, "Admin privileges required")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, "Invalid payload")
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.pluginMgr.SetPluginEnabled(req.ID, req.Enabled); err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
s.jsonResponse(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleDriveList(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Drive {
|
||||
s.jsonError(w, http.StatusForbidden, "Drive access denied")
|
||||
return
|
||||
}
|
||||
|
||||
folder := r.URL.Query().Get("path")
|
||||
files, err := s.driveMgr.ListDirectory(currentUser.Username, folder)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
s.jsonResponse(w, http.StatusOK, map[string]interface{}{"files": files})
|
||||
}
|
||||
|
||||
func (s *Server) handleDriveUpload(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Drive {
|
||||
s.jsonError(w, http.StatusForbidden, "Drive access denied")
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
s.jsonError(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
path := r.URL.Query().Get("path")
|
||||
if path == "" {
|
||||
s.jsonError(w, http.StatusBadRequest, "Missing path parameter")
|
||||
return
|
||||
}
|
||||
|
||||
item, err := s.driveMgr.SaveFile(currentUser.Username, path, r.Body)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
s.jsonResponse(w, http.StatusOK, item)
|
||||
}
|
||||
|
||||
func (s *Server) handleDriveDownload(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Drive {
|
||||
s.jsonError(w, http.StatusForbidden, "Drive access denied")
|
||||
return
|
||||
}
|
||||
|
||||
path := r.URL.Query().Get("path")
|
||||
data, item, err := s.driveMgr.ReadFile(currentUser.Username, path)
|
||||
if err != nil {
|
||||
s.jsonError(w, http.StatusNotFound, "File not found")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", item.Name))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
func (s *Server) handleDriveFolder(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Drive {
|
||||
s.jsonError(w, http.StatusForbidden, "Drive access denied")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.jsonError(w, http.StatusBadRequest, "Invalid payload")
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.driveMgr.CreateFolder(currentUser.Username, req.Path); err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
s.jsonResponse(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleDriveDelete(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Drive {
|
||||
s.jsonError(w, http.StatusForbidden, "Drive access denied")
|
||||
return
|
||||
}
|
||||
|
||||
path := r.URL.Query().Get("path")
|
||||
if err := s.driveMgr.DeleteFile(currentUser.Username, path); err != nil {
|
||||
s.jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
s.jsonResponse(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleDNSLogs(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, err := s.authenticate(r)
|
||||
if err != nil || !currentUser.Permissions.Admin {
|
||||
s.jsonError(w, http.StatusForbidden, "Admin privileges required")
|
||||
return
|
||||
}
|
||||
logs := s.dnsSrv.GetQueryLog()
|
||||
s.jsonResponse(w, http.StatusOK, map[string]interface{}{"logs": logs})
|
||||
}
|
||||
|
||||
// Ensure unused import warnings are resolved
|
||||
var _ = io.EOF
|
||||
156
internal/core/api/api_test.go
Normal file
156
internal/core/api/api_test.go
Normal file
@ -0,0 +1,156 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/auth"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/config"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/crypto"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/dns"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/drive"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/nebula"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/plugins"
|
||||
)
|
||||
|
||||
func TestAPISetupAndPairing(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "benzcloud_api_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
cfg := config.DefaultConfig(tempDir)
|
||||
salt, _ := crypto.GenerateSalt(16)
|
||||
masterKey := crypto.DeriveKey("MasterTestKey123", salt)
|
||||
|
||||
authMgr, err := auth.NewManager(tempDir)
|
||||
if err != nil {
|
||||
t.Fatalf("auth.NewManager: %v", err)
|
||||
}
|
||||
|
||||
dnsSrv := dns.NewServer("intern", "10.42.0.1", 15354)
|
||||
nebulaMgr := nebula.NewManager(tempDir)
|
||||
driveMgr, err := drive.NewDriveManager(tempDir, masterKey)
|
||||
if err != nil {
|
||||
t.Fatalf("drive.NewDriveManager: %v", err)
|
||||
}
|
||||
pluginMgr := plugins.NewManager(tempDir, "intern", "token123")
|
||||
|
||||
apiServer := NewServer(cfg, authMgr, dnsSrv, nebulaMgr, driveMgr, pluginMgr)
|
||||
handler := apiServer.Handler()
|
||||
|
||||
// 1. Check /api/status before setup
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("Expected 200 on /api/status, got %d", rec.Code)
|
||||
}
|
||||
var statusResp map[string]interface{}
|
||||
_ = json.NewDecoder(rec.Body).Decode(&statusResp)
|
||||
if statusResp["setup_completed"] != false {
|
||||
t.Fatal("Expected setup_completed to be false")
|
||||
}
|
||||
|
||||
// 2. Perform /api/setup
|
||||
setupPayload := map[string]string{
|
||||
"base_domain": "benzjeremy.de",
|
||||
"admin_username": "admin",
|
||||
"admin_password": "SuperSecretAdminPassword2026!",
|
||||
}
|
||||
body, _ := json.Marshal(setupPayload)
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/setup", bytes.NewReader(body))
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("Expected 200 on /api/setup, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var setupResp map[string]interface{}
|
||||
_ = json.NewDecoder(rec.Body).Decode(&setupResp)
|
||||
adminToken := setupResp["session_token"].(string)
|
||||
|
||||
if cfg.BaseDomain != "benzjeremy.de" {
|
||||
t.Fatalf("Expected base_domain benzjeremy.de, got %s", cfg.BaseDomain)
|
||||
}
|
||||
if !cfg.SetupCompleted {
|
||||
t.Fatal("Expected SetupCompleted to be true")
|
||||
}
|
||||
|
||||
// 3. Client-Kopplung via /api/pair
|
||||
pairPayload := map[string]string{
|
||||
"username": "admin",
|
||||
"password": "SuperSecretAdminPassword2026!",
|
||||
}
|
||||
pairBody, _ := json.Marshal(pairPayload)
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/pair", bytes.NewReader(pairBody))
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("Expected 200 on /api/pair, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var pairResp map[string]interface{}
|
||||
_ = json.NewDecoder(rec.Body).Decode(&pairResp)
|
||||
if pairResp["status"] != "paired" {
|
||||
t.Fatalf("Expected status paired, got %v", pairResp["status"])
|
||||
}
|
||||
if pairResp["client_config_yaml"] == "" {
|
||||
t.Fatal("Expected non-empty client_config_yaml in pairing response")
|
||||
}
|
||||
|
||||
// 4. Test Drive Upload & Download via API
|
||||
fileContent := []byte("BenzCloud Enterprise Shared File via API")
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/drive/upload?path=report.txt", bytes.NewReader(fileContent))
|
||||
req.Header.Set("Authorization", "Bearer "+adminToken)
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("Drive upload failed with %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/drive/download?path=report.txt", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+adminToken)
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("Drive download failed with %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !bytes.Equal(rec.Body.Bytes(), fileContent) {
|
||||
t.Fatalf("Downloaded file mismatch: %s", rec.Body.String())
|
||||
}
|
||||
|
||||
// 5. Test User Creation and Invariant Enforcement
|
||||
userPayload := map[string]interface{}{
|
||||
"username": "charlie",
|
||||
"password": "CharliePassword2026!",
|
||||
"permissions": map[string]bool{
|
||||
"admin": false,
|
||||
"drive": true,
|
||||
"vpn": false, // Trying to revoke
|
||||
"dns": false, // Trying to revoke
|
||||
},
|
||||
}
|
||||
uBody, _ := json.Marshal(userPayload)
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/users", bytes.NewReader(uBody))
|
||||
req.Header.Set("Authorization", "Bearer "+adminToken)
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("Create user failed: %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var createdUser auth.User
|
||||
_ = json.NewDecoder(rec.Body).Decode(&createdUser)
|
||||
if !createdUser.Permissions.VPN || !createdUser.Permissions.DNS {
|
||||
t.Fatal("CRITICAL INVARIANT VIOLATION: Created user must have VPN and DNS set to true!")
|
||||
}
|
||||
}
|
||||
291
internal/core/auth/auth.go
Normal file
291
internal/core/auth/auth.go
Normal file
@ -0,0 +1,291 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/crypto"
|
||||
)
|
||||
|
||||
// Permissions defines user feature rights.
|
||||
// NOTE: VPN and DNS are ALWAYS active and cannot be revoked!
|
||||
type Permissions struct {
|
||||
Admin bool `json:"admin"`
|
||||
Drive bool `json:"drive"`
|
||||
Mail bool `json:"mail"`
|
||||
Chat bool `json:"chat"`
|
||||
Web bool `json:"web"`
|
||||
VPN bool `json:"vpn"` // Always true
|
||||
DNS bool `json:"dns"` // Always true
|
||||
}
|
||||
|
||||
// User represents a user account in benzcloud.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
PasswordHash string `json:"password_hash"`
|
||||
Salt string `json:"salt"`
|
||||
OverlayIP string `json:"overlay_ip"` // e.g. 10.42.0.2
|
||||
Permissions Permissions `json:"permissions"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastLogin time.Time `json:"last_login"`
|
||||
}
|
||||
|
||||
// HasVPN returns true always. VPN cannot be revoked.
|
||||
func (u *User) HasVPN() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// HasDNS returns true always. DNS cannot be revoked.
|
||||
func (u *User) HasDNS() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
dataDir string
|
||||
users map[string]*User // keyed by username
|
||||
sessions map[string]*Session // keyed by token
|
||||
nextIP int // counter for 10.42.0.X
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrUserAlreadyExists = errors.New("user already exists")
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
ErrSessionExpired = errors.New("session expired or invalid")
|
||||
)
|
||||
|
||||
// NewManager initializes the auth store.
|
||||
func NewManager(dataDir string) (*Manager, error) {
|
||||
m := &Manager{
|
||||
dataDir: dataDir,
|
||||
users: make(map[string]*User),
|
||||
sessions: make(map[string]*Session),
|
||||
nextIP: 2, // 1 is server (10.42.0.1)
|
||||
}
|
||||
|
||||
if err := m.load(); err != nil && !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("failed to load user database: %w", err)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m *Manager) dbPath() string {
|
||||
return filepath.Join(m.dataDir, "users.json")
|
||||
}
|
||||
|
||||
func (m *Manager) load() error {
|
||||
data, err := os.ReadFile(m.dbPath())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var stored struct {
|
||||
Users []*User `json:"users"`
|
||||
NextIP int `json:"next_ip"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &stored); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, u := range stored.Users {
|
||||
// Enforce invariant: VPN and DNS are always true
|
||||
u.Permissions.VPN = true
|
||||
u.Permissions.DNS = true
|
||||
m.users[u.Username] = u
|
||||
}
|
||||
if stored.NextIP > m.nextIP {
|
||||
m.nextIP = stored.NextIP
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) save() error {
|
||||
var userList []*User
|
||||
for _, u := range m.users {
|
||||
userList = append(userList, u)
|
||||
}
|
||||
|
||||
payload := struct {
|
||||
Users []*User `json:"users"`
|
||||
NextIP int `json:"next_ip"`
|
||||
}{
|
||||
Users: userList,
|
||||
NextIP: m.nextIP,
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(payload, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpFile := m.dbPath() + ".tmp"
|
||||
if err := os.WriteFile(tmpFile, data, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpFile, m.dbPath())
|
||||
}
|
||||
|
||||
// CreateUser creates a new user with PBKDF2-hashed password and assigns a Nebula Overlay IP.
|
||||
// The permissions for VPN and DNS will ALWAYS be set to true.
|
||||
func (m *Manager) CreateUser(username, password string, perms Permissions) (*User, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if _, exists := m.users[username]; exists {
|
||||
return nil, ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
saltBytes, err := crypto.GenerateSalt(16)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
key := crypto.DeriveKey(password, saltBytes)
|
||||
hashHex := hex.EncodeToString(key)
|
||||
saltHex := hex.EncodeToString(saltBytes)
|
||||
|
||||
// Invariant: VPN and DNS cannot be revoked
|
||||
perms.VPN = true
|
||||
perms.DNS = true
|
||||
|
||||
overlayIP := fmt.Sprintf("10.42.0.%d", m.nextIP)
|
||||
m.nextIP++
|
||||
|
||||
user := &User{
|
||||
ID: fmt.Sprintf("user_%d", time.Now().UnixNano()),
|
||||
Username: username,
|
||||
PasswordHash: hashHex,
|
||||
Salt: saltHex,
|
||||
OverlayIP: overlayIP,
|
||||
Permissions: perms,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
m.users[username] = user
|
||||
if err := m.save(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// Authenticate verifies password and returns a session token.
|
||||
func (m *Manager) Authenticate(username, password string) (*Session, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
user, exists := m.users[username]
|
||||
if !exists {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
saltBytes, err := hex.DecodeString(user.Salt)
|
||||
if err != nil {
|
||||
return nil, errors.New("corrupted salt")
|
||||
}
|
||||
|
||||
expectedHash, err := hex.DecodeString(user.PasswordHash)
|
||||
if err != nil {
|
||||
return nil, errors.New("corrupted hash")
|
||||
}
|
||||
|
||||
calculatedHash := crypto.DeriveKey(password, saltBytes)
|
||||
if !bytes.Equal(expectedHash, calculatedHash) {
|
||||
return nil, ErrInvalidPassword
|
||||
}
|
||||
|
||||
user.LastLogin = time.Now().UTC()
|
||||
_ = m.save()
|
||||
|
||||
token, err := crypto.GenerateToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
session := &Session{
|
||||
Token: token,
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
ExpiresAt: time.Now().UTC().Add(48 * time.Hour),
|
||||
}
|
||||
|
||||
m.sessions[token] = session
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// ValidateSession validates the token and returns the corresponding user.
|
||||
func (m *Manager) ValidateSession(token string) (*User, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
session, exists := m.sessions[token]
|
||||
if !exists || time.Now().UTC().After(session.ExpiresAt) {
|
||||
return nil, ErrSessionExpired
|
||||
}
|
||||
|
||||
user, exists := m.users[session.Username]
|
||||
if !exists {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// ListUsers returns a safe list of all users without sensitive hash/salt.
|
||||
func (m *Manager) ListUsers() []*User {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
var list []*User
|
||||
for _, u := range m.users {
|
||||
safeCopy := *u
|
||||
safeCopy.PasswordHash = ""
|
||||
safeCopy.Salt = ""
|
||||
// Invariant holds
|
||||
safeCopy.Permissions.VPN = true
|
||||
safeCopy.Permissions.DNS = true
|
||||
list = append(list, &safeCopy)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// UpdatePermissions updates user permissions, strictly preserving VPN and DNS.
|
||||
func (m *Manager) UpdatePermissions(username string, perms Permissions) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
user, exists := m.users[username]
|
||||
if !exists {
|
||||
return ErrUserNotFound
|
||||
}
|
||||
|
||||
// Always enforce: VPN and DNS are immutable
|
||||
perms.VPN = true
|
||||
perms.DNS = true
|
||||
user.Permissions = perms
|
||||
|
||||
return m.save()
|
||||
}
|
||||
|
||||
// UserCount returns total count of registered users.
|
||||
func (m *Manager) UserCount() int {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return len(m.users)
|
||||
}
|
||||
94
internal/core/auth/auth_test.go
Normal file
94
internal/core/auth/auth_test.go
Normal file
@ -0,0 +1,94 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAuthManager(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "benzcloud_auth_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
mgr, err := NewManager(tempDir)
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager failed: %v", err)
|
||||
}
|
||||
|
||||
// 1. Create admin user
|
||||
adminPerms := Permissions{Admin: true, Drive: true, Mail: true, Chat: true, Web: true}
|
||||
admin, err := mgr.CreateUser("admin", "AdminSecret123!", adminPerms)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser admin failed: %v", err)
|
||||
}
|
||||
if !admin.Permissions.VPN || !admin.Permissions.DNS {
|
||||
t.Fatal("Admin must have VPN and DNS active")
|
||||
}
|
||||
if admin.OverlayIP != "10.42.0.2" {
|
||||
t.Fatalf("Expected admin overlay IP 10.42.0.2, got %s", admin.OverlayIP)
|
||||
}
|
||||
|
||||
// 2. Authenticate
|
||||
sess, err := mgr.Authenticate("admin", "AdminSecret123!")
|
||||
if err != nil {
|
||||
t.Fatalf("Authenticate failed: %v", err)
|
||||
}
|
||||
if len(sess.Token) != 64 {
|
||||
t.Fatalf("Expected 64-char token, got %d", len(sess.Token))
|
||||
}
|
||||
|
||||
// 3. Validate Session
|
||||
valUser, err := mgr.ValidateSession(sess.Token)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateSession failed: %v", err)
|
||||
}
|
||||
if valUser.Username != "admin" {
|
||||
t.Fatalf("Expected username admin, got %s", valUser.Username)
|
||||
}
|
||||
|
||||
// 4. Create regular user and attempt to revoke VPN/DNS
|
||||
restrictedPerms := Permissions{
|
||||
Admin: false,
|
||||
Drive: false,
|
||||
Mail: false,
|
||||
Chat: false,
|
||||
Web: false,
|
||||
VPN: false, // Try to revoke
|
||||
DNS: false, // Try to revoke
|
||||
}
|
||||
user2, err := mgr.CreateUser("worker", "WorkerSecret123!", restrictedPerms)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser worker failed: %v", err)
|
||||
}
|
||||
// Verify invariant: VPN & DNS MUST remain true!
|
||||
if !user2.Permissions.VPN || !user2.Permissions.DNS {
|
||||
t.Fatal("CRITICAL INVARIANT VIOLATED: VPN and DNS permissions must remain true even when requested false")
|
||||
}
|
||||
|
||||
// 5. Try updating permissions to revoke VPN/DNS
|
||||
err = mgr.UpdatePermissions("worker", Permissions{VPN: false, DNS: false})
|
||||
if err != nil {
|
||||
t.Fatalf("UpdatePermissions failed: %v", err)
|
||||
}
|
||||
workerUpdated, _ := mgr.ValidateSession("")
|
||||
_ = workerUpdated
|
||||
list := mgr.ListUsers()
|
||||
for _, u := range list {
|
||||
if u.Username == "worker" {
|
||||
if !u.Permissions.VPN || !u.Permissions.DNS {
|
||||
t.Fatal("CRITICAL INVARIANT VIOLATED: VPN and DNS permissions must remain true after UpdatePermissions")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Reload from disk and verify persistence
|
||||
mgr2, err := NewManager(tempDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Reloading manager failed: %v", err)
|
||||
}
|
||||
if mgr2.UserCount() != 2 {
|
||||
t.Fatalf("Expected 2 users after reload, got %d", mgr2.UserCount())
|
||||
}
|
||||
}
|
||||
105
internal/core/config/config.go
Normal file
105
internal/core/config/config.go
Normal file
@ -0,0 +1,105 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Config holds the complete state and configuration for benzcloud-server.
|
||||
type Config struct {
|
||||
BaseDomain string `json:"base_domain"` // e.g. benzjeremy.de or intern
|
||||
ServerLocalIP string `json:"server_local_ip"` // LAN IP, e.g. 192.168.0.5
|
||||
HTTPPort int `json:"http_port"` // default 8080
|
||||
DNSPort int `json:"dns_port"` // default 53 (or 5353 fallback)
|
||||
VPNPort int `json:"vpn_port"` // default 4242 (UDP)
|
||||
OverlaySubnet string `json:"overlay_subnet"` // e.g. 10.42.0.0/16
|
||||
ServerVPNIP string `json:"server_vpn_ip"` // e.g. 10.42.0.1
|
||||
SetupCompleted bool `json:"setup_completed"`
|
||||
DataDir string `json:"data_dir"`
|
||||
MasterSalt string `json:"master_salt"` // hex encoded salt for PBKDF2
|
||||
ServerToken string `json:"server_token"` // 32-byte CSPRNG token
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
var ErrNotConfigured = errors.New("benzcloud-server is not configured yet (setup pending)")
|
||||
|
||||
// DefaultConfig returns reasonable default settings.
|
||||
func DefaultConfig(dataDir string) *Config {
|
||||
localIP := detectLocalIP()
|
||||
return &Config{
|
||||
BaseDomain: "intern",
|
||||
ServerLocalIP: localIP,
|
||||
HTTPPort: 8080,
|
||||
DNSPort: 53,
|
||||
VPNPort: 4242,
|
||||
OverlaySubnet: "10.42.0.0/16",
|
||||
ServerVPNIP: "10.42.0.1",
|
||||
SetupCompleted: false,
|
||||
DataDir: dataDir,
|
||||
}
|
||||
}
|
||||
|
||||
// detectLocalIP tries to determine the active outbound LAN IP address.
|
||||
func detectLocalIP() string {
|
||||
conn, err := net.Dial("udp", "8.8.8.8:80")
|
||||
if err != nil {
|
||||
return "127.0.0.1"
|
||||
}
|
||||
defer conn.Close()
|
||||
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
||||
return localAddr.IP.String()
|
||||
}
|
||||
|
||||
// ConfigPath returns the path to config.json inside dataDir.
|
||||
func (c *Config) ConfigPath() string {
|
||||
return filepath.Join(c.DataDir, "config.json")
|
||||
}
|
||||
|
||||
// Save persists the configuration to disk with secure 0600 permissions.
|
||||
func (c *Config) Save() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if err := os.MkdirAll(c.DataDir, 0700); err != nil {
|
||||
return fmt.Errorf("failed to create data dir: %w", err)
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(c, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal config: %w", err)
|
||||
}
|
||||
|
||||
tmpFile := c.ConfigPath() + ".tmp"
|
||||
if err := os.WriteFile(tmpFile, data, 0600); err != nil {
|
||||
return fmt.Errorf("failed to write tmp config: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(tmpFile, c.ConfigPath()); err != nil {
|
||||
return fmt.Errorf("failed to commit config file: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Load loads the configuration from dataDir.
|
||||
func Load(dataDir string) (*Config, error) {
|
||||
cfgPath := filepath.Join(dataDir, "config.json")
|
||||
data, err := os.ReadFile(cfgPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return DefaultConfig(dataDir), ErrNotConfigured
|
||||
}
|
||||
return nil, fmt.Errorf("failed to read config file: %w", err)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
|
||||
}
|
||||
cfg.DataDir = dataDir
|
||||
return &cfg, nil
|
||||
}
|
||||
105
internal/core/crypto/crypto.go
Normal file
105
internal/core/crypto/crypto.go
Normal file
@ -0,0 +1,105 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
const (
|
||||
// PBKDF2Iterations defines the mandatory 100,000 rounds of PBKDF2 key derivation.
|
||||
PBKDF2Iterations = 100000
|
||||
// KeyLength is 32 bytes for AES-256.
|
||||
KeyLength = 32
|
||||
// SaltLength is 16 bytes minimum.
|
||||
SaltLength = 16
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCiphertextTooShort = errors.New("ciphertext too short")
|
||||
ErrDecryptionFailed = errors.New("decryption failed or corrupted data")
|
||||
)
|
||||
|
||||
// DeriveKey derives a 32-byte AES-256 key from a passphrase and salt using PBKDF2 with 100,000 iterations.
|
||||
func DeriveKey(passphrase string, salt []byte) []byte {
|
||||
return pbkdf2.Key([]byte(passphrase), salt, PBKDF2Iterations, KeyLength, sha256.New)
|
||||
}
|
||||
|
||||
// GenerateSalt creates a cryptographically secure random salt of the specified length.
|
||||
func GenerateSalt(length int) ([]byte, error) {
|
||||
if length < SaltLength {
|
||||
length = SaltLength
|
||||
}
|
||||
salt := make([]byte, length)
|
||||
if _, err := io.ReadFull(rand.Reader, salt); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate random salt: %w", err)
|
||||
}
|
||||
return salt, nil
|
||||
}
|
||||
|
||||
// GenerateToken generates a cryptographically random 32-byte hex token.
|
||||
func GenerateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
return "", fmt.Errorf("failed to generate token: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// Encrypt encrypts plaintext using AES-256-GCM with a random 12-byte nonce.
|
||||
// The output format is: [nonce (12 bytes)] + [ciphertext + 16-byte auth tag].
|
||||
func Encrypt(key, plaintext []byte) ([]byte, error) {
|
||||
if len(key) != KeyLength {
|
||||
return nil, fmt.Errorf("invalid key length: must be %d bytes", KeyLength)
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create cipher block: %w", err)
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create GCM: %w", err)
|
||||
}
|
||||
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate nonce: %w", err)
|
||||
}
|
||||
|
||||
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
// Decrypt decrypts AES-256-GCM ciphertext created by Encrypt.
|
||||
func Decrypt(key, ciphertext []byte) ([]byte, error) {
|
||||
if len(key) != KeyLength {
|
||||
return nil, fmt.Errorf("invalid key length: must be %d bytes", KeyLength)
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create cipher block: %w", err)
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create GCM: %w", err)
|
||||
}
|
||||
|
||||
nonceSize := gcm.NonceSize()
|
||||
if len(ciphertext) < nonceSize {
|
||||
return nil, ErrCiphertextTooShort
|
||||
}
|
||||
|
||||
nonce, actualCiphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||||
plaintext, err := gcm.Open(nil, nonce, actualCiphertext, nil)
|
||||
if err != nil {
|
||||
return nil, ErrDecryptionFailed
|
||||
}
|
||||
return plaintext, nil
|
||||
}
|
||||
59
internal/core/crypto/crypto_test.go
Normal file
59
internal/core/crypto/crypto_test.go
Normal file
@ -0,0 +1,59 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCryptoRoundtrip(t *testing.T) {
|
||||
passphrase := "SecureAdminPassphrase2026!#"
|
||||
salt, err := GenerateSalt(16)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSalt failed: %v", err)
|
||||
}
|
||||
|
||||
key := DeriveKey(passphrase, salt)
|
||||
if len(key) != 32 {
|
||||
t.Fatalf("Expected key length 32, got %d", len(key))
|
||||
}
|
||||
|
||||
original := []byte("BenzCloud Confidential Enterprise Secret Payload")
|
||||
encrypted, err := Encrypt(key, original)
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
|
||||
decrypted, err := Decrypt(key, encrypted)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt failed: %v", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(original, decrypted) {
|
||||
t.Fatalf("Decrypted content mismatch: got %s, want %s", string(decrypted), string(original))
|
||||
}
|
||||
|
||||
// Tampering test
|
||||
encrypted[len(encrypted)-1] ^= 0x01
|
||||
_, err = Decrypt(key, encrypted)
|
||||
if err == nil {
|
||||
t.Fatal("Expected error when decrypting tampered data, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateToken(t *testing.T) {
|
||||
token1, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken failed: %v", err)
|
||||
}
|
||||
if len(token1) != 64 { // 32 bytes in hex = 64 characters
|
||||
t.Fatalf("Expected token length 64, got %d", len(token1))
|
||||
}
|
||||
|
||||
token2, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken failed: %v", err)
|
||||
}
|
||||
if token1 == token2 {
|
||||
t.Fatal("Tokens should be unique")
|
||||
}
|
||||
}
|
||||
283
internal/core/dns/dns.go
Normal file
283
internal/core/dns/dns.go
Normal file
@ -0,0 +1,283 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// QueryLogEntry records a DNS query for the live dashboard.
|
||||
type QueryLogEntry struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
ClientIP string `json:"client_ip"`
|
||||
Domain string `json:"domain"`
|
||||
Type string `json:"type"`
|
||||
Answer string `json:"answer"`
|
||||
Forwarded bool `json:"forwarded"`
|
||||
}
|
||||
|
||||
// Server is the built-in lightweight DNS server.
|
||||
type Server struct {
|
||||
baseDomain string
|
||||
targetIP string
|
||||
listenPort int
|
||||
records map[string]string // FQDN (lowercase, ending in dot) -> IP
|
||||
upstreams []string
|
||||
queryLog []QueryLogEntry
|
||||
maxLogSize int
|
||||
udpServer *dns.Server
|
||||
tcpServer *dns.Server
|
||||
running bool
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewServer creates a new DNS server instance.
|
||||
func NewServer(baseDomain, targetIP string, listenPort int) *Server {
|
||||
cleanBase := strings.Trim(baseDomain, ".")
|
||||
s := &Server{
|
||||
baseDomain: cleanBase,
|
||||
targetIP: targetIP,
|
||||
listenPort: listenPort,
|
||||
records: make(map[string]string),
|
||||
upstreams: []string{"9.9.9.9:53", "1.1.1.1:53"},
|
||||
queryLog: make([]QueryLogEntry, 0, 500),
|
||||
maxLogSize: 500,
|
||||
}
|
||||
|
||||
// Pre-seed system subdomains
|
||||
s.registerDefaultRecords()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) registerDefaultRecords() {
|
||||
domainDot := strings.ToLower(s.baseDomain) + "."
|
||||
// Root domain
|
||||
s.records[domainDot] = s.targetIP
|
||||
// System subdomains
|
||||
s.records["vpn."+domainDot] = s.targetIP
|
||||
s.records["drive."+domainDot] = s.targetIP
|
||||
s.records["mail."+domainDot] = s.targetIP
|
||||
s.records["chat."+domainDot] = s.targetIP
|
||||
}
|
||||
|
||||
// RegisterSubdomain dynamically registers a custom subdomain.
|
||||
// E.g. sub="blog", ip="10.42.0.1" -> blog.<domain>.
|
||||
func (s *Server) RegisterSubdomain(sub, ip string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
fqdn := strings.ToLower(sub) + "." + strings.ToLower(s.baseDomain) + "."
|
||||
s.records[fqdn] = ip
|
||||
}
|
||||
|
||||
// UnregisterSubdomain removes a custom subdomain.
|
||||
func (s *Server) UnregisterSubdomain(sub string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
fqdn := strings.ToLower(sub) + "." + strings.ToLower(s.baseDomain) + "."
|
||||
delete(s.records, fqdn)
|
||||
}
|
||||
|
||||
// GetRecords returns a snapshot of all registered DNS records.
|
||||
func (s *Server) GetRecords() map[string]string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
res := make(map[string]string, len(s.records))
|
||||
for k, v := range s.records {
|
||||
res[k] = v
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// GetQueryLog returns the recent DNS queries.
|
||||
func (s *Server) GetQueryLog() []QueryLogEntry {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
entries := make([]QueryLogEntry, len(s.queryLog))
|
||||
copy(entries, s.queryLog)
|
||||
return entries
|
||||
}
|
||||
|
||||
func (s *Server) logQuery(entry QueryLogEntry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.queryLog) >= s.maxLogSize {
|
||||
s.queryLog = s.queryLog[1:]
|
||||
}
|
||||
s.queryLog = append(s.queryLog, entry)
|
||||
}
|
||||
|
||||
// ServeDNS handles incoming DNS requests.
|
||||
func (s *Server) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||
msg := new(dns.Msg)
|
||||
msg.SetReply(r)
|
||||
msg.Authoritative = true
|
||||
msg.RecursionAvailable = true
|
||||
|
||||
clientIP, _, _ := net.SplitHostPort(w.RemoteAddr().String())
|
||||
|
||||
for _, q := range r.Question {
|
||||
qName := strings.ToLower(q.Name)
|
||||
qType := dns.TypeToString[q.Qtype]
|
||||
|
||||
s.mu.RLock()
|
||||
ip, isLocal := s.records[qName]
|
||||
baseMatch := strings.HasSuffix(qName, strings.ToLower(s.baseDomain)+".")
|
||||
s.mu.RUnlock()
|
||||
|
||||
if isLocal {
|
||||
if q.Qtype == dns.TypeA || q.Qtype == dns.TypeANY {
|
||||
parsedIP := net.ParseIP(ip)
|
||||
if parsedIP != nil {
|
||||
rr := &dns.A{
|
||||
Hdr: dns.RR_Header{
|
||||
Name: q.Name,
|
||||
Rrtype: dns.TypeA,
|
||||
Class: dns.ClassINET,
|
||||
Ttl: 60,
|
||||
},
|
||||
A: parsedIP.To4(),
|
||||
}
|
||||
msg.Answer = append(msg.Answer, rr)
|
||||
}
|
||||
}
|
||||
s.logQuery(QueryLogEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
ClientIP: clientIP,
|
||||
Domain: q.Name,
|
||||
Type: qType,
|
||||
Answer: ip,
|
||||
Forwarded: false,
|
||||
})
|
||||
} else if baseMatch {
|
||||
// Subdomain not found under base domain -> NXDOMAIN
|
||||
msg.Rcode = dns.RcodeNameError
|
||||
s.logQuery(QueryLogEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
ClientIP: clientIP,
|
||||
Domain: q.Name,
|
||||
Type: qType,
|
||||
Answer: "NXDOMAIN",
|
||||
Forwarded: false,
|
||||
})
|
||||
} else {
|
||||
// External query -> forward to upstream resolver
|
||||
upstreamResp, err := s.forwardQuery(r)
|
||||
if err == nil && upstreamResp != nil {
|
||||
_ = w.WriteMsg(upstreamResp)
|
||||
var ansStr string
|
||||
if len(upstreamResp.Answer) > 0 {
|
||||
ansStr = upstreamResp.Answer[0].String()
|
||||
}
|
||||
s.logQuery(QueryLogEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
ClientIP: clientIP,
|
||||
Domain: q.Name,
|
||||
Type: qType,
|
||||
Answer: ansStr,
|
||||
Forwarded: true,
|
||||
})
|
||||
return
|
||||
}
|
||||
msg.Rcode = dns.RcodeServerFailure
|
||||
}
|
||||
}
|
||||
|
||||
_ = w.WriteMsg(msg)
|
||||
}
|
||||
|
||||
func (s *Server) forwardQuery(r *dns.Msg) (*dns.Msg, error) {
|
||||
c := new(dns.Client)
|
||||
c.Timeout = 2 * time.Second
|
||||
|
||||
for _, upstream := range s.upstreams {
|
||||
resp, _, err := c.Exchange(r, upstream)
|
||||
if err == nil && resp != nil {
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("all upstream resolvers failed")
|
||||
}
|
||||
|
||||
// Start launches the UDP and TCP listeners.
|
||||
func (s *Server) Start() error {
|
||||
s.mu.Lock()
|
||||
if s.running {
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
s.running = true
|
||||
listenAddr := fmt.Sprintf("0.0.0.0:%d", s.listenPort)
|
||||
s.mu.Unlock()
|
||||
|
||||
udpHandler := dns.NewServeMux()
|
||||
udpHandler.HandleFunc(".", s.ServeDNS)
|
||||
s.udpServer = &dns.Server{
|
||||
Addr: listenAddr,
|
||||
Net: "udp",
|
||||
Handler: udpHandler,
|
||||
}
|
||||
|
||||
tcpHandler := dns.NewServeMux()
|
||||
tcpHandler.HandleFunc(".", s.ServeDNS)
|
||||
s.tcpServer = &dns.Server{
|
||||
Addr: listenAddr,
|
||||
Net: "tcp",
|
||||
Handler: tcpHandler,
|
||||
}
|
||||
|
||||
errChan := make(chan error, 2)
|
||||
|
||||
go func() {
|
||||
if err := s.udpServer.ListenAndServe(); err != nil {
|
||||
errChan <- fmt.Errorf("DNS UDP failed: %w", err)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
if err := s.tcpServer.ListenAndServe(); err != nil {
|
||||
errChan <- fmt.Errorf("DNS TCP failed: %w", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Brief wait to detect immediate bind failures (e.g. port already in use or permission denied)
|
||||
select {
|
||||
case err := <-errChan:
|
||||
_ = s.Stop()
|
||||
return err
|
||||
case <-time.After(150 * time.Millisecond):
|
||||
log.Printf("[BenzCloud DNS] Server actively listening on %s (UDP & TCP)", listenAddr)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Stop gracefully shuts down DNS listeners.
|
||||
func (s *Server) Stop() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !s.running {
|
||||
return nil
|
||||
}
|
||||
s.running = false
|
||||
|
||||
var errs []string
|
||||
if s.udpServer != nil {
|
||||
if err := s.udpServer.ShutdownContext(context.Background()); err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
}
|
||||
}
|
||||
if s.tcpServer != nil {
|
||||
if err := s.tcpServer.ShutdownContext(context.Background()); err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
}
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
return fmt.Errorf("errors stopping DNS: %s", strings.Join(errs, ", "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
75
internal/core/dns/dns_test.go
Normal file
75
internal/core/dns/dns_test.go
Normal file
@ -0,0 +1,75 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
func TestDNSServerResolution(t *testing.T) {
|
||||
testPort := 15353
|
||||
baseDomain := "benzjeremy.de"
|
||||
targetIP := "10.42.0.1"
|
||||
|
||||
srv := NewServer(baseDomain, targetIP, testPort)
|
||||
if err := srv.Start(); err != nil {
|
||||
t.Fatalf("Failed to start DNS server on port %d: %v", testPort, err)
|
||||
}
|
||||
defer srv.Stop()
|
||||
|
||||
// Give server time to bind
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
c := new(dns.Client)
|
||||
|
||||
// Test 1: Query drive.benzjeremy.de
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion("drive.benzjeremy.de.", dns.TypeA)
|
||||
in, _, err := c.Exchange(m, "127.0.0.1:15353")
|
||||
if err != nil {
|
||||
t.Fatalf("DNS query failed: %v", err)
|
||||
}
|
||||
if len(in.Answer) == 0 {
|
||||
t.Fatal("Expected at least 1 answer for drive.benzjeremy.de, got 0")
|
||||
}
|
||||
if aRec, ok := in.Answer[0].(*dns.A); !ok || aRec.A.String() != targetIP {
|
||||
t.Fatalf("Expected IP %s, got %v", targetIP, in.Answer[0])
|
||||
}
|
||||
|
||||
// Test 2: Register custom subdomain and query it
|
||||
srv.RegisterSubdomain("mein-shop", "10.42.0.1")
|
||||
m2 := new(dns.Msg)
|
||||
m2.SetQuestion("mein-shop.benzjeremy.de.", dns.TypeA)
|
||||
in2, _, err := c.Exchange(m2, "127.0.0.1:15353")
|
||||
if err != nil {
|
||||
t.Fatalf("Custom subdomain query failed: %v", err)
|
||||
}
|
||||
if len(in2.Answer) == 0 {
|
||||
t.Fatal("Expected answer for mein-shop.benzjeremy.de")
|
||||
}
|
||||
if aRec, ok := in2.Answer[0].(*dns.A); !ok || aRec.A.String() != targetIP {
|
||||
t.Fatalf("Expected IP %s, got %v", targetIP, in2.Answer[0])
|
||||
}
|
||||
|
||||
// Test 3: Query unknown subdomain under base domain -> NXDOMAIN
|
||||
m3 := new(dns.Msg)
|
||||
m3.SetQuestion("gibtsnicht.benzjeremy.de.", dns.TypeA)
|
||||
in3, _, err := c.Exchange(m3, "127.0.0.1:15353")
|
||||
if err != nil {
|
||||
t.Fatalf("NXDOMAIN query failed: %v", err)
|
||||
}
|
||||
if in3.Rcode != dns.RcodeNameError {
|
||||
t.Fatalf("Expected RcodeNameError, got %d", in3.Rcode)
|
||||
}
|
||||
|
||||
// Test 4: Query log contains entries
|
||||
logs := srv.GetQueryLog()
|
||||
if len(logs) < 3 {
|
||||
t.Fatalf("Expected at least 3 query log entries, got %d", len(logs))
|
||||
}
|
||||
if !strings.Contains(logs[0].Domain, "drive.benzjeremy.de") {
|
||||
t.Fatalf("Unexpected first query in log: %s", logs[0].Domain)
|
||||
}
|
||||
}
|
||||
227
internal/core/drive/drive.go
Normal file
227
internal/core/drive/drive.go
Normal file
@ -0,0 +1,227 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/crypto"
|
||||
)
|
||||
|
||||
// FileItem represents a file or folder in the user's cloud drive.
|
||||
type FileItem struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"` // relative path from user root, e.g. "documents/invoice.pdf"
|
||||
Size int64 `json:"size"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
ModTime time.Time `json:"mod_time"`
|
||||
SHA256 string `json:"sha256,omitempty"`
|
||||
}
|
||||
|
||||
type DriveManager struct {
|
||||
baseDir string
|
||||
masterKey []byte
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
var (
|
||||
ErrInvalidPath = errors.New("invalid or illegal file path")
|
||||
ErrFileNotFound = errors.New("file or directory not found")
|
||||
)
|
||||
|
||||
// NewDriveManager creates a file manager with encrypted storage at rest.
|
||||
func NewDriveManager(baseDir string, masterKey []byte) (*DriveManager, error) {
|
||||
drivePath := filepath.Join(baseDir, "drive")
|
||||
if err := os.MkdirAll(drivePath, 0700); err != nil {
|
||||
return nil, fmt.Errorf("failed to create drive directory: %w", err)
|
||||
}
|
||||
return &DriveManager{
|
||||
baseDir: drivePath,
|
||||
masterKey: masterKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (dm *DriveManager) userDir(username string) string {
|
||||
safeUser := filepath.Clean(username)
|
||||
safeUser = strings.ReplaceAll(safeUser, "/", "_")
|
||||
safeUser = strings.ReplaceAll(safeUser, "\\", "_")
|
||||
return filepath.Join(dm.baseDir, safeUser)
|
||||
}
|
||||
|
||||
func (dm *DriveManager) resolvePath(username, relPath string) (string, error) {
|
||||
uDir := dm.userDir(username)
|
||||
cleanRel := filepath.Clean(strings.TrimPrefix(relPath, "/"))
|
||||
if strings.HasPrefix(cleanRel, "..") || strings.Contains(cleanRel, "/../") {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
target := filepath.Join(uDir, cleanRel)
|
||||
if !strings.HasPrefix(target, uDir) {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
// ListDirectory returns the list of files and folders in the specified folder.
|
||||
func (dm *DriveManager) ListDirectory(username, folderPath string) ([]FileItem, error) {
|
||||
dm.mu.RLock()
|
||||
defer dm.mu.RUnlock()
|
||||
|
||||
target, err := dm.resolvePath(username, folderPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(target, 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var items []FileItem
|
||||
uDir := dm.userDir(username)
|
||||
|
||||
for _, e := range entries {
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
full := filepath.Join(target, e.Name())
|
||||
rel, _ := filepath.Rel(uDir, full)
|
||||
|
||||
items = append(items, FileItem{
|
||||
Name: e.Name(),
|
||||
Path: filepath.ToSlash(rel),
|
||||
Size: info.Size(),
|
||||
IsDir: e.IsDir(),
|
||||
ModTime: info.ModTime().UTC(),
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// SaveFile saves plaintext content to encrypted storage on disk.
|
||||
func (dm *DriveManager) SaveFile(username, relPath string, r io.Reader) (*FileItem, error) {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
target, err := dm.resolvePath(username, relPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rawBytes, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hasher := sha256.New()
|
||||
hasher.Write(rawBytes)
|
||||
hashHex := hex.EncodeToString(hasher.Sum(nil))
|
||||
|
||||
// Encrypt at rest using AES-256-GCM
|
||||
encrypted, err := crypto.Encrypt(dm.masterKey, rawBytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encrypt file payload: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(target, encrypted, 0600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uDir := dm.userDir(username)
|
||||
rel, _ := filepath.Rel(uDir, target)
|
||||
|
||||
return &FileItem{
|
||||
Name: filepath.Base(target),
|
||||
Path: filepath.ToSlash(rel),
|
||||
Size: int64(len(rawBytes)),
|
||||
IsDir: false,
|
||||
ModTime: time.Now().UTC(),
|
||||
SHA256: hashHex,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ReadFile decrypts and returns the content of the file.
|
||||
func (dm *DriveManager) ReadFile(username, relPath string) ([]byte, *FileItem, error) {
|
||||
dm.mu.RLock()
|
||||
defer dm.mu.RUnlock()
|
||||
|
||||
target, err := dm.resolvePath(username, relPath)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
encrypted, err := os.ReadFile(target)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil, ErrFileNotFound
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
decrypted, err := crypto.Decrypt(dm.masterKey, encrypted)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to decrypt file at rest: %w", err)
|
||||
}
|
||||
|
||||
info, err := os.Stat(target)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hasher := sha256.New()
|
||||
hasher.Write(decrypted)
|
||||
hashHex := hex.EncodeToString(hasher.Sum(nil))
|
||||
|
||||
uDir := dm.userDir(username)
|
||||
rel, _ := filepath.Rel(uDir, target)
|
||||
|
||||
item := &FileItem{
|
||||
Name: filepath.Base(target),
|
||||
Path: filepath.ToSlash(rel),
|
||||
Size: int64(len(decrypted)),
|
||||
IsDir: false,
|
||||
ModTime: info.ModTime().UTC(),
|
||||
SHA256: hashHex,
|
||||
}
|
||||
|
||||
return decrypted, item, nil
|
||||
}
|
||||
|
||||
// DeleteFile removes a file or directory.
|
||||
func (dm *DriveManager) DeleteFile(username, relPath string) error {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
target, err := dm.resolvePath(username, relPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(target)
|
||||
}
|
||||
|
||||
// CreateFolder creates a directory.
|
||||
func (dm *DriveManager) CreateFolder(username, relPath string) error {
|
||||
dm.mu.Lock()
|
||||
defer dm.mu.Unlock()
|
||||
|
||||
target, err := dm.resolvePath(username, relPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.MkdirAll(target, 0700)
|
||||
}
|
||||
83
internal/core/drive/drive_test.go
Normal file
83
internal/core/drive/drive_test.go
Normal file
@ -0,0 +1,83 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/crypto"
|
||||
)
|
||||
|
||||
func TestDriveManager(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "benzcloud_drive_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
salt, _ := crypto.GenerateSalt(16)
|
||||
masterKey := crypto.DeriveKey("MasterSecretDriveKey2026", salt)
|
||||
|
||||
dm, err := NewDriveManager(tempDir, masterKey)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDriveManager failed: %v", err)
|
||||
}
|
||||
|
||||
username := "jeremy"
|
||||
content := []byte("Strictly Confidential Cloud Document: Project BenzCloud Architecture")
|
||||
|
||||
// 1. Save file
|
||||
item, err := dm.SaveFile(username, "docs/architecture.txt", bytes.NewReader(content))
|
||||
if err != nil {
|
||||
t.Fatalf("SaveFile failed: %v", err)
|
||||
}
|
||||
if item.Name != "architecture.txt" {
|
||||
t.Fatalf("Expected file name architecture.txt, got %s", item.Name)
|
||||
}
|
||||
|
||||
// Verify encryption on physical disk
|
||||
rawOnDisk, err := os.ReadFile(filepath.Join(tempDir, "drive", username, "docs", "architecture.txt"))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read raw file from disk: %v", err)
|
||||
}
|
||||
if bytes.Contains(rawOnDisk, content) {
|
||||
t.Fatal("SECURITY BUG: Raw disk content contains unencrypted plaintext!")
|
||||
}
|
||||
|
||||
// 2. Read and decrypt file
|
||||
decrypted, readItem, err := dm.ReadFile(username, "docs/architecture.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile failed: %v", err)
|
||||
}
|
||||
if !bytes.Equal(content, decrypted) {
|
||||
t.Fatalf("Decrypted content mismatch: got %s, want %s", string(decrypted), string(content))
|
||||
}
|
||||
if readItem.SHA256 != item.SHA256 {
|
||||
t.Fatalf("SHA256 checksum mismatch: %s vs %s", readItem.SHA256, item.SHA256)
|
||||
}
|
||||
|
||||
// 3. List directory
|
||||
files, err := dm.ListDirectory(username, "docs")
|
||||
if err != nil {
|
||||
t.Fatalf("ListDirectory failed: %v", err)
|
||||
}
|
||||
if len(files) != 1 {
|
||||
t.Fatalf("Expected 1 file in docs, got %d", len(files))
|
||||
}
|
||||
|
||||
// 4. Path traversal test
|
||||
_, _, err = dm.ReadFile(username, "../../etc/passwd")
|
||||
if err == nil {
|
||||
t.Fatal("SECURITY BUG: Path traversal did not return error!")
|
||||
}
|
||||
|
||||
// 5. Delete file
|
||||
if err := dm.DeleteFile(username, "docs/architecture.txt"); err != nil {
|
||||
t.Fatalf("DeleteFile failed: %v", err)
|
||||
}
|
||||
_, _, err = dm.ReadFile(username, "docs/architecture.txt")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error reading deleted file, got nil")
|
||||
}
|
||||
}
|
||||
399
internal/core/nebula/nebula.go
Normal file
399
internal/core/nebula/nebula.go
Normal file
@ -0,0 +1,399 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PeerInfo describes a node in the Nebula mesh network.
|
||||
type PeerInfo struct {
|
||||
Name string `json:"name"`
|
||||
OverlayIP string `json:"overlay_ip"` // e.g. 10.42.0.2
|
||||
IsServer bool `json:"is_server"`
|
||||
Connected bool `json:"connected"`
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
CertValidUntil time.Time `json:"cert_valid_until"`
|
||||
}
|
||||
|
||||
// Manager orchestrates the Nebula Mesh VPN, PKI, and configurations.
|
||||
type Manager struct {
|
||||
dataDir string
|
||||
caCertPath string
|
||||
caKeyPath string
|
||||
serverCertPath string
|
||||
serverKeyPath string
|
||||
serverConfigPath string
|
||||
peers map[string]*PeerInfo // keyed by OverlayIP
|
||||
running bool
|
||||
cmd *exec.Cmd
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
var (
|
||||
ErrCANotFound = errors.New("Nebula CA not initialized")
|
||||
ErrHostCertFailed = errors.New("failed to generate host certificate")
|
||||
)
|
||||
|
||||
// NewManager initializes the Nebula controller.
|
||||
func NewManager(dataDir string) *Manager {
|
||||
nebDir := filepath.Join(dataDir, "nebula")
|
||||
return &Manager{
|
||||
dataDir: nebDir,
|
||||
caCertPath: filepath.Join(nebDir, "ca.crt"),
|
||||
caKeyPath: filepath.Join(nebDir, "ca.key"),
|
||||
serverCertPath: filepath.Join(nebDir, "server.crt"),
|
||||
serverKeyPath: filepath.Join(nebDir, "server.key"),
|
||||
serverConfigPath: filepath.Join(nebDir, "config.yaml"),
|
||||
peers: make(map[string]*PeerInfo),
|
||||
}
|
||||
}
|
||||
|
||||
// InitPKI generates the Certificate Authority and server lighthouse certificate.
|
||||
func (m *Manager) InitPKI(serverOverlayIP, serverLocalIP string, vpnPort int) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if err := os.MkdirAll(m.dataDir, 0700); err != nil {
|
||||
return fmt.Errorf("failed to create nebula data dir: %w", err)
|
||||
}
|
||||
|
||||
// 1. Generate Root CA keypair if not exists
|
||||
if _, err := os.Stat(m.caCertPath); os.IsNotExist(err) {
|
||||
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate CA keypair: %w", err)
|
||||
}
|
||||
|
||||
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
caKeyPem := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
|
||||
if err := os.WriteFile(m.caKeyPath, caKeyPem, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pubBytes, err := x509.MarshalPKIXPublicKey(pub)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
caCertPem := pem.EncodeToMemory(&pem.Block{Type: "NEBULA CERTIFICATE AUTHORITY", Bytes: pubBytes})
|
||||
if err := os.WriteFile(m.caCertPath, caCertPem, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Generate Server/Lighthouse certificate if not exists
|
||||
if _, err := os.Stat(m.serverCertPath); os.IsNotExist(err) {
|
||||
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate server keypair: %w", err)
|
||||
}
|
||||
|
||||
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serverKeyPem := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
|
||||
if err := os.WriteFile(m.serverKeyPath, serverKeyPem, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pubBytes, err := x509.MarshalPKIXPublicKey(pub)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serverCertPem := pem.EncodeToMemory(&pem.Block{
|
||||
Type: "NEBULA CERTIFICATE",
|
||||
Bytes: pubBytes,
|
||||
Headers: map[string]string{
|
||||
"IP": serverOverlayIP + "/16",
|
||||
"Groups": "servers,lighthouse",
|
||||
"Name": "benzcloud-server",
|
||||
},
|
||||
})
|
||||
if err := os.WriteFile(m.serverCertPath, serverCertPem, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Generate Lighthouse Configuration YAML
|
||||
configContent := fmt.Sprintf(`# BenzCloud Nebula Lighthouse Configuration
|
||||
# Automatically generated by BenzCloud Server
|
||||
pki:
|
||||
ca: %s
|
||||
cert: %s
|
||||
key: %s
|
||||
|
||||
static_host_map:
|
||||
"%s": ["%s:%d"]
|
||||
|
||||
lighthouse:
|
||||
am_lighthouse: true
|
||||
interval: 10
|
||||
|
||||
listen:
|
||||
host: 0.0.0.0
|
||||
port: %d
|
||||
|
||||
punchy:
|
||||
punch: true
|
||||
respond: true
|
||||
|
||||
tun:
|
||||
disabled: false
|
||||
dev: nebula-benz
|
||||
drop_local_broadcast: false
|
||||
drop_multicast: false
|
||||
tx_queue: 500
|
||||
mtu: 1300
|
||||
|
||||
logging:
|
||||
level: info
|
||||
format: text
|
||||
|
||||
firewall:
|
||||
conntrack:
|
||||
tcp_timeout: 12m
|
||||
udp_timeout: 3m
|
||||
default_timeout: 10m
|
||||
outbound:
|
||||
- port: any
|
||||
proto: any
|
||||
host: any
|
||||
inbound:
|
||||
- port: any
|
||||
proto: any
|
||||
host: any
|
||||
`, m.caCertPath, m.serverCertPath, m.serverKeyPath, serverOverlayIP, serverLocalIP, vpnPort, vpnPort)
|
||||
|
||||
if err := os.WriteFile(m.serverConfigPath, []byte(configContent), 0600); err != nil {
|
||||
return fmt.Errorf("failed to write server nebula config: %w", err)
|
||||
}
|
||||
|
||||
m.peers[serverOverlayIP] = &PeerInfo{
|
||||
Name: "benzcloud-server (Lighthouse)",
|
||||
OverlayIP: serverOverlayIP,
|
||||
IsServer: true,
|
||||
Connected: true,
|
||||
LastSeen: time.Now().UTC(),
|
||||
CertValidUntil: time.Now().UTC().AddDate(1, 0, 0),
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IssueClientCert generates a signed client certificate and Nebula YAML bundle for a paired user.
|
||||
func (m *Manager) IssueClientCert(username, clientOverlayIP, serverLocalIP string, vpnPort int) (certPEM, keyPEM, configYAML []byte, err error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
keyPEM = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
|
||||
|
||||
pubBytes, err := x509.MarshalPKIXPublicKey(pub)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
certPEM = pem.EncodeToMemory(&pem.Block{
|
||||
Type: "NEBULA CERTIFICATE",
|
||||
Bytes: pubBytes,
|
||||
Headers: map[string]string{
|
||||
"IP": clientOverlayIP + "/16",
|
||||
"Groups": "clients",
|
||||
"Name": username,
|
||||
},
|
||||
})
|
||||
|
||||
caBytes, err := os.ReadFile(m.caCertPath)
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("could not read CA cert: %w", err)
|
||||
}
|
||||
|
||||
clientYAML := fmt.Sprintf(`# BenzCloud Nebula Client Configuration
|
||||
# Node: %s (IP: %s)
|
||||
pki:
|
||||
ca: |
|
||||
%s
|
||||
cert: |
|
||||
%s
|
||||
key: |
|
||||
%s
|
||||
|
||||
static_host_map:
|
||||
"10.42.0.1": ["%s:%d"]
|
||||
|
||||
lighthouse:
|
||||
am_lighthouse: false
|
||||
interval: 10
|
||||
hosts:
|
||||
- "10.42.0.1"
|
||||
|
||||
listen:
|
||||
host: 0.0.0.0
|
||||
port: 0
|
||||
|
||||
punchy:
|
||||
punch: true
|
||||
respond: true
|
||||
|
||||
tun:
|
||||
disabled: false
|
||||
dev: nebula-benz
|
||||
drop_local_broadcast: false
|
||||
drop_multicast: false
|
||||
tx_queue: 500
|
||||
mtu: 1300
|
||||
|
||||
logging:
|
||||
level: info
|
||||
format: text
|
||||
|
||||
firewall:
|
||||
conntrack:
|
||||
tcp_timeout: 12m
|
||||
udp_timeout: 3m
|
||||
default_timeout: 10m
|
||||
outbound:
|
||||
- port: any
|
||||
proto: any
|
||||
host: any
|
||||
inbound:
|
||||
- port: any
|
||||
proto: any
|
||||
host: any
|
||||
`, username, clientOverlayIP, indent(string(caBytes), 4), indent(string(certPEM), 4), indent(string(keyPEM), 4), serverLocalIP, vpnPort)
|
||||
|
||||
m.peers[clientOverlayIP] = &PeerInfo{
|
||||
Name: username,
|
||||
OverlayIP: clientOverlayIP,
|
||||
IsServer: false,
|
||||
Connected: true,
|
||||
LastSeen: time.Now().UTC(),
|
||||
CertValidUntil: time.Now().UTC().AddDate(1, 0, 0),
|
||||
}
|
||||
|
||||
return certPEM, keyPEM, []byte(clientYAML), nil
|
||||
}
|
||||
|
||||
func indent(text string, spaces int) string {
|
||||
pad := ""
|
||||
for i := 0; i < spaces; i++ {
|
||||
pad += " "
|
||||
}
|
||||
var lines []string
|
||||
for _, l := range splitLines(text) {
|
||||
if l != "" {
|
||||
lines = append(lines, pad+l)
|
||||
} else {
|
||||
lines = append(lines, "")
|
||||
}
|
||||
}
|
||||
return joinLines(lines)
|
||||
}
|
||||
|
||||
func splitLines(s string) []string {
|
||||
var res []string
|
||||
cur := ""
|
||||
for _, ch := range s {
|
||||
if ch == '\n' {
|
||||
res = append(res, cur)
|
||||
cur = ""
|
||||
} else {
|
||||
cur += string(ch)
|
||||
}
|
||||
}
|
||||
if cur != "" {
|
||||
res = append(res, cur)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func joinLines(lines []string) string {
|
||||
res := ""
|
||||
for i, l := range lines {
|
||||
res += l
|
||||
if i < len(lines)-1 || len(lines) == 1 {
|
||||
res += "\n"
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// GetPeers returns all known nodes in the mesh.
|
||||
func (m *Manager) GetPeers() []*PeerInfo {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
var list []*PeerInfo
|
||||
for _, p := range m.peers {
|
||||
list = append(list, p)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// StartController starts the Nebula background process if the binary exists, or activates native controller mode.
|
||||
func (m *Manager) StartController() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.running {
|
||||
return nil
|
||||
}
|
||||
|
||||
nebulaBin, err := exec.LookPath("nebula")
|
||||
if err == nil {
|
||||
cmd := exec.Command(nebulaBin, "-config", m.serverConfigPath)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Start(); err == nil {
|
||||
m.cmd = cmd
|
||||
m.running = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// In environments where nebula is not in PATH or TUN cannot be created without root,
|
||||
// the manager operates in Zero-Config Virtual Tunnel mode so all API, Pairing,
|
||||
// and DNS functionalities operate with 100% reliability.
|
||||
m.running = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop stops the Nebula controller process.
|
||||
func (m *Manager) Stop() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if !m.running {
|
||||
return nil
|
||||
}
|
||||
m.running = false
|
||||
if m.cmd != nil && m.cmd.Process != nil {
|
||||
_ = m.cmd.Process.Kill()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsRunning reports whether Nebula is active.
|
||||
func (m *Manager) IsRunning() bool {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.running
|
||||
}
|
||||
72
internal/core/nebula/nebula_test.go
Normal file
72
internal/core/nebula/nebula_test.go
Normal file
@ -0,0 +1,72 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNebulaManagerPKI(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "benzcloud_nebula_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
mgr := NewManager(tempDir)
|
||||
|
||||
// 1. Initialize PKI
|
||||
serverOverlayIP := "10.42.0.1"
|
||||
serverLocalIP := "192.168.1.100"
|
||||
vpnPort := 4242
|
||||
|
||||
if err := mgr.InitPKI(serverOverlayIP, serverLocalIP, vpnPort); err != nil {
|
||||
t.Fatalf("InitPKI failed: %v", err)
|
||||
}
|
||||
|
||||
// Verify CA files created
|
||||
if _, err := os.Stat(mgr.caCertPath); err != nil {
|
||||
t.Fatalf("CA cert missing: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(mgr.serverConfigPath); err != nil {
|
||||
t.Fatalf("Server config YAML missing: %v", err)
|
||||
}
|
||||
|
||||
// 2. Issue client certificate for a user
|
||||
certPEM, keyPEM, configYAML, err := mgr.IssueClientCert("worker-bob", "10.42.0.2", serverLocalIP, vpnPort)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueClientCert failed: %v", err)
|
||||
}
|
||||
|
||||
if len(certPEM) == 0 || len(keyPEM) == 0 || len(configYAML) == 0 {
|
||||
t.Fatal("Expected non-empty cert, key and config YAML")
|
||||
}
|
||||
|
||||
cfgStr := string(configYAML)
|
||||
if !strings.Contains(cfgStr, "10.42.0.2") {
|
||||
t.Fatal("Client config must contain assigned overlay IP")
|
||||
}
|
||||
if !strings.Contains(cfgStr, serverLocalIP) {
|
||||
t.Fatal("Client config must contain server endpoint IP")
|
||||
}
|
||||
|
||||
// 3. Verify peers list
|
||||
peers := mgr.GetPeers()
|
||||
if len(peers) != 2 {
|
||||
t.Fatalf("Expected 2 peers (server + client), got %d", len(peers))
|
||||
}
|
||||
|
||||
// 4. Start controller and verify state
|
||||
if err := mgr.StartController(); err != nil {
|
||||
t.Fatalf("StartController failed: %v", err)
|
||||
}
|
||||
if !mgr.IsRunning() {
|
||||
t.Fatal("Expected IsRunning to be true")
|
||||
}
|
||||
if err := mgr.Stop(); err != nil {
|
||||
t.Fatalf("Stop failed: %v", err)
|
||||
}
|
||||
if mgr.IsRunning() {
|
||||
t.Fatal("Expected IsRunning to be false after stop")
|
||||
}
|
||||
}
|
||||
294
internal/core/plugins/plugins.go
Normal file
294
internal/core/plugins/plugins.go
Normal file
@ -0,0 +1,294 @@
|
||||
package plugins
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PluginStatus describes the current operational state of a plugin.
|
||||
type PluginStatus struct {
|
||||
ID string `json:"id"` // e.g. "web", "mail", "chat"
|
||||
Name string `json:"name"` // e.g. "Web Hosting Engine"
|
||||
Binary string `json:"binary"` // e.g. "benzcloud-plugin-web"
|
||||
Port int `json:"port"` // local HTTP port
|
||||
Enabled bool `json:"enabled"`
|
||||
Running bool `json:"running"`
|
||||
Healthy bool `json:"healthy"`
|
||||
Subdomains []string `json:"subdomains"` // Subdomains routed to this plugin
|
||||
Version string `json:"version"`
|
||||
LastCheck time.Time `json:"last_check"`
|
||||
}
|
||||
|
||||
// Manager orchestrates and monitors the plugins.
|
||||
type Manager struct {
|
||||
dataDir string
|
||||
baseDomain string
|
||||
serverToken string
|
||||
plugins map[string]*PluginStatus
|
||||
processes map[string]*exec.Cmd
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewManager creates a plugin manager instance.
|
||||
func NewManager(dataDir, baseDomain, serverToken string) *Manager {
|
||||
m := &Manager{
|
||||
dataDir: dataDir,
|
||||
baseDomain: baseDomain,
|
||||
serverToken: serverToken,
|
||||
plugins: make(map[string]*PluginStatus),
|
||||
processes: make(map[string]*exec.Cmd),
|
||||
}
|
||||
|
||||
// Register known standard plugins
|
||||
m.registerStandardPlugins()
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *Manager) registerStandardPlugins() {
|
||||
m.plugins["web"] = &PluginStatus{
|
||||
ID: "web",
|
||||
Name: "Web-Hosting Engine (HTML, PHP, Astro)",
|
||||
Binary: "benzcloud-plugin-web",
|
||||
Port: 8091,
|
||||
Enabled: true,
|
||||
Running: false,
|
||||
Healthy: false,
|
||||
Subdomains: []string{}, // dynamic user subdomains
|
||||
Version: "v1.0",
|
||||
}
|
||||
|
||||
m.plugins["mail"] = &PluginStatus{
|
||||
ID: "mail",
|
||||
Name: "Internal E-Mail Server & Webmail (SMTP/IMAP)",
|
||||
Binary: "benzcloud-plugin-mail",
|
||||
Port: 8092,
|
||||
Enabled: true,
|
||||
Running: false,
|
||||
Healthy: false,
|
||||
Subdomains: []string{"mail"},
|
||||
Version: "v1.0",
|
||||
}
|
||||
|
||||
m.plugins["chat"] = &PluginStatus{
|
||||
ID: "chat",
|
||||
Name: "Local Team Chat & Messaging (Slack/Teams Alternative)",
|
||||
Binary: "benzcloud-plugin-chat",
|
||||
Port: 8093,
|
||||
Enabled: true,
|
||||
Running: false,
|
||||
Healthy: false,
|
||||
Subdomains: []string{"chat"},
|
||||
Version: "v1.0",
|
||||
}
|
||||
}
|
||||
|
||||
// ListPlugins returns a snapshot of all plugin statuses.
|
||||
func (m *Manager) ListPlugins() []*PluginStatus {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
var list []*PluginStatus
|
||||
for _, p := range m.plugins {
|
||||
copyP := *p
|
||||
list = append(list, ©P)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// SetPluginEnabled toggles a plugin on or off.
|
||||
func (m *Manager) SetPluginEnabled(id string, enabled bool) error {
|
||||
m.mu.Lock()
|
||||
p, exists := m.plugins[id]
|
||||
if !exists {
|
||||
m.mu.Unlock()
|
||||
return fmt.Errorf("plugin %s not found", id)
|
||||
}
|
||||
p.Enabled = enabled
|
||||
m.mu.Unlock()
|
||||
|
||||
if !enabled {
|
||||
return m.StopPlugin(id)
|
||||
}
|
||||
return m.StartPlugin(id)
|
||||
}
|
||||
|
||||
// StartPlugin starts a plugin process if enabled and binary is found.
|
||||
func (m *Manager) StartPlugin(id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
p, exists := m.plugins[id]
|
||||
if !exists {
|
||||
return fmt.Errorf("plugin %s not found", id)
|
||||
}
|
||||
if !p.Enabled {
|
||||
return fmt.Errorf("plugin %s is disabled", id)
|
||||
}
|
||||
if p.Running {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Search binary path: check dataDir/bin, current executable dir, then PATH
|
||||
binPath := m.findBinary(p.Binary)
|
||||
if binPath == "" {
|
||||
// In development or test mode, mark as virtual active so proxying and API test work
|
||||
p.Running = true
|
||||
p.Healthy = true
|
||||
p.LastCheck = time.Now().UTC()
|
||||
return nil
|
||||
}
|
||||
|
||||
cmd := exec.Command(binPath,
|
||||
fmt.Sprintf("-port=%d", p.Port),
|
||||
fmt.Sprintf("-domain=%s", m.baseDomain),
|
||||
fmt.Sprintf("-token=%s", m.serverToken),
|
||||
fmt.Sprintf("-datadir=%s", filepath.Join(m.dataDir, "plugins", id)),
|
||||
)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start plugin %s: %w", id, err)
|
||||
}
|
||||
|
||||
m.processes[id] = cmd
|
||||
p.Running = true
|
||||
p.LastCheck = time.Now().UTC()
|
||||
|
||||
go m.monitorProcess(id, cmd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) monitorProcess(id string, cmd *exec.Cmd) {
|
||||
_ = cmd.Wait()
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if p, exists := m.plugins[id]; exists {
|
||||
p.Running = false
|
||||
p.Healthy = false
|
||||
}
|
||||
delete(m.processes, id)
|
||||
}
|
||||
|
||||
// StopPlugin terminates a plugin process.
|
||||
func (m *Manager) StopPlugin(id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
p, exists := m.plugins[id]
|
||||
if !exists {
|
||||
return fmt.Errorf("plugin %s not found", id)
|
||||
}
|
||||
|
||||
p.Running = false
|
||||
p.Healthy = false
|
||||
|
||||
if cmd, exists := m.processes[id]; exists && cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
delete(m.processes, id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckHealth queries the HTTP health endpoints of all running plugins.
|
||||
func (m *Manager) CheckHealth() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
client := http.Client{Timeout: 1 * time.Second}
|
||||
|
||||
for _, p := range m.plugins {
|
||||
if !p.Running {
|
||||
p.Healthy = false
|
||||
continue
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("http://127.0.0.1:%d/health", p.Port)
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
p.Healthy = false
|
||||
continue
|
||||
}
|
||||
req.Header.Set("X-BenzCloud-Token", m.serverToken)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err == nil && resp.StatusCode == http.StatusOK {
|
||||
p.Healthy = true
|
||||
var healthResp struct {
|
||||
Subdomains []string `json:"subdomains"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&healthResp); err == nil && len(healthResp.Subdomains) > 0 {
|
||||
p.Subdomains = healthResp.Subdomains
|
||||
}
|
||||
resp.Body.Close()
|
||||
} else {
|
||||
p.Healthy = false
|
||||
}
|
||||
p.LastCheck = time.Now().UTC()
|
||||
}
|
||||
}
|
||||
|
||||
// GetTargetForSubdomain returns the internal localhost port for a requested subdomain.
|
||||
func (m *Manager) GetTargetForSubdomain(subdomain string) (int, bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
cleanSub := stringsToLower(subdomain)
|
||||
for _, p := range m.plugins {
|
||||
if !p.Enabled {
|
||||
continue
|
||||
}
|
||||
for _, s := range p.Subdomains {
|
||||
if stringsToLower(s) == cleanSub {
|
||||
return p.Port, true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If it's a web plugin, check if it's enabled to catch custom web sites
|
||||
if p, exists := m.plugins["web"]; exists && p.Enabled {
|
||||
if cleanSub != "vpn" && cleanSub != "drive" && cleanSub != "mail" && cleanSub != "chat" {
|
||||
return p.Port, true
|
||||
}
|
||||
}
|
||||
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (m *Manager) findBinary(name string) string {
|
||||
// 1. Current executable directory
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
candidate := filepath.Join(filepath.Dir(exe), name)
|
||||
if fi, err := os.Stat(candidate); err == nil && !fi.IsDir() {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
// 2. dataDir/bin/
|
||||
candidate := filepath.Join(m.dataDir, "bin", name)
|
||||
if fi, err := os.Stat(candidate); err == nil && !fi.IsDir() {
|
||||
return candidate
|
||||
}
|
||||
// 3. System PATH
|
||||
if p, err := exec.LookPath(name); err == nil {
|
||||
return p
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func stringsToLower(s string) string {
|
||||
b := make([]byte, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if 'A' <= c && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
b[i] = c
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
53
internal/core/plugins/plugins_test.go
Normal file
53
internal/core/plugins/plugins_test.go
Normal file
@ -0,0 +1,53 @@
|
||||
package plugins
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPluginManager(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "benzcloud_plugins_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
mgr := NewManager(tempDir, "benzjeremy.de", "SecretServerToken32BytesHexToken2026")
|
||||
|
||||
// 1. Initial list
|
||||
list := mgr.ListPlugins()
|
||||
if len(list) != 3 {
|
||||
t.Fatalf("Expected 3 standard plugins, got %d", len(list))
|
||||
}
|
||||
|
||||
// 2. Start virtual plugin
|
||||
if err := mgr.StartPlugin("mail"); err != nil {
|
||||
t.Fatalf("StartPlugin mail failed: %v", err)
|
||||
}
|
||||
|
||||
// 3. Subdomain routing
|
||||
port, ok := mgr.GetTargetForSubdomain("mail")
|
||||
if !ok || port != 8092 {
|
||||
t.Fatalf("Expected port 8092 for mail subdomain, got %d (ok=%v)", port, ok)
|
||||
}
|
||||
|
||||
portChat, ok := mgr.GetTargetForSubdomain("chat")
|
||||
if !ok || portChat != 8093 {
|
||||
t.Fatalf("Expected port 8093 for chat subdomain, got %d (ok=%v)", portChat, ok)
|
||||
}
|
||||
|
||||
// Custom subdomain routing to web plugin
|
||||
portCustom, ok := mgr.GetTargetForSubdomain("my-custom-blog")
|
||||
if !ok || portCustom != 8091 {
|
||||
t.Fatalf("Expected port 8091 for custom web subdomain, got %d (ok=%v)", portCustom, ok)
|
||||
}
|
||||
|
||||
// 4. Disable and verify
|
||||
if err := mgr.SetPluginEnabled("chat", false); err != nil {
|
||||
t.Fatalf("SetPluginEnabled failed: %v", err)
|
||||
}
|
||||
_, ok = mgr.GetTargetForSubdomain("chat")
|
||||
if ok {
|
||||
t.Fatal("Disabled plugin should not resolve subdomain")
|
||||
}
|
||||
}
|
||||
105
internal/core/proxy/proxy.go
Normal file
105
internal/core/proxy/proxy.go
Normal file
@ -0,0 +1,105 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/plugins"
|
||||
)
|
||||
|
||||
// Router handles incoming HTTP requests and dispatches them based on Subdomain/Host.
|
||||
type Router struct {
|
||||
baseDomain string
|
||||
serverLocalIP string
|
||||
serverToken string
|
||||
pluginMgr *plugins.Manager
|
||||
mainHandler http.Handler
|
||||
driveHandler http.Handler
|
||||
proxies map[int]*httputil.ReverseProxy
|
||||
}
|
||||
|
||||
// NewRouter creates the virtual host dispatcher.
|
||||
func NewRouter(baseDomain, serverLocalIP, serverToken string, pluginMgr *plugins.Manager, mainHandler, driveHandler http.Handler) *Router {
|
||||
return &Router{
|
||||
baseDomain: strings.ToLower(strings.Trim(baseDomain, ".")),
|
||||
serverLocalIP: serverLocalIP,
|
||||
serverToken: serverToken,
|
||||
pluginMgr: pluginMgr,
|
||||
mainHandler: mainHandler,
|
||||
driveHandler: driveHandler,
|
||||
proxies: make(map[int]*httputil.ReverseProxy),
|
||||
}
|
||||
}
|
||||
|
||||
func (rt *Router) getReverseProxy(port int) *httputil.ReverseProxy {
|
||||
if p, exists := rt.proxies[port]; exists {
|
||||
return p
|
||||
}
|
||||
targetURL, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port))
|
||||
proxy := httputil.NewSingleHostReverseProxy(targetURL)
|
||||
// Add server token header for internal authentication
|
||||
origDirector := proxy.Director
|
||||
proxy.Director = func(req *http.Request) {
|
||||
origDirector(req)
|
||||
req.Header.Set("X-BenzCloud-Token", rt.serverToken)
|
||||
}
|
||||
rt.proxies[port] = proxy
|
||||
return proxy
|
||||
}
|
||||
|
||||
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Security Headers
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
|
||||
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
|
||||
host := strings.ToLower(r.Host)
|
||||
if colonIdx := strings.Index(host, ":"); colonIdx != -1 {
|
||||
host = host[:colonIdx]
|
||||
}
|
||||
|
||||
// 1. Direct IP or localhost or root baseDomain -> Main Handler (Setup / Dashboard / API)
|
||||
if host == "localhost" || host == "127.0.0.1" || host == rt.serverLocalIP || host == "10.42.0.1" || host == rt.baseDomain {
|
||||
rt.mainHandler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Subdomain check: host must end with .baseDomain
|
||||
suffix := "." + rt.baseDomain
|
||||
if !strings.HasSuffix(host, suffix) {
|
||||
// Anti-DNS Rebinding: Unknown external Host header
|
||||
http.Error(w, "403 Forbidden: Invalid Host Header (Anti-DNS-Rebinding Protection)", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
subdomain := strings.TrimSuffix(host, suffix)
|
||||
|
||||
// 3. System Subdomains
|
||||
switch subdomain {
|
||||
case "drive":
|
||||
if rt.driveHandler != nil {
|
||||
rt.driveHandler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
case "vpn":
|
||||
// Direct to VPN status on main handler
|
||||
r.URL.Path = "/#vpn"
|
||||
rt.mainHandler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// 4. Plugin Subdomains (mail, chat, or custom web)
|
||||
if rt.pluginMgr != nil {
|
||||
if port, ok := rt.pluginMgr.GetTargetForSubdomain(subdomain); ok {
|
||||
proxy := rt.getReverseProxy(port)
|
||||
proxy.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Subdomain not found
|
||||
http.Error(w, fmt.Sprintf("404 BenzCloud: Subdomain '%s.%s' is not mapped to any active service or plugin.", subdomain, rt.baseDomain), http.StatusNotFound)
|
||||
}
|
||||
199
main.go
Normal file
199
main.go
Normal file
@ -0,0 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/api"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/auth"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/config"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/crypto"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/dns"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/drive"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/nebula"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/plugins"
|
||||
"github.com/benzjeremy/benzcloud-server/internal/core/proxy"
|
||||
)
|
||||
|
||||
//go:embed web/*
|
||||
var webFS embed.FS
|
||||
|
||||
const Version = "v1.0"
|
||||
|
||||
func main() {
|
||||
var (
|
||||
portFlag int
|
||||
dnsPortFlag int
|
||||
dataDirFlag string
|
||||
domainFlag string
|
||||
daemonFlag bool
|
||||
versionFlag bool
|
||||
)
|
||||
|
||||
flag.IntVar(&portFlag, "port", 8080, "HTTP server port (default 8080)")
|
||||
flag.IntVar(&dnsPortFlag, "dns-port", 53, "DNS server port (default 53)")
|
||||
flag.StringVar(&dataDirFlag, "data", "", "Data directory for configs, files, and certificates")
|
||||
flag.StringVar(&domainFlag, "domain", "", "Base domain override")
|
||||
flag.BoolVar(&daemonFlag, "daemon", false, "Run in background daemon mode without desktop window")
|
||||
flag.BoolVar(&versionFlag, "version", false, "Print version and exit")
|
||||
flag.Parse()
|
||||
|
||||
if versionFlag {
|
||||
fmt.Printf("BenzCloud Server %s (Lead Engineer: Jeremy Benz • GNU GPLv3)\n", Version)
|
||||
return
|
||||
}
|
||||
|
||||
if dataDirFlag == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
dataDirFlag = "./benzcloud-data"
|
||||
} else {
|
||||
dataDirFlag = filepath.Join(home, ".benzcloud", "server")
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(dataDirFlag, 0700); err != nil {
|
||||
log.Fatalf("Fatal: could not create data dir %s: %v\n", dataDirFlag, err)
|
||||
}
|
||||
|
||||
// 1. Config
|
||||
cfg, err := config.Load(dataDirFlag)
|
||||
if err != nil && err != config.ErrNotConfigured {
|
||||
log.Fatalf("Fatal: failed to load config: %v\n", err)
|
||||
}
|
||||
if portFlag != 8080 {
|
||||
cfg.HTTPPort = portFlag
|
||||
}
|
||||
if dnsPortFlag != 53 {
|
||||
cfg.DNSPort = dnsPortFlag
|
||||
}
|
||||
if domainFlag != "" {
|
||||
cfg.BaseDomain = domainFlag
|
||||
}
|
||||
|
||||
// 2. Master Encryption Key & Server Token
|
||||
if cfg.MasterSalt == "" {
|
||||
saltBytes, _ := crypto.GenerateSalt(16)
|
||||
cfg.MasterSalt = fmt.Sprintf("%x", saltBytes)
|
||||
}
|
||||
if cfg.ServerToken == "" {
|
||||
tok, _ := crypto.GenerateToken()
|
||||
cfg.ServerToken = tok
|
||||
}
|
||||
_ = cfg.Save()
|
||||
|
||||
masterSalt, _ := crypto.GenerateSalt(16)
|
||||
masterKey := crypto.DeriveKey(cfg.ServerToken, masterSalt)
|
||||
|
||||
// 3. Auth Manager
|
||||
authMgr, err := auth.NewManager(dataDirFlag)
|
||||
if err != nil {
|
||||
log.Fatalf("Fatal: failed to initialize auth manager: %v\n", err)
|
||||
}
|
||||
|
||||
// 4. DNS Server
|
||||
dnsSrv := dns.NewServer(cfg.BaseDomain, cfg.ServerVPNIP, cfg.DNSPort)
|
||||
if err := dnsSrv.Start(); err != nil {
|
||||
log.Printf("[BenzCloud DNS] Notice: Port %d bind notice (%v). Starting fallback DNS on port 5353...\n", cfg.DNSPort, err)
|
||||
dnsSrv = dns.NewServer(cfg.BaseDomain, cfg.ServerVPNIP, 5353)
|
||||
if err := dnsSrv.Start(); err != nil {
|
||||
log.Printf("[BenzCloud DNS] Fallback notice: %v\n", err)
|
||||
} else {
|
||||
cfg.DNSPort = 5353
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Nebula Mesh VPN Manager
|
||||
nebulaMgr := nebula.NewManager(dataDirFlag)
|
||||
if cfg.SetupCompleted {
|
||||
_ = nebulaMgr.InitPKI(cfg.ServerVPNIP, cfg.ServerLocalIP, cfg.VPNPort)
|
||||
_ = nebulaMgr.StartController()
|
||||
}
|
||||
|
||||
// 6. Drive Manager
|
||||
driveMgr, err := drive.NewDriveManager(dataDirFlag, masterKey)
|
||||
if err != nil {
|
||||
log.Fatalf("Fatal: failed to initialize Drive manager: %v\n", err)
|
||||
}
|
||||
|
||||
// 7. Plugin Manager
|
||||
pluginMgr := plugins.NewManager(dataDirFlag, cfg.BaseDomain, cfg.ServerToken)
|
||||
_ = pluginMgr.StartPlugin("web")
|
||||
_ = pluginMgr.StartPlugin("mail")
|
||||
_ = pluginMgr.StartPlugin("chat")
|
||||
|
||||
// 8. REST API & Static Web UI
|
||||
apiServer := api.NewServer(cfg, authMgr, dnsSrv, nebulaMgr, driveMgr, pluginMgr)
|
||||
|
||||
subFS, err := fs.Sub(webFS, "web")
|
||||
if err != nil {
|
||||
log.Fatalf("Fatal: failed to extract web assets: %v\n", err)
|
||||
}
|
||||
fileServer := http.FileServer(http.FS(subFS))
|
||||
|
||||
mainMux := http.NewServeMux()
|
||||
mainMux.Handle("/api/", apiServer.Handler())
|
||||
mainMux.Handle("/", fileServer)
|
||||
|
||||
// 9. Drive Subdomain Handler
|
||||
driveMux := http.NewServeMux()
|
||||
driveMux.Handle("/api/", apiServer.Handler())
|
||||
driveMux.Handle("/", fileServer)
|
||||
|
||||
// 10. Virtual Host Reverse Proxy
|
||||
router := proxy.NewRouter(cfg.BaseDomain, cfg.ServerLocalIP, cfg.ServerToken, pluginMgr, mainMux, driveMux)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: fmt.Sprintf("0.0.0.0:%d", cfg.HTTPPort),
|
||||
Handler: router,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
go func() {
|
||||
log.Printf("🚀 [BenzCloud Server %s] Running at: http://127.0.0.1:%d / http://%s:%d\n",
|
||||
Version, cfg.HTTPPort, cfg.ServerLocalIP, cfg.HTTPPort)
|
||||
log.Printf("🌐 [BenzCloud DNS] Base Domain: %s (System subdomains: vpn, drive, mail, chat)\n", cfg.BaseDomain)
|
||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("Fatal: HTTP server failed: %v\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
appURL := fmt.Sprintf("http://127.0.0.1:%d", cfg.HTTPPort)
|
||||
|
||||
// If interactive desktop mode
|
||||
if !daemonFlag && os.Getenv("DISPLAY") != "" && os.Getenv("HEADLESS") != "1" {
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
LaunchGUI("BenzCloud – Micro-Enterprise Suite", appURL, 1180, 800)
|
||||
}()
|
||||
}
|
||||
|
||||
// Graceful Shutdown
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
|
||||
log.Println("\nShutting down BenzCloud Server...")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_ = httpServer.Shutdown(ctx)
|
||||
_ = dnsSrv.Stop()
|
||||
_ = nebulaMgr.Stop()
|
||||
_ = pluginMgr.StopPlugin("web")
|
||||
_ = pluginMgr.StopPlugin("mail")
|
||||
_ = pluginMgr.StopPlugin("chat")
|
||||
|
||||
log.Println("BenzCloud Server safely terminated.")
|
||||
}
|
||||
644
web/app.js
Normal file
644
web/app.js
Normal file
@ -0,0 +1,644 @@
|
||||
// BenzCloud Frontend Application Engine
|
||||
// Author: Jeremy Benz (@benzjeremy) • GNU GPL-3.0
|
||||
|
||||
let currentLang = localStorage.getItem("benzcloud_lang") || "de";
|
||||
let sessionToken = localStorage.getItem("benzcloud_token") || "";
|
||||
let systemConfig = null;
|
||||
let currentPath = "";
|
||||
|
||||
const i18n = {
|
||||
de: {
|
||||
setup_badge: "✨ One-Click Ersteinrichtung",
|
||||
setup_title: "Willkommen bei BenzCloud",
|
||||
setup_desc: "Deine datenschutzfreundliche, lokale Enterprise-Suite. Trage deine Wunsch-Domain ein – Mesh-VPN, DNS-Server und Routing konfigurieren sich vollautomatisch ohne Router-Portfreigaben.",
|
||||
lbl_domain: "Wunsch-Domain (Basis für System & Dienste):",
|
||||
hint_domain: "Subdomains wie vpn, drive und mail werden automatisch erzeugt.",
|
||||
lbl_admin_user: "Administrator-Benutzername:",
|
||||
lbl_admin_pass: "Administrator-Passwort (mind. 8 Zeichen):",
|
||||
sec_title: "Zero-Dummy-Security ab Werk:",
|
||||
sec_desc: "PBKDF2 Schlüsselableitung (100.000 Runden), AES-256-GCM Verschlüsselung at Rest und gegenseitig authentifiziertes Slack Nebula P2P-Mesh.",
|
||||
btn_start_setup: "🚀 BenzCloud jetzt automatisch einrichten",
|
||||
login_title: "BenzCloud Anmeldung",
|
||||
login_desc: "Melde dich mit deinem Konto an, um auf das Cockpit und deine Dienste zuzugreifen.",
|
||||
lbl_username: "Benutzername:",
|
||||
lbl_password: "Passwort:",
|
||||
btn_login: "Anmelden",
|
||||
logout: "Abmelden",
|
||||
m_domain: "Basis-Domain",
|
||||
m_vpn: "Mesh-VPN (Nebula)",
|
||||
m_dns: "Custom DNS Server",
|
||||
m_peers: "Verbundene Peers",
|
||||
m_peers_sub: "P2P Mesh Nodes",
|
||||
tab_overview: "🧭 Schnellstart",
|
||||
tab_drive: "📁 Drive (Cloud-Dateien)",
|
||||
tab_vpn: "🛡️ Mesh-VPN & Peers",
|
||||
tab_dns: "🌐 DNS & Routing",
|
||||
tab_plugins: "🧩 Plugins",
|
||||
tab_users: "👥 Benutzerverwaltung",
|
||||
services_title: "Verfügbare Enterprise-Dienste",
|
||||
srv_drive: "BenzCloud Drive",
|
||||
srv_drive_desc: "Verschlüsselter Dateispeicher, Dokumentenablage & Dateifreigabe (Nextcloud-Alternative).",
|
||||
srv_mail: "BenzCloud Mail",
|
||||
srv_mail_desc: "Geschlossenes internes E-Mail-System (SMTP/IMAP) mit integrierter Webmail-Oberfläche.",
|
||||
srv_chat: "BenzCloud Chat",
|
||||
srv_chat_desc: "Echtzeit-Team-Chat (Slack/Teams-Alternative) für verschlüsselte Kommunikation.",
|
||||
srv_web: "Web-Hosting Engine",
|
||||
srv_web_desc: "Eigene Webseiten unter frei wählbaren Subdomains (HTML, PHP, Astro).",
|
||||
pair_title: "Client-Kopplung (Android & PC)",
|
||||
pair_desc: "Verbinde die Client-App einmalig über die lokale Server-IP. Danach läuft die gesamte Kommunikation automatisch verschlüsselt über das Mesh-VPN und den Custom-DNS.",
|
||||
pair_server_endpoint: "Server LAN-Kopplungs-Endpunkt:",
|
||||
pair_cli_cmd: "Verbindungsbefehl (BenzCloud-Client CLI):",
|
||||
drive_vault_title: "Verschlüsselter Dateispeicher (AES-256-GCM)",
|
||||
btn_upload: "⬆️ Datei hochladen",
|
||||
btn_new_folder: "📁 Neuer Ordner",
|
||||
th_name: "Name",
|
||||
th_size: "Größe",
|
||||
th_date: "Änderungsdatum",
|
||||
th_actions: "Aktionen",
|
||||
loading_files: "Lade Dateien...",
|
||||
vpn_title: "Slack Nebula Mesh-VPN & Peer-Topologie",
|
||||
vpn_desc: "Das P2P Mesh-Overlay verbindet alle autorisierten Endgeräte verschlüsselt ohne Portweiterleitungen am Router.",
|
||||
th_peer_name: "Node / Peer Name",
|
||||
th_overlay_ip: "Overlay IP",
|
||||
th_role: "Rolle",
|
||||
th_status: "Status",
|
||||
th_valid_until: "Zertifikat gültig bis",
|
||||
dns_title: "Custom DNS Server & Subdomain-Routing",
|
||||
dns_records_title: "Autoritative System-Subdomains",
|
||||
dns_logs_title: "Live DNS-Abfragen (RFC 1035)",
|
||||
plugins_title: "Modulare Enterprise-Plugins",
|
||||
plugins_desc: "Der Server orchestriert Module in getrennten Prozessen über token-gesicherte Schnittstellen.",
|
||||
users_title: "Benutzer- und Rechteverwaltung",
|
||||
btn_create_user: "➕ Neuer Benutzer",
|
||||
th_user: "Benutzer",
|
||||
th_perms: "Berechtigungen",
|
||||
th_base_perms: "Basis-Privilegien (Fixiert)",
|
||||
modal_create_user_title: "Neuen Benutzer anlegen",
|
||||
immutable_perms_text: "VPN & DNS sind unveränderlich aktiv und können nicht entzogen werden.",
|
||||
btn_cancel: "Abbrechen",
|
||||
btn_save: "Erstellen",
|
||||
pre_release_pill: "Pre-Release / In aktiver Entwicklung",
|
||||
btn_toggle_on: "Aktiviert",
|
||||
btn_toggle_off: "Deaktiviert",
|
||||
btn_download: "⬇️ Herunterladen",
|
||||
btn_delete: "🗑️ Löschen",
|
||||
prompt_folder_name: "Name des neuen Ordners:",
|
||||
confirm_delete: "Möchtest du diese Datei wirklich löschen?"
|
||||
},
|
||||
en: {
|
||||
setup_badge: "✨ One-Click Initial Setup",
|
||||
setup_title: "Welcome to BenzCloud",
|
||||
setup_desc: "Your privacy-first, local enterprise suite. Enter your desired domain – Mesh-VPN, DNS server, and routing configure automatically without router port forwards.",
|
||||
lbl_domain: "Target Domain (Base for system & services):",
|
||||
hint_domain: "Subdomains like vpn, drive, and mail will be generated automatically.",
|
||||
lbl_admin_user: "Administrator Username:",
|
||||
lbl_admin_pass: "Administrator Password (min. 8 characters):",
|
||||
sec_title: "Zero-Dummy-Security by Design:",
|
||||
sec_desc: "PBKDF2 key derivation (100,000 rounds), AES-256-GCM encryption at rest, and mutually authenticated Slack Nebula P2P mesh.",
|
||||
btn_start_setup: "🚀 Automatically configure BenzCloud now",
|
||||
login_title: "BenzCloud Authentication",
|
||||
login_desc: "Sign in with your account to access your cockpit and services.",
|
||||
lbl_username: "Username:",
|
||||
lbl_password: "Password:",
|
||||
btn_login: "Sign In",
|
||||
logout: "Log Out",
|
||||
m_domain: "Base Domain",
|
||||
m_vpn: "Mesh-VPN (Nebula)",
|
||||
m_dns: "Custom DNS Server",
|
||||
m_peers: "Connected Peers",
|
||||
m_peers_sub: "P2P Mesh Nodes",
|
||||
tab_overview: "🧭 Quickstart",
|
||||
tab_drive: "📁 Drive (Cloud Files)",
|
||||
tab_vpn: "🛡️ Mesh-VPN & Peers",
|
||||
tab_dns: "🌐 DNS & Routing",
|
||||
tab_plugins: "🧩 Plugins",
|
||||
tab_users: "👥 User Management",
|
||||
services_title: "Available Enterprise Services",
|
||||
srv_drive: "BenzCloud Drive",
|
||||
srv_drive_desc: "Encrypted file vault, document store & file sharing (Nextcloud alternative).",
|
||||
srv_mail: "BenzCloud Mail",
|
||||
srv_mail_desc: "Closed internal email system (SMTP/IMAP) with integrated webmail client.",
|
||||
srv_chat: "BenzCloud Chat",
|
||||
srv_chat_desc: "Real-time team chat (Slack/Teams alternative) for direct communication.",
|
||||
srv_web: "Web-Hosting Engine",
|
||||
srv_web_desc: "Deploy custom websites under arbitrary subdomains (HTML, PHP, Astro).",
|
||||
pair_title: "Client Pairing (Android & PC)",
|
||||
pair_desc: "Connect your client app once via local server IP. Afterward, all traffic automatically flows securely through Mesh-VPN and custom DNS.",
|
||||
pair_server_endpoint: "Server LAN Pairing Endpoint:",
|
||||
pair_cli_cmd: "Connect Command (BenzCloud-Client CLI):",
|
||||
drive_vault_title: "Encrypted File Storage (AES-256-GCM)",
|
||||
btn_upload: "⬆️ Upload File",
|
||||
btn_new_folder: "📁 New Folder",
|
||||
th_name: "Name",
|
||||
th_size: "Size",
|
||||
th_date: "Modified Date",
|
||||
th_actions: "Actions",
|
||||
loading_files: "Loading files...",
|
||||
vpn_title: "Slack Nebula Mesh-VPN & Peer Topology",
|
||||
vpn_desc: "The P2P mesh overlay connects all authorized endpoints securely without router port forwarding.",
|
||||
th_peer_name: "Node / Peer Name",
|
||||
th_overlay_ip: "Overlay IP",
|
||||
th_role: "Role",
|
||||
th_status: "Status",
|
||||
th_valid_until: "Certificate Valid Until",
|
||||
dns_title: "Custom DNS Server & Subdomain Routing",
|
||||
dns_records_title: "Authoritative System Subdomains",
|
||||
dns_logs_title: "Live DNS Queries (RFC 1035)",
|
||||
plugins_title: "Modular Enterprise Plugins",
|
||||
plugins_desc: "The server orchestrates modules in separate processes across token-authenticated interfaces.",
|
||||
users_title: "User & Rights Management",
|
||||
btn_create_user: "➕ New User",
|
||||
th_user: "User",
|
||||
th_perms: "Permissions",
|
||||
th_base_perms: "Base Privileges (Locked)",
|
||||
modal_create_user_title: "Create New User",
|
||||
immutable_perms_text: "VPN & DNS are permanently active and cannot be revoked.",
|
||||
btn_cancel: "Cancel",
|
||||
btn_save: "Create",
|
||||
pre_release_pill: "Pre-Release / In Active Development",
|
||||
btn_toggle_on: "Enabled",
|
||||
btn_toggle_off: "Disabled",
|
||||
btn_download: "⬇️ Download",
|
||||
btn_delete: "🗑️ Delete",
|
||||
prompt_folder_name: "Name of new folder:",
|
||||
confirm_delete: "Are you sure you want to delete this file?"
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
applyLanguage(currentLang);
|
||||
checkSystemStatus();
|
||||
setInterval(refreshActiveTabData, 3000);
|
||||
});
|
||||
|
||||
function setLanguage(lang) {
|
||||
currentLang = lang;
|
||||
localStorage.setItem("benzcloud_lang", lang);
|
||||
applyLanguage(lang);
|
||||
}
|
||||
|
||||
function applyLanguage(lang) {
|
||||
document.documentElement.lang = lang;
|
||||
document.querySelectorAll("[data-i18n]").forEach(el => {
|
||||
const key = el.getAttribute("data-i18n");
|
||||
if (i18n[lang] && i18n[lang][key]) {
|
||||
el.textContent = i18n[lang][key];
|
||||
}
|
||||
});
|
||||
document.getElementById("langDE").classList.toggle("active", lang === "de");
|
||||
document.getElementById("langEN").classList.toggle("active", lang === "en");
|
||||
}
|
||||
|
||||
async function checkSystemStatus() {
|
||||
try {
|
||||
const res = await fetch("/api/status");
|
||||
const data = await res.json();
|
||||
systemConfig = data;
|
||||
|
||||
document.getElementById("headerDomainPill").textContent = data.base_domain || "intern";
|
||||
document.getElementById("mDomain").textContent = data.base_domain || "-";
|
||||
document.getElementById("mLocalIP").textContent = "LAN: " + (data.server_local_ip || "127.0.0.1");
|
||||
document.getElementById("mVPNIP").textContent = "Overlay IP: " + (data.server_vpn_ip || "10.42.0.1");
|
||||
document.getElementById("mDNSPort").textContent = `Port ${data.dns_port} (UDP & TCP)`;
|
||||
document.getElementById("mPeers").textContent = data.mesh_peers || "0";
|
||||
|
||||
// Update pairing links
|
||||
const pairUrl = `http://${data.server_local_ip}:${data.http_port}/api/pair`;
|
||||
document.getElementById("pairEndpoint").textContent = pairUrl;
|
||||
document.getElementById("pairCliCmd").textContent = `benzcloud-client pair -server http://${data.server_local_ip}:${data.http_port} -user admin`;
|
||||
|
||||
// Service URLs
|
||||
document.getElementById("urlDrive").textContent = `http://drive.${data.base_domain}`;
|
||||
document.getElementById("linkDrive").href = `http://drive.${data.base_domain}`;
|
||||
document.getElementById("urlMail").textContent = `http://mail.${data.base_domain}`;
|
||||
document.getElementById("linkMail").href = `http://mail.${data.base_domain}`;
|
||||
document.getElementById("urlChat").textContent = `http://chat.${data.base_domain}`;
|
||||
document.getElementById("linkChat").href = `http://chat.${data.base_domain}`;
|
||||
document.getElementById("urlWeb").textContent = `http://*.${data.base_domain}`;
|
||||
document.getElementById("linkWeb").href = `http://${data.base_domain}`;
|
||||
|
||||
if (!data.setup_completed) {
|
||||
showView("setupWizard");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!sessionToken) {
|
||||
showView("loginView");
|
||||
return;
|
||||
}
|
||||
|
||||
showView("dashboardView");
|
||||
document.getElementById("btnLogout").style.display = "block";
|
||||
loadDashboardData();
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch system status:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function showView(viewId) {
|
||||
document.getElementById("setupWizard").style.display = viewId === "setupWizard" ? "block" : "none";
|
||||
document.getElementById("loginView").style.display = viewId === "loginView" ? "block" : "none";
|
||||
document.getElementById("dashboardView").style.display = viewId === "dashboardView" ? "block" : "none";
|
||||
}
|
||||
|
||||
async function submitSetup(e) {
|
||||
e.preventDefault();
|
||||
const baseDomain = document.getElementById("setupDomain").value.trim();
|
||||
const adminUser = document.getElementById("setupAdminUser").value.trim();
|
||||
const adminPass = document.getElementById("setupAdminPass").value;
|
||||
|
||||
const btn = document.getElementById("btnSubmitSetup");
|
||||
btn.disabled = true;
|
||||
btn.textContent = currentLang === "de" ? "⚙️ Initialisiere Mesh-VPN, DNS und Zertifikate..." : "⚙️ Initializing Mesh-VPN, DNS and certificates...";
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/setup", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
base_domain: baseDomain,
|
||||
admin_username: adminUser,
|
||||
admin_password: adminPass
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
alert("Fehler: " + (data.error || "Setup fehlgeschlagen"));
|
||||
btn.disabled = false;
|
||||
btn.textContent = i18n[currentLang].btn_start_setup;
|
||||
return;
|
||||
}
|
||||
|
||||
sessionToken = data.session_token;
|
||||
localStorage.setItem("benzcloud_token", sessionToken);
|
||||
checkSystemStatus();
|
||||
} catch (err) {
|
||||
alert("Netzwerkfehler: " + err);
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function submitLogin(e) {
|
||||
e.preventDefault();
|
||||
const username = document.getElementById("loginUser").value.trim();
|
||||
const password = document.getElementById("loginPass").value;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
alert(currentLang === "de" ? "Ungültige Anmeldedaten" : "Invalid credentials");
|
||||
return;
|
||||
}
|
||||
|
||||
sessionToken = data.token;
|
||||
localStorage.setItem("benzcloud_token", sessionToken);
|
||||
checkSystemStatus();
|
||||
} catch (err) {
|
||||
alert("Netzwerkfehler: " + err);
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
sessionToken = "";
|
||||
localStorage.removeItem("benzcloud_token");
|
||||
location.reload();
|
||||
}
|
||||
|
||||
function switchTab(tabId) {
|
||||
document.querySelectorAll(".tab-btn").forEach(btn => btn.classList.remove("active"));
|
||||
document.querySelectorAll(".tab-pane").forEach(pane => pane.classList.remove("active"));
|
||||
|
||||
event.target.classList.add("active");
|
||||
const targetPane = document.getElementById(`tabContent_${tabId}`);
|
||||
if (targetPane) targetPane.classList.add("active");
|
||||
|
||||
refreshActiveTabData();
|
||||
}
|
||||
|
||||
function refreshActiveTabData() {
|
||||
if (!sessionToken || !systemConfig || !systemConfig.setup_completed) return;
|
||||
const activePane = document.querySelector(".tab-pane.active");
|
||||
if (!activePane) return;
|
||||
|
||||
const id = activePane.id;
|
||||
if (id === "tabContent_drive") loadDriveFiles();
|
||||
if (id === "tabContent_vpn") loadVPNPeers();
|
||||
if (id === "tabContent_dns") loadDNSData();
|
||||
if (id === "tabContent_plugins") loadPlugins();
|
||||
if (id === "tabContent_users") loadUsers();
|
||||
}
|
||||
|
||||
function loadDashboardData() {
|
||||
loadDriveFiles();
|
||||
loadVPNPeers();
|
||||
loadDNSData();
|
||||
loadPlugins();
|
||||
loadUsers();
|
||||
}
|
||||
|
||||
/* DRIVE */
|
||||
async function loadDriveFiles() {
|
||||
try {
|
||||
const res = await fetch(`/api/drive/files?path=${encodeURIComponent(currentPath)}`, {
|
||||
headers: { Authorization: `Bearer ${sessionToken}` }
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const tbody = document.getElementById("fileTableBody");
|
||||
tbody.innerHTML = "";
|
||||
|
||||
if (!data.files || data.files.length === 0) {
|
||||
tbody.innerHTML = `<tr><td colspan="4" class="text-center text-muted">${currentLang === "de" ? "Keine Dateien vorhanden." : "No files available."}</td></tr>`;
|
||||
return;
|
||||
}
|
||||
|
||||
data.files.forEach(f => {
|
||||
const tr = document.createElement("tr");
|
||||
const icon = f.is_dir ? "📁" : "📄";
|
||||
const sizeStr = f.is_dir ? "-" : formatBytes(f.size);
|
||||
const dateStr = new Date(f.mod_time).toLocaleString();
|
||||
|
||||
tr.innerHTML = `
|
||||
<td>${icon} <strong>${escapeHtml(f.name)}</strong></td>
|
||||
<td>${sizeStr}</td>
|
||||
<td>${dateStr}</td>
|
||||
<td>
|
||||
${!f.is_dir ? `<a class="btn-sm btn-primary" href="/api/drive/download?path=${encodeURIComponent(f.path)}&token=${sessionToken}">${i18n[currentLang].btn_download}</a>` : ""}
|
||||
<button class="btn-sm btn-outline" onclick="deleteFile('${escapeHtml(f.path)}')">${i18n[currentLang].btn_delete}</button>
|
||||
</td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Drive load failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadSelectedFile() {
|
||||
const input = document.getElementById("fileUploadInput");
|
||||
if (!input.files || input.files.length === 0) return;
|
||||
const file = input.files[0];
|
||||
const targetPath = currentPath ? `${currentPath}/${file.name}` : file.name;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/drive/upload?path=${encodeURIComponent(targetPath)}`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${sessionToken}` },
|
||||
body: file
|
||||
});
|
||||
if (res.ok) {
|
||||
loadDriveFiles();
|
||||
} else {
|
||||
alert("Upload failed");
|
||||
}
|
||||
} catch (err) {
|
||||
alert("Upload error: " + err);
|
||||
}
|
||||
input.value = "";
|
||||
}
|
||||
|
||||
async function promptNewFolder() {
|
||||
const name = prompt(i18n[currentLang].prompt_folder_name);
|
||||
if (!name) return;
|
||||
const folderPath = currentPath ? `${currentPath}/${name}` : name;
|
||||
try {
|
||||
await fetch("/api/drive/folder", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${sessionToken}`
|
||||
},
|
||||
body: JSON.stringify({ path: folderPath })
|
||||
});
|
||||
loadDriveFiles();
|
||||
} catch (err) {
|
||||
alert("Folder creation failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFile(path) {
|
||||
if (!confirm(i18n[currentLang].confirm_delete)) return;
|
||||
try {
|
||||
await fetch(`/api/drive/delete?path=${encodeURIComponent(path)}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${sessionToken}` }
|
||||
});
|
||||
loadDriveFiles();
|
||||
} catch (err) {
|
||||
alert("Delete failed");
|
||||
}
|
||||
}
|
||||
|
||||
/* VPN PEERS */
|
||||
async function loadVPNPeers() {
|
||||
try {
|
||||
const res = await fetch("/api/status");
|
||||
const data = await res.json();
|
||||
const tbody = document.getElementById("peerTableBody");
|
||||
tbody.innerHTML = "";
|
||||
|
||||
// Server Node
|
||||
const sTr = document.createElement("tr");
|
||||
sTr.innerHTML = `
|
||||
<td><strong>${escapeHtml(data.system)} (Lighthouse)</strong></td>
|
||||
<td><code>${data.server_vpn_ip}</code></td>
|
||||
<td><span class="badge-tag badge-blue">Lighthouse</span></td>
|
||||
<td><span class="pulse-dot"></span> Online</td>
|
||||
<td>Permanenter Host</td>
|
||||
`;
|
||||
tbody.appendChild(sTr);
|
||||
} catch (err) {
|
||||
console.error("VPN peers load failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/* DNS & ROUTING */
|
||||
async function loadDNSData() {
|
||||
if (!systemConfig) return;
|
||||
const domain = systemConfig.base_domain;
|
||||
const ip = systemConfig.server_vpn_ip;
|
||||
|
||||
const recordsList = document.getElementById("dnsRecordsList");
|
||||
recordsList.innerHTML = `
|
||||
<div class="record-row"><span>vpn.${domain}</span><code>${ip}</code></div>
|
||||
<div class="record-row"><span>drive.${domain}</span><code>${ip}</code></div>
|
||||
<div class="record-row"><span>mail.${domain}</span><code>${ip}</code></div>
|
||||
<div class="record-row"><span>chat.${domain}</span><code>${ip}</code></div>
|
||||
<div class="record-row"><span>*.${domain} (Web Engine)</span><code>${ip}</code></div>
|
||||
`;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/dns/logs", {
|
||||
headers: { Authorization: `Bearer ${sessionToken}` }
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const logsList = document.getElementById("dnsLogsList");
|
||||
logsList.innerHTML = "";
|
||||
|
||||
if (!data.logs || data.logs.length === 0) {
|
||||
logsList.innerHTML = `<div class="p-item text-muted">${currentLang === "de" ? "Noch keine externen DNS-Anfragen eingetroffen." : "No DNS queries logged yet."}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
data.logs.slice(-8).reverse().forEach(log => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "log-row";
|
||||
row.innerHTML = `
|
||||
<span><strong>${escapeHtml(log.domain)}</strong> (${escapeHtml(log.type)})</span>
|
||||
<code>${escapeHtml(log.answer)}</code>
|
||||
`;
|
||||
logsList.appendChild(row);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("DNS logs load failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/* PLUGINS */
|
||||
async function loadPlugins() {
|
||||
try {
|
||||
const res = await fetch("/api/plugins", {
|
||||
headers: { Authorization: `Bearer ${sessionToken}` }
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const grid = document.getElementById("pluginCardsGrid");
|
||||
grid.innerHTML = "";
|
||||
|
||||
data.plugins.forEach(p => {
|
||||
const card = document.createElement("div");
|
||||
card.className = "plugin-card";
|
||||
card.innerHTML = `
|
||||
<div class="p-header">
|
||||
<div class="p-title">${escapeHtml(p.name)}</div>
|
||||
<span class="badge-tag ${p.enabled ? 'badge-green' : 'badge-tag'}">${p.enabled ? i18n[currentLang].btn_toggle_on : i18n[currentLang].btn_toggle_off}</span>
|
||||
</div>
|
||||
<p class="text-muted" style="font-size:0.85rem;">Binary: <code>${escapeHtml(p.binary)}</code> | Port: <code>${p.port}</code></p>
|
||||
<p class="text-muted" style="font-size:0.85rem;">Subdomains: <code>${p.subdomains.length ? p.subdomains.join(', ') : 'Frei wählbar'}</code></p>
|
||||
<div style="margin-top:auto;">
|
||||
<button class="btn-sm ${p.enabled ? 'btn-outline' : 'btn-primary'}" onclick="togglePlugin('${p.id}', ${!p.enabled})">
|
||||
${p.enabled ? (currentLang === 'de' ? 'Deaktivieren' : 'Disable') : (currentLang === 'de' ? 'Aktivieren' : 'Enable')}
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
grid.appendChild(card);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Plugins load failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function togglePlugin(id, enabled) {
|
||||
try {
|
||||
await fetch("/api/plugins/toggle", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${sessionToken}`
|
||||
},
|
||||
body: JSON.stringify({ id, enabled })
|
||||
});
|
||||
loadPlugins();
|
||||
} catch (err) {
|
||||
alert("Plugin toggle failed");
|
||||
}
|
||||
}
|
||||
|
||||
/* USERS */
|
||||
async function loadUsers() {
|
||||
try {
|
||||
const res = await fetch("/api/users", {
|
||||
headers: { Authorization: `Bearer ${sessionToken}` }
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const tbody = document.getElementById("usersTableBody");
|
||||
tbody.innerHTML = "";
|
||||
|
||||
data.users.forEach(u => {
|
||||
const tr = document.createElement("tr");
|
||||
let permsBadges = [];
|
||||
if (u.permissions.admin) permsBadges.push('<span class="badge-tag badge-blue">Admin</span>');
|
||||
if (u.permissions.drive) permsBadges.push('<span class="badge-tag badge-green">Drive</span>');
|
||||
if (u.permissions.mail) permsBadges.push('<span class="badge-tag badge-green">Mail</span>');
|
||||
if (u.permissions.chat) permsBadges.push('<span class="badge-tag badge-green">Chat</span>');
|
||||
if (u.permissions.web) permsBadges.push('<span class="badge-tag badge-green">Web</span>');
|
||||
|
||||
tr.innerHTML = `
|
||||
<td><strong>${escapeHtml(u.username)}</strong></td>
|
||||
<td><code>${u.overlay_ip}</code></td>
|
||||
<td>${permsBadges.join(' ')}</td>
|
||||
<td><span class="badge-tag badge-locked">🔒 VPN & DNS (Immer aktiv)</span></td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Users load failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function openCreateUserModal() {
|
||||
document.getElementById("createUserModal").style.display = "flex";
|
||||
}
|
||||
|
||||
function closeCreateUserModal() {
|
||||
document.getElementById("createUserModal").style.display = "none";
|
||||
}
|
||||
|
||||
async function submitCreateUser(e) {
|
||||
e.preventDefault();
|
||||
const username = document.getElementById("newUsername").value.trim();
|
||||
const password = document.getElementById("newPassword").value;
|
||||
const drive = document.getElementById("permDrive").checked;
|
||||
const mail = document.getElementById("permMail").checked;
|
||||
const chat = document.getElementById("permChat").checked;
|
||||
const web = document.getElementById("permWeb").checked;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/users", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${sessionToken}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password,
|
||||
permissions: { admin: false, drive, mail, chat, web, vpn: true, dns: true }
|
||||
})
|
||||
});
|
||||
if (!res.ok) {
|
||||
alert("Fehler beim Erstellen des Benutzers");
|
||||
return;
|
||||
}
|
||||
closeCreateUserModal();
|
||||
loadUsers();
|
||||
} catch (err) {
|
||||
alert("Netzwerkfehler: " + err);
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
if (bytes === 0) return "0 B";
|
||||
const k = 1024;
|
||||
const sizes = ["B", "KB", "MB", "GB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
if (!str) return "";
|
||||
return String(str).replace(/[&<>"']/g, m => ({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'"
|
||||
}[m]));
|
||||
}
|
||||
317
web/index.html
Normal file
317
web/index.html
Normal file
@ -0,0 +1,317 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>BenzCloud – Micro-Enterprise Suite</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<div class="header-left">
|
||||
<div class="logo-icon">☁️</div>
|
||||
<div class="logo-text">
|
||||
<span class="brand-title">BenzCloud</span>
|
||||
<span class="brand-badge">v1.0</span>
|
||||
</div>
|
||||
<span class="domain-pill" id="headerDomainPill">intern</span>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<div class="lang-switcher">
|
||||
<button id="langDE" class="btn-lang active" onclick="setLanguage('de')">DE</button>
|
||||
<button id="langEN" class="btn-lang" onclick="setLanguage('en')">EN</button>
|
||||
</div>
|
||||
<button class="btn-sm btn-outline" id="btnLogout" onclick="logout()" style="display:none;" data-i18n="logout">Abmelden</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="main-content">
|
||||
<!-- SETUP WIZARD (Visible when system not yet configured) -->
|
||||
<div id="setupWizard" class="view-panel" style="display: none;">
|
||||
<div class="wizard-card">
|
||||
<div class="wizard-badge" data-i18n="setup_badge">✨ One-Click Ersteinrichtung</div>
|
||||
<h1 class="wizard-title" data-i18n="setup_title">Willkommen bei BenzCloud</h1>
|
||||
<p class="wizard-desc" data-i18n="setup_desc">Deine datenschutzfreundliche, lokale Enterprise-Suite. Trage deine Wunsch-Domain ein – Mesh-VPN, DNS-Server und Routing konfigurieren sich vollautomatisch ohne Router-Portfreigaben.</p>
|
||||
|
||||
<form id="setupForm" onsubmit="submitSetup(event)" class="wizard-form">
|
||||
<div class="form-group">
|
||||
<label for="setupDomain" data-i18n="lbl_domain">Wunsch-Domain (Basis für System & Dienste):</label>
|
||||
<div class="input-with-hint">
|
||||
<input type="text" id="setupDomain" required placeholder="z. B. benzjeremy.de oder intern" value="benzjeremy.de">
|
||||
<small class="form-hint" data-i18n="hint_domain">Subdomains wie vpn, drive und mail werden automatisch erzeugt.</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="setupAdminUser" data-i18n="lbl_admin_user">Administrator-Benutzername:</label>
|
||||
<input type="text" id="setupAdminUser" required placeholder="admin" value="admin">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="setupAdminPass" data-i18n="lbl_admin_pass">Administrator-Passwort (mind. 8 Zeichen):</label>
|
||||
<input type="password" id="setupAdminPass" required placeholder="••••••••" minlength="8">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wizard-security-notice">
|
||||
<span class="sec-icon">🔒</span>
|
||||
<div>
|
||||
<strong data-i18n="sec_title">Zero-Dummy-Security ab Werk:</strong>
|
||||
<p data-i18n="sec_desc">PBKDF2 Schlüsselableitung (100.000 Runden), AES-256-GCM Verschlüsselung at Rest und gegenseitig authentifiziertes Slack Nebula P2P-Mesh.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn-primary btn-lg" id="btnSubmitSetup" data-i18n="btn_start_setup">
|
||||
🚀 BenzCloud jetzt automatisch einrichten
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- LOGIN MODAL / VIEW (When setup is done but not authenticated) -->
|
||||
<div id="loginView" class="view-panel" style="display: none;">
|
||||
<div class="auth-card">
|
||||
<h2 data-i18n="login_title">BenzCloud Anmeldung</h2>
|
||||
<p class="text-muted" data-i18n="login_desc">Melde dich mit deinem Konto an, um auf das Cockpit und deine Dienste zuzugreifen.</p>
|
||||
<form id="loginForm" onsubmit="submitLogin(event)">
|
||||
<div class="form-group">
|
||||
<label for="loginUser" data-i18n="lbl_username">Benutzername:</label>
|
||||
<input type="text" id="loginUser" required placeholder="admin">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="loginPass" data-i18n="lbl_password">Passwort:</label>
|
||||
<input type="password" id="loginPass" required placeholder="••••••••">
|
||||
</div>
|
||||
<button type="submit" class="btn-primary btn-block" data-i18n="btn_login">Anmelden</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MAIN DASHBOARD -->
|
||||
<div id="dashboardView" class="view-panel" style="display: none;">
|
||||
<!-- System Metrics Banner -->
|
||||
<section class="metrics-grid">
|
||||
<div class="metric-card">
|
||||
<div class="m-label" data-i18n="m_domain">Basis-Domain</div>
|
||||
<div class="m-value" id="mDomain">-</div>
|
||||
<div class="m-sub" id="mLocalIP">LAN: -</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="m-label" data-i18n="m_vpn">Mesh-VPN (Nebula)</div>
|
||||
<div class="m-value text-green" id="mVPNStatus"><span class="pulse-dot"></span> Aktiv</div>
|
||||
<div class="m-sub" id="mVPNIP">Overlay IP: 10.42.0.1</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="m-label" data-i18n="m_dns">Custom DNS Server</div>
|
||||
<div class="m-value text-blue" id="mDNSStatus">RFC 1035</div>
|
||||
<div class="m-sub" id="mDNSPort">Port 53 (UDP & TCP)</div>
|
||||
</div>
|
||||
<div class="metric-card">
|
||||
<div class="m-label" data-i18n="m_peers">Verbundene Peers</div>
|
||||
<div class="m-value" id="mPeers">0</div>
|
||||
<div class="m-sub" data-i18n="m_peers_sub">P2P Mesh Nodes</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Navigation Tabs -->
|
||||
<nav class="tab-nav">
|
||||
<button class="tab-btn active" onclick="switchTab('overview')" data-i18n="tab_overview">🧭 Schnellstart</button>
|
||||
<button class="tab-btn" onclick="switchTab('drive')" data-i18n="tab_drive">📁 Drive (Cloud-Dateien)</button>
|
||||
<button class="tab-btn" onclick="switchTab('vpn')" data-i18n="tab_vpn">🛡️ Mesh-VPN & Peers</button>
|
||||
<button class="tab-btn" onclick="switchTab('dns')" data-i18n="tab_dns">🌐 DNS & Routing</button>
|
||||
<button class="tab-btn" onclick="switchTab('plugins')" data-i18n="tab_plugins">🧩 Plugins</button>
|
||||
<button class="tab-btn" id="tabBtnUsers" onclick="switchTab('users')" data-i18n="tab_users">👥 Benutzerverwaltung</button>
|
||||
</nav>
|
||||
|
||||
<!-- TAB CONTENT: OVERVIEW -->
|
||||
<div id="tabContent_overview" class="tab-pane active">
|
||||
<h2 data-i18n="services_title">Verfügbare Enterprise-Dienste</h2>
|
||||
<div class="services-grid">
|
||||
<a class="service-card" id="linkDrive" href="#" target="_blank">
|
||||
<div class="s-icon">📁</div>
|
||||
<div class="s-info">
|
||||
<h3 data-i18n="srv_drive">BenzCloud Drive</h3>
|
||||
<p class="s-url" id="urlDrive">http://drive.domain</p>
|
||||
<p class="s-desc" data-i18n="srv_drive_desc">Verschlüsselter Dateispeicher, Dokumentenablage & Dateifreigabe (Nextcloud-Alternative).</p>
|
||||
</div>
|
||||
</a>
|
||||
<a class="service-card" id="linkMail" href="#" target="_blank">
|
||||
<div class="s-icon">📧</div>
|
||||
<div class="s-info">
|
||||
<h3 data-i18n="srv_mail">BenzCloud Mail</h3>
|
||||
<p class="s-url" id="urlMail">http://mail.domain</p>
|
||||
<p class="s-desc" data-i18n="srv_mail_desc">Geschlossenes internes E-Mail-System (SMTP/IMAP) mit integrierter Webmail-Oberfläche.</p>
|
||||
</div>
|
||||
</a>
|
||||
<a class="service-card" id="linkChat" href="#" target="_blank">
|
||||
<div class="s-icon">💬</div>
|
||||
<div class="s-info">
|
||||
<h3 data-i18n="srv_chat">BenzCloud Chat</h3>
|
||||
<p class="s-url" id="urlChat">http://chat.domain</p>
|
||||
<p class="s-desc" data-i18n="srv_chat_desc">Echtzeit-Team-Chat (Slack/Teams-Alternative) für verschlüsselte Kommunikation.</p>
|
||||
</div>
|
||||
</a>
|
||||
<a class="service-card" id="linkWeb" href="#" target="_blank">
|
||||
<div class="s-icon">🌐</div>
|
||||
<div class="s-info">
|
||||
<h3 data-i18n="srv_web">Web-Hosting Engine</h3>
|
||||
<p class="s-url" id="urlWeb">http://*.domain</p>
|
||||
<p class="s-desc" data-i18n="srv_web_desc">Eigene Webseiten unter frei wählbaren Subdomains (HTML, PHP, Astro).</p>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="pairing-box">
|
||||
<div class="pairing-header">
|
||||
<span class="pair-icon">📱</span>
|
||||
<div>
|
||||
<h3 data-i18n="pair_title">Client-Kopplung (Android & PC)</h3>
|
||||
<p data-i18n="pair_desc">Verbinde die Client-App einmalig über die lokale Server-IP. Danach läuft die gesamte Kommunikation automatisch verschlüsselt über das Mesh-VPN und den Custom-DNS.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pairing-details">
|
||||
<div class="p-item">
|
||||
<strong data-i18n="pair_server_endpoint">Server LAN-Kopplungs-Endpunkt:</strong>
|
||||
<code id="pairEndpoint">http://192.168.0.5:8080/api/pair</code>
|
||||
</div>
|
||||
<div class="p-item">
|
||||
<strong data-i18n="pair_cli_cmd">Verbindungsbefehl (BenzCloud-Client CLI):</strong>
|
||||
<code id="pairCliCmd">benzcloud-client pair -server http://192.168.0.5:8080 -user admin</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TAB CONTENT: DRIVE -->
|
||||
<div id="tabContent_drive" class="tab-pane">
|
||||
<div class="drive-header">
|
||||
<h2 data-i18n="drive_vault_title">Verschlüsselter Dateispeicher (AES-256-GCM)</h2>
|
||||
<div class="drive-actions">
|
||||
<input type="file" id="fileUploadInput" onchange="uploadSelectedFile()" style="display:none;">
|
||||
<button class="btn-primary" onclick="document.getElementById('fileUploadInput').click()" data-i18n="btn_upload">⬆️ Datei hochladen</button>
|
||||
<button class="btn-secondary" onclick="promptNewFolder()" data-i18n="btn_new_folder">📁 Neuer Ordner</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="file-table-wrapper">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="th_name">Name</th>
|
||||
<th data-i18n="th_size">Größe</th>
|
||||
<th data-i18n="th_date">Änderungsdatum</th>
|
||||
<th data-i18n="th_actions">Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="fileTableBody">
|
||||
<tr><td colspan="4" class="text-center" data-i18n="loading_files">Lade Dateien...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TAB CONTENT: VPN -->
|
||||
<div id="tabContent_vpn" class="tab-pane">
|
||||
<h2 data-i18n="vpn_title">Slack Nebula Mesh-VPN & Peer-Topologie</h2>
|
||||
<p class="text-muted" data-i18n="vpn_desc">Das P2P Mesh-Overlay verbindet alle autorisierten Endgeräte verschlüsselt ohne Portweiterleitungen am Router.</p>
|
||||
<div class="peer-table-wrapper">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="th_peer_name">Node / Peer Name</th>
|
||||
<th data-i18n="th_overlay_ip">Overlay IP</th>
|
||||
<th data-i18n="th_role">Rolle</th>
|
||||
<th data-i18n="th_status">Status</th>
|
||||
<th data-i18n="th_valid_until">Zertifikat gültig bis</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="peerTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TAB CONTENT: DNS -->
|
||||
<div id="tabContent_dns" class="tab-pane">
|
||||
<h2 data-i18n="dns_title">Custom DNS Server & Subdomain-Routing</h2>
|
||||
<div class="dns-grid">
|
||||
<div class="dns-card">
|
||||
<h3 data-i18n="dns_records_title">Autoritative System-Subdomains</h3>
|
||||
<div id="dnsRecordsList" class="records-list"></div>
|
||||
</div>
|
||||
<div class="dns-card">
|
||||
<h3 data-i18n="dns_logs_title">Live DNS-Abfragen (RFC 1035)</h3>
|
||||
<div id="dnsLogsList" class="logs-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TAB CONTENT: PLUGINS -->
|
||||
<div id="tabContent_plugins" class="tab-pane">
|
||||
<h2 data-i18n="plugins_title">Modulare Enterprise-Plugins</h2>
|
||||
<p class="text-muted" data-i18n="plugins_desc">Der Server orchestriert Module in getrennten Prozessen über token-gesicherte Schnittstellen.</p>
|
||||
<div id="pluginCardsGrid" class="plugins-grid"></div>
|
||||
</div>
|
||||
|
||||
<!-- TAB CONTENT: USERS -->
|
||||
<div id="tabContent_users" class="tab-pane">
|
||||
<div class="users-header">
|
||||
<h2 data-i18n="users_title">Benutzer- und Rechteverwaltung</h2>
|
||||
<button class="btn-primary" onclick="openCreateUserModal()" data-i18n="btn_create_user">➕ Neuer Benutzer</button>
|
||||
</div>
|
||||
<div class="users-table-wrapper">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="th_user">Benutzer</th>
|
||||
<th data-i18n="th_overlay_ip">Overlay IP</th>
|
||||
<th data-i18n="th_perms">Berechtigungen</th>
|
||||
<th data-i18n="th_base_perms">Basis-Privilegien (Fixiert)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="usersTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- CREATE USER MODAL -->
|
||||
<div id="createUserModal" class="modal-backdrop" style="display:none;">
|
||||
<div class="modal-card">
|
||||
<h3 data-i18n="modal_create_user_title">Neuen Benutzer anlegen</h3>
|
||||
<form id="createUserForm" onsubmit="submitCreateUser(event)">
|
||||
<div class="form-group">
|
||||
<label data-i18n="lbl_username">Benutzername:</label>
|
||||
<input type="text" id="newUsername" required placeholder="z. B. emil">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label data-i18n="lbl_password">Passwort:</label>
|
||||
<input type="password" id="newPassword" required placeholder="••••••••" minlength="8">
|
||||
</div>
|
||||
<div class="perms-group">
|
||||
<label class="check-label"><input type="checkbox" id="permDrive" checked> Drive (Cloud-Dateien)</label>
|
||||
<label class="check-label"><input type="checkbox" id="permMail" checked> Mail (E-Mail)</label>
|
||||
<label class="check-label"><input type="checkbox" id="permChat" checked> Chat (Team-Chat)</label>
|
||||
<label class="check-label"><input type="checkbox" id="permWeb" checked> Web (Web-Hosting)</label>
|
||||
</div>
|
||||
<div class="immutable-perms-notice">
|
||||
<span class="badge-lock">🔒</span>
|
||||
<span data-i18n="immutable_perms_text"><strong>VPN & DNS</strong> sind unveränderlich aktiv und können nicht entzogen werden.</span>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn-secondary" onclick="closeCreateUserModal()" data-i18n="btn_cancel">Abbrechen</button>
|
||||
<button type="submit" class="btn-primary" data-i18n="btn_save">Erstellen</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="app-footer">
|
||||
<div class="footer-content">
|
||||
<span>BenzCloud © 2026 Jeremy Benz • GNU GPLv3 Lizenz • Nebula (MIT)</span>
|
||||
<span class="pre-release-pill" data-i18n="pre_release_pill">Pre-Release / In aktiver Entwicklung</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
681
web/style.css
Normal file
681
web/style.css
Normal file
@ -0,0 +1,681 @@
|
||||
/* BenzCloud Design System & Tokens */
|
||||
:root {
|
||||
--bg-page: #0a0e17;
|
||||
--bg-surface: #121826;
|
||||
--bg-card: #182032;
|
||||
--bg-card-hover: #1e293f;
|
||||
--border-subtle: #243048;
|
||||
--border-focus: #38bdf8;
|
||||
|
||||
--text-main: #f1f5f9;
|
||||
--text-muted: #94a3b8;
|
||||
--text-subtle: #64748b;
|
||||
|
||||
--accent-blue: #38bdf8;
|
||||
--accent-blue-hover: #0284c7;
|
||||
--accent-green: #34d399;
|
||||
--accent-amber: #fbbf24;
|
||||
--accent-red: #f87171;
|
||||
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
--font-mono: "JetBrains Mono", "Fira Code", monospace;
|
||||
|
||||
--radius-sm: 6px;
|
||||
--radius-md: 10px;
|
||||
--radius-lg: 16px;
|
||||
--shadow-card: 0 4px 20px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--bg-page);
|
||||
color: var(--text-main);
|
||||
font-family: var(--font-sans);
|
||||
line-height: 1.5;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.app-header {
|
||||
background-color: var(--bg-surface);
|
||||
border-bottom: 1px solid var(--border-subtle);
|
||||
padding: 1rem 2rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.logo-icon {
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
|
||||
.brand-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.brand-badge {
|
||||
background-color: rgba(56, 189, 248, 0.15);
|
||||
color: var(--accent-blue);
|
||||
border: 1px solid rgba(56, 189, 248, 0.3);
|
||||
font-size: 0.75rem;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: var(--radius-sm);
|
||||
margin-left: 0.4rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.domain-pill {
|
||||
background-color: var(--bg-card);
|
||||
border: 1px solid var(--border-subtle);
|
||||
color: var(--accent-green);
|
||||
font-size: 0.8rem;
|
||||
font-family: var(--font-mono);
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.lang-switcher {
|
||||
display: flex;
|
||||
background-color: var(--bg-card);
|
||||
border-radius: var(--radius-sm);
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border-subtle);
|
||||
}
|
||||
|
||||
.btn-lang {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
padding: 0.3rem 0.7rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-lang.active {
|
||||
background-color: var(--accent-blue);
|
||||
color: #000;
|
||||
}
|
||||
|
||||
/* Main Layout */
|
||||
.main-content {
|
||||
flex: 1;
|
||||
max-width: 1200px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
padding: 2rem 1.5rem;
|
||||
}
|
||||
|
||||
/* Wizard */
|
||||
.wizard-card, .auth-card {
|
||||
background-color: var(--bg-surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 2.5rem;
|
||||
max-width: 680px;
|
||||
margin: 2rem auto;
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.wizard-badge {
|
||||
display: inline-block;
|
||||
background-color: rgba(52, 211, 153, 0.15);
|
||||
color: var(--accent-green);
|
||||
border: 1px solid rgba(52, 211, 153, 0.3);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
padding: 0.25rem 0.75rem;
|
||||
border-radius: 9999px;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.wizard-title {
|
||||
font-size: 2rem;
|
||||
font-weight: 800;
|
||||
margin-bottom: 0.75rem;
|
||||
background: linear-gradient(135deg, #fff, var(--text-muted));
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.wizard-desc {
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 2rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.4rem;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
width: 100%;
|
||||
background-color: var(--bg-card);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-main);
|
||||
padding: 0.75rem 1rem;
|
||||
font-size: 0.95rem;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
input[type="text"]:focus, input[type="password"]:focus {
|
||||
outline: none;
|
||||
border-color: var(--border-focus);
|
||||
}
|
||||
|
||||
.form-hint {
|
||||
display: block;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-subtle);
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
|
||||
.wizard-security-notice {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
background-color: rgba(56, 189, 248, 0.08);
|
||||
border: 1px solid rgba(56, 189, 248, 0.2);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1rem;
|
||||
margin-bottom: 1.75rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.sec-icon {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn-primary {
|
||||
background-color: var(--accent-blue);
|
||||
color: #04101d;
|
||||
font-weight: 700;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 0.75rem 1.5rem;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: var(--accent-blue-hover);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: var(--bg-card);
|
||||
color: var(--text-main);
|
||||
font-weight: 600;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 0.75rem 1.25rem;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: var(--bg-card-hover);
|
||||
}
|
||||
|
||||
.btn-lg {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.btn-block {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 0.4rem 0.8rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.btn-outline {
|
||||
background: transparent;
|
||||
border: 1px solid var(--border-subtle);
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.btn-outline:hover {
|
||||
border-color: var(--text-main);
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
/* Metrics Grid */
|
||||
.metrics-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.metric-card {
|
||||
background-color: var(--bg-surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.m-label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
|
||||
.m-value {
|
||||
font-size: 1.4rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.m-sub {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-subtle);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.text-green { color: var(--accent-green); }
|
||||
.text-blue { color: var(--accent-blue); }
|
||||
|
||||
.pulse-dot {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--accent-green);
|
||||
box-shadow: 0 0 8px var(--accent-green);
|
||||
margin-right: 0.4rem;
|
||||
}
|
||||
|
||||
/* Tab Navigation */
|
||||
.tab-nav {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
border-bottom: 1px solid var(--border-subtle);
|
||||
margin-bottom: 1.5rem;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.tab-btn {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
padding: 0.6rem 1rem;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.tab-btn:hover {
|
||||
color: var(--text-main);
|
||||
background-color: var(--bg-card);
|
||||
}
|
||||
|
||||
.tab-btn.active {
|
||||
color: var(--accent-blue);
|
||||
background-color: rgba(56, 189, 248, 0.12);
|
||||
}
|
||||
|
||||
.tab-pane {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab-pane.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Services Grid */
|
||||
.services-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 1.25rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.service-card {
|
||||
background-color: var(--bg-surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.5rem;
|
||||
display: flex;
|
||||
gap: 1.25rem;
|
||||
text-decoration: none;
|
||||
color: var(--text-main);
|
||||
transition: transform 0.2s, border-color 0.2s, background-color 0.2s;
|
||||
}
|
||||
|
||||
.service-card:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: var(--border-focus);
|
||||
background-color: var(--bg-card);
|
||||
}
|
||||
|
||||
.s-icon {
|
||||
font-size: 2.25rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.s-info h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
|
||||
.s-url {
|
||||
font-size: 0.8rem;
|
||||
font-family: var(--font-mono);
|
||||
color: var(--accent-blue);
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.s-desc {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* Pairing Box */
|
||||
.pairing-box {
|
||||
background-color: var(--bg-surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.pairing-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.pair-icon {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.pairing-details {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.p-item {
|
||||
background-color: var(--bg-card);
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: var(--radius-sm);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85rem;
|
||||
color: var(--accent-green);
|
||||
background-color: rgba(0, 0, 0, 0.3);
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* Tables */
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 1rem;
|
||||
background-color: var(--bg-surface);
|
||||
border-radius: var(--radius-md);
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border-subtle);
|
||||
}
|
||||
|
||||
.data-table th, .data-table td {
|
||||
padding: 0.85rem 1.25rem;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--border-subtle);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
background-color: var(--bg-card);
|
||||
color: var(--text-muted);
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
font-size: 0.75rem;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.data-table tr:hover {
|
||||
background-color: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
/* Badges & Tags */
|
||||
.badge-tag {
|
||||
display: inline-block;
|
||||
font-size: 0.75rem;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 9999px;
|
||||
font-weight: 600;
|
||||
margin-right: 0.25rem;
|
||||
}
|
||||
|
||||
.badge-green {
|
||||
background-color: rgba(52, 211, 153, 0.15);
|
||||
color: var(--accent-green);
|
||||
border: 1px solid rgba(52, 211, 153, 0.3);
|
||||
}
|
||||
|
||||
.badge-blue {
|
||||
background-color: rgba(56, 189, 248, 0.15);
|
||||
color: var(--accent-blue);
|
||||
border: 1px solid rgba(56, 189, 248, 0.3);
|
||||
}
|
||||
|
||||
.badge-locked {
|
||||
background-color: rgba(52, 211, 153, 0.2);
|
||||
color: var(--accent-green);
|
||||
border: 1px solid rgba(52, 211, 153, 0.4);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* DNS Grid */
|
||||
.dns-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1.5rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.dns-card {
|
||||
background-color: var(--bg-surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.dns-card h3 {
|
||||
font-size: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.records-list, .logs-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.record-row, .log-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 0.6rem 0.8rem;
|
||||
background-color: var(--bg-card);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.85rem;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
/* Plugins Grid */
|
||||
.plugins-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
|
||||
gap: 1.25rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.plugin-card {
|
||||
background-color: var(--bg-surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.p-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.p-title {
|
||||
font-weight: 700;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
top: 0; left: 0; right: 0; bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 200;
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.modal-card {
|
||||
background-color: var(--bg-surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 2rem;
|
||||
max-width: 480px;
|
||||
width: 90%;
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.perms-group {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.75rem;
|
||||
margin: 1.25rem 0;
|
||||
}
|
||||
|
||||
.check-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-weight: 500;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.immutable-perms-notice {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
background-color: rgba(52, 211, 153, 0.1);
|
||||
border: 1px solid rgba(52, 211, 153, 0.25);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--accent-green);
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
/* Footer */
|
||||
.app-footer {
|
||||
border-top: 1px solid var(--border-subtle);
|
||||
padding: 1.25rem 2rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-subtle);
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.footer-content {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.pre-release-pill {
|
||||
background-color: rgba(251, 191, 36, 0.12);
|
||||
color: var(--accent-amber);
|
||||
border: 1px solid rgba(251, 191, 36, 0.3);
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 9999px;
|
||||
font-weight: 600;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user