Compare commits

...

9 Commits

Author SHA1 Message Date
Maycon Santos
d9fb379abf Enable connect buttons (#493)
Some checks failed
build and push / build_n_push (push) Has been cancelled
2025-10-06 16:23:00 -03:00
Eduard Gert
831673d0d6 Sync with cloud (#491)
Some checks failed
build and push / build_n_push (push) Has been cancelled
implements a "Sync with cloud" functionality that includes various UI improvements, code refactoring, and component extractions. The changes focus on enhancing the user interface, improving code organization, and adding new features for remote access and activity tracking.

- Refactors inline components into reusable shared components
- Adds new activity tracking for group operations
- Updates remote access configuration and UI components
- Enhances styling and layout for better user experience
2025-10-03 14:37:11 +02:00
Maycon Santos
bc4aac10aa Add browser client support (#490)
Some checks failed
build and push / build_n_push (push) Has been cancelled
* Sync wasm rdp and ssh client

* sync package-lock

* remove msp ref

* add ephemeral info
2025-10-02 00:41:08 +02:00
Eduard Gert
38e14a6c64 Allow delete groups issued by jwt (#487)
Some checks failed
build and push / build_n_push (push) Has been cancelled
2025-09-10 14:41:19 +02:00
Maycon Santos
b79c6615b4 Add user approval feature (#486)
Some checks failed
build and push / build_n_push (push) Has been cancelled
implements a user approval feature that allows administrators to manually approve new users before they can access the system. The feature adds approval workflow controls and error handling for blocked/pending users.

Adds user approval toggle in authentication settings
Implements approve/reject actions for pending users in the users table
Creates error page for blocked/pending approval scenarios
2025-09-02 15:25:30 +02:00
hakansa
5d4e491611 Add skip_auto_apply feature to exit nodes and update related components (#484)
Some checks failed
build and push / build_n_push (push) Has been cancelled
2025-08-20 13:11:45 +02:00
Eduard Gert
9b1f920863 Update dependencies (#483) 2025-08-19 17:32:22 +02:00
Eduard Gert
7c7f0a0f10 Add network range (#482)
Some checks failed
build and push / build_n_push (push) Has been cancelled
2025-08-13 14:18:59 +02:00
braginini
76541c701c Update LICENSE 2025-08-05 11:19:13 +02:00
109 changed files with 8321 additions and 923 deletions

View File

@@ -28,6 +28,33 @@ jobs:
- run: echo '{}' > .local-config.json
- name: Download IronRDP release TS files
uses: robinraju/release-downloader@v1.7
with:
token: ${{ secrets.GITHUB_TOKEN }}
repository: netbirdio/IronRDP
latest: true
fileName: "*.ts"
out-file-path: 'public/ironrdp-pkg'
- name: Download IronRDP release JS files
uses: robinraju/release-downloader@v1.7
with:
token: ${{ secrets.GITHUB_TOKEN }}
repository: netbirdio/IronRDP
latest: true
fileName: "*.js"
out-file-path: 'public/ironrdp-pkg'
- name: Download IronRDP release WASM file
uses: robinraju/release-downloader@v1.7
with:
token: ${{ secrets.GITHUB_TOKEN }}
repository: netbirdio/IronRDP
latest: true
fileName: "ironrdp_web_bg.wasm"
out-file-path: 'public/ironrdp-pkg'
- name: Build
run: npm run build
-
@@ -44,7 +71,6 @@ jobs:
images: ${{ env.IMAGE_NAME }}
-
name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
with:
username: ${{ secrets.NB_DOCKER_USER }}
@@ -55,7 +81,7 @@ jobs:
with:
context: .
file: docker/Dockerfile
push: ${{ github.event_name != 'pull_request' }}
push: true
platforms: linux/amd64,linux/arm64,linux/arm
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

5
.gitignore vendored
View File

@@ -41,3 +41,8 @@ next-env.d.ts
.configs/.staging-config.json
.configs/.temp-config.json
.configs
/public/ironrdp-pkg/
/public/netbird.wasm
.idea
src/.local-config*

662
LICENSE
View File

@@ -1,13 +1,661 @@
BSD 3-Clause License
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2024 Wiretrustee UG (haftungsbeschränkt) & AUTHORS
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.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Preamble
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -3,6 +3,10 @@ server {
listen [::]:80 default_server;
root /usr/share/nginx/html;
location = /netbird.wasm {
root /usr/share/nginx/html;
default_type application/wasm;
}
location / {
try_files $uri $uri.html $uri/ =404;

View File

@@ -101,6 +101,7 @@ http {
application/rss+xml
application/vnd.geo+json
application/vnd.ms-fontobject
application/wasm
application/x-font-ttf
application/x-web-app-manifest+json
application/xhtml+xml

159
package-lock.json generated
View File

@@ -35,6 +35,8 @@
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/react-window": "^1.8.8",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
"autoprefixer": "^10",
"chart.js": "^4.4.8",
"chroma-js": "^3.1.2",
@@ -513,9 +515,9 @@
"license": "MIT"
},
"node_modules/@next/env": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.28.tgz",
"integrity": "sha512-PAmWhJfJQlP+kxZwCjrVd9QnR5x0R3u0mTXTiZDgSd4h5LdXmjxCCWbN9kq6hkZBOax8Rm3xDW5HagWyJuT37g==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.32.tgz",
"integrity": "sha512-n9mQdigI6iZ/DF6pCTwMKeWgF2e8lg7qgt5M7HXMLtyhZYMnf/u905M18sSpPmHL9MKp9JHo56C6jrD2EvWxng==",
"license": "MIT"
},
"node_modules/@next/eslint-plugin-next": {
@@ -529,9 +531,9 @@
}
},
"node_modules/@next/eslint-plugin-next/node_modules/brace-expansion": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
"integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -578,9 +580,9 @@
}
},
"node_modules/@next/swc-darwin-arm64": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.28.tgz",
"integrity": "sha512-kzGChl9setxYWpk3H6fTZXXPFFjg7urptLq5o5ZgYezCrqlemKttwMT5iFyx/p1e/JeglTwDFRtb923gTJ3R1w==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.32.tgz",
"integrity": "sha512-osHXveM70zC+ilfuFa/2W6a1XQxJTvEhzEycnjUaVE8kpUS09lDpiDDX2YLdyFCzoUbvbo5r0X1Kp4MllIOShw==",
"cpu": [
"arm64"
],
@@ -594,9 +596,9 @@
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.28.tgz",
"integrity": "sha512-z6FXYHDJlFOzVEOiiJ/4NG8aLCeayZdcRSMjPDysW297Up6r22xw6Ea9AOwQqbNsth8JNgIK8EkWz2IDwaLQcw==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.32.tgz",
"integrity": "sha512-P9NpCAJuOiaHHpqtrCNncjqtSBi1f6QUdHK/+dNabBIXB2RUFWL19TY1Hkhu74OvyNQEYEzzMJCMQk5agjw1Qg==",
"cpu": [
"x64"
],
@@ -610,9 +612,9 @@
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.28.tgz",
"integrity": "sha512-9ARHLEQXhAilNJ7rgQX8xs9aH3yJSj888ssSjJLeldiZKR4D7N08MfMqljk77fAwZsWwsrp8ohHsMvurvv9liQ==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.32.tgz",
"integrity": "sha512-v7JaO0oXXt6d+cFjrrKqYnR2ubrD+JYP7nQVRZgeo5uNE5hkCpWnHmXm9vy3g6foMO8SPwL0P3MPw1c+BjbAzA==",
"cpu": [
"arm64"
],
@@ -626,9 +628,9 @@
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.28.tgz",
"integrity": "sha512-p6gvatI1nX41KCizEe6JkF0FS/cEEF0u23vKDpl+WhPe/fCTBeGkEBh7iW2cUM0rvquPVwPWdiUR6Ebr/kQWxQ==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.32.tgz",
"integrity": "sha512-tA6sIKShXtSJBTH88i0DRd6I9n3ZTirmwpwAqH5zdJoQF7/wlJXR8DkPmKwYl5mFWhEKr5IIa3LfpMW9RRwKmQ==",
"cpu": [
"arm64"
],
@@ -642,9 +644,9 @@
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.28.tgz",
"integrity": "sha512-nsiSnz2wO6GwMAX2o0iucONlVL7dNgKUqt/mDTATGO2NY59EO/ZKnKEr80BJFhuA5UC1KZOMblJHWZoqIJddpA==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.32.tgz",
"integrity": "sha512-7S1GY4TdnlGVIdeXXKQdDkfDysoIVFMD0lJuVVMeb3eoVjrknQ0JNN7wFlhCvea0hEk0Sd4D1hedVChDKfV2jw==",
"cpu": [
"x64"
],
@@ -658,9 +660,9 @@
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.28.tgz",
"integrity": "sha512-+IuGQKoI3abrXFqx7GtlvNOpeExUH1mTIqCrh1LGFf8DnlUcTmOOCApEnPJUSLrSbzOdsF2ho2KhnQoO0I1RDw==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.32.tgz",
"integrity": "sha512-OHHC81P4tirVa6Awk6eCQ6RBfWl8HpFsZtfEkMpJ5GjPsJ3nhPe6wKAJUZ/piC8sszUkAgv3fLflgzPStIwfWg==",
"cpu": [
"x64"
],
@@ -674,9 +676,9 @@
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.28.tgz",
"integrity": "sha512-l61WZ3nevt4BAnGksUVFKy2uJP5DPz2E0Ma/Oklvo3sGj9sw3q7vBWONFRgz+ICiHpW5mV+mBrkB3XEubMrKaA==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.32.tgz",
"integrity": "sha512-rORQjXsAFeX6TLYJrCG5yoIDj+NKq31Rqwn8Wpn/bkPNy5rTHvOXkW8mLFonItS7QC6M+1JIIcLe+vOCTOYpvg==",
"cpu": [
"arm64"
],
@@ -690,9 +692,9 @@
}
},
"node_modules/@next/swc-win32-ia32-msvc": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.28.tgz",
"integrity": "sha512-+Kcp1T3jHZnJ9v9VTJ/yf1t/xmtFAc/Sge4v7mVc1z+NYfYzisi8kJ9AsY8itbgq+WgEwMtOpiLLJsUy2qnXZw==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.32.tgz",
"integrity": "sha512-jHUeDPVHrgFltqoAqDB6g6OStNnFxnc7Aks3p0KE0FbwAvRg6qWKYF5mSTdCTxA3axoSAUwxYdILzXJfUwlHhA==",
"cpu": [
"ia32"
],
@@ -706,9 +708,9 @@
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.28.tgz",
"integrity": "sha512-1gCmpvyhz7DkB1srRItJTnmR2UwQPAUXXIg9r0/56g3O8etGmwlX68skKXJOp9EejW3hhv7nSQUJ2raFiz4MoA==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.32.tgz",
"integrity": "sha512-2N0lSoU4GjfLSO50wvKpMQgKd4HdI2UHEhQPPPnlgfBJlOgJxkjpkYBqzk08f1gItBB6xF/n+ykso2hgxuydsA==",
"cpu": [
"x64"
],
@@ -2809,9 +2811,9 @@
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
"integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2894,6 +2896,21 @@
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz",
"integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ=="
},
"node_modules/@xterm/addon-fit": {
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.10.0.tgz",
"integrity": "sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==",
"license": "MIT",
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
},
"node_modules/@xterm/xterm": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",
"integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==",
"license": "MIT"
},
"node_modules/acorn": {
"version": "8.14.1",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz",
@@ -3396,9 +3413,10 @@
"dev": true
},
"node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
@@ -4532,14 +4550,16 @@
}
},
"node_modules/es-set-tostringtag": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.2.tgz",
"integrity": "sha512-BuDyupZt65P9D2D2vA/zqcI3G5xRsklm5N3xCwuiy+/vKy8i0ifdsQP1sLgO4tZDSCaQUSnmC48khknGMV3D2Q==",
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"dev": true,
"license": "MIT",
"dependencies": {
"get-intrinsic": "^1.2.2",
"has-tostringtag": "^1.0.0",
"hasown": "^2.0.0"
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
@@ -5310,14 +5330,16 @@
}
},
"node_modules/form-data": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz",
"integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"dev": true,
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@@ -5683,12 +5705,13 @@
}
},
"node_modules/has-tostringtag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz",
"integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==",
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.2"
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
@@ -6783,12 +6806,12 @@
"integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="
},
"node_modules/next": {
"version": "14.2.28",
"resolved": "https://registry.npmjs.org/next/-/next-14.2.28.tgz",
"integrity": "sha512-QLEIP/kYXynIxtcKB6vNjtWLVs3Y4Sb+EClTC/CSVzdLD1gIuItccpu/n1lhmduffI32iPGEK2cLLxxt28qgYA==",
"version": "14.2.32",
"resolved": "https://registry.npmjs.org/next/-/next-14.2.32.tgz",
"integrity": "sha512-fg5g0GZ7/nFc09X8wLe6pNSU8cLWbLRG3TZzPJ1BJvi2s9m7eF991se67wliM9kR5yLHRkyGKU49MMx58s3LJg==",
"license": "MIT",
"dependencies": {
"@next/env": "14.2.28",
"@next/env": "14.2.32",
"@swc/helpers": "0.5.5",
"busboy": "1.6.0",
"caniuse-lite": "^1.0.30001579",
@@ -6803,15 +6826,15 @@
"node": ">=18.17.0"
},
"optionalDependencies": {
"@next/swc-darwin-arm64": "14.2.28",
"@next/swc-darwin-x64": "14.2.28",
"@next/swc-linux-arm64-gnu": "14.2.28",
"@next/swc-linux-arm64-musl": "14.2.28",
"@next/swc-linux-x64-gnu": "14.2.28",
"@next/swc-linux-x64-musl": "14.2.28",
"@next/swc-win32-arm64-msvc": "14.2.28",
"@next/swc-win32-ia32-msvc": "14.2.28",
"@next/swc-win32-x64-msvc": "14.2.28"
"@next/swc-darwin-arm64": "14.2.32",
"@next/swc-darwin-x64": "14.2.32",
"@next/swc-linux-arm64-gnu": "14.2.32",
"@next/swc-linux-arm64-musl": "14.2.32",
"@next/swc-linux-x64-gnu": "14.2.32",
"@next/swc-linux-x64-musl": "14.2.32",
"@next/swc-win32-arm64-msvc": "14.2.32",
"@next/swc-win32-ia32-msvc": "14.2.32",
"@next/swc-win32-x64-msvc": "14.2.32"
},
"peerDependencies": {
"@opentelemetry/api": "^1.1.0",
@@ -8565,9 +8588,9 @@
"license": "MIT"
},
"node_modules/tmp": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.3.tgz",
"integrity": "sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==",
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz",
"integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==",
"dev": true,
"license": "MIT",
"engines": {

View File

@@ -40,6 +40,8 @@
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/react-window": "^1.8.8",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
"autoprefixer": "^10",
"chart.js": "^4.4.8",
"chroma-js": "^3.1.2",

575
public/wasm_exec.js Normal file
View File

@@ -0,0 +1,575 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
"use strict";
(() => {
const enosys = () => {
const err = new Error("not implemented");
err.code = "ENOSYS";
return err;
};
if (!globalThis.fs) {
let outputBuf = "";
globalThis.fs = {
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
writeSync(fd, buf) {
outputBuf += decoder.decode(buf);
const nl = outputBuf.lastIndexOf("\n");
if (nl != -1) {
console.log(outputBuf.substring(0, nl));
outputBuf = outputBuf.substring(nl + 1);
}
return buf.length;
},
write(fd, buf, offset, length, position, callback) {
if (offset !== 0 || length !== buf.length || position !== null) {
callback(enosys());
return;
}
const n = this.writeSync(fd, buf);
callback(null, n);
},
chmod(path, mode, callback) { callback(enosys()); },
chown(path, uid, gid, callback) { callback(enosys()); },
close(fd, callback) { callback(enosys()); },
fchmod(fd, mode, callback) { callback(enosys()); },
fchown(fd, uid, gid, callback) { callback(enosys()); },
fstat(fd, callback) { callback(enosys()); },
fsync(fd, callback) { callback(null); },
ftruncate(fd, length, callback) { callback(enosys()); },
lchown(path, uid, gid, callback) { callback(enosys()); },
link(path, link, callback) { callback(enosys()); },
lstat(path, callback) { callback(enosys()); },
mkdir(path, perm, callback) { callback(enosys()); },
open(path, flags, mode, callback) { callback(enosys()); },
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
readdir(path, callback) { callback(enosys()); },
readlink(path, callback) { callback(enosys()); },
rename(from, to, callback) { callback(enosys()); },
rmdir(path, callback) { callback(enosys()); },
stat(path, callback) { callback(enosys()); },
symlink(path, link, callback) { callback(enosys()); },
truncate(path, length, callback) { callback(enosys()); },
unlink(path, callback) { callback(enosys()); },
utimes(path, atime, mtime, callback) { callback(enosys()); },
};
}
if (!globalThis.process) {
globalThis.process = {
getuid() { return -1; },
getgid() { return -1; },
geteuid() { return -1; },
getegid() { return -1; },
getgroups() { throw enosys(); },
pid: -1,
ppid: -1,
umask() { throw enosys(); },
cwd() { throw enosys(); },
chdir() { throw enosys(); },
}
}
if (!globalThis.path) {
globalThis.path = {
resolve(...pathSegments) {
return pathSegments.join("/");
}
}
}
if (!globalThis.crypto) {
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
}
if (!globalThis.performance) {
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
}
if (!globalThis.TextEncoder) {
throw new Error("globalThis.TextEncoder is not available, polyfill required");
}
if (!globalThis.TextDecoder) {
throw new Error("globalThis.TextDecoder is not available, polyfill required");
}
const encoder = new TextEncoder("utf-8");
const decoder = new TextDecoder("utf-8");
globalThis.Go = class {
constructor() {
this.argv = ["js"];
this.env = {};
this.exit = (code) => {
if (code !== 0) {
console.warn("exit code:", code);
}
};
this._exitPromise = new Promise((resolve) => {
this._resolveExitPromise = resolve;
});
this._pendingEvent = null;
this._scheduledTimeouts = new Map();
this._nextCallbackTimeoutID = 1;
const setInt64 = (addr, v) => {
this.mem.setUint32(addr + 0, v, true);
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
}
const setInt32 = (addr, v) => {
this.mem.setUint32(addr + 0, v, true);
}
const getInt64 = (addr) => {
const low = this.mem.getUint32(addr + 0, true);
const high = this.mem.getInt32(addr + 4, true);
return low + high * 4294967296;
}
const loadValue = (addr) => {
const f = this.mem.getFloat64(addr, true);
if (f === 0) {
return undefined;
}
if (!isNaN(f)) {
return f;
}
const id = this.mem.getUint32(addr, true);
return this._values[id];
}
const storeValue = (addr, v) => {
const nanHead = 0x7FF80000;
if (typeof v === "number" && v !== 0) {
if (isNaN(v)) {
this.mem.setUint32(addr + 4, nanHead, true);
this.mem.setUint32(addr, 0, true);
return;
}
this.mem.setFloat64(addr, v, true);
return;
}
if (v === undefined) {
this.mem.setFloat64(addr, 0, true);
return;
}
let id = this._ids.get(v);
if (id === undefined) {
id = this._idPool.pop();
if (id === undefined) {
id = this._values.length;
}
this._values[id] = v;
this._goRefCounts[id] = 0;
this._ids.set(v, id);
}
this._goRefCounts[id]++;
let typeFlag = 0;
switch (typeof v) {
case "object":
if (v !== null) {
typeFlag = 1;
}
break;
case "string":
typeFlag = 2;
break;
case "symbol":
typeFlag = 3;
break;
case "function":
typeFlag = 4;
break;
}
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
this.mem.setUint32(addr, id, true);
}
const loadSlice = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
}
const loadSliceOfValues = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
const a = new Array(len);
for (let i = 0; i < len; i++) {
a[i] = loadValue(array + i * 8);
}
return a;
}
const loadString = (addr) => {
const saddr = getInt64(addr + 0);
const len = getInt64(addr + 8);
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
}
const testCallExport = (a, b) => {
this._inst.exports.testExport0();
return this._inst.exports.testExport(a, b);
}
const timeOrigin = Date.now() - performance.now();
this.importObject = {
_gotest: {
add: (a, b) => a + b,
callExport: testCallExport,
},
gojs: {
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
// This changes the SP, thus we have to update the SP used by the imported function.
// func wasmExit(code int32)
"runtime.wasmExit": (sp) => {
sp >>>= 0;
const code = this.mem.getInt32(sp + 8, true);
this.exited = true;
delete this._inst;
delete this._values;
delete this._goRefCounts;
delete this._ids;
delete this._idPool;
this.exit(code);
},
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
"runtime.wasmWrite": (sp) => {
sp >>>= 0;
const fd = getInt64(sp + 8);
const p = getInt64(sp + 16);
const n = this.mem.getInt32(sp + 24, true);
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
},
// func resetMemoryDataView()
"runtime.resetMemoryDataView": (sp) => {
sp >>>= 0;
this.mem = new DataView(this._inst.exports.mem.buffer);
},
// func nanotime1() int64
"runtime.nanotime1": (sp) => {
sp >>>= 0;
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
},
// func walltime() (sec int64, nsec int32)
"runtime.walltime": (sp) => {
sp >>>= 0;
const msec = (new Date).getTime();
setInt64(sp + 8, msec / 1000);
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
},
// func scheduleTimeoutEvent(delay int64) int32
"runtime.scheduleTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this._nextCallbackTimeoutID;
this._nextCallbackTimeoutID++;
this._scheduledTimeouts.set(id, setTimeout(
() => {
this._resume();
while (this._scheduledTimeouts.has(id)) {
// for some reason Go failed to register the timeout event, log and try again
// (temporary workaround for https://github.com/golang/go/issues/28975)
console.warn("scheduleTimeoutEvent: missed timeout event");
this._resume();
}
},
getInt64(sp + 8),
));
this.mem.setInt32(sp + 16, id, true);
},
// func clearTimeoutEvent(id int32)
"runtime.clearTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this.mem.getInt32(sp + 8, true);
clearTimeout(this._scheduledTimeouts.get(id));
this._scheduledTimeouts.delete(id);
},
// func getRandomData(r []byte)
"runtime.getRandomData": (sp) => {
sp >>>= 0;
crypto.getRandomValues(loadSlice(sp + 8));
},
// func finalizeRef(v ref)
"syscall/js.finalizeRef": (sp) => {
sp >>>= 0;
const id = this.mem.getUint32(sp + 8, true);
this._goRefCounts[id]--;
if (this._goRefCounts[id] === 0) {
const v = this._values[id];
this._values[id] = null;
this._ids.delete(v);
this._idPool.push(id);
}
},
// func stringVal(value string) ref
"syscall/js.stringVal": (sp) => {
sp >>>= 0;
storeValue(sp + 24, loadString(sp + 8));
},
// func valueGet(v ref, p string) ref
"syscall/js.valueGet": (sp) => {
sp >>>= 0;
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 32, result);
},
// func valueSet(v ref, p string, x ref)
"syscall/js.valueSet": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
},
// func valueDelete(v ref, p string)
"syscall/js.valueDelete": (sp) => {
sp >>>= 0;
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
},
// func valueIndex(v ref, i int) ref
"syscall/js.valueIndex": (sp) => {
sp >>>= 0;
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
},
// valueSetIndex(v ref, i int, x ref)
"syscall/js.valueSetIndex": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
},
// func valueCall(v ref, m string, args []ref) (ref, bool)
"syscall/js.valueCall": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const m = Reflect.get(v, loadString(sp + 16));
const args = loadSliceOfValues(sp + 32);
const result = Reflect.apply(m, v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, result);
this.mem.setUint8(sp + 64, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, err);
this.mem.setUint8(sp + 64, 0);
}
},
// func valueInvoke(v ref, args []ref) (ref, bool)
"syscall/js.valueInvoke": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.apply(v, undefined, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueNew(v ref, args []ref) (ref, bool)
"syscall/js.valueNew": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.construct(v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueLength(v ref) int
"syscall/js.valueLength": (sp) => {
sp >>>= 0;
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
},
// valuePrepareString(v ref) (ref, int)
"syscall/js.valuePrepareString": (sp) => {
sp >>>= 0;
const str = encoder.encode(String(loadValue(sp + 8)));
storeValue(sp + 16, str);
setInt64(sp + 24, str.length);
},
// valueLoadString(v ref, b []byte)
"syscall/js.valueLoadString": (sp) => {
sp >>>= 0;
const str = loadValue(sp + 8);
loadSlice(sp + 16).set(str);
},
// func valueInstanceOf(v ref, t ref) bool
"syscall/js.valueInstanceOf": (sp) => {
sp >>>= 0;
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
},
// func copyBytesToGo(dst []byte, src ref) (int, bool)
"syscall/js.copyBytesToGo": (sp) => {
sp >>>= 0;
const dst = loadSlice(sp + 8);
const src = loadValue(sp + 32);
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
// func copyBytesToJS(dst ref, src []byte) (int, bool)
"syscall/js.copyBytesToJS": (sp) => {
sp >>>= 0;
const dst = loadValue(sp + 8);
const src = loadSlice(sp + 16);
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
"debug": (value) => {
console.log(value);
},
}
};
}
async run(instance) {
if (!(instance instanceof WebAssembly.Instance)) {
throw new Error("Go.run: WebAssembly.Instance expected");
}
this._inst = instance;
this.mem = new DataView(this._inst.exports.mem.buffer);
this._values = [ // JS values that Go currently has references to, indexed by reference id
NaN,
0,
null,
true,
false,
globalThis,
this,
];
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
this._ids = new Map([ // mapping from JS values to reference ids
[0, 1],
[null, 2],
[true, 3],
[false, 4],
[globalThis, 5],
[this, 6],
]);
this._idPool = []; // unused ids that have been garbage collected
this.exited = false; // whether the Go program has exited
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
let offset = 4096;
const strPtr = (str) => {
const ptr = offset;
const bytes = encoder.encode(str + "\0");
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
offset += bytes.length;
if (offset % 8 !== 0) {
offset += 8 - (offset % 8);
}
return ptr;
};
const argc = this.argv.length;
const argvPtrs = [];
this.argv.forEach((arg) => {
argvPtrs.push(strPtr(arg));
});
argvPtrs.push(0);
const keys = Object.keys(this.env).sort();
keys.forEach((key) => {
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
});
argvPtrs.push(0);
const argv = offset;
argvPtrs.forEach((ptr) => {
this.mem.setUint32(offset, ptr, true);
this.mem.setUint32(offset + 4, 0, true);
offset += 8;
});
// The linker guarantees global data starts from at least wasmMinDataAddr.
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
const wasmMinDataAddr = 4096 + 8192;
if (offset >= wasmMinDataAddr) {
throw new Error("total length of command line and environment variables exceeds limit");
}
this._inst.exports.run(argc, argv);
if (this.exited) {
this._resolveExitPromise();
}
await this._exitPromise;
}
_resume() {
if (this.exited) {
throw new Error("Go program has already exited");
}
this._inst.exports.resume();
if (this.exited) {
this._resolveExitPromise();
}
}
_makeFuncWrapper(id) {
const go = this;
return function () {
const event = { id: id, this: this, args: arguments };
go._pendingEvent = event;
go._resume();
return event.result;
};
}
}
})();

View File

@@ -2,6 +2,7 @@
import Breadcrumbs from "@components/Breadcrumbs";
import Button from "@components/Button";
import { Callout } from "@components/Callout";
import Card from "@components/Card";
import FancyToggleSwitch from "@components/FancyToggleSwitch";
import FullTooltip from "@components/FullTooltip";
@@ -32,6 +33,7 @@ import dayjs from "dayjs";
import { isEmpty, trim } from "lodash";
import {
Barcode,
CalendarDays,
Cpu,
FlagIcon,
Globe,
@@ -64,6 +66,8 @@ import useGroupHelper from "@/modules/groups/useGroupHelper";
import { AccessiblePeersSection } from "@/modules/peer/AccessiblePeersSection";
import { PeerExpirationToggle } from "@/modules/peer/PeerExpirationToggle";
import { PeerNetworkRoutesSection } from "@/modules/peer/PeerNetworkRoutesSection";
import { RDPButton } from "@/modules/remote-access/rdp/RDPButton";
import { SSHButton } from "@/modules/remote-access/ssh/SSHButton";
export default function PeerPage() {
const queryParameter = useSearchParams();
@@ -219,7 +223,7 @@ const PeerGeneralInformation = () => {
<ModalTrigger>
<div
className={
"flex items-center gap-2 dark:text-neutral-300 text-neutral-500 hover:text-neutral-100 transition-all hover:bg-nb-gray-800/60 py-2 px-3 rounded-md cursor-pointer"
"flex h-8 w-8 items-center justify-center gap-2 dark:text-neutral-300 text-neutral-500 hover:text-neutral-100 transition-all hover:bg-nb-gray-800/60 rounded-md cursor-pointer"
}
>
<PencilIcon size={16} />
@@ -324,7 +328,7 @@ const PeerGeneralInformation = () => {
}
interactive={false}
className={"w-full block"}
disabled={!permission.peers.update}
disabled={permission.peers.update}
>
<FancyToggleSwitch
value={ssh}
@@ -346,6 +350,16 @@ const PeerGeneralInformation = () => {
/>
</FullTooltip>
{/* Remote Access Buttons */}
<div>
<Label>Remote Access</Label>
<HelpText>Connect directly to this peer via SSH or RDP.</HelpText>
<div className="flex gap-3">
<SSHButton peer={peer} />
<RDPButton peer={peer} />
</div>
</div>
{permission.groups.read && (
<div>
<Label>Assigned Groups</Label>
@@ -415,158 +429,217 @@ const PeerOverviewTabs = () => {
function PeerInformationCard({ peer }: Readonly<{ peer: Peer }>) {
const { isLoading, getRegionByPeer } = useCountries();
const { update } = usePeer();
const { mutate } = useSWRConfig();
const [showEditIPModal, setShowEditIPModal] = useState(false);
const { permission } = usePermissions();
const countryText = useMemo(() => {
return getRegionByPeer(peer);
}, [getRegionByPeer, peer]);
return (
<Card className={"w-full xl:w-1/2"}>
<Card.List>
<Card.ListItem
copy
copyText={"NetBird IP-Address"}
label={
<>
<MapPin size={16} />
NetBird IP-Address
</>
}
value={peer.ip}
<>
<Modal open={showEditIPModal} onOpenChange={setShowEditIPModal}>
<EditIPModal
onSuccess={(newIP) => {
notify({
title: peer.name,
description: "Peer IP was successfully updated",
promise: update({ ip: newIP }).then(() => {
mutate("/peers/" + peer.id);
setShowEditIPModal(false);
}),
loadingMessage: "Updating peer IP...",
});
}}
peer={peer}
key={showEditIPModal ? 1 : 0}
/>
<Card.ListItem
copy
copyText={"Public IP-Address"}
label={
<>
<NetworkIcon size={16} />
Public IP-Address
</>
}
value={peer.connection_ip}
/>
<Card.ListItem
copy
copyText={"DNS label"}
label={
<>
<Globe size={16} />
Domain Name
</>
}
className={
peer?.extra_dns_labels && peer.extra_dns_labels.length > 0
? "items-start"
: ""
}
value={peer.dns_label}
extraText={peer?.extra_dns_labels}
/>
<Card.ListItem
copy
copyText={"Hostname"}
label={
<>
<MonitorSmartphoneIcon size={16} />
Hostname
</>
}
value={peer.hostname}
/>
<Card.ListItem
label={
<>
<FlagIcon size={16} />
Region
</>
}
tooltip={false}
value={
isEmpty(peer.country_code) ? (
"Unknown"
) : (
</Modal>
<Card className={"w-full xl:w-1/2"}>
<Card.List>
<Card.ListItem
copy
tooltip={false}
copyText={"NetBird IP Address"}
label={
<>
{isLoading ? (
<Skeleton width={140} />
) : (
<div className={"flex gap-2 items-center"}>
<div className={"border-0 border-nb-gray-800 rounded-full"}>
<RoundedFlag country={peer.country_code} size={12} />
</div>
{countryText}
</div>
)}
<MapPin size={16} />
NetBird IP Address
</>
)
}
/>
}
valueToCopy={peer.ip}
value={
<div className="flex items-center gap-2 justify-between w-full">
<span>{peer.ip}</span>
{permission.peers.update && (
<button
className="flex w-7 h-7 items-center justify-center gap-2 text-nb-gray-400 hover:text-neutral-100 transition-all hover:bg-nb-gray-800/60 rounded-md cursor-pointer"
onClick={(e) => {
e.stopPropagation();
setShowEditIPModal(true);
}}
>
<PencilIcon size={14} />
</button>
)}
</div>
}
/>
<Card.ListItem
label={
<>
<Cpu size={16} />
Operating System
</>
}
value={peer.os}
/>
<Card.ListItem
copy
copyText={"Public IP Address"}
label={
<>
<NetworkIcon size={16} />
Public IP Address
</>
}
value={peer.connection_ip}
/>
<Card.ListItem
copy
copyText={"DNS label"}
label={
<>
<Globe size={16} />
Domain Name
</>
}
className={
peer?.extra_dns_labels && peer.extra_dns_labels.length > 0
? "items-start"
: ""
}
value={peer.dns_label}
extraText={peer?.extra_dns_labels}
/>
<Card.ListItem
copy
copyText={"Hostname"}
label={
<>
<MonitorSmartphoneIcon size={16} />
Hostname
</>
}
value={peer.hostname}
/>
{peer.serial_number && peer.serial_number !== "" && (
<Card.ListItem
label={
<>
<Barcode size={16} />
Serial Number
<FlagIcon size={16} />
Region
</>
}
value={peer.serial_number}
tooltip={false}
value={
isEmpty(peer.country_code) ? (
"Unknown"
) : (
<>
{isLoading ? (
<Skeleton width={140} />
) : (
<div className={"flex gap-2 items-center"}>
<div
className={"border-0 border-nb-gray-800 rounded-full"}
>
<RoundedFlag country={peer.country_code} size={12} />
</div>
{countryText}
</div>
)}
</>
)
}
/>
)}
<Card.ListItem
label={
<>
<History size={16} />
Last seen
</>
}
value={
peer.connected
? "just now"
: dayjs(peer.last_seen).format("D MMMM, YYYY [at] h:mm A") +
<Card.ListItem
label={
<>
<Cpu size={16} />
Operating System
</>
}
value={peer.os}
/>
{peer.serial_number && peer.serial_number !== "" && (
<Card.ListItem
label={
<>
<Barcode size={16} />
Serial Number
</>
}
value={peer.serial_number}
/>
)}
{peer.created_at && (
<Card.ListItem
label={
<>
<CalendarDays size={16} />
Registered on
</>
}
value={
dayjs(peer.created_at).format("D MMMM, YYYY [at] h:mm A") +
" (" +
dayjs().to(peer.last_seen) +
dayjs().to(peer.created_at) +
")"
}
/>
}
/>
)}
<Card.ListItem
label={
<>
<NetBirdIcon size={16} />
Agent Version
</>
}
value={peer.version}
/>
<Card.ListItem
label={
<>
<History size={16} />
Last seen
</>
}
value={
peer.connected
? "just now"
: dayjs(peer.last_seen).format("D MMMM, YYYY [at] h:mm A") +
" (" +
dayjs().to(peer.last_seen) +
")"
}
/>
{peer.ui_version && (
<Card.ListItem
label={
<>
<NetBirdIcon size={16} />
UI Version
Agent Version
</>
}
value={peer.ui_version?.replace("netbird-desktop-ui/", "")}
value={peer.version}
/>
)}
</Card.List>
</Card>
{peer.ui_version && (
<Card.ListItem
label={
<>
<NetBirdIcon size={16} />
UI Version
</>
}
value={peer.ui_version?.replace("netbird-desktop-ui/", "")}
/>
)}
</Card.List>
</Card>
</>
);
}
@@ -654,3 +727,83 @@ function EditNameModal({ onSuccess, peer, initialName }: Readonly<ModalProps>) {
</ModalContent>
);
}
interface EditIPModalProps {
onSuccess: (ip: string) => void;
peer: Peer;
}
function EditIPModal({ onSuccess, peer }: Readonly<EditIPModalProps>) {
const [ip, setIP] = useState(peer.ip);
const [error, setError] = useState("");
const validateIP = (ipAddress: string) => {
const ipRegex =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return ipRegex.test(ipAddress);
};
const isDisabled = useMemo(() => {
if (ip === peer.ip) return true;
const trimmedIP = trim(ip);
return trimmedIP.length === 0 || !validateIP(ip);
}, [ip, peer.ip]);
React.useEffect(() => {
switch (true) {
case ip === peer.ip:
setError("");
break;
case !validateIP(ip):
setError("Please enter a valid IP, e.g., 100.64.0.15");
break;
default:
setError("");
break;
}
}, [ip, peer.ip]);
return (
<ModalContent maxWidthClass={"max-w-md"}>
<form>
<ModalHeader
title={"Edit Peer IP Address"}
description={"Update the NetBird IP address for this peer."}
color={"blue"}
/>
<div className={"p-default flex flex-col gap-4"}>
<div>
<Input
placeholder={"e.g., 100.64.0.15"}
value={ip}
onChange={(e) => setIP(e.target.value)}
error={error}
/>
</div>
<Callout>Changes take effect when the peer reconnects.</Callout>
</div>
<ModalFooter className={"items-center"} separator={false}>
<div className={"flex gap-3 w-full justify-end"}>
<ModalClose asChild={true}>
<Button variant={"secondary"} className={"w-full"}>
Cancel
</Button>
</ModalClose>
<Button
variant={"primary"}
className={"w-full"}
onClick={() => onSuccess(ip)}
disabled={isDisabled}
>
Save
</Button>
</div>
</ModalFooter>
</form>
</ModalContent>
);
}

View File

@@ -289,6 +289,7 @@ function UserInformationCard({ user }: Readonly<{ user: User }>) {
const neverLoggedIn = dayjs(user.last_login).isBefore(
dayjs().subtract(1000, "years"),
);
const isPendingApproval = user?.pending_approval;
return (
<Card>
@@ -328,18 +329,20 @@ function UserInformationCard({ user }: Readonly<{ user: User }>) {
{!isServiceUser && (
<>
{!user.is_current && user.role != Role.Owner && (
<Card.ListItem
tooltip={false}
label={
<>
<Ban size={16} />
Block User
</>
}
value={<UserBlockCell user={user} isUserPage={true} />}
/>
)}
{!user.is_current &&
user.role != Role.Owner &&
!isPendingApproval && (
<Card.ListItem
tooltip={false}
label={
<>
<Ban size={16} />
Block User
</>
}
value={<UserBlockCell user={user} isUserPage={true} />}
/>
)}
<Card.ListItem
label={

View File

@@ -0,0 +1,9 @@
"use client";
import UsersProvider from "@/contexts/UsersProvider";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<UsersProvider>{children}</UsersProvider>
);
}

View File

@@ -0,0 +1,212 @@
"use client";
import { notify } from "@components/Notification";
import FullScreenLoading from "@components/ui/FullScreenLoading";
import { IconCircleX } from "@tabler/icons-react";
import useFetchApi from "@utils/api";
import { Loader2Icon } from "lucide-react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import type { Peer } from "@/interfaces/Peer";
import { RDPCertificateModal } from "@/modules/remote-access/rdp/RDPCertificateModal";
import { RDPCredentialsModal } from "@/modules/remote-access/rdp/RDPCredentialsModal";
import { useRDPQueryParams } from "@/modules/remote-access/rdp/useRDPQueryParams";
import {
RDPCredentials,
RDPStatus,
useRemoteDesktop,
} from "@/modules/remote-access/rdp/useRemoteDesktop";
import {
NetBirdStatus,
useNetBirdClient,
} from "@/modules/remote-access/useNetBirdClient";
import { cn } from "@utils/helpers";
export default function RDPPage() {
const { peerId } = useRDPQueryParams();
const {
data: peer,
isLoading,
error,
} = useFetchApi<Peer>(`/peers/${peerId}`, true, false, !!peerId);
return (
<div className={"w-screen h-screen overflow-hidden"}>
{peerId && peer && !isLoading ? (
<RDPSession key={peer.id} peer={peer} />
) : (
<FullScreenLoading />
)}
</div>
);
}
type Props = {
peer: Peer;
};
function RDPSession({ peer }: Props) {
const client = useNetBirdClient();
const [isNetBirdConnecting, setIsNetBirdConnecting] = useState(false);
const rdp = useRemoteDesktop(client);
const [credentialsModal, setCredentialsModal] = useState(true);
const [credentials, setCredentials] = useState<RDPCredentials | null>(null);
const connected = useRef(false);
useEffect(() => {
document.title = `${peer.name} - ${peer.ip} - RDP`;
}, []);
const sendErrorNotification = (title: string, message: string) => {
notify({
title: title,
description: message,
icon: <IconCircleX size={24} />,
backgroundColor: "bg-red-500",
duration: 10000,
});
};
const reset = useCallback(async () => {
setCredentials(null);
connected.current = false;
setCredentialsModal(true);
rdp.session?.disconnect();
await client.disconnect();
}, [client, rdp]);
/**
* Establishes a connection to the peer
*/
const connect = async (rdpCredentials: RDPCredentials) => {
if (!peer?.id) return;
if (client.status === NetBirdStatus.DISCONNECTED) {
try {
setCredentials(rdpCredentials);
setIsNetBirdConnecting(true);
await client.connectTemporary(peer.id, [`tcp/${rdpCredentials.port}`]);
setIsNetBirdConnecting(false);
} catch (error) {
sendErrorNotification(
"NetBird Connection Error",
(error as Error).message,
);
setIsNetBirdConnecting(false);
}
}
};
const startSession = useCallback(async () => {
if (!credentials) return;
try {
const result = await rdp.connect({
hostname: peer.ip,
port: credentials.port,
username: credentials.username,
password: credentials.password,
width: window.innerWidth,
height: window.innerHeight,
});
if (result === RDPStatus.CONNECTED) {
connected.current = true;
} else {
}
} catch (error) {
sendErrorNotification("RDP Connection Error", (error as Error).message);
setCredentialsModal(true);
await reset();
}
}, [credentials, peer.ip, rdp, reset]);
/**
* Establish RDP session when NetBird connection is ready
*/
useEffect(() => {
if (
client.status === NetBirdStatus.CONNECTED &&
rdp.status === RDPStatus.DISCONNECTED &&
credentials &&
!connected.current &&
!isNetBirdConnecting
) {
startSession().catch(console.error);
}
}, [
client.status,
credentials,
peer.ip,
rdp,
startSession,
isNetBirdConnecting,
]);
/**
* Display notifications for RDP and NetBird client errors
*/
useEffect(() => {
if (rdp.error) {
sendErrorNotification("RDP Error", rdp.error);
}
if (client.error) {
sendErrorNotification("NetBird Client Error", client.error);
}
}, [rdp, client]);
/**
* Close credentials modal when RDP is connected
*/
useEffect(() => {
if (rdp.status === RDPStatus.CONNECTED) {
setCredentialsModal(false);
}
}, [rdp.status]);
const isLoading =
client.status === NetBirdStatus.CONNECTING ||
rdp.status === RDPStatus.CONNECTING ||
rdp.isResizing ||
isNetBirdConnecting;
return (
<>
{/* Credentials Modal */}
<RDPCredentialsModal
open={credentialsModal}
peer={peer}
onConnect={connect}
loading={isLoading}
/>
{/* Certificate Modal */}
<RDPCertificateModal
open={!!rdp.pendingCertificate}
certificateInfo={rdp.pendingCertificate}
onAccept={rdp.acceptCertificatePrompt}
onReject={async () => {
rdp.rejectCertificatePrompt();
await reset();
}}
/>
{rdp.isResizing && (
<div
className={
"fixed w-screen h-screen z-50 backdrop-blur bg-black/50 flex items-center justify-center"
}
>
<Loader2Icon size={20} className={"animate-spin"} />
</div>
)}
{/* RDP Canvas */}
<canvas
ref={rdp.canvasRef}
className={cn(
rdp.status === RDPStatus.CONNECTED ? "block" : "hidden",
"w-full h-full select-none bg-nb-gray-950",
)}
style={{ imageRendering: "pixelated" }}
/>
</>
);
}

View File

@@ -0,0 +1,233 @@
"use client";
import { PageNotFound } from "@components/ui/PageNotFound";
import useFetchApi, { ErrorResponse } from "@utils/api";
import { CircleXIcon, InfoIcon, Loader2Icon } from "lucide-react";
import React, { useEffect, useRef } from "react";
import type { Peer } from "@/interfaces/Peer";
import { Terminal } from "@/modules/remote-access/ssh/Terminal";
import { SSHStatus, useSSH } from "@/modules/remote-access/ssh/useSSH";
import { useSSHQueryParams } from "@/modules/remote-access/ssh/useSSHQueryParams";
import {
NetBirdStatus,
useNetBirdClient,
} from "@/modules/remote-access/useNetBirdClient";
export default function SSHPage() {
const { peerId, username, port } = useSSHQueryParams();
const {
data: peer,
isLoading,
error,
} = useFetchApi<Peer>(`/peers/${peerId}`, true, false, !!peerId);
if (error) {
return (
<div className={"w-screen h-screen overflow-hidden"}>
<ErrorMessage
error={{
message:
"This peer may have been deleted, or you may not have permission to view it.",
code: error.code,
}}
/>
</div>
);
}
return (
<div className={"w-screen h-screen overflow-hidden"}>
{peerId && peer && !isLoading && username && port ? (
<SSHTerminal
key={peer.id}
peer={peer}
username={username}
port={port}
/>
) : (
<LoadingMessage message={"Starting ssh session..."} />
)}
</div>
);
}
type Props = {
username: string;
port: string;
peer: Peer;
};
function SSHTerminal({ username, port, peer }: Props) {
const client = useNetBirdClient();
const connected = useRef(false);
const sshConnectedOnce = useRef(false);
const {
connect: ssh,
disconnect,
status,
session,
error: sshError,
} = useSSH(client);
const isSSHConnecting = status === SSHStatus.CONNECTING;
const isSSHConnected = status === SSHStatus.CONNECTED;
const isSSHDisconnected = status === SSHStatus.DISCONNECTED;
const isClientDisconnected = client.status === NetBirdStatus.DISCONNECTED;
const isClientConnecting = client.status === NetBirdStatus.CONNECTING;
useEffect(() => {
document.title = `${username}@${peer.ip} - ${peer.hostname}`;
}, [username, peer, client]);
const handleReconnect = async () => {
if (!peer?.id) return;
if (isSSHConnected || isSSHConnecting) return;
connected.current = false;
try {
const rules = [`tcp/${port}`];
await client?.connectTemporary(peer.id, rules);
await ssh({
hostname: peer.ip,
port: Number(port),
username,
});
} catch (error) {
console.error("Reconnection failed:", error);
}
};
useEffect(() => {
if (isSSHConnected || isSSHConnecting) return;
if (isClientConnecting || client.status === NetBirdStatus.CONNECTED) return;
const connect = async () => {
if (!peer.id) return;
if (connected.current) return;
connected.current = true;
try {
const rules = [`tcp/${port}`];
await client?.connectTemporary(peer.id, rules);
const res = await ssh({
hostname: peer.ip,
port: Number(port),
username,
});
if (res === SSHStatus.CONNECTED) {
sshConnectedOnce.current = true;
}
} catch (error) {
console.error("Connection failed:", error);
}
};
if (isClientDisconnected) connect().catch(console.error);
}, [
isClientDisconnected,
isSSHConnected,
isSSHConnecting,
isClientConnecting,
peer.id,
port,
ssh,
username,
client.connectTemporary,
client.status,
]);
if (client.error) {
return <ErrorMessage error={{ message: client.error, code: 0 }} />;
}
if (sshError) {
return <ErrorMessage error={{ message: sshError, code: 0 }} />;
}
if (isSSHDisconnected && sshConnectedOnce.current) {
return (
<DisconnectedMessage
username={username}
peerIp={peer.ip}
onReconnect={handleReconnect}
/>
);
}
return (
<>
{session && <Terminal session={session} onClose={disconnect} />}
{!isSSHConnected && (
<LoadingMessage message={`Connecting to ${username}@${peer.ip}...`} />
)}
</>
);
}
type MessageProps = {
message?: string;
error?: ErrorResponse;
};
const LoadingMessage = ({ message }: MessageProps) => {
return (
<div
className={
"w-full h-full flex items-center justify-center flex-col text-center"
}
>
<div className="text-nb-gray-200 font-normal text-base flex gap-2 items-center justify-center">
<Loader2Icon size={16} className={"animate-spin shrink-0"} />
{message}
</div>
</div>
);
};
const ErrorMessage = ({ error }: MessageProps) => {
return (
<div
className={
"w-full h-full flex items-center justify-center flex-col text-center"
}
>
<div className="text-nb-gray-200 font-normal text-base flex gap-2 items-center justify-center">
<CircleXIcon size={16} className={"shrink-0 text-red-500"} />
{error?.message}
</div>
</div>
);
};
type DisconnectedMessageProps = {
username: string;
peerIp: string;
onReconnect: () => void;
};
const DisconnectedMessage = ({
username,
peerIp,
onReconnect,
}: DisconnectedMessageProps) => {
return (
<div
className={
"w-full h-full flex items-center justify-center flex-col text-center gap-4"
}
>
<div className="text-nb-gray-200 font-normal text-base flex gap-2 items-center justify-center">
<InfoIcon size={16} className={"shrink-0 text-nb-gray-200"} />
Disconnected from {username}@{peerIp}
<button
className={
"underline-offset-4 items-center transition-all duration-200 inline-flex texts-inherit gap-1 text-netbird hover:underline font-normal"
}
onClick={onReconnect}
>
Reconnect
</button>
</div>
</div>
);
};

115
src/app/error/page.tsx Normal file
View File

@@ -0,0 +1,115 @@
"use client";
import { useOidc } from "@axa-fr/react-oidc";
import Button from "@components/Button";
import Paragraph from "@components/Paragraph";
import loadConfig from "@utils/config";
import { ArrowRightIcon, RefreshCw } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import NetBirdIcon from "@/assets/icons/NetBirdIcon";
const config = loadConfig();
export default function ErrorPage() {
const { logout, isAuthenticated } = useOidc();
const router = useRouter();
const searchParams = useSearchParams();
const [error, setError] = useState<{
code: number;
message: string;
type: string;
} | null>(null);
useEffect(() => {
// Get error details from URL params
const code = searchParams.get("code");
const message = searchParams.get("message");
const type = searchParams.get("type");
if (code && message) {
setError({
code: parseInt(code),
message: decodeURIComponent(message),
type: type || "error",
});
}
}, [searchParams]);
const handleLogout = () => {
// Use the same logout pattern as OIDCError
logout("/", { client_id: config.clientId });
};
const handleRetry = () => {
router.push("/");
};
if (!isAuthenticated) {
// If not authenticated, redirect to home
router.push("/");
return null;
}
const isBlockedUser =
error?.code === 403 && error?.message?.toLowerCase().includes("blocked");
const isPendingApproval =
error?.code === 403 &&
error?.message?.toLowerCase().includes("pending approval");
const getTitle = () => {
if (isBlockedUser) return "User Account Blocked";
if (isPendingApproval) return "User Approval Pending";
return "Access Error";
};
const getDescription = () => {
if (isBlockedUser) {
return "Your access has been blocked by the NetBird account administrator, possibly due to new user approval requirements or security policies. Please contact your administrator to regain access.";
}
if (isPendingApproval) {
return "Your account is pending approval from an administrator. Please wait for approval before accessing the dashboard.";
}
return "An error occurred while trying to access the dashboard. Please try again or contact your administrator.";
};
return (
<div className="flex items-center justify-center flex-col h-screen max-w-xl mx-auto">
<div className="bg-nb-gray-930 mb-3 border border-nb-gray-900 h-12 w-12 rounded-md flex items-center justify-center">
<NetBirdIcon size={23} />
</div>
<h1 className="text-center mt-2">{getTitle()}</h1>
<Paragraph className="text-center mt-2 block">
{getDescription()}
</Paragraph>
{error && (
<div className="bg-nb-gray-930 border border-nb-gray-800 rounded-md p-4 mt-4 max-w-md font-mono mb-2">
<div className="text-center text-sm text-netbird">
<div>response_message: {error.message}</div>
</div>
</div>
)}
<Paragraph className="text-center mt-2 text-sm">
If you believe this is an error, please contact your administrator.
</Paragraph>
<div className="mt-5 space-y-3">
{!isBlockedUser && !isPendingApproval && (
<Button variant="default-outline" size="sm" onClick={handleRetry}>
<RefreshCw size={16} className="mr-2" />
Try Again
</Button>
)}
<Button variant="primary" size="sm" onClick={handleLogout}>
{isBlockedUser || isPendingApproval ? "Sign Out" : "Logout"}
<ArrowRightIcon size={16} />
</Button>
</div>
</div>
);
}

View File

@@ -157,3 +157,14 @@ p {
.animate-bg-scroll-faster {
animation: bg-scroll 1.8s linear infinite;
}
/**
* Terminal (xterm)
*/
.xterm {
@apply m-0 p-1 box-border h-full w-full;
}
.xterm-viewport {
@apply m-0 p-0 box-border;
}

View File

@@ -35,6 +35,7 @@ export default function NotFound() {
}
const Redirect = ({ url, queryParams }: Props) => {
useRedirect("/peers" + (queryParams && `?${queryParams}`));
const params = queryParams && `?${queryParams}`;
useRedirect(url == "/" ? `/peers${params}` : `${url}${params}`);
return <FullScreenLoading />;
};

View File

@@ -58,6 +58,10 @@ export default function OIDCProvider({ children }: Props) {
"utm_content",
"utm_campaign",
"hs_id",
"page",
"page_size",
"user",
"port",
];
try {

View File

@@ -18,7 +18,7 @@ export const buttonVariants = cva(
"relative",
"text-sm focus:z-10 focus:ring-2 font-medium focus:outline-none whitespace-nowrap shadow-sm",
"inline-flex gap-2 items-center justify-center transition-colors focus:ring-offset-1",
"disabled:opacity-20 disabled:cursor-not-allowed disabled:dark:text-nb-gray-300 dark:ring-offset-neutral-950/50",
"disabled:opacity-40 disabled:cursor-not-allowed disabled:dark:text-nb-gray-300 dark:ring-offset-neutral-950/50",
],
{
variants: {
@@ -34,7 +34,7 @@ export const buttonVariants = cva(
secondary: [
"bg-white hover:text-black focus:ring-zinc-200/50 hover:bg-gray-100 border-gray-200 text-gray-900",
"dark:ring-offset-neutral-950/50 dark:focus:ring-neutral-500/20 ",
"dark:bg-nb-gray-900/30 dark:text-gray-400 dark:border-gray-700/40 dark:hover:text-white dark:hover:bg-zinc-800/50",
"dark:bg-nb-gray-920 dark:text-gray-400 dark:border-gray-700/40 dark:hover:text-white dark:hover:bg-zinc-800/50",
],
secondaryLighter: [
"bg-white hover:text-black focus:ring-zinc-200/50 hover:bg-gray-100 border-gray-200 text-gray-900",

View File

@@ -26,7 +26,7 @@ export const calloutVariants = cva(
export const Callout = ({
children,
icon = <InfoIcon size={14} className={"shrink-0 relative top-[2px]"} />,
icon = <InfoIcon size={14} className={"shrink-0 relative top-[3px]"} />,
className,
variant = "default",
}: Props) => {

View File

@@ -29,6 +29,7 @@ function CardList({ children }: Props) {
type CardListItemProps = {
label: React.ReactNode;
value: React.ReactNode;
valueToCopy?: string;
className?: string;
copy?: boolean;
copyText?: string;
@@ -39,6 +40,7 @@ type CardListItemProps = {
function CardListItem({
label,
value,
valueToCopy,
className,
copy = false,
copyText,
@@ -57,6 +59,7 @@ function CardListItem({
<CardTextItem
label={label}
value={value}
valueToCopy={valueToCopy}
copy={copy}
copyText={copyText}
tooltip={tooltip}
@@ -79,6 +82,7 @@ function CardListItem({
type CardTextItemProps = {
label: React.ReactNode;
value: React.ReactNode;
valueToCopy?: string;
copy?: boolean;
copyText?: string;
tooltip?: boolean;
@@ -88,10 +92,11 @@ const CardTextItem = ({
label,
value,
copy = false,
valueToCopy,
copyText,
tooltip = true,
}: CardTextItemProps) => {
const [, copyToClipBoard] = useCopyToClipboard(value as string);
const [, copyToClipBoard] = useCopyToClipboard(valueToCopy ?? `${value}`);
return (
<div
className={cn(

View File

@@ -25,6 +25,8 @@ type Props = {
customOnOpenChange?: React.Dispatch<React.SetStateAction<boolean>>;
delayDuration?: number;
skipDelayDuration?: number;
alignOffset?: number;
sideOffset?: number;
} & TooltipProps &
TooltipVariants;
@@ -45,6 +47,8 @@ export default function FullTooltip({
delayDuration = 1,
skipDelayDuration = 300,
variant = "default",
alignOffset = 20,
sideOffset,
}: Props) {
const [open, setOpen] = useState(!!keepOpen);
@@ -83,7 +87,8 @@ export default function FullTooltip({
)}
{!disabled && (
<TooltipContent
alignOffset={20}
alignOffset={alignOffset}
sideOffset={sideOffset}
forceMount={true}
className={contentClassName}
variant={variant}

View File

@@ -0,0 +1,29 @@
import * as React from "react";
import { cn } from "@utils/helpers";
export const ListItem = ({
icon,
label,
value,
className,
}: {
icon?: React.ReactNode;
label: string;
value: string | React.ReactNode;
className?: string;
}) => {
return (
<div
className={cn(
"flex justify-between gap-12 border-b border-nb-gray-920 py-2 px-4 last:border-b-0",
className,
)}
>
<div className={"flex items-center gap-2 text-nb-gray-100 font-medium"}>
{icon}
{label}
</div>
<div className={"text-nb-gray-300"}>{value}</div>
</div>
);
};

View File

@@ -0,0 +1,44 @@
import InlineLink from "@components/InlineLink";
import SquareIcon from "@components/SquareIcon";
import AddPeerButton from "@components/ui/AddPeerButton";
import GetStartedTest from "@components/ui/GetStartedTest";
import { ExternalLinkIcon } from "lucide-react";
import * as React from "react";
import PeerIcon from "@/assets/icons/PeerIcon";
type Props = {
showBackground?: boolean;
};
export const NoPeersGettingStarted = ({ showBackground = true }) => {
return (
<GetStartedTest
showBackground={showBackground}
icon={
<SquareIcon
icon={<PeerIcon className={"fill-nb-gray-200"} size={20} />}
color={"gray"}
size={"large"}
/>
}
title={"Get Started with NetBird"}
description={
"It looks like you don't have any connected machines.\n" +
"Get started by adding one to your network."
}
button={<AddPeerButton />}
learnMore={
<>
Learn more in our{" "}
<InlineLink
href={"https://docs.netbird.io/how-to/getting-started"}
target={"_blank"}
>
Getting Started Guide
<ExternalLinkIcon size={12} />
</InlineLink>
</>
}
/>
);
};

View File

@@ -42,8 +42,15 @@ import { NetworkResource } from "@/interfaces/Network";
import type { Peer } from "@/interfaces/Peer";
import { PolicyRuleResource } from "@/interfaces/Policy";
import { User } from "@/interfaces/User";
import { PeerOperatingSystemIcon } from "@/modules/peers/PeerOperatingSystemIcon";
import { HorizontalUsersStack } from "@/modules/users/HorizontalUsersStack";
const groupsSearchPredicate = (item: Group, query: string) => {
const lowerCaseQuery = query.toLowerCase();
if (item.name.toLowerCase().includes(lowerCaseQuery)) return true;
return item?.id?.toLowerCase().includes(lowerCaseQuery) ?? false;
};
interface MultiSelectProps {
values: Group[];
onChange: React.Dispatch<React.SetStateAction<Group[]>>;
@@ -60,6 +67,7 @@ interface MultiSelectProps {
dataCy?: string;
showResourceCounter?: boolean;
showResources?: boolean;
showPeers?: boolean;
resource?: PolicyRuleResource;
onResourceChange?: (resource?: PolicyRuleResource) => void;
placeholder?: string;
@@ -67,6 +75,7 @@ interface MultiSelectProps {
align?: "start" | "end";
side?: "top" | "bottom";
users?: User[];
placeholderForSearch?: string;
}
export function PeerGroupSelector({
onChange,
@@ -84,6 +93,7 @@ export function PeerGroupSelector({
dataCy = "group-selector-dropdown",
showResourceCounter = true,
showResources = false,
showPeers = false,
resource,
onResourceChange,
placeholder = "Add or select group(s)...",
@@ -91,16 +101,36 @@ export function PeerGroupSelector({
align = "start",
side = "bottom",
users,
placeholderForSearch = 'Search groups or add new group by pressing "Enter"...',
}: Readonly<MultiSelectProps>) {
const { data: resources, isLoading: isResourcesLoading } = useFetchApi<
NetworkResource[]
>("/networks/resources");
const { data: peers, isLoading: isPeersLoading } =
useFetchApi<Peer[]>("/peers");
const { groups, dropdownOptions, setDropdownOptions, addDropdownOptions } =
useGroups();
const searchRef = React.useRef<HTMLInputElement>(null);
const [inputRef, { width }] = useElementSize<
HTMLButtonElement | HTMLSpanElement
>();
const [search, setSearch] = useState("");
const { data: resources, isLoading } = useFetchApi<NetworkResource[]>(
"/networks/resources",
const [open, setOpen] = useState(false);
const sortedDropdownOptions = useSortedDropdownOptions(
dropdownOptions,
values,
open,
);
const [filteredGroups, search, setSearch] = useSearch(
sortedDropdownOptions,
groupsSearchPredicate,
{ filter: true, debounce: 150 },
);
// Update dropdown options when groups change
@@ -189,16 +219,6 @@ export function PeerGroupSelector({
return isSearching && groupDoesNotExist && !isAllGroup;
}, [search, dropdownOptions]);
const [open, setOpen] = useState(false);
const folderIcon = useMemo(() => {
return <FolderGit2 size={12} className={"shrink-0"} />;
}, []);
const peerIcon = useMemo(() => {
return <MonitorSmartphoneIcon size={14} className={"shrink-0"} />;
}, []);
const [slice, setSlice] = useState(10);
const [tab, setTab] = useState("groups");
@@ -219,12 +239,6 @@ export function PeerGroupSelector({
onChange(union);
};
const sortedDropdownOptions = useSortedDropdownOptions(
dropdownOptions,
values,
open,
);
// Reset the search input when switching tabs
useEffect(() => {
setSearch("");
@@ -233,10 +247,12 @@ export function PeerGroupSelector({
}, 0);
}, [tab]);
const searchPlaceholder =
tab === "groups"
? 'Search groups or add new group by pressing "Enter"...'
: "Search resource...";
const searchPlaceholder = useMemo(() => {
if (tab === "groups") return placeholderForSearch;
if (tab === "resources") return "Search resource...";
if (tab === "peers") return "Search peer...";
return "Search...";
}, [tab, placeholderForSearch]);
const selectResource = (resource?: NetworkResource) => {
onResourceChange?.(
@@ -250,6 +266,15 @@ export function PeerGroupSelector({
onChange([]);
};
const selectPeer = (peer?: Peer) => {
if (!peer?.id) return;
onResourceChange?.({
id: peer.id,
type: "peer",
});
onChange([]);
};
return (
<Popover
open={open}
@@ -288,6 +313,7 @@ export function PeerGroupSelector({
<ResourceBadge
className={"py-[3px]"}
resource={resources?.find((r) => r.id === resource.id)}
peer={peers?.find((p) => p.id === resource.id)}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
@@ -364,16 +390,7 @@ export function PeerGroupSelector({
side={side}
sideOffset={10}
>
<Command
className={"w-full flex"}
loop
filter={(value, search) => {
const formatValue = trim(value.toLowerCase());
const formatSearch = trim(search.toLowerCase());
if (formatValue.includes(formatSearch)) return 1;
return 0;
}}
>
<Command className={"w-full flex"} loop shouldFilter={false}>
<CommandList className={"w-full"}>
<div className={"relative"}>
<CommandInput
@@ -414,13 +431,17 @@ export function PeerGroupSelector({
</div>
<Tabs defaultValue={"groups"} value={tab} onValueChange={setTab}>
{showResources && <TabTriggers searchRef={searchRef} />}
<TabTriggers
searchRef={searchRef}
showPeers={showPeers}
showResources={showResources}
/>
<TabsContent value={"groups"} className={"p-0 my-0"}>
<CommandGroup>
<ScrollArea
className={cn(
"max-h-[195px] flex flex-col gap-1 pl-2 py-2 pr-3",
sortedDropdownOptions.length == 0 && !search && "py-0",
filteredGroups.length == 0 && !search && "py-0",
)}
>
{searchedGroupNotFound && (
@@ -433,8 +454,8 @@ export function PeerGroupSelector({
value={search}
onClick={(e) => e.preventDefault()}
>
<Badge variant={"gray-ghost"}>
{folderIcon}
<Badge variant={"gray-ghost"} className={"h-7"}>
<FolderGit2 size={12} className={"shrink-0"} />
{search}
</Badge>
<div
@@ -448,7 +469,7 @@ export function PeerGroupSelector({
</CommandItem>
)}
{sortedDropdownOptions.slice(0, slice).map((option) => {
{filteredGroups.slice(0, slice).map((option) => {
const isSelected =
values.find((group) => group.name == option.name) !=
undefined;
@@ -490,7 +511,11 @@ export function PeerGroupSelector({
onClick={(e) => e.preventDefault()}
>
<div className={"flex items-center gap-2"}>
<GroupBadge group={option} showNewBadge={true} />
<GroupBadge
group={option}
showNewBadge={true}
className={"h-7"}
/>
</div>
<div className={"flex items-center gap-5"}>
@@ -509,7 +534,10 @@ export function PeerGroupSelector({
"text-neutral-500 dark:text-nb-gray-300 font-medium flex items-center gap-2"
}
>
{peerIcon}
<MonitorSmartphoneIcon
size={14}
className={"shrink-0"}
/>
{peerCount} Peer(s)
</div>
) : (
@@ -535,12 +563,23 @@ export function PeerGroupSelector({
<ResourcesList
search={search}
resources={resources}
isLoading={isLoading}
isLoading={isResourcesLoading}
value={resource}
onChange={selectResource}
/>
</TabsContent>
)}
{showPeers && (
<TabsContent value={"peers"} className={"p-0 my-0"}>
<PeersList
search={search}
peers={peers}
isLoading={isPeersLoading}
value={resource}
onChange={selectPeer}
/>
</TabsContent>
)}
</Tabs>
</CommandList>
</Command>
@@ -551,9 +590,15 @@ export function PeerGroupSelector({
const TabTriggers = ({
searchRef,
showResources = false,
showPeers = false,
}: {
searchRef: React.MutableRefObject<HTMLInputElement | null>;
showResources?: boolean;
showPeers?: boolean;
}) => {
if (!showResources && !showPeers) return null;
return (
<TabsList justify={"start"} className={"px-3"}>
<TabsTrigger
@@ -569,19 +614,38 @@ const TabTriggers = ({
/>
Groups
</TabsTrigger>
<TabsTrigger
value={"resources"}
className={"text-[.8rem] font-normal"}
onClick={() => searchRef.current?.focus()}
>
<Layers3Icon
className={
"text-nb-gray-500 group-data-[state=active]/trigger:text-netbird transition-all"
}
size={14}
/>
Resource
</TabsTrigger>
{showResources && (
<TabsTrigger
value={"resources"}
className={"text-[.8rem] font-normal"}
onClick={() => searchRef.current?.focus()}
>
<Layers3Icon
className={
"text-nb-gray-500 group-data-[state=active]/trigger:text-netbird transition-all"
}
size={14}
/>
Resources
</TabsTrigger>
)}
{showPeers && (
<TabsTrigger
value={"peers"}
className={"text-[.8rem] font-normal"}
onClick={() => searchRef.current?.focus()}
>
<MonitorSmartphoneIcon
className={
"text-nb-gray-500 group-data-[state=active]/trigger:text-netbird transition-all"
}
size={14}
/>
Peers
</TabsTrigger>
)}
</TabsList>
);
};
@@ -700,7 +764,7 @@ const ResourcesList = ({
useHover={true}
data-cy={"group-badge"}
variant={"gray-ghost"}
className={cn("transition-all group whitespace-nowrap")}
className={cn("transition-all group whitespace-nowrap h-7")}
onClick={(e) => {
e.preventDefault();
}}
@@ -736,3 +800,107 @@ const ResourcesList = ({
</Radio>
);
};
const peersSearchPredicate = (item: Peer, query: string) => {
const lowerCaseQuery = query.toLowerCase();
if (item.name.toLowerCase().includes(lowerCaseQuery)) return true;
return item.ip.toLowerCase().includes(lowerCaseQuery);
};
const PeersList = ({
search,
peers,
isLoading,
value,
onChange,
}: {
search: string;
peers?: Peer[];
isLoading: boolean;
value?: PolicyRuleResource;
onChange: (peer: Peer) => void;
}) => {
const [filteredItems, _, setSearch] = useSearch(
peers || [],
peersSearchPredicate,
{ filter: true, debounce: 150 },
);
useEffect(() => {
setSearch(search);
}, [search, setSearch]);
if (isLoading) {
return (
<div className={"max-h-[195px] flex flex-col gap-1 py-2 px-2"}>
<Skeleton height={42} className={"rounded-md"} />
<Skeleton height={42} className={"rounded-md"} />
<Skeleton height={42} className={"rounded-md"} />
<Skeleton height={42} className={"rounded-md"} />
</div>
);
}
if (search != "" && filteredItems.length == 0) {
return (
<DropdownInfoText className={"mt-5 max-w-sm mx-auto"}>
There are no peers matching your search. Please try a different search
term.
</DropdownInfoText>
);
}
if (search == "" && filteredItems.length == 0) {
return (
<DropdownInfoText className={"mt-5 max-w-sm mx-auto"}>
There are no peers available yet. <br />
Go to <InlineLink href={"/peers"}>Peers</InlineLink> to add some peers.
</DropdownInfoText>
);
}
return (
<Radio defaultValue={value?.id} name={"peer"} value={value?.id}>
<VirtualScrollAreaList
items={filteredItems}
onSelect={onChange}
itemClassName={"dark:aria-selected:bg-nb-gray-800/20"}
renderItem={(res) => {
if (!res?.id) return;
return (
<Fragment key={res.id}>
<div className={"flex items-center gap-2"}>
<Badge
useHover={true}
data-cy={"group-badge"}
variant={"gray-ghost"}
className={cn(
"transition-all group whitespace-nowrap h-7 px-2",
)}
onClick={(e) => {
e.preventDefault();
}}
>
<PeerOperatingSystemIcon os={res.os} />
<TextWithTooltip text={res?.name || ""} maxChars={20} />
</Badge>
</div>
<div className={"flex items-center gap-5"}>
<div
className={
"text-neutral-500 dark:text-nb-gray-300 font-medium flex items-center gap-2"
}
>
{res.ip}
<RadioItem value={res.id} />
</div>
</div>
</Fragment>
);
}}
/>
</Radio>
);
};

View File

@@ -4,7 +4,6 @@ import FullTooltip from "@components/FullTooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@components/Popover";
import TextWithTooltip from "@components/ui/TextWithTooltip";
import { VirtualScrollAreaList } from "@components/VirtualScrollAreaList";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { useSearch } from "@hooks/useSearch";
import useFetchApi from "@utils/api";
import { cn } from "@utils/helpers";
@@ -16,7 +15,7 @@ import { memo, useEffect, useState } from "react";
import { useElementSize } from "@/hooks/useElementSize";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
import { Peer } from "@/interfaces/Peer";
import { OSLogo } from "@/modules/peers/PeerOSCell";
import { PeerOperatingSystemIcon } from "@/modules/peers/PeerOperatingSystemIcon";
const MapPinIcon = memo(() => <MapPin size={12} />);
MapPinIcon.displayName = "MapPinIcon";
@@ -182,7 +181,6 @@ export function PeerSelector({
togglePeer(item);
}}
renderItem={(option) => {
const os = getOperatingSystem(option.os);
const isSupported = isRoutingPeerSupported(
option.version,
option.os,
@@ -210,19 +208,10 @@ export function PeerSelector({
: "text-nb-gray-300",
)}
>
<div
className={cn(
"flex items-center justify-center grayscale brightness-[100%] contrast-[40%]",
"w-4 h-4 shrink-0",
os === OperatingSystem.WINDOWS && "p-[2.5px]",
os === OperatingSystem.APPLE && "p-[2.7px]",
os === OperatingSystem.FREEBSD && "p-[1.5px]",
!isSupported && "opacity-50",
)}
>
<OSLogo os={option.os} />
</div>
<PeerOperatingSystemIcon
os={option.os}
className={isSupported ? "" : "opacity-50"}
/>
<div className={cn(!isSupported && "opacity-50")}>
<TextWithTooltip
text={option.name}

View File

@@ -44,10 +44,12 @@ function Trigger({
children,
value,
disabled = false,
className,
}: {
children: React.ReactNode;
value: string;
disabled?: boolean;
className?: string;
}) {
const currentValue = useTabContext();
return (
@@ -60,6 +62,7 @@ function Trigger({
: disabled
? ""
: "text-nb-gray-400 hover:bg-nb-gray-900/50",
className,
)}
value={value}
>

View File

@@ -14,6 +14,7 @@ type Props<T extends { id?: string }> = {
renderHeading?: (item: T) => React.ReactNode;
renderBeforeItem?: (item: T) => React.ReactNode;
itemClassName?: string;
itemClassNameWithItem?: (item: T) => string;
itemWrapperClassName?: string;
scrollAreaClassName?: string;
maxHeight?: number;
@@ -21,6 +22,7 @@ type Props<T extends { id?: string }> = {
estimatedHeadingHeight?: number;
heightAdjustment?: number;
groupKey?: (item: T) => string | undefined;
itemKey?: (item: T) => string;
};
export function VirtualScrollAreaList<T extends { id?: string }>({
@@ -30,6 +32,7 @@ export function VirtualScrollAreaList<T extends { id?: string }>({
renderBeforeItem,
renderHeading,
itemClassName,
itemClassNameWithItem,
itemWrapperClassName,
scrollAreaClassName,
maxHeight,
@@ -37,6 +40,7 @@ export function VirtualScrollAreaList<T extends { id?: string }>({
estimatedHeadingHeight = 16,
heightAdjustment = 8,
groupKey,
itemKey,
}: Readonly<Props<T>>) {
const virtuosoRef = useRef<VirtuosoHandle>(null);
const [lastInputMethod, setLastInputMethod] = useState<"mouse" | "keyboard">(
@@ -159,10 +163,14 @@ export function VirtualScrollAreaList<T extends { id?: string }>({
setSelected(index);
}
}}
id={option.id}
id={itemKey ? itemKey(option) : option?.id}
onClick={() => onClick(option)}
ariaSelected={selected === index}
itemClassName={itemClassName}
itemClassName={
itemClassNameWithItem
? itemClassNameWithItem(option)
: itemClassName
}
className={itemWrapperClassName}
isLast={index === items.length - 1}
>

View File

@@ -37,6 +37,10 @@ interface SelectDropdownProps {
searchPlaceholder?: string;
isLoading?: boolean;
variant?: ButtonVariants["variant"];
className?: string;
size?: "xs" | "sm";
children?: React.ReactNode;
maxHeight?: number;
}
export function SelectDropdown({
@@ -51,6 +55,10 @@ export function SelectDropdown({
searchPlaceholder = "Search...",
isLoading = false,
variant = "input",
className,
size = "sm",
children,
maxHeight,
}: Readonly<SelectDropdownProps>) {
const [inputRef, { width }] = useElementSize<HTMLButtonElement>();
@@ -79,6 +87,46 @@ export function SelectDropdown({
});
}, [options, debouncedSearch]);
const Loading = () => {
return (
<div className={"flex items-center gap-2"}>
<Skeleton width={20} />
<Skeleton width={100} />
</div>
);
};
const SelectedItem = () => {
return (
<div className={"flex items-center gap-2.5"}>
{selected?.icon && <selected.icon size={14} width={14} />}
<div
className={cn(
"flex flex-col text-sm font-medium",
size === "xs" && "text-xs",
)}
>
<span className={"text-nb-gray-200"}>{selected?.label}</span>
</div>
</div>
);
};
const PlaceholderItem = () => {
return (
<div className={"flex items-center gap-2.5"}>
<div
className={cn(
"flex flex-col text-sm font-medium",
size === "xs" && "text-xs",
)}
>
<span className={"text-nb-gray-200"}>{placeholder}</span>
</div>
</div>
);
};
return (
<Popover
open={open}
@@ -91,45 +139,26 @@ export function SelectDropdown({
setOpen(isOpen);
}}
>
<PopoverTrigger asChild={true} disabled={disabled || isLoading}>
<Button
variant={variant}
disabled={disabled || isLoading}
ref={inputRef}
className={"w-full"}
>
<div className={"w-full flex justify-between items-center gap-2"}>
{isLoading ? (
<div className={"flex gap-2"}>
<Skeleton width={20} />
<Skeleton width={100} />
<PopoverTrigger asChild={!children} disabled={disabled || isLoading}>
{children ? (
children
) : (
<Button
variant={variant}
disabled={disabled || isLoading}
ref={inputRef}
className={cn("w-full", className)}
>
<div className={"w-full flex justify-between items-center gap-2"}>
{isLoading && <Loading />}
{!isLoading && selected && <SelectedItem />}
{!isLoading && !selected && <PlaceholderItem />}
<div className={"pl-2"}>
<ChevronsUpDown size={18} className={"shrink-0"} />
</div>
) : selected ? (
<React.Fragment>
<div className={"flex items-center gap-2.5"}>
{selected?.icon && <selected.icon size={14} width={14} />}
<div className={"flex flex-col text-sm font-medium"}>
<span className={"text-nb-gray-200"}>
{selected?.label}
</span>
</div>
</div>
</React.Fragment>
) : (
<React.Fragment>
<div className={"flex items-center gap-2.5"}>
<div className={"flex flex-col text-sm font-medium"}>
<span className={"text-nb-gray-200"}>{placeholder}</span>
</div>
</div>
</React.Fragment>
)}
<div className={"pl-2"}>
<ChevronsUpDown size={18} className={"shrink-0"} />
</div>
</div>
</Button>
</Button>
)}
</PopoverTrigger>
<PopoverContent
className="w-full p-0 shadow-sm shadow-nb-gray-950 focus:outline-none"
@@ -164,18 +193,22 @@ export function SelectDropdown({
<ScrollArea
className={cn(
"max-h-[380px] overflow-y-auto flex flex-col gap-1 pl-2 pb-2 pr-3",
"overflow-y-auto flex flex-col gap-1 pl-2 pr-3",
!showSearch && "pt-2",
)}
style={{
maxHeight: maxHeight ?? 380,
}}
>
<CommandGroup>
<div className={"grid grid-cols-1 gap-1"}>
<div className={"grid grid-cols-1 gap-1 pb-2"}>
{filteredItems.map((option) => (
<SelectDropdownItem
option={option}
toggle={toggle}
key={option.value}
showValue={showValues}
size={size}
/>
))}
</div>
@@ -192,10 +225,12 @@ const SelectDropdownItem = ({
option,
toggle,
showValue = false,
size = "sm",
}: {
option: SelectOption;
toggle: (value: string) => void;
showValue?: boolean;
size: "xs" | "sm";
}) => {
const value = option.value || "" + option.label || "";
const elementRef = useRef<HTMLDivElement>(null);
@@ -221,13 +256,20 @@ const SelectDropdownItem = ({
>
<div className={"flex items-center gap-2.5 p-1"}>
{option.icon && <option.icon size={14} width={14} />}
<div className={"flex flex-col text-sm font-medium"}>
<div
className={cn(
"flex flex-col text-sm font-medium",
size === "xs" && "text-xs",
)}
>
<span className={"text-nb-gray-200"}>{option.label}</span>
</div>
</div>
{showValue && (
<div className={"flex items-center gap-2.5 p-1"}>
<Paragraph className={cn("text-sm text-right")}>
<Paragraph
className={cn("text-sm text-right", size === "xs" && "text-xs")}
>
{option.value}
</Paragraph>
</div>

View File

@@ -1,4 +1,3 @@
import { IconArrowBack } from "@tabler/icons-react";
import { cn } from "@utils/helpers";
import { SearchIcon } from "lucide-react";
import * as React from "react";
@@ -38,15 +37,9 @@ export const SelectDropdownSearchInput = forwardRef<HTMLInputElement, Props>(
<SearchIcon size={14} />
</div>
</div>
<div className={"absolute right-0 top-0 h-full flex items-center pr-4"}>
<div
className={
"flex items-center bg-nb-gray-800 py-1 px-1.5 rounded-[4px] border border-nb-gray-500"
}
>
<IconArrowBack size={10} />
</div>
</div>
<div
className={"absolute right-0 top-0 h-full flex items-center pr-4"}
></div>
</div>
);
},

View File

@@ -35,7 +35,7 @@ export default function DataTableRefreshButton({ onClick, isDisabled }: Props) {
}}
>
<Button
className={"h-[42px]"}
className={"h-[44px]"}
variant={"secondary"}
disabled={isDisabled == true ? true : disabled}
>

View File

@@ -36,7 +36,7 @@ export default function DataTableResetFilterButton<TData>({
}}
>
<Button
className={"h-[42px]"}
className={"h-[44px]"}
variant={"secondary"}
onClick={onClick}
>

View File

@@ -10,6 +10,7 @@ type Props = {
description?: string;
button?: React.ReactNode;
learnMore?: React.ReactNode;
showBackground?: boolean;
};
export default function GetStartedTest({
@@ -18,28 +19,33 @@ export default function GetStartedTest({
description,
button,
learnMore,
showBackground = true,
}: Props) {
return (
<div className={"px-8 mt-8"}>
<Card className={"w-full relative overflow-hidden"}>
<div
className={
"absolute z-20 bg-gradient-to-b dark:to-nb-gray-950 dark:from-nb-gray-950/40 w-full h-full"
}
></div>
<div
className={
"absolute w-full h-full left-0 top-0 z-10 px-5 py-3 overflow-hidden"
}
>
<div className={"flex flex-col gap-2"}>
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
</div>
</div>
{showBackground && (
<>
<div
className={
"absolute z-20 bg-gradient-to-b dark:to-nb-gray-950 dark:from-nb-gray-950/40 w-full h-full"
}
></div>
<div
className={
"absolute w-full h-full left-0 top-0 z-10 px-5 py-3 overflow-hidden"
}
>
<div className={"flex flex-col gap-2"}>
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
<Skeleton className={"w-full"} height={70} duration={4} />
</div>
</div>
</>
)}
<div className={"w-full h-full z-20 relative left-0 top-0 flex py-8"}>
<div className={"inline-flex justify-center w-full"}>
<div>

View File

@@ -11,9 +11,11 @@ import { useGroupIdentification } from "@/modules/groups/useGroupIdentification"
export const GroupBadgeIcon = ({
id,
issued,
size = 12,
}: {
id?: string;
issued?: GroupIssued;
size?: number;
}) => {
const { groups } = useGroups();
const group = groups?.find((g) => g.id === id);
@@ -22,11 +24,12 @@ export const GroupBadgeIcon = ({
useGroupIdentification({ id, issued: issued ?? group?.issued });
if (isGoogleGroup)
return <GoogleIcon size={11} className={"shrink-0 mr-0.5"} />;
return <GoogleIcon size={size - 1} className={"shrink-0 mr-0.5"} />;
if (isAzureGroup)
return <EntraIcon size={13} className={"shrink-0 mr-0.5"} />;
if (isOktaGroup) return <OktaIcon size={11} className={"shrink-0 mr-0.5"} />;
if (isJWTGroup) return <JWTIcon size={12} className={"shrink-0"} />;
return <EntraIcon size={size + 1} className={"shrink-0 mr-0.5"} />;
if (isOktaGroup)
return <OktaIcon size={size - 1} className={"shrink-0 mr-0.5"} />;
if (isJWTGroup) return <JWTIcon size={size} className={"shrink-0"} />;
return <FolderGit2 size={12} className={"shrink-0"} />;
return <FolderGit2 size={size} className={"shrink-0"} />;
};

View File

@@ -3,7 +3,7 @@ import { memo } from "react";
import NetBirdIcon from "@/assets/icons/NetBirdIcon";
const MemoizedNetBirdIcon = () => {
return <NetBirdIcon size={16} />;
return <NetBirdIcon size={14} />;
};
export default memo(MemoizedNetBirdIcon);

View File

@@ -8,12 +8,12 @@ export const NotificationCountBadge = ({ count = 0 }: Props) => {
return count ? (
<div
className={cn(
count <= 9 ? "w-5 h-5" : "py-2.5 px-2",
"relative bg-netbird flex items-center justify-center rounded-full text-white !leading-[0] text-xs font-semibold",
count <= 9 ? "w-4 h-4" : "py-2 px-1.5",
"relative bg-netbird flex items-center justify-center rounded-full text-white !leading-[0] text-[0.6rem] font-semibold",
)}
>
<span className="animate-ping absolute left-0 inline-flex h-full w-full rounded-full bg-netbird opacity-20"></span>
{count || 0}
<span className={"relative -left-[0.5px]"}>{count || 0}</span>
</div>
) : null;
};

View File

@@ -4,9 +4,13 @@ import { cn } from "@utils/helpers";
import { GlobeIcon, NetworkIcon, WorkflowIcon, XIcon } from "lucide-react";
import * as React from "react";
import { NetworkResource } from "@/interfaces/Network";
import { Peer } from "@/interfaces/Peer";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
import { PeerOperatingSystemIcon } from "@/modules/peers/PeerOperatingSystemIcon";
type Props = {
resource?: NetworkResource;
peer?: Peer;
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
showX?: boolean;
children?: React.ReactNode;
@@ -15,35 +19,44 @@ type Props = {
export default function ResourceBadge({
onClick,
resource,
peer,
showX = false,
children,
className,
}: Readonly<Props>) {
if (!resource) return;
if (!resource && !peer) return;
const isPeer = !!peer;
const key = resource ? resource.id || resource?.name : peer?.id || peer?.name;
return (
<Badge
key={resource.id || resource?.name}
key={key}
useHover={true}
data-cy={"resource-badge"}
variant={"gray-ghost"}
className={cn("transition-all group whitespace-nowrap", className)}
className={cn(
"transition-all group whitespace-nowrap",
className,
isPeer && "px-2",
)}
onClick={(e) => {
e.preventDefault();
onClick?.(e);
}}
>
{resource.type === "host" && (
<WorkflowIcon size={12} className={"shrink-0"} />
)}
{resource.type === "domain" && (
<GlobeIcon size={12} className={"shrink-0"} />
)}
{resource.type === "subnet" && (
<NetworkIcon size={12} className={"shrink-0"} />
{isPeer ? (
<>
<PeerOperatingSystemIcon os={peer?.os} />
<TruncatedText text={peer?.name || ""} maxChars={20} />
</>
) : (
<>
<ResourceIcon type={resource?.type || ""} />
<TruncatedText text={resource?.name || ""} maxChars={20} />
</>
)}
<TruncatedText text={resource?.name || ""} maxChars={20} />
{children}
{showX && (
<XIcon
@@ -56,3 +69,16 @@ export default function ResourceBadge({
</Badge>
);
}
const ResourceIcon = ({ type }: { type: string }) => {
switch (type) {
case "host":
return <WorkflowIcon size={12} className={"shrink-0"} />;
case "domain":
return <GlobeIcon size={12} className={"shrink-0"} />;
case "subnet":
return <NetworkIcon size={12} className={"shrink-0"} />;
default:
return null;
}
};

View File

@@ -24,7 +24,7 @@ export default function TextWithTooltip({
<FullTooltip
disabled={charCount <= maxChars || hideTooltip}
interactive={false}
className={"truncate w-full min-w-0"}
className={"truncate w-auto min-w-0"}
skipDelayDuration={350}
delayDuration={200}
content={

View File

@@ -26,6 +26,7 @@ const PeerContext = React.createContext(
loginExpiration?: boolean;
inactivityExpiration?: boolean;
approval_required?: boolean;
ip?: string;
}) => Promise<Peer>;
openSSHDialog: () => Promise<boolean>;
deletePeer: () => void;
@@ -36,7 +37,7 @@ const PeerContext = React.createContext(
export default function PeerProvider({ children, peer }: Props) {
const user = usePeerUser(peer);
const { peerGroups, isLoading } = usePeerGroups(peer);
const peerRequest = useApiCall<Peer>("/peers");
const peerRequest = useApiCall<Peer>("/peers", true);
const { confirm } = useDialog();
const { mutate } = useSWRConfig();
@@ -68,6 +69,7 @@ export default function PeerProvider({ children, peer }: Props) {
loginExpiration?: boolean;
inactivityExpiration?: boolean;
approval_required?: boolean;
ip?: string;
}) => {
return peerRequest.put(
{
@@ -86,6 +88,7 @@ export default function PeerProvider({ children, peer }: Props) {
props?.approval_required == undefined
? undefined
: props.approval_required,
ip: props.ip != undefined ? props.ip : undefined,
},
`/${peer.id}`,
);
@@ -94,11 +97,22 @@ export default function PeerProvider({ children, peer }: Props) {
const openSSHDialog = async (): Promise<boolean> => {
return await confirm({
title: `Enable SSH Server for ${peer.name}?`,
description:
"Experimental feature. Enabling this option allows remote SSH access to this machine from other connected network participants.",
description: (
<div className={"flex flex-col gap-2"}>
<div>
Enabling this option allows remote SSH access to this machine from
other connected network participants.
</div>
<div>
Make sure SSH is allowed in the NetBird Client under{" "}
<span className={"text-white"}>Settings &rarr; Allow SSH</span>
</div>
</div>
),
confirmText: "Enable",
cancelText: "Cancel",
type: "warning",
maxWidthClass: "max-w-lg",
});
};

View File

@@ -61,6 +61,7 @@ export default function RoutesProvider({ children }: Readonly<Props>) {
: toUpdate.access_control_groups ??
route.access_control_groups ??
undefined,
skip_auto_apply: toUpdate.skip_auto_apply ?? route.skip_auto_apply ?? true,
},
`/${route.id}`,
)
@@ -94,6 +95,7 @@ export default function RoutesProvider({ children }: Readonly<Props>) {
masquerade: route.masquerade,
groups: route.groups || [],
access_control_groups: route?.access_control_groups || undefined,
skip_auto_apply: route.skip_auto_apply ?? true,
})
.then((route) => {
mutate("/routes");

View File

@@ -68,12 +68,17 @@ const UserProfileProvider = ({ children }: Props) => {
};
}, [loggedInUser]);
return !isLoading && loggedInUser ? (
// Show loading only when we're still loading and don't have user data
if (isLoading || !loggedInUser) {
return <FullScreenLoading />;
}
// For blocked or pending approval users, we still need to provide the context
// so they can access their user data on the blocked page
return (
<UserProfileContext.Provider value={data}>
<PermissionsProvider user={loggedInUser}>{children}</PermissionsProvider>
</UserProfileContext.Provider>
) : (
<FullScreenLoading />
);
};

View File

@@ -23,6 +23,7 @@ export default function useOperatingSystem() {
* Falls back to Linux if the operating system is not recognized
*/
export const getOperatingSystem = (os: string) => {
if (!os) return OperatingSystem.LINUX as const;
if (os.toLowerCase().includes("freebsd"))
return OperatingSystem.FREEBSD as const;
if (os.toLowerCase().includes("darwin"))

View File

@@ -7,6 +7,7 @@ export interface Account {
settings: {
extra: {
peer_approval_enabled: boolean;
user_approval_required: boolean;
};
peer_login_expiration_enabled: boolean;
peer_login_expiration: number;
@@ -19,6 +20,7 @@ export interface Account {
regular_users_view_blocked: boolean;
routing_peer_dns_resolution_enabled: boolean;
dns_domain: string;
network_range?: string;
lazy_connection_enabled: boolean;
};
}

View File

@@ -6,6 +6,7 @@ export interface Peer {
name: string;
ip: string;
connected: boolean;
created_at?: Date;
last_seen: Date;
os: string;
version: string;
@@ -15,6 +16,7 @@ export interface Peer {
user_id?: string;
user?: User;
ui_version?: string;
kernel_version?: string;
dns_label: string;
extra_dns_labels?: string[];
last_login: Date;
@@ -26,4 +28,5 @@ export interface Peer {
country_code: string;
connection_ip: string;
serial_number: string;
ephemeral: boolean;
}

View File

@@ -34,7 +34,7 @@ export interface PortRange {
export interface PolicyRuleResource {
id: string;
type: "domain" | "host" | "subnet" | undefined;
type?: "domain" | "host" | "subnet" | "peer";
}
export type Protocol = "all" | "tcp" | "udp" | "icmp";

View File

@@ -12,6 +12,7 @@ export interface Route {
groups: string[];
keep_route?: boolean;
access_control_groups?: string[];
skip_auto_apply?: boolean;
// Frontend only
peer_groups?: string[];
routesGroups?: string[];

View File

@@ -10,6 +10,7 @@ export interface User {
is_current?: boolean;
is_service_user?: boolean;
is_blocked?: boolean;
pending_approval?: boolean;
last_login?: Date;
permissions: Permissions;
}

View File

@@ -31,7 +31,7 @@ export default function NavbarWithDropdown() {
<AnnouncementBanner />
<div
className={cn(
"bg-white px-2 py-4 dark:border-gray-700 dark:bg-nb-gray/50 backdrop-blur-lg sm:px-6",
"bg-white px-2 py-4 dark:border-gray-700 dark:bg-nb-gray backdrop-blur-lg sm:px-6",
"border-b dark:border-zinc-700/40 px-3 md:px-4 w-full",
"flex justify-between items-center transition-all",
)}

View File

@@ -156,6 +156,8 @@ export function AccessControlModalContent({
submit,
isPostureChecksLoading,
getPolicyData,
sourceResource,
setSourceResource,
destinationResource,
setDestinationResource,
portRanges,
@@ -176,15 +178,17 @@ export function AccessControlModalContent({
return "policy";
});
const continuePostureChecksDisabled = useMemo(() => {
if (sourceGroups.length > 0 && destinationResource) return false;
if (sourceGroups.length == 0 || destinationGroups.length == 0) return true;
}, [sourceGroups, destinationGroups, destinationResource]);
const canContinueToPostureChecks = useMemo(() => {
const hasSource = sourceGroups.length > 0 || !!sourceResource;
const hasDestination =
destinationGroups.length > 0 || !!destinationResource;
return hasSource && hasDestination;
}, [sourceGroups, destinationGroups, destinationResource, sourceResource]);
const submitDisabled = useMemo(() => {
if (name.length == 0) return true;
if (continuePostureChecksDisabled) return true;
}, [name, continuePostureChecksDisabled]);
if (!canContinueToPostureChecks) return true;
}, [name, canContinueToPostureChecks]);
const handleProtocolChange = (p: Protocol) => {
setProtocol(p);
@@ -220,11 +224,8 @@ export function AccessControlModalContent({
<ArrowRightLeft size={16} />
Policy
</TabsTrigger>
<PostureCheckTabTrigger disabled={continuePostureChecksDisabled} />
<TabsTrigger
value={"general"}
disabled={continuePostureChecksDisabled}
>
<PostureCheckTabTrigger disabled={!canContinueToPostureChecks} />
<TabsTrigger value={"general"} disabled={!canContinueToPostureChecks}>
<Text
size={16}
className={
@@ -283,14 +284,19 @@ export function AccessControlModalContent({
</Label>
<PeerGroupSelector
dataCy={"source-group-selector"}
popoverWidth={500}
placeholder={"Select source(s)..."}
showRoutes={true}
showResources={false}
showPeers={true}
showResourceCounter={true}
showPeerCount={allowEditPeers}
disableInlineRemoveGroup={false}
popoverWidth={500}
showRoutes={false}
onChange={setSourceGroups}
values={sourceGroups}
onChange={setSourceGroups}
resource={sourceResource}
onResourceChange={setSourceResource}
saveGroupAssignments={useSave}
showResourceCounter={false}
disabled={
!permission.policies.update || !permission.policies.create
}
@@ -310,17 +316,19 @@ export function AccessControlModalContent({
</Label>
<PeerGroupSelector
dataCy={"destination-group-selector"}
popoverWidth={500}
placeholder={"Select destination(s)..."}
showRoutes={true}
showResources={true}
showPeers={true}
showResourceCounter={true}
showPeerCount={allowEditPeers}
disableInlineRemoveGroup={false}
popoverWidth={500}
onChange={setDestinationGroups}
values={destinationGroups}
saveGroupAssignments={useSave}
onChange={setDestinationGroups}
resource={destinationResource}
onResourceChange={setDestinationResource}
showResources={true}
placeholder={"Select destination(s)..."}
saveGroupAssignments={useSave}
disabled={
!permission.policies.update || !permission.policies.create
}
@@ -453,35 +461,36 @@ export function AccessControlModalContent({
{!policy ? (
<>
{tab == "policy" && (
<ModalClose asChild={true}>
<Button variant={"secondary"}>Cancel</Button>
</ModalClose>
<>
<ModalClose asChild={true}>
<Button variant={"secondary"}>Cancel</Button>
</ModalClose>
<Button
variant={"primary"}
onClick={() => setTab("posture_checks")}
disabled={!canContinueToPostureChecks}
>
Continue
</Button>
</>
)}
{tab == "posture_checks" && (
<Button variant={"secondary"} onClick={() => setTab("policy")}>
Back
</Button>
)}
{tab == "policy" && (
<Button
variant={"primary"}
onClick={() => setTab("posture_checks")}
disabled={continuePostureChecksDisabled}
>
Continue
</Button>
)}
{tab == "posture_checks" && (
<Button
variant={"primary"}
onClick={() => setTab("general")}
disabled={continuePostureChecksDisabled}
>
Continue
</Button>
<>
<Button
variant={"secondary"}
onClick={() => setTab("policy")}
>
Back
</Button>
<Button
variant={"primary"}
onClick={() => setTab("general")}
disabled={!canContinueToPostureChecks}
>
Continue
</Button>
</>
)}
{tab == "general" && (

View File

@@ -1,11 +1,9 @@
import MultipleGroups from "@components/ui/MultipleGroups";
import ResourceBadge from "@components/ui/ResourceBadge";
import useFetchApi from "@utils/api";
import React, { useMemo } from "react";
import Skeleton from "react-loading-skeleton";
import { Group } from "@/interfaces/Group";
import { NetworkResource } from "@/interfaces/Network";
import { Policy, PolicyRuleResource } from "@/interfaces/Policy";
import { Policy } from "@/interfaces/Policy";
import { AccessControlResourceCell } from "@/modules/access-control/table/AccessControlResourceCell";
import EmptyRow from "@/modules/common-table-rows/EmptyRow";
type Props = {
policy: Policy;
@@ -20,30 +18,13 @@ export default function AccessControlDestinationsCell({
if (firstRule?.destinationResource) {
return (
<AccessControlDestinationResourceCell
resource={firstRule.destinationResource}
/>
<AccessControlResourceCell resource={firstRule.destinationResource} />
);
}
return firstRule ? (
<MultipleGroups groups={firstRule.destinations as Group[]} />
) : null;
) : (
<EmptyRow />
);
}
const AccessControlDestinationResourceCell = ({
resource,
}: {
resource: PolicyRuleResource;
}) => {
const { data: resources, isLoading } = useFetchApi<NetworkResource[]>(
"/networks/resources",
);
if (isLoading) return <Skeleton height={35} width={"50%"} />;
return (
<div className={"flex"}>
<ResourceBadge resource={resources?.find((r) => r.id === resource.id)} />
</div>
);
};

View File

@@ -0,0 +1,34 @@
import ResourceBadge from "@components/ui/ResourceBadge";
import useFetchApi from "@utils/api";
import * as React from "react";
import Skeleton from "react-loading-skeleton";
import { NetworkResource } from "@/interfaces/Network";
import { Peer } from "@/interfaces/Peer";
import { PolicyRuleResource } from "@/interfaces/Policy";
type Props = {
resource?: PolicyRuleResource;
};
export const AccessControlResourceCell = ({ resource }: Props) => {
const { data: resources, isLoading: isLoadingResources } = useFetchApi<
NetworkResource[]
>("/networks/resources");
const { data: peers, isLoading: isLoadingPeers } =
useFetchApi<Peer[]>("/peers");
const isPeer = resource?.type === "peer";
const peer = peers?.find((p) => p.id === resource?.id);
if ((isPeer && isLoadingPeers) || (!isPeer && isLoadingResources))
return <Skeleton height={35} width={"50%"} />;
return (
<div className={"flex"}>
<ResourceBadge
resource={resources?.find((r) => r.id === resource?.id)}
peer={peer}
/>
</div>
);
};

View File

@@ -2,6 +2,8 @@ import MultipleGroups from "@components/ui/MultipleGroups";
import React, { useMemo } from "react";
import { Group } from "@/interfaces/Group";
import { Policy } from "@/interfaces/Policy";
import { AccessControlResourceCell } from "@/modules/access-control/table/AccessControlResourceCell";
import EmptyRow from "@/modules/common-table-rows/EmptyRow";
type Props = {
policy: Policy;
@@ -12,7 +14,13 @@ export default function AccessControlSourcesCell({ policy }: Props) {
return undefined;
}, [policy]);
if (firstRule?.sourceResource) {
return <AccessControlResourceCell resource={firstRule.sourceResource} />;
}
return firstRule ? (
<MultipleGroups groups={firstRule.sources as Group[]} />
) : null;
) : (
<EmptyRow />
);
}

View File

@@ -1,5 +1,6 @@
import Button from "@components/Button";
import ButtonGroup from "@components/ButtonGroup";
import FullTooltip from "@components/FullTooltip";
import InlineLink from "@components/InlineLink";
import SquareIcon from "@components/SquareIcon";
import { DataTable } from "@components/table/DataTable";
@@ -9,9 +10,9 @@ import { DataTableRowsPerPage } from "@components/table/DataTableRowsPerPage";
import GetStartedTest from "@components/ui/GetStartedTest";
import type { ColumnDef, SortingState } from "@tanstack/react-table";
import { removeAllSpaces } from "@utils/helpers";
import { ExternalLinkIcon, PlusCircle } from "lucide-react";
import { ClockFadingIcon, ExternalLinkIcon, PlusCircle } from "lucide-react";
import { usePathname, useSearchParams } from "next/navigation";
import React, { useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useSWRConfig } from "swr";
import AccessControlIcon from "@/assets/icons/AccessControlIcon";
import { usePermissions } from "@/contexts/PermissionsProvider";
@@ -200,6 +201,41 @@ export default function AccessControlTable({
const [currentRow, setCurrentRow] = useState<Policy>();
const [currentCellClicked, setCurrentCellClicked] = useState("");
const [showTemporaryPolicies, setShowTemporaryPolicies] = useState(false);
const withTemporaryPolicies = useCallback(
(condition: boolean) =>
policies?.filter((policy) =>
condition
? policy?.name?.startsWith("Temporary") &&
policy?.name?.endsWith("client") &&
policy?.description?.startsWith("Temporary") &&
policy?.description?.endsWith("client")
: !(
policy?.name?.startsWith("Temporary") &&
policy?.name?.endsWith("client") &&
policy?.description?.startsWith("Temporary") &&
policy?.description?.endsWith("client")
),
) ?? [],
[policies],
);
const tempPolicies = useMemo(
() => withTemporaryPolicies(true),
[withTemporaryPolicies],
);
const regularPolicies = useMemo(
() => withTemporaryPolicies(false),
[withTemporaryPolicies],
);
useEffect(() => {
if (showTemporaryPolicies && tempPolicies?.length === 0) {
setShowTemporaryPolicies(false);
}
}, [showTemporaryPolicies, tempPolicies]);
return (
<>
{editModal && currentRow && (
@@ -232,8 +268,9 @@ export default function AccessControlTable({
columnVisibility={{
description: false,
id: false,
temporary: false,
}}
data={policies}
data={showTemporaryPolicies ? tempPolicies : regularPolicies}
onRowClick={(row, cell) => {
setCurrentRow(row.original);
setEditModal(true);
@@ -301,65 +338,90 @@ export default function AccessControlTable({
</>
)}
>
{(table) => (
<>
<ButtonGroup disabled={policies?.length == 0}>
<ButtonGroup.Button
onClick={() => {
table.setPageIndex(0);
table.getColumn("enabled")?.setFilterValue(undefined);
}}
{(table) => {
return (
<>
<ButtonGroup disabled={policies?.length == 0}>
<ButtonGroup.Button
onClick={() => {
table.setPageIndex(0);
table.getColumn("enabled")?.setFilterValue(undefined);
}}
disabled={policies?.length == 0}
variant={
table.getColumn("enabled")?.getFilterValue() === undefined
? "tertiary"
: "secondary"
}
>
All
</ButtonGroup.Button>
<ButtonGroup.Button
onClick={() => {
table.setPageIndex(0);
table.getColumn("enabled")?.setFilterValue(true);
}}
disabled={policies?.length == 0}
variant={
table.getColumn("enabled")?.getFilterValue() === true
? "tertiary"
: "secondary"
}
>
Active
</ButtonGroup.Button>
<ButtonGroup.Button
onClick={() => {
table.setPageIndex(0);
table.getColumn("enabled")?.setFilterValue(false);
}}
disabled={policies?.length == 0}
variant={
table.getColumn("enabled")?.getFilterValue() === false
? "tertiary"
: "secondary"
}
>
Inactive
</ButtonGroup.Button>
</ButtonGroup>
<DataTableRowsPerPage
table={table}
disabled={policies?.length == 0}
variant={
table.getColumn("enabled")?.getFilterValue() === undefined
? "tertiary"
: "secondary"
}
>
All
</ButtonGroup.Button>
<ButtonGroup.Button
/>
{tempPolicies?.length > 0 && (
<FullTooltip
content={
<div className={"max-w-sm text-xs"}>
Show temporary policies created by the NetBird browser
client. These policies are ephemeral and will be deleted
automatically after a short period of time.
</div>
}
>
<Button
className={"h-[44px]"}
variant={showTemporaryPolicies ? "tertiary" : "secondary"}
onClick={() => {
setShowTemporaryPolicies(!showTemporaryPolicies);
}}
>
<ClockFadingIcon size={16} />
</Button>
</FullTooltip>
)}
<DataTableRefreshButton
isDisabled={policies?.length == 0}
onClick={() => {
table.setPageIndex(0);
table.getColumn("enabled")?.setFilterValue(true);
mutate("/policies").then();
mutate("/groups").then();
}}
disabled={policies?.length == 0}
variant={
table.getColumn("enabled")?.getFilterValue() === true
? "tertiary"
: "secondary"
}
>
Active
</ButtonGroup.Button>
<ButtonGroup.Button
onClick={() => {
table.setPageIndex(0);
table.getColumn("enabled")?.setFilterValue(false);
}}
disabled={policies?.length == 0}
variant={
table.getColumn("enabled")?.getFilterValue() === false
? "tertiary"
: "secondary"
}
>
Inactive
</ButtonGroup.Button>
</ButtonGroup>
<DataTableRowsPerPage
table={table}
disabled={policies?.length == 0}
/>
<DataTableRefreshButton
isDisabled={policies?.length == 0}
onClick={() => {
mutate("/policies").then();
mutate("/groups").then();
}}
/>
</>
)}
/>
</>
);
}}
</DataTable>
</>
);

View File

@@ -126,6 +126,10 @@ export const useAccessControl = ({
: initialDestinationGroups ?? [],
});
const [sourceResource, setSourceResource] = useState(
firstRule?.sourceResource,
);
const [destinationResource, setDestinationResource] = useState(
firstRule?.destinationResource,
);
@@ -163,8 +167,9 @@ export const useAccessControl = ({
bidirectional: direction == "bi",
description,
name,
sources: sources,
sources: sourceResource ? undefined : sources,
destinations: destinationResource ? undefined : destinations,
sourceResource: sourceResource || undefined,
destinationResource: destinationResource || undefined,
action: "accept",
protocol,
@@ -241,8 +246,9 @@ export const useAccessControl = ({
action: "accept",
protocol,
enabled,
sources,
sources: sourceResource ? undefined : sources,
destinations: destinationResource ? undefined : destinations,
sourceResource: sourceResource || undefined,
destinationResource: destinationResource || undefined,
ports: newPorts,
port_ranges: newPortRanges,
@@ -254,9 +260,9 @@ export const useAccessControl = ({
updatePolicy(
policy,
policyObj,
() => {
(p) => {
mutate("/policies");
onSuccess && onSuccess(policy);
onSuccess && onSuccess(p);
},
"The policy was successfully saved",
);
@@ -345,6 +351,8 @@ export const useAccessControl = ({
getPolicyData,
portDisabled,
isPostureChecksLoading,
sourceResource,
setSourceResource,
destinationResource,
setDestinationResource,
destinationHasResources,

View File

@@ -63,11 +63,12 @@ export default function ActivityDescription({ event }: Props) {
</div>
);
if (event.activity_code == "setupkey.peer.add")
if (event.activity_code == "peer.setupkey.add")
return (
<div className={"inline"}>
Peer <Value>{m.name}</Value> <PeerConnectionInfo meta={m} /> was added
with the NetBird IP <Value>{m.ip}</Value>
with the NetBird IP <Value>{m.ip}</Value> using the setup key{" "}
<Value>{m.setup_key_name}</Value>
</div>
);
@@ -252,6 +253,22 @@ export default function ActivityDescription({ event }: Props) {
</div>
);
if (event.activity_code == "user.approve")
return (
<div className={"inline"}>
User <Value>{event.meta.username}</Value>{" "}
<Value>{event.meta.email}</Value> was approved
</div>
);
if (event.activity_code == "user.reject")
return (
<div className={"inline"}>
User <Value>{event.meta.username}</Value>{" "}
<Value>{event.meta.email}</Value> was rejected
</div>
);
/**
* Service User
*/
@@ -340,6 +357,22 @@ export default function ActivityDescription({ event }: Props) {
</div>
);
if (event.activity_code == "peer.ip.update")
return (
<div className={"inline"}>
Peer <Value>{m.name}</Value> IP address was updated from{" "}
<Value>{m.old_ip}</Value> to <Value>{m.ip}</Value>
</div>
);
if (event.activity_code == "peer.user.add")
return (
<div className={"inline"}>
Peer <Value>{m.name}</Value> <PeerConnectionInfo meta={m} /> was added
with the NetBird IP <Value>{m.ip}</Value>
</div>
);
/**
* Group
*/
@@ -378,6 +411,15 @@ export default function ActivityDescription({ event }: Props) {
if (event.activity_code == "account.setting.peer.login.expiration.disable")
return <div className={"inline"}>Global login expiration was disabled</div>;
if (event.activity_code == "account.network.range.update")
return (
<div className={"inline"}>
Account network range was updated from{" "}
<Value>{m.old_network_range}</Value> to{" "}
<Value>{m.new_network_range}</Value>
</div>
);
/**
* Nameserver
*/
@@ -635,6 +677,20 @@ export default function ActivityDescription({ event }: Props) {
</div>
);
if (event.activity_code == "account.settings.extra.flow.group.remove")
return (
<div className={"inline"}>
Limit traffic event group <Value>{m.group_name}</Value> removed
</div>
);
if (event.activity_code == "account.settings.extra.flow.group.add")
return (
<div className={"inline"}>
Limit traffic event group <Value>{m.group_name}</Value> added
</div>
);
return (
<div className={"flex gap-2.5 items-center"}>
<span className={"mb-[1px]"}>{event.activity}</span>

View File

@@ -1,16 +1,16 @@
import Button from "@components/Button";
import { CommandItem } from "@components/Command";
import { DropdownInfoText } from "@components/DropdownInfoText";
import { DropdownInput } from "@components/DropdownInput";
import { Popover, PopoverContent, PopoverTrigger } from "@components/Popover";
import { ScrollArea } from "@components/ScrollArea";
import { SmallBadge } from "@components/ui/SmallBadge";
import TextWithTooltip from "@components/ui/TextWithTooltip";
import { cn, generateColorFromString } from "@utils/helpers";
import { Command, CommandGroup, CommandInput, CommandList } from "cmdk";
import { sortBy, trim, uniqBy } from "lodash";
import { ChevronsUpDown, Cog, SearchIcon, UserCircle2 } from "lucide-react";
import { VirtualScrollAreaList } from "@components/VirtualScrollAreaList";
import { useSearch } from "@hooks/useSearch";
import { generateColorFromString } from "@utils/helpers";
import { sortBy, uniqBy } from "lodash";
import { ChevronsUpDown, Cog, UserCircle2 } from "lucide-react";
import * as React from "react";
import { useMemo, useState } from "react";
import { useDebounce } from "@/hooks/useDebounce";
import { useElementSize } from "@/hooks/useElementSize";
import { SmallUserAvatar } from "@/modules/users/SmallUserAvatar";
@@ -29,17 +29,35 @@ export type UserSelectOption = {
external?: boolean;
};
const searchPredicate = (item: UserSelectOption, query: string) => {
const lowerCaseQuery = query.toLowerCase();
if (
item.email === "NetBird" &&
"NetBird System".toLowerCase().includes(lowerCaseQuery)
)
return true;
if (item.name.toLowerCase().includes(lowerCaseQuery)) return true;
if (item.email?.toLowerCase().includes(lowerCaseQuery)) return true;
return item.id.toLowerCase().startsWith(lowerCaseQuery);
};
export function UsersDropdownSelector({
onChange,
value,
disabled = false,
popoverWidth = 250,
options,
}: Props) {
const searchRef = React.useRef<HTMLInputElement>(null);
}: Readonly<Props>) {
const [filteredItems, search, setSearch] = useSearch(
options.concat({
id: "all-users",
name: "All Users",
email: "Include all users",
}),
searchPredicate,
{ filter: true, debounce: 150 },
);
const [inputRef, { width }] = useElementSize<HTMLButtonElement>();
const [searchInput, setSearchInput] = useState("");
const search = useDebounce(searchInput, 500);
const toggle = (item: string | undefined) => {
const isSelected = value == item;
@@ -47,7 +65,7 @@ export function UsersDropdownSelector({
onChange && onChange(undefined);
} else {
onChange && onChange(item);
setSearchInput("");
setSearch("");
}
setOpen(false);
};
@@ -55,11 +73,17 @@ export function UsersDropdownSelector({
const [open, setOpen] = useState(false);
const sortedOptions = useMemo(() => {
return sortBy(
uniqBy(options, (o) => o.email),
const sorted = sortBy(
uniqBy(filteredItems, (o) => o.email),
["external", "name"],
);
}, [options]);
const allUsersIndex = sorted.findIndex((o) => o.id === "all-users");
if (allUsersIndex > -1) {
const allUsers = sorted.splice(allUsersIndex, 1)[0];
sorted.unshift(allUsers);
}
return sorted;
}, [filteredItems]);
const selectedUser = useMemo(() => {
return options.find((user) => user.email == value);
@@ -71,7 +95,7 @@ export function UsersDropdownSelector({
onOpenChange={(isOpen) => {
if (!isOpen) {
setTimeout(() => {
setSearchInput("");
setSearch("");
}, 100);
}
setOpen(isOpen);
@@ -137,145 +161,105 @@ export function UsersDropdownSelector({
side={"bottom"}
sideOffset={10}
>
<Command
className={"w-full flex"}
loop
filter={(value, search) => {
const formatValue = trim(value.toLowerCase());
const formatSearch = trim(search.toLowerCase());
if (formatValue.includes(formatSearch)) return 1;
return 0;
}}
>
<CommandList className={"w-full"}>
<div className={"relative"}>
<CommandInput
className={cn(
"min-h-[42px] w-full relative",
"border-b-0 border-t-0 border-r-0 border-l-0 border-neutral-200 dark:border-nb-gray-700 items-center",
"bg-transparent text-sm outline-none focus-visible:outline-none ring-0 focus-visible:ring-0",
"dark:placeholder:text-nb-gray-400 font-light placeholder:text-neutral-500 pl-10",
)}
ref={searchRef}
value={searchInput}
onValueChange={setSearchInput}
placeholder={"Search user..."}
/>
<div
className={
"absolute left-0 top-0 h-full flex items-center pl-4"
}
>
<div className={"flex items-center"}>
<SearchIcon size={14} />
</div>
</div>
</div>
<div className={"w-full"}>
<DropdownInput
value={search}
onChange={setSearch}
placeholder={"Search user..."}
hideEnterIcon={true}
/>
<ScrollArea
className={
"max-h-[380px] overflow-y-hidden flex flex-col gap-1 pl-2 py-2 pr-3"
}
>
<CommandGroup>
<div className={"grid grid-cols-1 gap-1"}>
<CommandItem
value={undefined}
className={"py-1 px-2"}
onSelect={() => {
toggle(undefined);
}}
onClick={(e) => e.preventDefault()}
>
<div className={"flex items-center gap-2"}>
{options.length == 0 && !search && (
<div className={"max-w-xs mx-auto"}>
<DropdownInfoText>
{"No users available to select."}
</DropdownInfoText>
</div>
)}
{filteredItems.length == 0 && search != "" && (
<div className={"px-10"}>
<DropdownInfoText>
There are no users matching your search.
</DropdownInfoText>
</div>
)}
{sortedOptions.length > 0 && (
<VirtualScrollAreaList
items={sortedOptions}
estimatedItemHeight={52}
maxHeight={380}
scrollAreaClassName={"pt-0"}
onSelect={(item) => {
if (item.id === "all-users") {
toggle(undefined);
return;
}
toggle(item.email);
}}
renderItem={(user) => {
const isSystemUser = user.email === "NetBird";
return (
<div className={"flex items-center gap-2 w-full"}>
{user.id === "all-users" ? (
<div
className={
"w-7 h-7 rounded-full flex items-center justify-center uppercase text-[9px] font-medium bg-sky-400 text-white"
"w-7 h-7 shrink-0 rounded-full flex items-center justify-center uppercase text-[9px] font-medium bg-sky-400 text-white"
}
>
<UserCircle2 size={16} />
</div>
) : (
<SmallUserAvatar
name={user?.name}
email={user?.email}
id={user?.id}
/>
)}
<div className={"flex flex-col text-xs"}>
<span className={"text-nb-gray-200"}>All Users</span>
<span className={"text-nb-gray-400 font-light"}>
Include all users
</span>
</div>
</div>
</CommandItem>
{sortedOptions.map((user) => {
const isSystemUser = user.email === "NetBird";
const searchValue = isSystemUser
? "NetBird System"
: user.name + " " + user.id + " " + user.email;
return (
<CommandItem
key={user.id}
value={searchValue}
className={"py-1 px-2"}
onSelect={() => {
toggle(user.email);
}}
onClick={(e) => e.preventDefault()}
<div className={"flex flex-col text-xs w-full"}>
<span
className={
"text-nb-gray-200 flex items-center gap-1.5 w-full"
}
>
<div className={"flex items-center gap-2 w-full"}>
<SmallUserAvatar
name={user?.name}
email={user?.email}
id={user?.id}
/>
<div className={"flex flex-col text-xs w-full"}>
<span
className={
"text-nb-gray-200 flex items-center gap-1.5 w-full"
}
>
<TextWithTooltip
text={
isSystemUser
? "System"
: user?.name || user?.id
}
maxChars={20}
/>
</span>
<span
className={
"text-nb-gray-400 font-light flex items-center gap-1"
}
>
<TextWithTooltip
text={user?.email || "NetBird"}
maxChars={20}
/>
</span>
</div>
{user.external && (
<span
className={"flex items-center ml-auto relative"}
>
<SmallBadge
text={"External"}
variant={"sky"}
className={
"text-[8.5px] py-[0.15rem] px-[.32rem] leading-none rounded-full -top-0"
}
/>
</span>
)}
</div>
</CommandItem>
);
})}
</div>
</CommandGroup>
</ScrollArea>
</CommandList>
</Command>
<TextWithTooltip
text={
isSystemUser ? "System" : user?.name || user?.id
}
maxChars={20}
/>
</span>
<span
className={
"text-nb-gray-400 font-light flex items-center gap-1"
}
>
<TextWithTooltip
text={user?.email || "NetBird"}
maxChars={20}
/>
</span>
</div>
{user.external && (
<span className={"flex items-center ml-auto relative"}>
<SmallBadge
text={"External"}
variant={"sky"}
className={
"text-[8.5px] py-[0.15rem] px-[.32rem] leading-none rounded-full -top-0"
}
/>
</span>
)}
</div>
);
}}
/>
)}
</div>
</PopoverContent>
</Popover>
);

View File

@@ -18,7 +18,9 @@ const ACTION_COLOR_MAPPING: Record<string, ActionStatus> = {
// Error actions
delete: ActionStatus.ERROR,
revoke: ActionStatus.ERROR,
remove: ActionStatus.ERROR,
block: ActionStatus.ERROR,
reject: ActionStatus.ERROR,
// Warning actions
overuse: ActionStatus.WARNING,

View File

@@ -37,12 +37,13 @@ export default function ActiveInactiveRow({
<div className={"flex gap-2.5 items-start"}>
<CircleIcon
active={active}
size={8}
inactiveDot={inactiveDot}
className={"mt-[0.34rem] shrink-0"}
className={"mt-[0.45rem] shrink-0"}
/>
<div className={"flex flex-col min-w-0"}>
<div
className={"font-medium flex gap-2 items-center justify-center"}
className={"font-medium flex gap-2 items-center justify-start"}
>
<TextWithTooltip text={text as string} maxChars={25} />
{additionalInfo}

View File

@@ -15,7 +15,7 @@ type Props = {
export const ExitNodeDropdownButton = ({ peer }: Props) => {
const [modal, setModal] = useState(false);
const hasExitNodes = useHasExitNodes(peer);
const exitNodeInfo = useHasExitNodes(peer);
const { permission } = usePermissions();
return (
@@ -25,7 +25,7 @@ export const ExitNodeDropdownButton = ({ peer }: Props) => {
disabled={!permission.routes.create}
>
<div className={"flex gap-3 items-center w-full"}>
{hasExitNodes ? (
{exitNodeInfo.hasExitNode ? (
<>
<IconCirclePlus size={14} className={"shrink-0"} />
<div className={"flex justify-between items-center w-full"}>

View File

@@ -8,18 +8,22 @@ type Props = {
peer: Peer;
};
export const ExitNodePeerIndicator = ({ peer }: Props) => {
const hasExitNode = useHasExitNodes(peer);
const exitNodeInfo = useHasExitNodes(peer);
return hasExitNode ? (
<FullTooltip
content={
<div className={"text-xs max-w-xs"}>
This peer is an exit node. Traffic from the configured distribution
groups will be routed through this peer.
</div>
}
>
<IconDirectionSign size={15} className={"text-yellow-400 shrink-0"} />
if (!exitNodeInfo.hasExitNode) {
return null;
}
const tooltipContent = exitNodeInfo.skipAutoApply === false
? "This peer is an auto-applied exit node. Traffic from the configured distribution groups will be routed through this peer."
: "This peer is an exit node. Traffic from the configured distribution groups will be routed through this peer.";
return (
<FullTooltip content={<div className={"text-xs max-w-xs"}>{tooltipContent}</div>}>
<IconDirectionSign
size={15}
className={`shrink-0 ${exitNodeInfo.skipAutoApply === false ? "text-green-400" : "text-yellow-400"}`}
/>
</FullTooltip>
) : null;
);
};

View File

@@ -3,7 +3,12 @@ import { useLoggedInUser } from "@/contexts/UsersProvider";
import { Peer } from "@/interfaces/Peer";
import { Route } from "@/interfaces/Route";
export const useHasExitNodes = (peer?: Peer) => {
export interface ExitNodeInfo {
hasExitNode: boolean;
skipAutoApply?: boolean;
}
export const useHasExitNodes = (peer?: Peer): ExitNodeInfo => {
const { isOwnerOrAdmin } = useLoggedInUser();
const { data: routes } = useFetchApi<Route[]>(
`/routes`,
@@ -11,9 +16,17 @@ export const useHasExitNodes = (peer?: Peer) => {
true,
isOwnerOrAdmin,
);
return peer
? routes?.some(
(route) => route?.peer === peer.id && route?.network === "0.0.0.0/0",
) || false
: false;
if (!peer || !routes) {
return { hasExitNode: false };
}
const exitNodeRoute = routes.find(
(route) => route?.peer === peer.id && route?.network === "0.0.0.0/0",
);
return {
hasExitNode: !!exitNodeRoute,
skipAutoApply: exitNodeRoute?.skip_auto_apply,
};
};

View File

@@ -20,9 +20,9 @@ export const NetworkInformationSquare = ({
return (
<button
className={cn(
"flex w-full items-center max-w-[300px] gap-4 dark:text-neutral-300 text-neutral-500 transition-all group/network rounded-md",
"flex w-full items-center max-w-[450px] gap-4 dark:text-neutral-300 text-neutral-500 transition-all group/network rounded-md",
onClick
? "hover:text-neutral-100 hover:bg-nb-gray-910 cursor-pointer py-2 pl-3 pr-5 relative"
? "hover:text-neutral-100 hover:bg-nb-gray-910 cursor-pointer py-2 pl-3 pr-14 relative"
: "cursor-default",
)}
onClick={onClick}
@@ -53,7 +53,7 @@ export const NetworkInformationSquare = ({
<div className={"mt-[0px] flex items-center flex-wrap"}>
<p
className={cn(
"font-medium",
"font-medium text-left whitespace-nowrap",
size == "md" ? "text-sm" : "text-xl leading-none mb-0.5",
)}
>

View File

@@ -0,0 +1,21 @@
import FullTooltip from "@components/FullTooltip";
import * as React from "react";
import { Peer } from "@/interfaces/Peer";
import {PowerOffIcon} from "lucide-react";
type Props = {
peer: Peer;
};
export const EphemeralPeerIndicator = ({ peer }: Props) => {
if (!peer.ephemeral) {
return null;
}
const tooltipContent = "This peer is an ephemeral peer. If it is disconnected for more than 10 minutes it will be removed.";
return (
<FullTooltip content={<div className={"text-xs max-w-xs"}>{tooltipContent}</div>}>
<PowerOffIcon size={12} className={"shrink-0 text-yellow-400"} />
</FullTooltip>
);
};

View File

@@ -0,0 +1,23 @@
import FullTooltip from "@components/FullTooltip";
import { TimerResetIcon } from "lucide-react";
import * as React from "react";
import { Peer } from "@/interfaces/Peer";
type Props = {
peer: Peer;
};
export const ExpirationDisabledIndicator = ({ peer }: Props) => {
if (peer.login_expiration_enabled) {
return null;
}
const tooltipContent = "Expiration is disabled for this peer.";
return (
<FullTooltip
content={<div className={"text-xs max-w-xs"}>{tooltipContent}</div>}
>
<TimerResetIcon size={14} className={"shrink-0 text-nb-gray-300"} />
</FullTooltip>
);
};

View File

@@ -0,0 +1,27 @@
import FullTooltip from "@components/FullTooltip";
import { AlertTriangle } from "lucide-react";
import * as React from "react";
import { Peer } from "@/interfaces/Peer";
type Props = {
peer: Peer;
};
export const LoginRequiredIndicator = ({ peer }: Props) => {
if (!peer.login_expired) {
return null;
}
return (
<FullTooltip
content={
<div className={"text-xs max-w-xs"}>
{" "}
This peer is offline and needs to be <br />
re-authenticated because its login has expired.
</div>
}
>
<AlertTriangle size={14} className={"shrink-0 text-red-500"} />
</FullTooltip>
);
};

View File

@@ -17,7 +17,7 @@ type Props = {
export const PeerNetworkRoutesSection = ({ peer }: Props) => {
const { peerRoutes, isLoading } = usePeerRoutes({ peer });
const hasExitNodes = useHasExitNodes(peer);
const exitNodeInfo = useHasExitNodes(peer);
const { ref: headingRef, portalTarget } =
usePortalElement<HTMLHeadingElement>();
@@ -34,7 +34,7 @@ export const PeerNetworkRoutesSection = ({ peer }: Props) => {
</div>
<div className={"inline-flex gap-4 justify-end"}>
<div className={"gap-4 flex"}>
<AddExitNodeButton peer={peer} firstTime={!hasExitNodes} />
<AddExitNodeButton peer={peer} firstTime={!exitNodeInfo.hasExitNode} />
<AddRouteDropdownButton />
</div>
</div>

View File

@@ -64,7 +64,7 @@ export default function PeerActionCell() {
};
return (
<div className={"flex justify-end pr-4"}>
<div className={"flex justify-end pr-4 gap-3"}>
<DropdownMenu modal={false}>
<DropdownMenuTrigger
asChild={true}

View File

@@ -23,7 +23,7 @@ export default function PeerAddressCell({ peer }: Props) {
>
<div
className={
"flex gap-4 items-center min-w-[320px] max-w-[320px] group/cell transition-all hover:bg-nb-gray-800/10 py-2 px-3 rounded-md cursor-default"
"flex gap-2.5 items-center min-w-[300px] max-w-[300px] group/cell transition-all hover:bg-nb-gray-800/10 py-2 px-3 rounded-md cursor-default"
}
onClick={(e) => {
e.stopPropagation();
@@ -32,13 +32,13 @@ export default function PeerAddressCell({ peer }: Props) {
>
<div
className={cn(
"flex items-center justify-center rounded-full h-8 w-8 shrink-0 bg-nb-gray-920/80 transition-all",
"flex items-center justify-center rounded-full h-3 w-3 shrink-0 relative -top-[0.5rem]",
)}
>
{isEmpty(peer.country_code) ? (
<GlobeIcon size={16} className={"text-nb-gray-300"} />
) : (
<RoundedFlag country={peer.country_code} size={20} />
<RoundedFlag country={peer.country_code} size={12} />
)}
</div>
<div className="flex flex-col gap-0 dark:text-neutral-300 text-neutral-500 font-light truncate">

View File

@@ -1,5 +1,5 @@
import CopyToClipboardText from "@components/CopyToClipboardText";
import { cn } from "@utils/helpers";
import { ListItem } from "@components/ListItem";
import { FlagIcon, GlobeIcon, MapPin, NetworkIcon } from "lucide-react";
import * as React from "react";
import { useMemo } from "react";
@@ -104,30 +104,3 @@ export const PeerAddressTooltipContent = ({ peer }: Props) => {
</div>
);
};
const ListItem = ({
icon,
label,
value,
className,
}: {
icon: React.ReactNode;
label: string;
value: string | React.ReactNode;
className?: string;
}) => {
return (
<div
className={cn(
"flex justify-between gap-12 border-b border-nb-gray-920 py-2 px-4 last:border-b-0",
className,
)}
>
<div className={"flex items-center gap-2 text-nb-gray-100 font-medium"}>
{icon}
{label}
</div>
<div className={"text-nb-gray-300"}>{value}</div>
</div>
);
};

View File

@@ -0,0 +1,80 @@
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@components/DropdownMenu";
import FullTooltip from "@components/FullTooltip";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { IconChevronDown } from "@tabler/icons-react";
import * as React from "react";
import { usePeer } from "@/contexts/PeerProvider";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
import { RDPButton } from "@/modules/remote-access/rdp/RDPButton";
import { SSHButton } from "@/modules/remote-access/ssh/SSHButton";
import { cn } from "@utils/helpers";
export const PeerConnectButton = () => {
const { peer } = usePeer();
const isConnected = peer.connected;
const os = getOperatingSystem(peer?.os);
const isMobile = os === OperatingSystem.ANDROID || os === OperatingSystem.IOS;
if (isMobile) return;
return isConnected ? (
<>
<DropdownMenu modal={false}>
<DropdownMenuTrigger
asChild={true}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
>
<div className={"group"}>
<ConnectButton />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-auto"
align="start"
side={"bottom"}
sideOffset={8}
>
<SSHButton peer={peer} isDropdown={true} />
<RDPButton peer={peer} isDropdown={true} />
</DropdownMenuContent>
</DropdownMenu>
</>
) : (
<FullTooltip
content={
<div className={"max-w-[200px] text-xs"}>
Connecting via SSH or RDP is only available when the peer is online.
</div>
}
>
<ConnectButton disabled={true} />
</FullTooltip>
);
};
const ConnectButton = ({ disabled }: { disabled?: boolean }) => {
return (
<button
className={cn(
"flex gap-2 items-center text-sm text-nb-gray-300 hover:text-white disabled:cursor-not-allowed enabled:cursor-pointer enabled:hover:bg-nb-gray-800/60 rounded-md py-2 px-3 disabled:text-nb-gray-700",
// group data state open
"group-data-[state=open]:bg-nb-gray-800/30",
)}
disabled={disabled}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
>
Connect
<IconChevronDown size={14} />
</button>
);
};

View File

@@ -6,6 +6,9 @@ import { useLoggedInUser, useUsers } from "@/contexts/UsersProvider";
import { Peer } from "@/interfaces/Peer";
import ActiveInactiveRow from "@/modules/common-table-rows/ActiveInactiveRow";
import { ExitNodePeerIndicator } from "@/modules/exit-node/ExitNodePeerIndicator";
import { EphemeralPeerIndicator } from "@/modules/peer/EphemeralPeerIndicator";
import { ExpirationDisabledIndicator } from "@/modules/peer/ExpirationDisabledIndicator";
import { LoginRequiredIndicator } from "@/modules/peer/LoginRequiredIndicator";
type Props = {
peer: Peer;
@@ -27,7 +30,7 @@ export default function PeerNameCell({ peer, linkToPeer = true }: Props) {
<div>
<div
className={cn(
"flex items-center max-w-[300px] gap-2 dark:text-neutral-300 text-neutral-500 transition-all py-2 px-3 rounded-md ",
"flex items-center max-w-[280px] gap-2 dark:text-neutral-300 text-neutral-500 transition-all py-2 px-3 rounded-md ",
linkToPeer &&
"hover:text-neutral-100 hover:bg-nb-gray-800/60 cursor-pointer",
)}
@@ -39,7 +42,14 @@ export default function PeerNameCell({ peer, linkToPeer = true }: Props) {
active={peer.connected}
text={peer.name}
additionalInfo={
isOwnerOrAdmin && <ExitNodePeerIndicator peer={peer} />
isOwnerOrAdmin && (
<>
<ExitNodePeerIndicator peer={peer} />
<EphemeralPeerIndicator peer={peer} />
<ExpirationDisabledIndicator peer={peer} />
<LoginRequiredIndicator peer={peer} />
</>
)
}
>
<div className={"text-nb-gray-400 font-light truncate"}>

View File

@@ -0,0 +1,28 @@
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { cn } from "@utils/helpers";
import * as React from "react";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
import { OSLogo } from "@/modules/peers/PeerOSCell";
type Props = {
os: string;
className?: string;
};
export const PeerOperatingSystemIcon = ({ os, className }: Props) => {
const operatingSystem = getOperatingSystem(os);
return (
<div
className={cn(
"flex items-center justify-center grayscale brightness-[100%] contrast-[40%]",
"w-4 h-4 shrink-0",
operatingSystem === OperatingSystem.WINDOWS && "p-[2.5px]",
operatingSystem === OperatingSystem.APPLE && "p-[2.7px]",
operatingSystem === OperatingSystem.FREEBSD && "p-[1.5px]",
className,
)}
>
<OSLogo os={os} />
</div>
);
};

View File

@@ -2,8 +2,7 @@ import Badge from "@components/Badge";
import Button from "@components/Button";
import FullTooltip from "@components/FullTooltip";
import { notify } from "@components/Notification";
import LoginExpiredBadge from "@components/ui/LoginExpiredBadge";
import { HelpCircle, TimerResetIcon } from "lucide-react";
import { HelpCircle } from "lucide-react";
import * as React from "react";
import { useSWRConfig } from "swr";
import { useDialog } from "@/contexts/DialogProvider";
@@ -49,46 +48,39 @@ export default function PeerStatusCell({ peer }: Props) {
}
};
return needsApproval ? (
<div className={"flex gap-3 items-center text-xs"}>
<FullTooltip
content={
<div className={"max-w-xs text-xs"}>
The peer needs to be approved by an administrator before it can
connect to other peers.
</div>
}
interactive={false}
>
<Badge variant={"netbird"} className={"px-3 font-medium"}>
<HelpCircle size={12} />
Approval required
</Badge>
</FullTooltip>
<Button
variant={"secondary"}
size={"xs"}
className={"h-[32px]"}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
if (!canApprove) return;
approvePeer();
}}
>
Approve
</Button>
</div>
) : (
<div className={"flex gap-3 items-center text-xs"}>
{!peer.login_expiration_enabled && (
<Badge variant={"gray"} className={"px-2"}>
<TimerResetIcon size={13} className={"relative -top-[1px]"} />
Expiration disabled
</Badge>
)}
<LoginExpiredBadge loginExpired={peer.login_expired} />
</div>
);
}
return (
needsApproval && (
<div className={"flex gap-3 items-center text-xs"}>
<FullTooltip
content={
<div className={"max-w-xs text-xs"}>
The peer needs to be approved by an administrator before it can
connect to other peers.
</div>
}
interactive={false}
>
<Badge variant={"netbird"} className={"px-3 font-medium"}>
<HelpCircle size={12} />
Approval required
</Badge>
</FullTooltip>
{ canApprove && (
<Button
variant={"secondary"}
size={"xs"}
className={"h-[32px]"}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
if (!canApprove) return;
approvePeer();
}}
>
Approve
</Button>
)}
</div>
)
);
}

View File

@@ -1,3 +1,4 @@
import FullTooltip from "@components/FullTooltip";
import InlineLink from "@components/InlineLink";
import {
Tooltip,
@@ -8,17 +9,20 @@ import {
import MemoizedNetBirdIcon from "@components/ui/MemoizedNetBirdIcon";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { parseVersionString } from "@utils/version";
import { trim } from "lodash";
import { ArrowRightIcon, ArrowUpCircleIcon } from "lucide-react";
import * as React from "react";
import { useMemo } from "react";
import { useApplicationContext } from "@/contexts/ApplicationProvider";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
import { PeerOperatingSystemIcon } from "@/modules/peers/PeerOperatingSystemIcon";
type Props = {
version: string;
os: string;
serial?: string;
};
export default function PeerVersionCell({ version, os }: Props) {
export default function PeerVersionCell({ version, os, serial }: Props) {
const { latestVersion, latestUrl } = useApplicationContext();
const updateAvailable = useMemo(() => {
@@ -35,56 +39,85 @@ export default function PeerVersionCell({ version, os }: Props) {
return <ArrowUpCircleIcon size={15} className={"text-netbird"} />;
}, []);
return updateAvailable ? (
<TooltipProvider>
<Tooltip delayDuration={10}>
<TooltipTrigger>
<div className="flex gap-2 dark:text-neutral-300 text-neutral-500 hover:text-neutral-100 transition-all hover:bg-nb-gray-800/60 py-2 px-3 rounded-md items-center">
<MemoizedNetBirdIcon />
{version == "development" ? "dev" : version}
<div className={"relative"}>
<span className="animate-ping absolute left-0 inline-flex h-[15px] w-[15px] rounded-full bg-netbird opacity-20"></span>
{updateIcon}
const isWasmClient = trim(os) === "js";
return (
<div className={"flex flex-col gap-1"}>
{updateAvailable ? (
<TooltipProvider>
<Tooltip delayDuration={10}>
<TooltipTrigger>
<div className="flex gap-2 dark:text-neutral-300 text-neutral-500 hover:text-neutral-100 transition-all rounded-md items-center">
<MemoizedNetBirdIcon />
{version == "development" ? "dev" : version}
<div className={"relative"}>
<span className="animate-ping absolute left-0 inline-flex h-[15px] w-[15px] rounded-full bg-netbird opacity-20"></span>
{updateIcon}
</div>
</div>
</TooltipTrigger>
<TooltipContent>
<div
className={
" inline-flex gap-2 items-center rounded-md text-xs my-2"
}
>
<MemoizedNetBirdIcon />
<span>{version}</span>
<ArrowRightIcon size={16} className={"text-netbird"} />
<span className={"text-netbird"}>{latestVersion}</span>
</div>
<p className={"font-medium"}>Update available </p>
<div
className={
"text-neutral-300 flex flex-col gap-1 max-w-[300px] text-xs mt-1"
}
>
A new version of Netbird is available. Please update your client
to get the latest features and bug fixes.
</div>
<InlineLink
onClick={(e) => e.stopPropagation()}
href={latestUrl as string}
target={"_blank"}
className={"mt-2 mb-2 text-xs"}
>
Download & Changelog
</InlineLink>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
<div className="inline-flex gap-2 dark:text-neutral-300 text-neutral-500 items-center">
<MemoizedNetBirdIcon />
{version == "development" ? "dev" : version}
</div>
)}
{os && os !== "" && os !== " " && (
<FullTooltip
delayDuration={500}
disabled={!serial || serial === ""}
content={
<div className={"text-xs"}>
<span className={"text-nb-gray-100 font-medium"}>Serial: </span>
{serial}
</div>
</div>
</TooltipTrigger>
<TooltipContent>
}
>
<div
className={
" inline-flex gap-2 items-center rounded-md text-xs my-2"
"flex items-center gap-2 text-neutral-300 whitespace-nowrap"
}
>
<MemoizedNetBirdIcon />
<span>{version}</span>
<ArrowRightIcon size={16} className={"text-netbird"} />
<span className={"text-netbird"}>{latestVersion}</span>
</div>
<p className={"font-medium"}>Update available </p>
<PeerOperatingSystemIcon os={os} />
<div
className={
"text-neutral-300 flex flex-col gap-1 max-w-[300px] text-xs mt-1"
}
>
A new version of Netbird is available. Please update your client to
get the latest features and bug fixes.
{isWasmClient ? "Web Client" : os}
</div>
<InlineLink
onClick={(e) => e.stopPropagation()}
href={latestUrl as string}
target={"_blank"}
className={"mt-2 mb-2 text-xs"}
>
Download & Changelog
</InlineLink>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
<div className="inline-flex gap-2 dark:text-neutral-300 text-neutral-500 py-2 px-3 items-center">
<MemoizedNetBirdIcon />
{version == "development" ? "dev" : version}
</FullTooltip>
)}
</div>
);
}

View File

@@ -1,26 +1,24 @@
import Button from "@components/Button";
import ButtonGroup from "@components/ButtonGroup";
import { Checkbox } from "@components/Checkbox";
import InlineLink from "@components/InlineLink";
import SquareIcon from "@components/SquareIcon";
import FullTooltip from "@components/FullTooltip";
import { NoPeersGettingStarted } from "@components/NoPeersGettingStarted";
import { DataTable } from "@components/table/DataTable";
import DataTableHeader from "@components/table/DataTableHeader";
import DataTableRefreshButton from "@components/table/DataTableRefreshButton";
import { DataTableRowsPerPage } from "@components/table/DataTableRowsPerPage";
import AddPeerButton from "@components/ui/AddPeerButton";
import GetStartedTest from "@components/ui/GetStartedTest";
import { NotificationCountBadge } from "@components/ui/NotificationCountBadge";
import {
ColumnDef,
RowSelectionState,
SortingState,
} from "@tanstack/react-table";
import { uniqBy } from "lodash";
import { ExternalLinkIcon } from "lucide-react";
import { trim, uniqBy } from "lodash";
import { MonitorDotIcon } from "lucide-react";
import { usePathname } from "next/navigation";
import React, { useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useSWRConfig } from "swr";
import PeerIcon from "@/assets/icons/PeerIcon";
import PeerProvider from "@/contexts/PeerProvider";
import { usePermissions } from "@/contexts/PermissionsProvider";
import { useLoggedInUser } from "@/contexts/UsersProvider";
@@ -30,6 +28,7 @@ import { Peer } from "@/interfaces/Peer";
import { GroupFilterSelector } from "@/modules/groups/GroupFilterSelector";
import PeerActionCell from "@/modules/peers/PeerActionCell";
import PeerAddressCell from "@/modules/peers/PeerAddressCell";
import { PeerConnectButton } from "@/modules/peers/PeerConnectButton";
import PeerGroupCell from "@/modules/peers/PeerGroupCell";
import PeerLastSeenCell from "@/modules/peers/PeerLastSeenCell";
import { PeerMultiSelect } from "@/modules/peers/PeerMultiSelect";
@@ -72,6 +71,16 @@ const PeersTableColumns: ColumnDef<Peer>[] = [
sortingFn: "text",
cell: ({ row }) => <PeerNameCell peer={row.original} />,
},
{
id: "connect",
accessorKey: "id",
header: "",
cell: ({ row }) => (
<PeerProvider peer={row.original}>
<PeerConnectButton />
</PeerProvider>
),
},
{
id: "approval_required",
accessorKey: "approval_required",
@@ -157,7 +166,11 @@ const PeersTableColumns: ColumnDef<Peer>[] = [
return <DataTableHeader column={column}>Version</DataTableHeader>;
},
cell: ({ row }) => (
<PeerVersionCell version={row.original.version} os={row.original.os} />
<PeerVersionCell
version={row.original.version}
os={row.original.os}
serial={row.original.serial_number}
/>
),
},
{
@@ -243,6 +256,30 @@ export default function PeersTable({
}
};
const [showBrowserPeers, setShowBrowserPeers] = useState(false);
const withBrowserPeers = useCallback(
(condition: boolean) =>
peers?.filter((peer) =>
condition ? trim(peer.os) === "js" : trim(peer.os) !== "js",
) ?? [],
[peers],
);
const browserPeers = useMemo(() => {
return withBrowserPeers(true);
}, [withBrowserPeers]);
const regularPeers = useMemo(() => {
return withBrowserPeers(false);
}, [withBrowserPeers]);
useEffect(() => {
if (showBrowserPeers && browserPeers?.length === 0) {
setShowBrowserPeers(false);
}
}, [showBrowserPeers, browserPeers]);
return (
<>
<PeerMultiSelect
@@ -258,7 +295,7 @@ export default function PeersTable({
sorting={sorting}
setSorting={setSorting}
columns={PeersTableColumns}
data={peers}
data={showBrowserPeers ? browserPeers : regularPeers}
searchPlaceholder={"Search by name, IP, owner or group..."}
columnVisibility={{
select: permission.groups.read,
@@ -271,38 +308,12 @@ export default function PeersTable({
user_name: false,
user_email: false,
actions: permission.peers.update,
connect: permission.peers.update,
groups: permission.groups.read,
os: false,
}}
isLoading={isLoading}
getStartedCard={
<GetStartedTest
icon={
<SquareIcon
icon={<PeerIcon className={"fill-nb-gray-200"} size={20} />}
color={"gray"}
size={"large"}
/>
}
title={"Get Started with NetBird"}
description={
"It looks like you don't have any connected machines.\n" +
"Get started by adding one to your network."
}
button={<AddPeerButton />}
learnMore={
<>
Learn more in our{" "}
<InlineLink
href={"https://docs.netbird.io/how-to/getting-started"}
target={"_blank"}
>
Getting Started Guide
<ExternalLinkIcon size={12} />
</InlineLink>
</>
}
/>
}
getStartedCard={<NoPeersGettingStarted showBackground={true} />}
rightSide={() => <>{peers && peers.length > 0 && <AddPeerButton />}</>}
>
{(table) => (
@@ -471,6 +482,28 @@ export default function PeersTable({
/>
)}
{browserPeers?.length > 0 && (
<FullTooltip
content={
<div className={"max-w-sm text-xs"}>
Show temporary peers created by the NetBird browser client.
These peers are ephemeral and will be deleted automatically
after a short period of time.
</div>
}
>
<Button
className={"h-[44px]"}
variant={showBrowserPeers ? "tertiary" : "secondary"}
onClick={() => {
setShowBrowserPeers(!showBrowserPeers);
}}
>
<MonitorDotIcon size={16} />
</Button>
</FullTooltip>
)}
<DataTableRefreshButton
isDisabled={peers?.length == 0}
onClick={() => {

View File

@@ -0,0 +1,72 @@
import Button from "@components/Button";
import { DropdownMenuItem } from "@components/DropdownMenu";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { CircleHelpIcon, MonitorIcon } from "lucide-react";
import * as React from "react";
import { useState } from "react";
import { usePermissions } from "@/contexts/PermissionsProvider";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
import { Peer } from "@/interfaces/Peer";
import { RDPTooltip } from "@/modules/remote-access/rdp/RDPTooltip";
import { SSHCredentialsModal } from "@/modules/remote-access/ssh/SSHCredentialsModal";
type Props = {
peer: Peer;
isDropdown?: boolean;
};
export const RDPButton = ({ peer, isDropdown = false }: Props) => {
const [modal, setModal] = useState(false);
const { permission } = usePermissions();
const disabled = !peer.connected || !permission.peers.update;
const hasPermission = permission.peers.update;
const isWindows = getOperatingSystem(peer?.os) === OperatingSystem.WINDOWS;
const openRDPPage = () => {
window.open(
`peer/rdp?id=${peer.id}`,
"_blank",
"noopener,noreferrer,width=1200,height=650,left=100,top=100,location=no,toolbar=no,menubar=no,status=no",
);
};
return (
isWindows && (
<>
<div>
<RDPTooltip
disabled={!disabled}
hasPermission={hasPermission}
side={isDropdown ? "left" : "top"}
>
{isDropdown ? (
<DropdownMenuItem
onClick={openRDPPage}
disabled={disabled}
className={"w-full"}
>
<div className={"flex gap-3 items-center w-full"}>
<MonitorIcon size={14} className={"shrink-0"} />
RDP
</div>
</DropdownMenuItem>
) : (
<Button
variant="secondary"
size="sm"
onClick={openRDPPage}
disabled={disabled}
>
<MonitorIcon size={16} />
RDP
{disabled && <CircleHelpIcon size={12} />}
</Button>
)}
</RDPTooltip>
</div>
</>
)
);
};

View File

@@ -0,0 +1,170 @@
import Button from "@components/Button";
import { Callout } from "@components/Callout";
import { Checkbox } from "@components/Checkbox";
import HelpText from "@components/HelpText";
import { Label } from "@components/Label";
import { Modal, ModalContent, ModalFooter } from "@components/modal/Modal";
import ModalHeader from "@components/modal/ModalHeader";
import Separator from "@components/Separator";
import { LockIcon } from "lucide-react";
import * as React from "react";
import { useState } from "react";
import {
CertificateInfo,
CertificatePromptInfo,
} from "./useRDPCertificateHandler";
type Props = {
open: boolean;
certificateInfo: CertificatePromptInfo | null;
onAccept: (remember: boolean) => void;
onReject: () => void;
};
export const RDPCertificateModal = ({
open,
certificateInfo,
onAccept,
onReject,
}: Props) => {
const [rememberCertificate, setRememberCertificate] = useState(false);
if (!certificateInfo) return null;
const { hostname, certificate, isChange } = certificateInfo;
return (
<Modal open={open} onOpenChange={undefined}>
<ModalContent maxWidthClass={"max-w-2xl"} showClose={false}>
<ModalHeader
icon={<LockIcon className={"text-netbird"} size={18} />}
title={"RDP Certificate"}
description={hostname}
color={"netbird"}
/>
<Separator />
<div className={"px-8 py-6 flex flex-col gap-6"}>
{isChange && (
<Callout variant={"warning"}>
Warning! Certificate has changed. Only proceed if you trust this
connection.
</Callout>
)}
<div>
<Label>Certificate Details</Label>
<HelpText>
Certificated could not be verified by a trusted authority. Review
the certificate information before proceeding with the connection.
</HelpText>
<CertificateDetailsList certificate={certificate} />
</div>
<label className={"flex items-center space-x-3 cursor-pointer"}>
<Checkbox
id="remember-cert"
checked={rememberCertificate}
variant={"tableCell"}
onCheckedChange={(checked) =>
setRememberCertificate(checked === true)
}
/>
<div className={"font-normal text-sm text-nb-gray-200"}>
Always trust{" "}
<span className={"text-white font-medium"}>
{'"' + certificate?.issuer?.replace("CN=", "") + '"'}
</span>{" "}
when connecting to{" "}
<span className={"text-white font-medium"}>
{'"' + hostname + '"'}
</span>
</div>
</label>
</div>
<ModalFooter className={"items-center"}>
<div className={"flex gap-3 w-full justify-end"}>
<Button variant={"secondary"} onClick={onReject}>
Cancel
</Button>
<Button
variant={"primary"}
onClick={() => onAccept(rememberCertificate)}
>
Accept & Continue
</Button>
</div>
</ModalFooter>
</ModalContent>
</Modal>
);
};
const CertificateDetailsList = ({
certificate,
}: {
certificate: CertificateInfo;
}) => {
if (!certificate) return null;
return (
<div
className={
"bg-nb-gray-930 border border-nb-gray-900 rounded-md mt-3 flex flex-col py-3 px-4 gap-2"
}
>
<CertificateDetailsListItem
label={"Issuer"}
value={certificate.issuer || "N/A"}
/>
<CertificateDetailsListItem
label={"Subject"}
value={certificate.subject || "N/A"}
/>
<CertificateDetailsListItem
label={"Valid From"}
value={
certificate.validFrom
? new Date(certificate.validFrom).toLocaleString()
: "N/A"
}
/>
<CertificateDetailsListItem
label={"Valid To"}
value={
certificate.validTo
? new Date(certificate.validTo).toLocaleString()
: "N/A"
}
/>
<CertificateDetailsListItem
label={"Key Size"}
value={certificate.keySize ? `${certificate.keySize} bits` : "N/A"}
/>
<CertificateDetailsListItem
label={"Serial Number"}
value={certificate.serialNumber || "N/A"}
/>
<CertificateDetailsListItem
label={"Fingerprint"}
value={certificate.fingerprint || "N/A"}
/>
</div>
);
};
const CertificateDetailsListItem = ({
label,
value,
}: {
label: string;
value: string;
}) => {
return (
<div key={label} className={"flex justify-between text-xs gap-10"}>
<span className={"font-mono text-nb-gray-200 w-[200px]"}>{label}:</span>
<span className={"font-mono text-nb-gray-300 break-all text-left w-full"}>
{value}
</span>
</div>
);
};

View File

@@ -0,0 +1,200 @@
import * as React from "react";
import { useCallback, useMemo, useState } from "react";
import { Modal, ModalContent, ModalFooter } from "@components/modal/Modal";
import ModalHeader from "@components/modal/ModalHeader";
import { Peer } from "@/interfaces/Peer";
import {
ChevronsLeftRightEllipsis,
ExternalLinkIcon,
KeyRoundIcon,
MonitorIcon,
User2,
} from "lucide-react";
import Separator from "@components/Separator";
import Paragraph from "@components/Paragraph";
import InlineLink from "@components/InlineLink";
import Button from "@components/Button";
import { Label } from "@components/Label";
import HelpText from "@components/HelpText";
import { Input } from "@components/Input";
import {
RDP_DOCS_LINK,
RDPCredentials,
} from "@/modules/remote-access/rdp/useRemoteDesktop";
import { IconLoader2 } from "@tabler/icons-react";
type Props = {
open: boolean;
peer: Peer;
onConnect?: (credentials: RDPCredentials) => void;
error?: string;
loading?: boolean;
};
export const RDPCredentialsModal = ({
open,
peer,
onConnect,
error,
loading,
}: Props) => {
const [username, setUsername] = useState("Administrator");
const [password, setPassword] = useState("");
const [port, setPort] = useState("3389");
const userNameError = useMemo(() => {
if (username?.length === 0) return "Username cannot be empty";
}, [username]);
const portError = useMemo(() => {
const portNumber = Number(port);
const isValid =
Number.isInteger(portNumber) && portNumber > 0 && portNumber <= 65535;
if (!isValid) return "Port must be a number between 1 and 65535";
}, [port]);
const hasAnyError = useMemo(() => {
if (userNameError !== undefined) return true;
return portError !== undefined;
}, [userNameError, portError]);
const handleConnect = useCallback(() => {
if (hasAnyError || !onConnect) return;
onConnect({
username,
password,
port: Number(port),
});
}, [hasAnyError, onConnect, username, password, port]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Enter" && !hasAnyError && !loading) {
handleConnect();
}
},
[handleConnect, hasAnyError, loading],
);
return (
<Modal open={open} onOpenChange={undefined}>
<ModalContent maxWidthClass={"max-w-xl"} showClose={false}>
<ModalHeader
icon={<MonitorIcon className={"text-netbird"} size={18} />}
title={peer.name}
description={`Connect to ${peer.ip} via RDP`}
color={"netbird"}
/>
<Separator />
<form
className={"px-8 py-6 flex flex-col gap-8"}
onSubmit={(e) => {
e.preventDefault();
handleConnect();
}}
>
{error && (
<div className={"bg-red-50 border border-red-200 rounded-md p-4"}>
<div
className={
"flex items-center gap-2 text-red-800 font-medium mb-1"
}
>
Error
</div>
<p className={"text-sm text-red-700"}>{error}</p>
</div>
)}
<div>
<Label>Username & Password</Label>
<HelpText>
Enter the credentials required to authenticate with the remote
host.
</HelpText>
<div className={"flex flex-col gap-2 w-full"}>
<Input
placeholder={"Administrator"}
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={handleKeyDown}
name="username"
autoComplete={"username"}
error={userNameError}
errorTooltip={true}
errorTooltipPosition={"top-right"}
customPrefix={
<User2 size={16} className={"text-nb-gray-300"} />
}
/>
<Input
value={password}
placeholder={"Enter password"}
type={"password"}
onChange={(e) => setPassword(e.target.value)}
onKeyDown={handleKeyDown}
name="password"
autoComplete={"current-password"}
error={undefined}
errorTooltip={true}
errorTooltipPosition={"top-right"}
customPrefix={
<KeyRoundIcon size={16} className={"text-nb-gray-300"} />
}
/>
</div>
</div>
<div>
<Label>Port</Label>
<HelpText>
Specify the RDP port for your remote connection.
</HelpText>
<Input
maxWidthClass={""}
placeholder={"3389"}
min={1}
max={65535}
value={port}
type={"number"}
error={portError}
errorTooltip={true}
errorTooltipPosition={"top-right"}
onChange={(e) => setPort(e.target.value)}
onKeyDown={handleKeyDown}
customPrefix={
<ChevronsLeftRightEllipsis
size={16}
className={"text-nb-gray-300"}
/>
}
/>
</div>
</form>
<ModalFooter className={"items-center"}>
<div className={"w-full"}>
<Paragraph className={"text-sm mt-auto"}>
Learn more about
<InlineLink href={RDP_DOCS_LINK} target={"_blank"}>
RDP
<ExternalLinkIcon size={12} />
</InlineLink>
</Paragraph>
</div>
<div className={"flex gap-3 w-full justify-end"}>
<Button
type="submit"
variant={"primary"}
disabled={hasAnyError || loading}
onClick={handleConnect}
>
{loading && <IconLoader2 size={16} className={"animate-spin"} />}
Connect
</Button>
</div>
</ModalFooter>
</ModalContent>
</Modal>
);
};

View File

@@ -0,0 +1,37 @@
import FullTooltip from "@components/FullTooltip";
import * as React from "react";
type Props = {
disabled?: boolean;
children?: React.ReactNode;
hasPermission?: boolean;
side?: "top" | "right" | "bottom" | "left";
};
export const RDPTooltip = ({
disabled,
children,
hasPermission,
side = "top",
}: Props) => {
return (
<FullTooltip
className={"w-full"}
side={side}
content={
<div className={"max-w-xs text-xs flex flex-col gap-2"}>
{hasPermission ? (
<div>This peer is offline and cannot be accessed via RDP.</div>
) : (
<div>
You do not have permission to launch an RDP session. Please
contact your administrator.
</div>
)}
</div>
}
disabled={disabled}
>
{children}
</FullTooltip>
);
};

View File

@@ -0,0 +1,809 @@
/**
* IronRDP Input Handler for NetBird WASM Client
* Handles mouse and keyboard input for IronRDP sessions
*/
import type { IronRDPModule, RDPSession } from "./ironrdp-wasm-bridge";
interface DeviceEvent {
free?(): void;
}
interface InputTransaction {
addEvent(event: DeviceEvent): void;
free?(): void;
}
interface IronRDPAPI extends IronRDPModule {
DeviceEvent: {
mouseButtonPressed(button: number): DeviceEvent;
mouseButtonReleased(button: number): DeviceEvent;
mouseMove(x: number, y: number): DeviceEvent;
wheelRotations(isVertical: boolean, rotationUnits: number): DeviceEvent;
keyPressed(scancode: number): DeviceEvent;
keyReleased(scancode: number): DeviceEvent;
unicode(code: number): DeviceEvent;
};
InputTransaction: new () => InputTransaction;
}
interface ExtendedRDPSession extends RDPSession {
applyInputs(transaction: InputTransaction): void;
}
interface CoordinateResult {
x: number;
y: number;
}
declare global {
interface Window {
toggleFullscreen?: () => void;
}
}
export class IronRDPInputHandler {
private ironrdp: IronRDPAPI;
private session: ExtendedRDPSession;
private canvas: HTMLCanvasElement;
private isActive = false;
private mouseButtonStates: Record<number, boolean> = {
0: false,
1: false,
2: false,
};
private keyStates = new Map<string, boolean>();
private currentMouseX = 0;
private currentMouseY = 0;
// Bound event handlers for proper cleanup
private boundHandlers = {
mouseDown: this.handleMouseDown.bind(this),
mouseUp: this.handleMouseUp.bind(this),
mouseMove: this.handleMouseMove.bind(this),
mouseEnter: this.handleMouseEnter.bind(this),
wheel: this.handleWheel.bind(this),
touchStart: this.handleTouchStart.bind(this),
touchMove: this.handleTouchMove.bind(this),
touchEnd: this.handleTouchEnd.bind(this),
keyDown: this.handleKeyDown.bind(this),
keyUp: this.handleKeyUp.bind(this),
paste: this.handlePaste.bind(this),
copy: this.handleCopy.bind(this),
contextMenu: (e: Event) => e.preventDefault(),
focus: this.handleFocus.bind(this),
blur: this.handleBlur.bind(this),
click: this.handleClick.bind(this),
globalKeyDown: this.handleGlobalKeyDown.bind(this),
};
// Keyboard code to scancode mappings (using event.code instead of deprecated keyCode)
private readonly codeToScancode: Record<string, number> = {
// Letters
KeyA: 0x1e,
KeyB: 0x30,
KeyC: 0x2e,
KeyD: 0x20,
KeyE: 0x12,
KeyF: 0x21,
KeyG: 0x22,
KeyH: 0x23,
KeyI: 0x17,
KeyJ: 0x24,
KeyK: 0x25,
KeyL: 0x26,
KeyM: 0x32,
KeyN: 0x31,
KeyO: 0x18,
KeyP: 0x19,
KeyQ: 0x10,
KeyR: 0x13,
KeyS: 0x1f,
KeyT: 0x14,
KeyU: 0x16,
KeyV: 0x2f,
KeyW: 0x11,
KeyX: 0x2d,
KeyY: 0x15,
KeyZ: 0x2c,
// Numbers
Digit0: 0x0b,
Digit1: 0x02,
Digit2: 0x03,
Digit3: 0x04,
Digit4: 0x05,
Digit5: 0x06,
Digit6: 0x07,
Digit7: 0x08,
Digit8: 0x09,
Digit9: 0x0a,
// Function keys
F1: 0x3b,
F2: 0x3c,
F3: 0x3d,
F4: 0x3e,
F5: 0x3f,
F6: 0x40,
F7: 0x41,
F8: 0x42,
F9: 0x43,
F10: 0x44,
F11: 0x57,
F12: 0x58,
// Special keys
Backspace: 0x0e,
Tab: 0x0f,
Enter: 0x1c,
ShiftLeft: 0x2a,
ShiftRight: 0x36,
ControlLeft: 0x1d,
ControlRight: 0x9d,
AltLeft: 0x38,
AltRight: 0xb8,
CapsLock: 0x3a,
Escape: 0x01,
Space: 0x39,
PageUp: 0xe049,
PageDown: 0xe051,
End: 0xe04f,
Home: 0xe047,
ArrowLeft: 0xe04b,
ArrowUp: 0xe048,
ArrowRight: 0xe04d,
ArrowDown: 0xe050,
Insert: 0xe052,
Delete: 0xe053,
MetaLeft: this.isMacOS() ? 0x1d : 0x5b,
MetaRight: this.isMacOS() ? 0x9d : 0x5c,
// Punctuation
Semicolon: 0x27,
Equal: 0x0d,
Comma: 0x33,
Minus: 0x0c,
Period: 0x34,
Slash: 0x35,
Backquote: 0x29,
BracketLeft: 0x1a,
Backslash: 0x2b,
BracketRight: 0x1b,
Quote: 0x28,
// Numpad keys
Numpad0: 0x52,
Numpad1: 0x4f,
Numpad2: 0x50,
Numpad3: 0x51,
Numpad4: 0x4b,
Numpad5: 0x4c,
Numpad6: 0x4d,
Numpad7: 0x47,
Numpad8: 0x48,
Numpad9: 0x49,
NumpadDecimal: 0x53,
NumpadDivide: 0xe035,
NumpadMultiply: 0x37,
NumpadSubtract: 0x4a,
NumpadAdd: 0x4e,
NumpadEnter: 0xe01c,
NumLock: 0x45,
// System keys
PrintScreen: 0xe037,
ScrollLock: 0x46,
Pause: 0xe11d,
// Additional Windows/Context keys
ContextMenu: 0xe05d,
// Additional function keys (F13-F24)
F13: 0x64,
F14: 0x65,
F15: 0x66,
F16: 0x67,
F17: 0x68,
F18: 0x69,
F19: 0x6a,
F20: 0x6b,
F21: 0x6c,
F22: 0x6d,
F23: 0x6e,
F24: 0x76,
// Media keys
AudioVolumeDown: 0xe02e,
AudioVolumeUp: 0xe030,
AudioVolumeMute: 0xe020,
MediaPlayPause: 0xe022,
MediaStop: 0xe024,
MediaTrackPrevious: 0xe010,
MediaTrackNext: 0xe019,
// Browser/Application keys
BrowserBack: 0xe06a,
BrowserForward: 0xe069,
BrowserRefresh: 0xe067,
BrowserStop: 0xe068,
BrowserSearch: 0xe065,
BrowserFavorites: 0xe066,
BrowserHome: 0xe032,
LaunchMail: 0xe06c,
LaunchApp1: 0xe06b,
LaunchApp2: 0xe021,
// International keys
IntlBackslash: 0x56,
IntlRo: 0x73,
IntlYen: 0x7d,
};
private readonly mouseButtonMap: Record<number, number> = {
0: 0,
1: 1,
2: 2,
};
private touchState = {
lastX: 0,
lastY: 0,
touching: false,
};
constructor(
ironrdp: IronRDPModule,
session: RDPSession,
canvas: HTMLCanvasElement,
) {
this.ironrdp = ironrdp as IronRDPAPI;
this.session = session as ExtendedRDPSession;
this.canvas = canvas;
this.setupEventListeners();
// Initialize mouse position to unknown - will be set on first mouse event
this.currentMouseX = -1;
this.currentMouseY = -1;
}
/**
* Detect if the current platform is macOS
*/
private isMacOS(): boolean {
if ("userAgentData" in navigator && (navigator as any).userAgentData) {
return (navigator as any).userAgentData.platform === "macOS";
}
// Fallback
return /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);
}
/**
* Calculate canvas coordinates with letterbox correction for fullscreen mode
*/
private getCanvasCoordinates(
clientX: number,
clientY: number,
): CoordinateResult {
const rect = this.canvas.getBoundingClientRect();
// Calculate the actual rendered size of the canvas content
const canvasAspectRatio = this.canvas.width / this.canvas.height;
const containerAspectRatio = rect.width / rect.height;
let renderWidth: number,
renderHeight: number,
offsetX: number,
offsetY: number;
// Check if we're using object-fit: contain (letterboxing)
const isFullscreen =
document.fullscreenElement === this.canvas ||
document.fullscreenElement === this.canvas.parentElement;
const hasLetterbox = isFullscreen && this.canvas.style.objectFit !== "fill";
if (hasLetterbox && canvasAspectRatio !== containerAspectRatio) {
// Calculate actual rendered dimensions with letterboxing
if (canvasAspectRatio > containerAspectRatio) {
// Canvas is wider - letterbox on top/bottom
renderWidth = rect.width;
renderHeight = rect.width / canvasAspectRatio;
offsetX = 0;
offsetY = (rect.height - renderHeight) / 2;
} else {
// Canvas is taller - letterbox on left/right
renderWidth = rect.height * canvasAspectRatio;
renderHeight = rect.height;
offsetX = (rect.width - renderWidth) / 2;
offsetY = 0;
}
} else {
// No letterboxing - canvas fills the entire rect
renderWidth = rect.width;
renderHeight = rect.height;
offsetX = 0;
offsetY = 0;
}
// Calculate scale factors based on actual render size
const scaleX = this.canvas.width / renderWidth;
const scaleY = this.canvas.height / renderHeight;
// Adjust coordinates for letterbox offset
const relativeX = clientX - rect.left - offsetX;
const relativeY = clientY - rect.top - offsetY;
// Clamp to valid canvas area
const x = Math.max(
0,
Math.min(this.canvas.width - 1, Math.round(relativeX * scaleX)),
);
const y = Math.max(
0,
Math.min(this.canvas.height - 1, Math.round(relativeY * scaleY)),
);
return { x, y };
}
private setupEventListeners(): void {
this.canvas.tabIndex = 1;
this.canvas.style.outline = "none";
// Mouse events
this.canvas.addEventListener("mousedown", this.boundHandlers.mouseDown);
this.canvas.addEventListener("mouseup", this.boundHandlers.mouseUp);
this.canvas.addEventListener("mousemove", this.boundHandlers.mouseMove);
this.canvas.addEventListener("mouseenter", this.boundHandlers.mouseEnter);
this.canvas.addEventListener("wheel", this.boundHandlers.wheel);
this.canvas.addEventListener("contextmenu", this.boundHandlers.contextMenu);
// Touch events
this.canvas.addEventListener("touchstart", this.boundHandlers.touchStart);
this.canvas.addEventListener("touchmove", this.boundHandlers.touchMove);
this.canvas.addEventListener("touchend", this.boundHandlers.touchEnd);
// Keyboard events
this.canvas.addEventListener("keydown", this.boundHandlers.keyDown);
this.canvas.addEventListener("keyup", this.boundHandlers.keyUp);
this.canvas.addEventListener("paste", this.boundHandlers.paste);
this.canvas.addEventListener("copy", this.boundHandlers.copy);
// Focus events
this.canvas.addEventListener("focus", this.boundHandlers.focus);
this.canvas.addEventListener("blur", this.boundHandlers.blur);
this.canvas.addEventListener("click", this.boundHandlers.click);
// Global keyboard shortcuts
document.addEventListener("keydown", this.boundHandlers.globalKeyDown);
}
private updateVisualIndicator(active: boolean): void {
if (!this.canvas.parentElement) return;
const controls = this.canvas.parentElement.querySelector(
"#rdpControls",
) as HTMLElement;
if (!controls) return;
controls.style.borderBottom = active ? "2px solid #4CAF50" : "none";
}
private handleGlobalKeyDown(e: KeyboardEvent): void {
if (!this.isActive) return;
// F11 for fullscreen toggle
if (e.key === "F11") {
e.preventDefault();
if (window.toggleFullscreen) {
window.toggleFullscreen();
}
}
// Ctrl+Alt+Enter for fullscreen toggle
else if (e.ctrlKey && e.altKey && e.key === "Enter") {
e.preventDefault();
if (window.toggleFullscreen) {
window.toggleFullscreen();
}
}
}
private handleFocus(): void {
this.isActive = true;
this.updateVisualIndicator(true);
// Trigger clipboard sync when canvas gains focus
this.requestClipboardSync();
}
private handleBlur(): void {
this.isActive = false;
this.releaseAllKeys();
this.updateVisualIndicator(false);
}
private handleClick(): void {
this.canvas.focus();
// Also sync clipboard on click to ensure paste works
this.requestClipboardSync();
}
private handlePaste(event: ClipboardEvent): void {
if (!this.isActive) return;
// Only prevent default if we successfully handle the paste
const clipboardData = event.clipboardData;
if (!clipboardData) return;
const text = clipboardData.getData("text/plain");
if (!text) return;
// Prevent the default paste behavior only after we have the text
event.preventDefault();
// Send Ctrl+V combination to RDP session first to maintain consistency
this.sendPasteKeyCombination();
// Then send the actual text content
this.sendTextAsKeystrokes(text);
}
private handleCopy(event: ClipboardEvent): void {
if (!this.isActive) return;
// Send Ctrl+C combination to RDP session
this.sendCopyKeyCombination();
// Let the browser handle the actual copy operation
// Don't prevent default - we want the browser to copy from the RDP canvas
}
private sendPasteKeyCombination(): void {
if (!this.session || !this.ironrdp) return;
try {
const transaction = new this.ironrdp.InputTransaction();
// Send Ctrl (or Cmd on Mac) key down
const ctrlScancode = this.isMacOS()
? this.codeToScancode.MetaLeft
: this.codeToScancode.ControlLeft;
const vScancode = this.codeToScancode.KeyV;
if (ctrlScancode && vScancode) {
// Ctrl/Cmd down
const ctrlDown = this.ironrdp.DeviceEvent.keyPressed(ctrlScancode);
transaction.addEvent(ctrlDown);
// V down
const vDown = this.ironrdp.DeviceEvent.keyPressed(vScancode);
transaction.addEvent(vDown);
// V up
const vUp = this.ironrdp.DeviceEvent.keyReleased(vScancode);
transaction.addEvent(vUp);
// Ctrl/Cmd up
const ctrlUp = this.ironrdp.DeviceEvent.keyReleased(ctrlScancode);
transaction.addEvent(ctrlUp);
this.session.applyInputs(transaction);
}
} catch (err) {
console.error("Error sending paste key combination:", err);
}
}
private sendCopyKeyCombination(): void {
if (!this.session || !this.ironrdp) return;
try {
const transaction = new this.ironrdp.InputTransaction();
// Send Ctrl (or Cmd on Mac) key down
const ctrlScancode = this.isMacOS()
? this.codeToScancode.MetaLeft
: this.codeToScancode.ControlLeft;
const cScancode = this.codeToScancode.KeyC;
if (ctrlScancode && cScancode) {
// Ctrl/Cmd down
const ctrlDown = this.ironrdp.DeviceEvent.keyPressed(ctrlScancode);
transaction.addEvent(ctrlDown);
// C down
const cDown = this.ironrdp.DeviceEvent.keyPressed(cScancode);
transaction.addEvent(cDown);
// C up
const cUp = this.ironrdp.DeviceEvent.keyReleased(cScancode);
transaction.addEvent(cUp);
// Ctrl/Cmd up
const ctrlUp = this.ironrdp.DeviceEvent.keyReleased(ctrlScancode);
transaction.addEvent(ctrlUp);
this.session.applyInputs(transaction);
}
} catch (err) {
console.error("Error sending copy key combination:", err);
}
}
private sendTextAsKeystrokes(text: string): void {
if (!this.session || !this.ironrdp) return;
try {
const transaction = new this.ironrdp.InputTransaction();
// Send each character as unicode event
for (let i = 0; i < text.length; i++) {
const charCode = text.charCodeAt(i);
const deviceEvent = this.ironrdp.DeviceEvent.unicode(charCode);
transaction.addEvent(deviceEvent);
}
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error sending paste text:", err);
}
}
private requestClipboardSync(): void {
// Notify the WASM bridge to check and sync clipboard, only for chrome for now, firefox and safari have issues with this
if (!/Chrome/.test(navigator.userAgent)) {
return;
}
if (
window.IronRDPBridge &&
(window.IronRDPBridge as any).checkAndSendClipboard
) {
setTimeout(() => {
(window.IronRDPBridge as any).checkAndSendClipboard();
}, 50);
}
}
private handleMouseDown(event: MouseEvent): void {
event.preventDefault();
this.canvas.focus();
if (!this.isActive) {
this.isActive = true;
}
const { x, y } = this.getCanvasCoordinates(event.clientX, event.clientY);
const button = this.mouseButtonMap[event.button];
if (button === undefined) return;
if (this.mouseButtonStates[event.button]) return;
this.mouseButtonStates[event.button] = true;
try {
if (!this.session || !this.ironrdp) return;
const transaction = new this.ironrdp.InputTransaction();
// Always send mouse position first, then the button press
const moveEvent = this.ironrdp.DeviceEvent.mouseMove(x, y);
const clickEvent = this.ironrdp.DeviceEvent.mouseButtonPressed(button);
transaction.addEvent(moveEvent);
transaction.addEvent(clickEvent);
this.session.applyInputs(transaction);
this.currentMouseX = x;
this.currentMouseY = y;
} catch (err) {
console.error("Error sending mouse down:", err);
}
}
private handleMouseUp(event: MouseEvent): void {
event.preventDefault();
const button = this.mouseButtonMap[event.button];
if (button === undefined) return;
if (!this.mouseButtonStates[event.button]) return;
this.mouseButtonStates[event.button] = false;
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.mouseButtonReleased(button);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error sending mouse up:", err);
}
}
private handleMouseEnter(event: MouseEvent): void {
// Always sync position when entering
this.handleMouseMove(event);
}
private handleMouseMove(event: MouseEvent): void {
const { x, y } = this.getCanvasCoordinates(event.clientX, event.clientY);
// Skip if position hasn't changed
if (x === this.currentMouseX && y === this.currentMouseY) {
return;
}
this.currentMouseX = x;
this.currentMouseY = y;
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.mouseMove(x, y);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error sending mouse move:", err);
}
}
private handleWheel(event: WheelEvent): void {
event.preventDefault();
if (!this.isActive) return;
// Calculate rotation units (120 units = 1 notch)
const delta = event.deltaY > 0 ? -1 : 1;
const rotationUnits = delta * 120;
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.wheelRotations(
true,
rotationUnits,
);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error sending wheel event:", err);
}
}
private handleKeyDown(event: KeyboardEvent): void {
if (!this.isActive) return;
// For clipboard operations, don't prevent default to allow clipboard events to fire
const isClipboardPaste =
(event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "v";
const isClipboardCopy =
(event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c";
if (!isClipboardPaste && !isClipboardCopy) {
event.preventDefault();
}
// Don't send clipboard combinations here - let the clipboard events handle them (only for Chromium browsers)
const isChromium = /Chrome/.test(navigator.userAgent);
if ((isClipboardPaste || isClipboardCopy) && isChromium) {
return;
}
const scancode = this.codeToScancode[event.code];
if (scancode !== undefined) {
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.keyPressed(scancode);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error sending key down:", err);
}
} else if (event.key.length === 1) {
// For printable characters not in our scancode map, use unicode
try {
if (!this.session || !this.ironrdp) return;
const charCode = event.key.charCodeAt(0);
const deviceEvent = this.ironrdp.DeviceEvent.unicode(charCode);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error sending unicode char:", err);
}
}
}
private handleKeyUp(event: KeyboardEvent): void {
if (!this.isActive) return;
// For clipboard operations, don't prevent default to allow clipboard events to fire
const isClipboardPaste =
(event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "v";
const isClipboardCopy =
(event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c";
if (!isClipboardPaste && !isClipboardCopy) {
event.preventDefault();
}
// Don't send clipboard combinations here - let the clipboard events handle them
const isChromium = /Chrome/.test(navigator.userAgent);
if ((isClipboardPaste || isClipboardCopy) && isChromium) {
return;
}
const scancode = this.codeToScancode[event.code];
if (scancode === undefined) return;
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.keyReleased(scancode);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error sending key up:", err);
}
}
private handleTouchStart(event: TouchEvent): void {
event.preventDefault();
if (event.touches.length !== 1) return;
const touch = event.touches[0];
const { x, y } = this.getCanvasCoordinates(touch.clientX, touch.clientY);
this.touchState.lastX = x;
this.touchState.lastY = y;
this.touchState.touching = true;
// Simulate mouse down
try {
if (!this.session || !this.ironrdp) return;
const moveEvent = this.ironrdp.DeviceEvent.mouseMove(x, y);
const clickEvent = this.ironrdp.DeviceEvent.mouseButtonPressed(0);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(moveEvent);
transaction.addEvent(clickEvent);
this.session.applyInputs(transaction);
this.currentMouseX = x;
this.currentMouseY = y;
} catch (err) {
console.error("Error handling touch start:", err);
}
}
private handleTouchMove(event: TouchEvent): void {
event.preventDefault();
if (!this.touchState.touching || event.touches.length !== 1) return;
const touch = event.touches[0];
const { x, y } = this.getCanvasCoordinates(touch.clientX, touch.clientY);
if (x === this.touchState.lastX && y === this.touchState.lastY) return;
this.touchState.lastX = x;
this.touchState.lastY = y;
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.mouseMove(x, y);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
this.currentMouseX = x;
this.currentMouseY = y;
} catch (err) {
console.error("Error handling touch move:", err);
}
}
private handleTouchEnd(event: TouchEvent): void {
event.preventDefault();
if (!this.touchState.touching) return;
this.touchState.touching = false;
// Simulate mouse up
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.mouseButtonReleased(0);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error handling touch end:", err);
}
}
private releaseAllKeys(): void {
this.keyStates.forEach((pressed, code) => {
if (!pressed) return;
const scancode = this.codeToScancode[code];
if (scancode === undefined) return;
try {
if (!this.session || !this.ironrdp) return;
const deviceEvent = this.ironrdp.DeviceEvent.keyReleased(scancode);
const transaction = new this.ironrdp.InputTransaction();
transaction.addEvent(deviceEvent);
this.session.applyInputs(transaction);
} catch (err) {
console.error("Error releasing key:", err);
}
});
this.keyStates.clear();
}
destroy(): void {
// Remove all event listeners using the same bound functions
this.canvas.removeEventListener("mousedown", this.boundHandlers.mouseDown);
this.canvas.removeEventListener("mouseup", this.boundHandlers.mouseUp);
this.canvas.removeEventListener("mousemove", this.boundHandlers.mouseMove);
this.canvas.removeEventListener(
"mouseenter",
this.boundHandlers.mouseEnter,
);
this.canvas.removeEventListener("wheel", this.boundHandlers.wheel);
this.canvas.removeEventListener(
"contextmenu",
this.boundHandlers.contextMenu,
);
this.canvas.removeEventListener(
"touchstart",
this.boundHandlers.touchStart,
);
this.canvas.removeEventListener("touchmove", this.boundHandlers.touchMove);
this.canvas.removeEventListener("touchend", this.boundHandlers.touchEnd);
this.canvas.removeEventListener("keydown", this.boundHandlers.keyDown);
this.canvas.removeEventListener("keyup", this.boundHandlers.keyUp);
this.canvas.removeEventListener("paste", this.boundHandlers.paste);
this.canvas.removeEventListener("copy", this.boundHandlers.copy);
this.canvas.removeEventListener("focus", this.boundHandlers.focus);
this.canvas.removeEventListener("blur", this.boundHandlers.blur);
this.canvas.removeEventListener("click", this.boundHandlers.click);
document.removeEventListener("keydown", this.boundHandlers.globalKeyDown);
this.releaseAllKeys();
this.isActive = false;
}
}
if (typeof window !== "undefined") {
(window as any).IronRDPInputHandler = IronRDPInputHandler;
}

View File

@@ -0,0 +1,450 @@
export interface IronRDPModule {
SessionBuilder: new () => SessionBuilder;
DesktopSize: new (width: number, height: number) => DesktopSize;
ClipboardData?: new () => ClipboardData;
default?: () => Promise<void>;
init?: () => Promise<void>;
}
interface DesktopSize {
width: number;
height: number;
}
interface SessionBuilder {
username(user: string): SessionBuilder;
password(pwd: string): SessionBuilder;
destination(dest: string): SessionBuilder;
serverDomain(domain: string): SessionBuilder;
desktopSize(size: DesktopSize): SessionBuilder;
renderCanvas(canvas: HTMLCanvasElement): SessionBuilder;
proxyAddress(url: string): SessionBuilder;
authToken(token: string): SessionBuilder;
setCursorStyleCallback(cb: (style: string) => void): void;
setCursorStyleCallbackContext(ctx: unknown): void;
remoteClipboardChangedCallback(cb: (data: ClipboardData) => void): void;
forceClipboardUpdateCallback(cb: () => void): void;
connect(): Promise<RDPSession>;
}
export interface RDPSession {
run(): Promise<TerminationInfo>;
shutdown(): void;
sendInput(input: unknown): void;
onClipboardPaste?(content: ClipboardData): Promise<void>;
inputHandler?: IronRDPInputHandler;
}
interface TerminationInfo {
reason(): string;
}
interface ClipboardData {
items(): ClipboardItem[];
addText(mimeType: string, text: string): void;
addBinary(mimeType: string, binary: Uint8Array): void;
isEmpty(): boolean;
}
interface ClipboardItem {
mimeType(): string;
value(): string;
}
interface RDPConfig {
username: string;
password: string;
domain?: string;
width: number;
height: number;
enable_tls: boolean;
enable_credssp: boolean;
enable_nla: boolean;
}
declare global {
interface Window {
IronRDPBridge: IronRDPWASMBridge;
IronRDPInputHandler?: new (
ironrdp: IronRDPModule,
session: RDPSession,
canvas: HTMLCanvasElement,
) => IronRDPInputHandler;
initializeIronRDP: () => Promise<boolean>;
onIronRDPReady?: () => void;
createRDCleanPathProxy?: (
hostname: string,
port: number,
) => Promise<string>;
}
}
interface IronRDPInputHandler {
destroy(): void;
}
const IRON_RDP_PKG = "/ironrdp-pkg/ironrdp_web.js";
export class IronRDPWASMBridge {
private ironrdp: IronRDPModule | null = null;
private initialized = false;
private sessions = new Map<string, RDPSession>();
private lastClipboardContent = "";
private clipboardEventListeners: (() => void)[] = [];
// Expose clipboard sync method for input handler
async initialize(): Promise<void> {
if (this.initialized) return;
try {
// @ts-ignore - Dynamic import from public directory
const ironrdpModule = (await import(
/* webpackIgnore: true */ IRON_RDP_PKG
)) as IronRDPModule;
try {
if (ironrdpModule.default) {
await ironrdpModule.default();
}
} catch (e) {
if (ironrdpModule.init) {
await ironrdpModule.init();
}
}
this.ironrdp = ironrdpModule;
this.initialized = true;
if (window.onIronRDPReady) {
window.onIronRDPReady();
}
} catch (error) {
console.error("Failed to load IronRDP WASM:", error);
this.initialized = false;
}
}
async connect(
hostname: string,
port: number,
username: string,
password: string,
canvas: HTMLCanvasElement,
enableClipboard = true,
netbirdClient?: {
createRDPProxy: (hostname: string, port: string) => Promise<string>;
},
): Promise<string> {
if (!this.initialized) {
await this.initialize();
}
if (!this.ironrdp) {
throw new Error("IronRDP module not loaded");
}
const sessionId = `${hostname}:${port}_${Date.now()}`;
try {
const config: RDPConfig = {
username,
password,
domain: "",
width: canvas.width || 1024,
height: canvas.height || 768,
enable_tls: true,
enable_credssp: true,
enable_nla: true,
};
const builder = new this.ironrdp.SessionBuilder();
builder
.username(username)
.password(password)
.destination(`${hostname}:${port}`);
if (config.domain) {
builder.serverDomain(config.domain);
}
const desktopSize = new this.ironrdp.DesktopSize(
config.width,
config.height,
);
builder.desktopSize(desktopSize);
if (canvas) {
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
}
builder.renderCanvas(canvas);
}
builder.setCursorStyleCallback((style: string) => {});
builder.setCursorStyleCallbackContext(null);
if (enableClipboard) {
this.setupClipboard(builder);
}
// RDCleanPath proxy is required for IronRDP
if (!netbirdClient || !netbirdClient.createRDPProxy) {
throw new Error("NetBird client with RDP proxy support is required");
}
const proxyURL = await netbirdClient.createRDPProxy(
hostname,
port.toString(),
);
builder.proxyAddress(proxyURL);
builder.authToken("");
const session = await builder.connect();
this.sessions.set(sessionId, session);
if (canvas) {
this.attachInputHandler(session, canvas);
}
if (enableClipboard) {
this.startClipboardEventListeners();
}
this.startSession(session, sessionId);
return sessionId;
} catch (error) {
console.error(`IronRDP connection failed:`, error);
this.logIronError(error);
throw error;
}
}
private setupClipboard(builder: SessionBuilder): void {
if (!this.ironrdp?.ClipboardData) {
console.warn("ClipboardData class not available in IronRDP module");
return;
}
builder.remoteClipboardChangedCallback((clipboardData: ClipboardData) => {
this.handleRemoteClipboard(clipboardData);
});
builder.forceClipboardUpdateCallback(() => {
this.handleLocalClipboardRequest();
});
}
private attachInputHandler(
session: RDPSession,
canvas: HTMLCanvasElement,
): void {
if (!window.IronRDPInputHandler) {
console.warn("IronRDPInputHandler not loaded - input will not work");
return;
}
if (!this.ironrdp) {
console.warn("IronRDP module not available");
return;
}
session.inputHandler = new window.IronRDPInputHandler(
this.ironrdp,
session,
canvas,
);
}
private startSession(session: RDPSession, sessionId: string): void {
session
.run()
.then((termInfo) => {
this.cleanupSession(session, sessionId);
})
.catch((err) => {
console.error("IronRDP session error:", err);
this.cleanupSession(session, sessionId);
throw Error(err);
});
}
private cleanupSession(session: RDPSession, sessionId: string): void {
if (session.inputHandler) {
session.inputHandler.destroy();
}
this.sessions.delete(sessionId);
// Stop clipboard event listeners if no active sessions
if (this.sessions.size === 0) {
this.stopClipboardEventListeners();
}
}
private logIronError(error: unknown): void {
const ironError = error as any;
if (!ironError || !ironError.__wbg_ptr) return;
try {
if (ironError.backtrace) {
console.error("IronRDP backtrace:", ironError.backtrace());
}
if (ironError.kind) {
const errorKind = ironError.kind();
const errorKindNames = [
"General",
"WrongPassword",
"LogonFailure",
"AccessDenied",
"RDCleanPath",
"ProxyConnect",
"NegotiationFailure",
];
const errorKindName = errorKindNames[errorKind] || "Unknown";
console.error("IronRDP error kind:", errorKindName, `(${errorKind})`);
}
} catch (e) {
console.error("Could not extract IronError details:", e);
}
}
disconnect(sessionId: string): void {
const session = this.sessions.get(sessionId);
if (!session) return;
if (session.inputHandler) {
session.inputHandler.destroy();
session.inputHandler = undefined;
}
if (session.shutdown) {
session.shutdown();
}
this.sessions.delete(sessionId);
// Stop clipboard event listeners if no active sessions
if (this.sessions.size === 0) {
this.stopClipboardEventListeners();
}
}
private handleRemoteClipboard(clipboardData: ClipboardData): void {
if (!navigator.clipboard?.writeText) {
console.warn("Browser clipboard API not available");
return;
}
if (!clipboardData.items) {
console.error("clipboardData.items() method not found");
return;
}
const items = clipboardData.items();
if (items.length === 0) return;
for (const item of items) {
const mimeType = item.mimeType();
const value = item.value();
if (mimeType !== "text/plain") {
continue;
}
navigator.clipboard
.writeText(value)
.then(() => {
//this.showClipboardNotification("Clipboard updated from RDP");
})
.catch((err) => {
console.error("Failed to copy to browser clipboard:", err);
this.fallbackClipboardCopy(value);
});
return; // Only handle first text item
}
}
private fallbackClipboardCopy(text: string): void {
try {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
const success = document.execCommand("copy");
document.body.removeChild(textarea);
if (success) {
//this.showClipboardNotification("Clipboard updated from RDP");
}
} catch (err) {
console.error("Fallback clipboard error:", err);
}
}
private async handleLocalClipboardRequest(): Promise<void> {
if (!navigator.clipboard?.readText) {
console.warn("Browser clipboard read API not available");
return;
}
try {
const clipboardText = await navigator.clipboard.readText();
if (clipboardText && clipboardText !== this.lastClipboardContent) {
await this.sendClipboardToRDP(clipboardText);
this.lastClipboardContent = clipboardText;
}
} catch (err) {
console.warn("Could not read from clipboard:", err);
}
}
private async sendClipboardToRDP(text: string): Promise<void> {
if (!this.ironrdp?.ClipboardData) return;
for (const [sessionId, session] of this.sessions) {
try {
const clipboardData = new this.ironrdp.ClipboardData();
clipboardData.addText("text/plain", text);
if (session.onClipboardPaste) {
await session.onClipboardPaste(clipboardData);
}
//this.showClipboardNotification("Clipboard sent to RDP");
} catch (err) {
console.error("Failed to send clipboard to RDP:", err);
}
}
}
private startClipboardEventListeners(): void {
if (this.clipboardEventListeners.length > 0) return;
// Listen for keyboard shortcuts (Ctrl+C, Ctrl+V, Ctrl+X)
const handleKeyboardShortcut = async (event: KeyboardEvent) => {
if (
(event.ctrlKey || event.metaKey) &&
["c", "x", "v"].includes(event.key.toLowerCase())
) {
// For copy/cut operations, check clipboard after delay
if (["c", "x"].includes(event.key.toLowerCase())) {
setTimeout(async () => {
await this.checkAndSendClipboard();
}, 100);
}
// For paste, check immediately to ensure up-to-date content
else if (event.key.toLowerCase() === "v") {
await this.checkAndSendClipboard();
}
}
};
// Listen for clipboard events (more reliable when available)
const handleClipboardChange = async () => {
await this.checkAndSendClipboard();
};
// Listen for focus events - check clipboard when window regains focus
const handleFocus = async () => {
await this.checkAndSendClipboard();
};
// Add event listeners
document.addEventListener("keydown", handleKeyboardShortcut);
document.addEventListener("copy", handleClipboardChange);
document.addEventListener("cut", handleClipboardChange);
window.addEventListener("focus", handleFocus);
// Store cleanup functions
this.clipboardEventListeners = [
() => document.removeEventListener("keydown", handleKeyboardShortcut),
() => document.removeEventListener("copy", handleClipboardChange),
() => document.removeEventListener("cut", handleClipboardChange),
() => window.removeEventListener("focus", handleFocus),
];
}
private stopClipboardEventListeners(): void {
this.clipboardEventListeners.forEach((cleanup) => cleanup());
this.clipboardEventListeners = [];
}
public async checkAndSendClipboard(): Promise<void> {
if (!navigator.clipboard?.readText) return;
if (!/Chrome/.test(navigator.userAgent)) {
return;
}
try {
const clipboardText = await navigator.clipboard.readText();
if (clipboardText && clipboardText !== this.lastClipboardContent) {
await this.sendClipboardToRDP(clipboardText);
this.lastClipboardContent = clipboardText;
}
} catch (err) {
// Ignore clipboard read errors - might be due to focus/permission issues
}
}
}
if (typeof window !== "undefined") {
window.IronRDPBridge = new IronRDPWASMBridge();
window.initializeIronRDP = async function (): Promise<boolean> {
try {
await window.IronRDPBridge.initialize();
return true;
} catch (error) {
console.error("Failed to initialize IronRDP:", error);
return false;
}
};
}

View File

@@ -0,0 +1,397 @@
/**
* RDP Certificate Handler
* Handles X.509 certificate validation and user acceptance for RDP connections
*/
export interface CertificateInfo {
raw?: Uint8Array;
fingerprint: string;
hostname: string;
subject?: string;
issuer?: string;
validFrom?: Date;
validTo?: Date;
serialNumber?: string;
keySize?: number;
}
interface TrustedCertificate {
fingerprint: string;
hostname: string;
addedAt: string;
subject?: string;
}
export interface RDCleanPathResponse {
ServerAddr?: string;
ServerCertChain?: Uint8Array[];
CertificateInfo?: CertificateInfo;
}
export interface CertificateHandler {
validateCertificate(certInfo: CertificateInfo, hostname?: string): Promise<boolean>;
handleRDCleanPathResponse(response: RDCleanPathResponse): Promise<boolean>;
}
export class RDPCertificateHandler implements CertificateHandler {
private readonly STORAGE_KEY = 'netbird-rdp-trusted-certs';
private modalElement: HTMLElement | null = null;
/**
* Handle RDCleanPath response containing server certificates
*/
async handleRDCleanPathResponse(response: RDCleanPathResponse): Promise<boolean> {
if (!response.ServerCertChain || response.ServerCertChain.length === 0) {
console.error('No certificate chain provided - rejecting connection for security');
return false;
}
const serverAddr = response.ServerAddr || 'unknown';
const hostname = serverAddr.split(':')[0];
const certBytes = response.ServerCertChain[0];
try {
// Check if response already has parsed certificate info from Go proxy
if (response.CertificateInfo) {
return await this.validateCertificate(response.CertificateInfo, hostname);
}
// Fallback to parsing the raw certificate
const certInfo = await this.parseCertificate(certBytes, hostname);
return await this.validateCertificate(certInfo, hostname);
} catch (error) {
console.error('Certificate validation error:', error);
return await this.promptRawCertificateAcceptance(certBytes, hostname);
}
}
/**
* Parse X.509 certificate bytes to extract relevant information
* Note: For proper X.509 parsing, the Go proxy should provide parsed certificate info
*/
async parseCertificate(certBytes: Uint8Array, hostname: string): Promise<CertificateInfo> {
const fingerprint = await this.calculateFingerprint(certBytes);
// Basic certificate info - actual parsing should be done by Go proxy
const certInfo: CertificateInfo = {
raw: certBytes,
fingerprint: fingerprint,
hostname: hostname
};
// Try to extract basic info from certificate if not provided by proxy
// This is a fallback - proper X.509 parsing should be done server-side
const certString = new TextDecoder('latin1').decode(certBytes);
const cnMatch = certString.match(/CN=([^,\0]+)/);
if (cnMatch) {
certInfo.subject = cnMatch[0];
}
return certInfo;
}
/**
* Extract serial number from certificate bytes
* Note: This is a placeholder - actual serial number extraction requires proper ASN.1 parsing
*/
private extractSerialNumber(certBytes: Uint8Array): string | undefined {
// Serial number extraction should be done by the Go proxy
// This is just a fallback that won't work reliably
return undefined;
}
/**
* Calculate SHA-256 fingerprint of certificate
*/
async calculateFingerprint(certBytes: Uint8Array): Promise<string> {
const hashBuffer = await crypto.subtle.digest('SHA-256', certBytes);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray
.map(b => b.toString(16).padStart(2, '0'))
.join(':')
.toUpperCase();
}
/**
* Validate certificate against stored trust database
*/
async validateCertificate(certInfo: CertificateInfo, hostname?: string): Promise<boolean> {
const host = hostname || certInfo.hostname;
const trustedCerts = this.loadTrustedCerts();
if (trustedCerts[host]) {
const stored = trustedCerts[host];
if (stored.fingerprint === certInfo.fingerprint) {
return true;
} else {
console.warn(`Certificate for ${host} has changed!`);
return await this.promptCertificateChange(host, certInfo, stored);
}
}
console.log(`New certificate for ${host} - requesting user acceptance`);
return await this.promptUserAcceptance(host, certInfo);
}
/**
* Load trusted certificates from storage
*/
private loadTrustedCerts(): Record<string, TrustedCertificate> {
try {
const stored = localStorage.getItem(this.STORAGE_KEY);
return stored ? JSON.parse(stored) : {};
} catch (error) {
console.error('Failed to load trusted certificates:', error);
return {};
}
}
/**
* Save trusted certificate to storage
*/
private saveTrustedCert(hostname: string, certInfo: CertificateInfo): void {
try {
const trustedCerts = this.loadTrustedCerts();
trustedCerts[hostname] = {
fingerprint: certInfo.fingerprint,
hostname: hostname,
addedAt: new Date().toISOString(),
subject: certInfo.subject
};
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(trustedCerts));
} catch (error) {
console.error('Failed to save trusted certificate:', error);
}
}
/**
* Prompt user to accept a new certificate
*/
private async promptUserAcceptance(hostname: string, certInfo: CertificateInfo): Promise<boolean> {
return new Promise((resolve) => {
const modal = this.createCertificateModal(hostname, certInfo, false);
const acceptBtn = modal.querySelector('#cert-accept') as HTMLButtonElement;
const rejectBtn = modal.querySelector('#cert-reject') as HTMLButtonElement;
const rememberCheck = modal.querySelector('#cert-remember') as HTMLInputElement;
acceptBtn.onclick = () => {
const remember = rememberCheck.checked;
if (remember) {
this.saveTrustedCert(hostname, certInfo);
}
this.closeModal();
resolve(true);
};
rejectBtn.onclick = () => {
this.closeModal();
resolve(false);
};
});
}
/**
* Prompt user when certificate has changed
*/
private async promptCertificateChange(
hostname: string,
newCert: CertificateInfo,
oldCert: TrustedCertificate
): Promise<boolean> {
return new Promise((resolve) => {
const modal = this.createCertificateModal(hostname, newCert, true);
// Add warning about certificate change
const warningDiv = modal.querySelector('.cert-warning') as HTMLElement;
warningDiv.innerHTML = `
<strong>⚠️ Certificate has changed!</strong><br>
<small>Previous fingerprint: ${oldCert.fingerprint.substring(0, 32)}...</small>
`;
const acceptBtn = modal.querySelector('#cert-accept') as HTMLButtonElement;
const rejectBtn = modal.querySelector('#cert-reject') as HTMLButtonElement;
const rememberCheck = modal.querySelector('#cert-remember') as HTMLInputElement;
acceptBtn.onclick = () => {
const remember = rememberCheck.checked;
if (remember) {
this.saveTrustedCert(hostname, newCert);
}
this.closeModal();
resolve(true);
};
rejectBtn.onclick = () => {
this.closeModal();
resolve(false);
};
});
}
/**
* Prompt for raw certificate acceptance when parsing fails
*/
private async promptRawCertificateAcceptance(certBytes: Uint8Array, hostname: string): Promise<boolean> {
const fingerprint = await this.calculateFingerprint(certBytes);
const certInfo: CertificateInfo = {
raw: certBytes,
fingerprint: fingerprint,
hostname: hostname,
subject: 'Unable to parse',
issuer: 'Unable to parse'
};
return this.promptUserAcceptance(hostname, certInfo);
}
/**
* Create certificate acceptance modal
*/
private createCertificateModal(hostname: string, certInfo: CertificateInfo, isChange: boolean): HTMLElement {
// Remove any existing modal
this.closeModal();
const modal = document.createElement('div');
modal.className = 'rdp-cert-modal';
modal.innerHTML = `
<div class="rdp-cert-overlay"></div>
<div class="rdp-cert-dialog">
<h2>RDP Certificate Verification</h2>
<div class="cert-warning" style="color: #ff9800; margin-bottom: 15px;"></div>
<p>The server <strong>${hostname}</strong> is presenting a certificate:</p>
<div class="cert-details">
<table>
<tr><td><strong>Subject:</strong></td><td>${certInfo.subject || 'Unknown'}</td></tr>
<tr><td><strong>Issuer:</strong></td><td>${certInfo.issuer || 'Unknown'}</td></tr>
${certInfo.serialNumber ? `<tr><td><strong>Serial:</strong></td><td style="font-family: monospace; font-size: 0.9em;">${certInfo.serialNumber}</td></tr>` : ''}
<tr><td><strong>SHA-256:</strong></td><td style="font-family: monospace; font-size: 0.9em;">
${certInfo.fingerprint}</td></tr>
</table>
</div>
<div class="cert-question">
<p>Do you trust this certificate?</p>
<label>
<input type="checkbox" id="cert-remember" checked>
Remember this certificate for future connections
</label>
</div>
<div class="cert-buttons">
<button id="cert-reject" class="cert-btn cert-btn-reject">Reject</button>
<button id="cert-accept" class="cert-btn cert-btn-accept">Accept</button>
</div>
</div>
`;
// Add styles if not already present
if (!document.querySelector('#rdp-cert-styles')) {
const styles = document.createElement('style');
styles.id = 'rdp-cert-styles';
styles.textContent = this.getModalStyles();
document.head.appendChild(styles);
}
document.body.appendChild(modal);
this.modalElement = modal;
return modal;
}
/**
* Close the certificate modal
*/
private closeModal(): void {
if (this.modalElement) {
document.body.removeChild(this.modalElement);
this.modalElement = null;
}
}
/**
* Get modal CSS styles
*/
private getModalStyles(): string {
return `
.rdp-cert-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
}
.rdp-cert-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
}
.rdp-cert-dialog {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
border-radius: 8px;
padding: 25px;
max-width: 600px;
width: 90%;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.rdp-cert-dialog h2 {
margin-top: 0;
color: #333;
border-bottom: 2px solid #0078d4;
padding-bottom: 10px;
}
.cert-details {
background: #f5f5f5;
border: 1px solid #ddd;
border-radius: 4px;
padding: 15px;
margin: 15px 0;
}
.cert-details table {
width: 100%;
border-collapse: collapse;
}
.cert-details td {
padding: 5px 10px;
vertical-align: top;
}
.cert-details td:first-child {
width: 100px;
text-align: right;
padding-right: 10px;
}
.cert-question {
margin: 20px 0;
}
.cert-question label {
display: flex;
align-items: center;
cursor: pointer;
}
.cert-question input {
margin-right: 8px;
}
.cert-buttons {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 20px;
}
.cert-btn {
padding: 10px 20px;
border: none;
border-radius: 4px;
font-size: 14px;
cursor: pointer;
transition: background-color 0.2s;
}
.cert-btn-accept {
background: #0078d4;
color: white;
}
.cert-btn-accept:hover {
background: #106ebe;
}
.cert-btn-reject {
background: #e0e0e0;
color: #333;
}
.cert-btn-reject:hover {
background: #d0d0d0;
}
`;
}
/**
* Clear all trusted certificates
*/
clearTrustedCerts(): void {
localStorage.removeItem(this.STORAGE_KEY);
console.log('Cleared all trusted RDP certificates');
}
/**
* Get list of trusted certificates
*/
getTrustedCerts(): TrustedCertificate[] {
const trustedCerts = this.loadTrustedCerts();
return Object.values(trustedCerts);
}
}
// Export as global for compatibility
declare global {
interface Window {
RDPCertificateHandler: typeof RDPCertificateHandler;
}
}
if (typeof window !== 'undefined') {
window.RDPCertificateHandler = RDPCertificateHandler;
}

View File

@@ -0,0 +1,320 @@
import { useCallback, useState } from "react";
export interface CertificateInfo {
raw?: Uint8Array;
fingerprint: string;
hostname: string;
subject?: string;
issuer?: string;
validFrom?: Date;
validTo?: Date;
serialNumber?: string;
keySize?: number;
}
interface TrustedCertificate {
fingerprint: string;
hostname: string;
addedAt: string;
subject?: string;
}
export interface RDCleanPathResponse {
ServerAddr?: string;
ServerCertChain?: Uint8Array[];
CertificateInfo?: CertificateInfo;
}
export interface CertificatePromptInfo {
hostname: string;
certificate: CertificateInfo;
isChange: boolean;
previousCertificate?: TrustedCertificate;
}
export interface CertificateValidationResult {
isValid: boolean;
needsUserConfirmation: boolean;
promptInfo?: CertificatePromptInfo;
}
const STORAGE_KEY = "netbird-rdp-trusted-certs";
export const useRDPCertificateHandler = () => {
const [isValidating, setIsValidating] = useState(false);
const calculateFingerprint = useCallback(
async (certBytes: Uint8Array): Promise<string> => {
try {
const hashBuffer = await crypto.subtle.digest("SHA-256", certBytes);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const fingerprint = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join(":")
.toUpperCase();
return fingerprint;
} catch (error) {
return "FINGERPRINT_CALCULATION_FAILED";
}
},
[],
);
const parseCertificate = useCallback(
async (
certBytes: Uint8Array,
hostname: string,
): Promise<CertificateInfo> => {
const fingerprint = await calculateFingerprint(certBytes);
const certInfo: CertificateInfo = {
raw: certBytes,
fingerprint,
hostname,
};
try {
const certString = new TextDecoder("latin1").decode(certBytes);
// Parse subject (CN)
const cnMatch = certString.match(/CN=([^,\0\x00-\x1f]+)/);
if (cnMatch) {
certInfo.subject = `CN=${cnMatch[1].trim()}`;
}
// Parse issuer - look for issuer field
const issuerMatch = certString.match(
/(?:issuer|Issuer).*?CN=([^,\0\x00-\x1f]+)/i,
);
if (issuerMatch) {
certInfo.issuer = `CN=${issuerMatch[1].trim()}`;
} else {
// Fallback: look for second CN occurrence (often issuer)
const cnMatches = [...certString.matchAll(/CN=([^,\0\x00-\x1f]+)/g)];
if (cnMatches.length > 1) {
certInfo.issuer = `CN=${cnMatches[1][1].trim()}`;
}
}
// Estimate key size based on certificate structure and length
if (certBytes.length > 100) {
// Look for RSA signature patterns or use length heuristic
if (certBytes.length > 1400) {
certInfo.keySize = 2048;
} else if (certBytes.length > 1000) {
certInfo.keySize = 1024;
} else if (certBytes.length > 600) {
certInfo.keySize = 1024;
} else {
certInfo.keySize = 512;
}
}
// Try to parse serial number (look for sequence of hex bytes)
const serialMatch = certString.match(
/[\x02][\x01-\x10]([\x00-\xff]{1,16})/,
);
if (serialMatch && serialMatch[1]) {
const serialBytes = Array.from(serialMatch[1], (char) =>
char.charCodeAt(0),
);
certInfo.serialNumber = serialBytes
.map((b) => b.toString(16).padStart(2, "0"))
.join(":")
.toUpperCase();
}
// Try to parse validity dates (basic ASN.1 time format)
// Look for UTCTime or GeneralizedTime patterns
const timePattern =
/[\x17\x18][\x0d\x0f](\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z?/g;
const timeMatches = [...certString.matchAll(timePattern)];
if (timeMatches.length >= 2) {
const parseTime = (match: RegExpMatchArray) => {
let year = parseInt(match[1]);
// Handle 2-digit years (UTCTime format)
if (year < 50) year += 2000;
else if (year < 100) year += 1900;
const month = parseInt(match[2]) - 1; // JS months are 0-based
const day = parseInt(match[3]);
const hour = parseInt(match[4]);
const minute = parseInt(match[5]);
const second = parseInt(match[6]);
return new Date(year, month, day, hour, minute, second);
};
certInfo.validFrom = parseTime(timeMatches[0]);
certInfo.validTo = parseTime(timeMatches[1]);
}
} catch (error) {
console.warn("Failed to parse certificate details:", error);
}
return certInfo;
},
[calculateFingerprint],
);
const getTrustedCerts = useCallback((): Record<
string,
TrustedCertificate
> => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored ? JSON.parse(stored) : {};
} catch (error) {
console.error("Failed to load trusted certificates:", error);
return {};
}
}, []);
const saveTrustedCert = useCallback(
(hostname: string, certInfo: CertificateInfo): void => {
try {
const trustedCerts = getTrustedCerts();
trustedCerts[hostname] = {
fingerprint: certInfo.fingerprint,
hostname,
addedAt: new Date().toISOString(),
subject: certInfo.subject,
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(trustedCerts));
} catch (error) {
console.error("Failed to save trusted certificate:", error);
}
},
[getTrustedCerts],
);
const validateCertificate = useCallback(
async (
certInfo: CertificateInfo,
hostname?: string,
): Promise<CertificateValidationResult> => {
const host = hostname || certInfo.hostname;
const trustedCerts = getTrustedCerts();
const stored = trustedCerts[host];
if (stored) {
if (stored.fingerprint === certInfo.fingerprint) {
return { isValid: true, needsUserConfirmation: false };
}
console.warn(`Certificate for ${host} has changed!`);
return {
isValid: false,
needsUserConfirmation: true,
promptInfo: {
hostname: host,
certificate: certInfo,
isChange: true,
previousCertificate: stored,
},
};
}
return {
isValid: false,
needsUserConfirmation: true,
promptInfo: {
hostname: host,
certificate: certInfo,
isChange: false,
},
};
},
[getTrustedCerts],
);
const handleRDCleanPathResponse = useCallback(
async (
response: RDCleanPathResponse,
): Promise<CertificateValidationResult> => {
setIsValidating(true);
try {
if (!response.ServerCertChain?.length) {
return { isValid: false, needsUserConfirmation: false };
}
const serverAddr = response.ServerAddr || "unknown";
const hostname = serverAddr.split(":")[0];
const certBytes = response.ServerCertChain[0];
let certInfo: CertificateInfo;
if (response.CertificateInfo) {
certInfo = response.CertificateInfo;
// Add missing fingerprint and keySize that the server doesn't provide
if (!certInfo.fingerprint) {
certInfo.fingerprint = await calculateFingerprint(certBytes);
}
if (!certInfo.keySize && certBytes.length > 100) {
if (certBytes.length > 1400) {
certInfo.keySize = 2048;
} else if (certBytes.length > 1000) {
certInfo.keySize = 1024;
} else if (certBytes.length > 600) {
certInfo.keySize = 1024;
} else {
certInfo.keySize = 512;
}
}
} else {
try {
certInfo = await parseCertificate(certBytes, hostname);
} catch (error) {
console.error("Certificate parsing error:", error);
const fingerprint = await calculateFingerprint(certBytes);
certInfo = {
raw: certBytes,
fingerprint,
hostname,
subject: "Unable to parse",
issuer: "Unable to parse",
};
}
}
return await validateCertificate(certInfo, hostname);
} finally {
setIsValidating(false);
}
},
[parseCertificate, validateCertificate, calculateFingerprint],
);
const acceptCertificate = useCallback(
(
hostname: string,
certInfo: CertificateInfo,
remember: boolean = true,
): void => {
if (remember) {
saveTrustedCert(hostname, certInfo);
}
},
[saveTrustedCert],
);
const clearTrustedCerts = useCallback((): void => {
localStorage.removeItem(STORAGE_KEY);
}, []);
const listTrustedCerts = useCallback((): TrustedCertificate[] => {
return Object.values(getTrustedCerts());
}, [getTrustedCerts]);
return {
isValidating,
handleRDCleanPathResponse,
validateCertificate,
acceptCertificate,
clearTrustedCerts,
getTrustedCerts: listTrustedCerts,
calculateFingerprint,
parseCertificate,
};
};

View File

@@ -0,0 +1,58 @@
import { useLocalStorage } from "@hooks/useLocalStorage";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
interface RDPQueryParams {
peerId: string | null;
}
export function useRDPQueryParams() {
const searchParams = useSearchParams();
const router = useRouter();
const [params, setParams] = useState<RDPQueryParams>({
peerId: null,
});
const [, setLocalQueryParams] = useLocalStorage("netbird-query-params", "");
useEffect(() => {
const peerId = searchParams.get("id");
// If all params are present in URL, use them
if (peerId) {
setParams({ peerId });
return;
}
// Otherwise, try to restore from localStorage
const storedParams = localStorage.getItem("netbird-query-params");
if (!storedParams) return;
// Handle JSON encoded strings from localStorage
let paramsString = storedParams;
if (storedParams.startsWith('"') && storedParams.endsWith('"')) {
try {
paramsString = JSON.parse(storedParams);
} catch (e) {
return;
}
}
const urlParams = new URLSearchParams(paramsString);
const storedPeerId = urlParams.get("id");
if (storedPeerId) {
const newSearchParams = new URLSearchParams();
newSearchParams.set("id", storedPeerId);
router.replace(`/peer/rdp?${newSearchParams.toString()}`);
setParams({
peerId: storedPeerId,
});
// Clear stored params after restoring
setLocalQueryParams("");
}
}, [searchParams, router]);
return params;
}

View File

@@ -0,0 +1,325 @@
import { useCallback, useEffect, useRef, useState } from "react";
import {
CertificatePromptInfo,
useRDPCertificateHandler,
} from "./useRDPCertificateHandler";
interface IronError {
message: string;
backtrace?: () => string;
}
interface RDPConfig {
hostname: string;
port: number;
username: string;
password: string;
width?: number;
height?: number;
}
export interface RDPCredentials {
username: string;
password: string;
port: number;
}
interface RDPConnection {
id: string;
disconnect: (options?: {
preserveConfig?: boolean;
preserveCertificateState?: boolean;
}) => void;
}
export enum RDPStatus {
DISCONNECTED = 0,
CONNECTED = 1,
CONNECTING = 2,
}
export const RDP_DOCS_LINK = "https://docs.netbird.io/";
export const useRemoteDesktop = (client: any) => {
const [status, setStatus] = useState(RDPStatus.DISCONNECTED);
const [config, setConfig] = useState<RDPConfig | null>(null);
const [error, setError] = useState("");
const [pendingCertificate, setPendingCertificate] =
useState<CertificatePromptInfo | null>(null);
const session = useRef<RDPConnection | null>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const [isResizing, setIsResizing] = useState(false);
const resizeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const lastConnectedConfigRef = useRef<RDPConfig | null>(null);
const certificatePromiseRef = useRef<{
resolve: (value: boolean) => void;
reject: (reason?: any) => void;
} | null>(null);
const { handleRDCleanPathResponse, acceptCertificate } =
useRDPCertificateHandler();
const certificateAccepted = useRef(false);
/**
* Reset the RDP state, optionally preserving config and/or certificate state
*/
const resetState = useCallback(
(
options: {
preserveConfig?: boolean;
preserveCertificateState?: boolean;
} = {},
) => {
session.current = null;
setStatus(RDPStatus.DISCONNECTED);
if (!options.preserveConfig) {
setConfig(null);
}
setError("");
if (!options.preserveCertificateState) {
setPendingCertificate(null);
certificatePromiseRef.current = null;
}
},
[],
);
/**
* Set up the global RDPCertificateHandler to intercept certificate prompts
*/
const setupCertificateHandler = useCallback(() => {
const originalHandler = (window as any).RDPCertificateHandler;
(window as any).RDPCertificateHandler = function () {
this.handleRDCleanPathResponse = async (response: any) => {
const result = await handleRDCleanPathResponse(response);
if (result.isValid) {
return true;
}
if (result.needsUserConfirmation && result.promptInfo) {
setPendingCertificate(result.promptInfo);
return new Promise((resolve, reject) => {
certificatePromiseRef.current = { resolve, reject };
});
}
return false;
};
if (originalHandler?.prototype) {
Object.getOwnPropertyNames(originalHandler.prototype).forEach(
(name) => {
if (
name !== "constructor" &&
name !== "handleRDCleanPathResponse"
) {
this[name] = originalHandler.prototype[name];
}
},
);
}
};
return originalHandler;
}, [handleRDCleanPathResponse]);
/**
* Establish an RDP connection
*/
const connect = useCallback(
async (rdpConfig: RDPConfig): Promise<RDPStatus> => {
if (status === RDPStatus.CONNECTING) return status;
setStatus(RDPStatus.CONNECTING);
setConfig(rdpConfig);
setError("");
try {
if (!canvasRef.current) {
throw new Error("Canvas not available for RDP rendering");
}
if (!client?.ironRDPBridge || !client?.initializeIronRDP) {
throw new Error("IronRDP components not available from client");
}
const canvas = canvasRef.current;
canvas.width = rdpConfig.width || 1024;
canvas.height = rdpConfig.height || 768;
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
}
const initialized = await client.initializeIronRDP();
if (!initialized) {
throw new Error("Failed to initialize IronRDP");
}
const originalHandler = setupCertificateHandler();
try {
const sessionId = await client.ironRDPBridge.connect(
rdpConfig.hostname,
rdpConfig.port,
rdpConfig.username,
rdpConfig.password,
canvas,
true,
client.client,
);
session.current = {
id: sessionId,
disconnect: (options = {}) => {
try {
if (client.ironRDPBridge && sessionId) {
client.ironRDPBridge.disconnect(sessionId);
}
resetState(options);
} catch (err) {
resetState(options);
}
},
};
setStatus(RDPStatus.CONNECTED);
lastConnectedConfigRef.current = rdpConfig;
return RDPStatus.CONNECTED;
} catch (err) {
const ironError = err as IronError;
const errorMessage = ironError.backtrace
? ironError.backtrace()
: "RDP connection failed";
setError(errorMessage);
resetState();
throw Error(errorMessage);
} finally {
(window as any).RDPCertificateHandler = originalHandler;
}
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : "RDP connection failed";
setError(errorMessage);
resetState();
throw Error(errorMessage);
}
},
[client, status, setupCertificateHandler, resetState],
);
/**
* Accept the pending certificate prompt
*/
const acceptCertificatePrompt = useCallback(
(remember: boolean = false) => {
if (!pendingCertificate || !certificatePromiseRef.current) return;
acceptCertificate(
pendingCertificate.hostname,
pendingCertificate.certificate,
remember,
);
certificatePromiseRef.current.resolve(true);
setPendingCertificate(null);
certificatePromiseRef.current = null;
certificateAccepted.current = true;
},
[pendingCertificate, acceptCertificate],
);
/**
* Reject the pending certificate prompt
*/
const rejectCertificatePrompt = useCallback(() => {
if (!certificatePromiseRef.current) return;
certificatePromiseRef.current.resolve(false);
setPendingCertificate(null);
certificatePromiseRef.current = null;
}, []);
/**
* Handle window resize events - reconnect with new dimensions
*/
useEffect(() => {
const handleResize = () => {
// Only handle resize if we're connected and have a previous config
if (status !== RDPStatus.CONNECTED || !lastConnectedConfigRef.current) {
return;
}
// Clear any existing timeout
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
}
setIsResizing(true);
// Debounce resize handling for 1 second
resizeTimeoutRef.current = setTimeout(async () => {
try {
// Disconnect current session
if (session.current) {
session.current.disconnect({
preserveConfig: true,
preserveCertificateState: true,
});
}
// Wait for cleanup
await new Promise((resolve) => setTimeout(resolve, 300));
// Reconnect with new dimensions
const newConfig = {
...lastConnectedConfigRef.current!,
width: window.innerWidth,
height: window.innerHeight,
};
await connect(newConfig);
} finally {
setIsResizing(false);
}
}, 1000);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
}
};
}, [status, connect]);
/**
* Auto accept certificate if previously accepted (for reconnects)
*/
useEffect(() => {
if (pendingCertificate && certificateAccepted.current) {
acceptCertificatePrompt();
}
}, [acceptCertificatePrompt, pendingCertificate]);
return {
connect,
status,
config,
error,
isResizing,
session: session.current,
canvasRef,
// Certificate handling
pendingCertificate,
acceptCertificatePrompt,
rejectCertificatePrompt,
};
};

View File

@@ -0,0 +1,206 @@
/**
* WebSocket Proxy System for RDCleanPath connections
* Provides WebSocket interface that routes through RDCleanPath proxy
*/
import type { CertificateHandler, CertificateInfo, RDCleanPathResponse } from './rdp-certificate-handler';
declare global {
interface Window {
handleRDCleanPathWebSocket?: (ws: RDCleanPathProxyWebSocket, proxyID: string) => void;
createRDCleanPathProxy?: (hostname: string, port: number) => Promise<string>;
getRDCleanPathCertificate?: (proxyID: string) => Promise<RDCleanPathResponse | null>;
RDCleanPathProxyWebSocket?: typeof RDCleanPathProxyWebSocket;
sendToRDCleanPathProxy?: (proxyID: string, data: ArrayBuffer | Uint8Array | string) => void;
closeRDCleanPathProxy?: (proxyID: string) => void;
}
}
abstract class BaseWebSocketProxy extends EventTarget {
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
url: string;
readyState: number;
readonly protocol: string = '';
readonly extensions: string = '';
readonly bufferedAmount: number = 0;
readonly binaryType: BinaryType = 'blob';
onopen: ((event: Event) => void) | null = null;
onclose: ((event: CloseEvent) => void) | null = null;
onerror: ((event: Event) => void) | null = null;
onmessage: ((event: MessageEvent) => void) | null = null;
protected messageQueue: any[] = [];
constructor(url: string) {
super();
this.url = url;
this.readyState = BaseWebSocketProxy.CONNECTING;
}
get CONNECTING() { return BaseWebSocketProxy.CONNECTING; }
get OPEN() { return BaseWebSocketProxy.OPEN; }
get CLOSING() { return BaseWebSocketProxy.CLOSING; }
get CLOSED() { return BaseWebSocketProxy.CLOSED; }
protected emitOpen(): void {
this.readyState = BaseWebSocketProxy.OPEN;
const event = new Event('open');
this.onopen?.(event);
this.dispatchEvent(event);
}
protected emitError(error: any): void {
const event = new Event('error');
this.onerror?.(event);
this.dispatchEvent(event);
}
protected emitMessage(data: any): void {
const event = new MessageEvent('message', { data });
this.onmessage?.(event);
this.dispatchEvent(event);
}
protected emitClose(code = 1000, reason = ''): void {
this.readyState = BaseWebSocketProxy.CLOSED;
const event = new CloseEvent('close', { code, reason, wasClean: code === 1000 });
this.onclose?.(event);
this.dispatchEvent(event);
}
abstract send(data: ArrayBuffer | Uint8Array | string | Blob | ArrayBufferView): void;
abstract close(code?: number, reason?: string): void;
}
export class RDCleanPathProxyWebSocket extends BaseWebSocketProxy {
private proxyID: string;
private certificateHandler: CertificateHandler | null;
onGoMessage?: (data: Uint8Array) => void;
onGoClose?: () => void;
onCertificateRequest?: (certData: RDCleanPathResponse) => Promise<boolean>;
constructor(url: string) {
super(url);
const match = url.match(/rdcleanpath\.proxy\.local\/(.+)/);
this.proxyID = match?.[1] || 'default';
if (window.RDPCertificateHandler) {
this.certificateHandler = new window.RDPCertificateHandler();
} else {
this.certificateHandler = null;
}
this.onCertificateRequest = async (certData) => {
return this.validateCertificate(certData);
};
void this._connect();
}
private async _connect(): Promise<void> {
try {
const handler = (window as any)[`handleRDCleanPathWebSocket_${this.proxyID}`];
if (!handler) {
throw new Error(`RDCleanPath WebSocket handler not available for proxy ${this.proxyID}`);
}
handler(this);
this.emitOpen();
} catch (error) {
console.error('RDCleanPath WebSocket connection failed:', error);
this.emitError(error);
this.emitClose(1006, error instanceof Error ? error.message : 'Connection failed');
}
}
protected _sendInternal(data: Uint8Array): void {
if (this.onGoMessage) {
this.onGoMessage(data);
} else {
console.warn('onGoMessage not set for proxy', this.proxyID);
}
}
send(data: ArrayBuffer | Uint8Array | string | Blob | ArrayBufferView): void {
if (this.readyState === BaseWebSocketProxy.CONNECTING) {
this.messageQueue.push(data);
return;
}
if (this.readyState !== BaseWebSocketProxy.OPEN) {
throw new Error('WebSocket is not open');
}
// Convert all data types to Uint8Array
if (data instanceof Blob) {
const reader = new FileReader();
reader.onload = () => {
this._sendInternal(new Uint8Array(reader.result as ArrayBuffer));
};
reader.readAsArrayBuffer(data);
} else if (typeof data === 'string') {
const encoder = new TextEncoder();
this._sendInternal(encoder.encode(data));
} else if (data instanceof ArrayBuffer) {
this._sendInternal(new Uint8Array(data));
} else if ('buffer' in data && data.buffer instanceof ArrayBuffer) {
const view = data as ArrayBufferView;
this._sendInternal(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
} else {
this._sendInternal(data as Uint8Array);
}
}
private async validateCertificate(certData: RDCleanPathResponse): Promise<boolean> {
if (!this.certificateHandler) {
return false;
}
try {
return await this.certificateHandler.handleRDCleanPathResponse(certData);
} catch (error) {
console.error('Certificate validation error:', error);
return false;
}
}
// Called from Go side to pass data to JavaScript
receiveFromGo(data: ArrayBuffer): void {
this.emitMessage(data);
}
// Called from Go side to close the connection
closeFromGo(code?: number, reason?: string): void {
this.emitClose(code, reason);
}
close(code = 1000, reason = ''): void {
if (this.readyState === BaseWebSocketProxy.CLOSING || this.readyState === BaseWebSocketProxy.CLOSED) {
return;
}
this.readyState = BaseWebSocketProxy.CLOSING;
if (this.onGoClose) {
this.onGoClose();
} else if (window.closeRDCleanPathProxy) {
window.closeRDCleanPathProxy(this.proxyID);
}
setTimeout(() => {
this.emitClose(code, reason);
}, 0);
}
}
export function installWebSocketProxy(): void {
const OriginalWebSocket = window.WebSocket;
window.WebSocket = new Proxy(OriginalWebSocket, {
construct(_target, args) {
const url = args[0] as string;
if (url?.includes('rdcleanpath.proxy.local')) {
window.RDCleanPathProxyWebSocket = RDCleanPathProxyWebSocket;
return new RDCleanPathProxyWebSocket(url) as unknown as WebSocket;
}
return new OriginalWebSocket(url, args[1]);
}
}) as typeof WebSocket;
}

View File

@@ -0,0 +1,76 @@
import Button from "@components/Button";
import { DropdownMenuItem } from "@components/DropdownMenu";
import { CircleHelpIcon, TerminalIcon } from "lucide-react";
import * as React from "react";
import { useState } from "react";
import { usePermissions } from "@/contexts/PermissionsProvider";
import { Peer } from "@/interfaces/Peer";
import { SSHCredentialsModal } from "@/modules/remote-access/ssh/SSHCredentialsModal";
import { SSHTooltip } from "@/modules/remote-access/ssh/SSHTooltip";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
type Props = {
peer: Peer;
isDropdown?: boolean;
};
export const SSHButton = ({ peer, isDropdown = false }: Props) => {
const [modal, setModal] = useState(false);
const { permission } = usePermissions();
const disabled =
!peer.connected || !peer.ssh_enabled || !permission.peers.update;
const hasPermission = permission.peers.update;
const os = getOperatingSystem(peer?.os);
const isWindows = os === OperatingSystem.WINDOWS;
const isMobile = os === OperatingSystem.ANDROID || os === OperatingSystem.IOS;
const isSSHSupported = !isWindows && !isMobile;
return (
isSSHSupported && (
<>
{modal && (
<SSHCredentialsModal
open={modal}
onOpenChange={setModal}
peer={peer}
/>
)}
<div>
<SSHTooltip
disabled={!disabled}
hasPermission={hasPermission}
side={isDropdown ? "left" : "top"}
>
{isDropdown ? (
<DropdownMenuItem
onClick={() => setModal(true)}
disabled={disabled}
className={"w-full"}
>
<div className={"flex gap-3 items-center w-full"}>
<TerminalIcon size={14} className={"shrink-0"} />
SSH
</div>
</DropdownMenuItem>
) : (
<Button
variant="secondary"
size="sm"
onClick={() => setModal(true)}
disabled={disabled}
>
<TerminalIcon size={16} />
SSH
{disabled && <CircleHelpIcon size={12} />}
</Button>
)}
</SSHTooltip>
</div>
</>
)
);
};

View File

@@ -0,0 +1,155 @@
import * as React from "react";
import { useMemo, useState } from "react";
import {
Modal,
ModalClose,
ModalContent,
ModalFooter,
} from "@components/modal/Modal";
import ModalHeader from "@components/modal/ModalHeader";
import { Peer } from "@/interfaces/Peer";
import {
ChevronsLeftRightEllipsis,
ExternalLinkIcon,
TerminalIcon,
User2,
} from "lucide-react";
import Separator from "@components/Separator";
import Paragraph from "@components/Paragraph";
import InlineLink from "@components/InlineLink";
import Button from "@components/Button";
import { Label } from "@components/Label";
import HelpText from "@components/HelpText";
import { Input } from "@components/Input";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { OperatingSystem } from "@/interfaces/OperatingSystem";
import { isNativeSSHSupported } from "@utils/version";
import { SSH_DOCS_LINK } from "@/modules/remote-access/ssh/useSSH";
type Props = {
open: boolean;
onOpenChange: (open: boolean) => void;
peer: Peer;
};
export const SSHCredentialsModal = ({ open, onOpenChange, peer }: Props) => {
const [username, setUsername] = useState(
getOperatingSystem(peer.os) === OperatingSystem.WINDOWS
? "Administrator"
: "root",
);
const [port, setPort] = useState(
isNativeSSHSupported(peer.version) ? "22" : "44338",
);
const userNameError = useMemo(() => {
if (username?.length === 0) return "Username cannot be empty";
}, [username]);
const portError = useMemo(() => {
const portNumber = Number(port);
const isValid =
Number.isInteger(portNumber) && portNumber > 0 && portNumber <= 65535;
if (!isValid) return "Port must be a number between 1 and 65535";
}, [port]);
const hasAnyError = useMemo(() => {
if (userNameError !== undefined) return true;
return portError !== undefined;
}, [userNameError, portError]);
const openSSHWindow = () => {
const encodedUsername = encodeURIComponent(username.trim());
const encodedPort = encodeURIComponent(port.trim());
window.open(
`peer/ssh?id=${peer.id}&user=${encodedUsername}&port=${encodedPort}`,
"_blank",
"noopener,noreferrer,width=800,height=450,left=100,top=100,location=no,toolbar=no,menubar=no,status=no",
);
onOpenChange(false);
};
return (
<Modal open={open} onOpenChange={onOpenChange}>
<ModalContent maxWidthClass={"max-w-lg"}>
<ModalHeader
icon={<TerminalIcon className={"text-netbird"} size={18} />}
title={peer.name}
description={`Connect to ${peer.ip} via SSH`}
color={"netbird"}
/>
<Separator />
<div className={"px-8 py-6 flex flex-col gap-8"}>
<div className={""}>
<Label>Username & Port</Label>
<HelpText>
The username and port you will use to connect to the remote host.
</HelpText>
<div className={"flex flex-col gap-2 w-full"}>
<Input
placeholder={"root"}
value={username}
onChange={(e) => setUsername(e.target.value)}
customSuffix={`@${peer.ip}`}
data-1p-ignore
autoComplete={"off"}
error={userNameError}
errorTooltip={true}
errorTooltipPosition={"top-right"}
customPrefix={
<User2 size={16} className={"text-nb-gray-300"} />
}
/>
<Input
maxWidthClass={""}
placeholder={"22"}
min={1}
max={65535}
value={port}
type={"number"}
error={portError}
errorTooltip={true}
errorTooltipPosition={"top-right"}
onChange={(e) => setPort(e.target.value)}
customPrefix={
<ChevronsLeftRightEllipsis
size={16}
className={"text-nb-gray-300"}
/>
}
/>
</div>
</div>
</div>
<ModalFooter className={"items-center"}>
<div className={"w-full"}>
<Paragraph className={"text-sm mt-auto"}>
Learn more about
<InlineLink href={SSH_DOCS_LINK} target={"_blank"}>
SSH
<ExternalLinkIcon size={12} />
</InlineLink>
</Paragraph>
</div>
<div className={"flex gap-3 w-full justify-end"}>
<ModalClose asChild={true}>
<Button variant={"secondary"}>Cancel</Button>
</ModalClose>
<Button
variant={"primary"}
disabled={hasAnyError}
onClick={openSSHWindow}
>
Connect
</Button>
</div>
</ModalFooter>
</ModalContent>
</Modal>
);
};

View File

@@ -0,0 +1,55 @@
import FullTooltip from "@components/FullTooltip";
import InlineLink from "@components/InlineLink";
import { ExternalLinkIcon } from "lucide-react";
import * as React from "react";
import { SSH_DOCS_LINK } from "@/modules/remote-access/ssh/useSSH";
type Props = {
disabled?: boolean;
children?: React.ReactNode;
hasPermission?: boolean;
side?: "top" | "right" | "bottom" | "left";
};
export const SSHTooltip = ({
disabled,
children,
hasPermission,
side = "top",
}: Props) => {
return (
<FullTooltip
className={"w-full"}
side={side}
content={
<div className={"max-w-xs text-xs flex flex-col gap-2"}>
{hasPermission ? (
<>
<div>
This peer is either offline or SSH access is not enabled.
</div>
<div>
Please enable SSH access for this peer in the dashboard and make
sure SSH is allowed in the NetBird Client under{" "}
<span className={"text-white"}>Settings &rarr; Allow SSH</span>.
</div>
<div>
Learn more about{" "}
<InlineLink href={SSH_DOCS_LINK} target={"_blank"}>
SSH <ExternalLinkIcon size={12} />
</InlineLink>
</div>
</>
) : (
<div>
You do not have permission to launch the SSH console. Please
contact your administrator.
</div>
)}
</div>
}
disabled={disabled}
>
{children}
</FullTooltip>
);
};

View File

@@ -0,0 +1,172 @@
"use client";
import "@xterm/xterm/css/xterm.css";
import { cn } from "@utils/helpers";
import { useCallback, useEffect, useRef } from "react";
const TERMINAL_OPTIONS = {
theme: {
background: "#181a1d",
foreground: "#e4e7e9",
cursor: "#e4e7e9",
},
fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
fontSize: 13,
cursorBlink: true,
convertEol: true,
scrollback: 1000,
allowTransparency: true,
};
interface TerminalWithCore {
_core?: { _isDisposed: boolean };
dispose(): void;
write(data: string | Uint8Array): void;
writeln(data: string): void;
onData(callback: (data: string) => void): void;
onResize(callback: (event: { cols: number; rows: number }) => void): void;
focus(): void;
cols: number;
rows: number;
}
interface SSHTerminalWrapperProps {
session: any;
onResize?: (cols: number, rows: number) => void;
onClose?: () => void;
className?: string;
}
export const Terminal = ({
session,
onResize,
onClose,
className = "",
}: SSHTerminalWrapperProps) => {
const terminalRef = useRef<HTMLDivElement>(null);
const terminalInstanceRef = useRef<{
terminal: TerminalWithCore;
fitAddon: any;
} | null>(null);
const handlersSetRef = useRef(false);
const fitTerminal = useCallback(() => {
if (terminalInstanceRef.current?.fitAddon) {
terminalInstanceRef.current.fitAddon.fit();
}
}, []);
const initializeTerminal = useCallback(async () => {
if (terminalInstanceRef.current || !terminalRef.current) return;
const { Terminal: XTerminal } = await import("@xterm/xterm");
const { FitAddon } = await import("@xterm/addon-fit");
const terminal = new XTerminal(TERMINAL_OPTIONS);
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
if (!terminalRef.current) return;
terminalRef.current.innerHTML = "";
terminal.open(terminalRef.current);
// Set terminal focus behavior
const terminalElement = terminalRef.current.querySelector(
".xterm",
) as HTMLElement;
if (terminalElement) {
terminalElement.setAttribute("tabindex", "0");
terminalElement.addEventListener("click", () => terminal.focus());
terminalElement.addEventListener("keydown", (e) => e.stopPropagation());
}
terminalInstanceRef.current = {
terminal: terminal as TerminalWithCore,
fitAddon,
};
// Initial fit with delay to ensure proper sizing
setTimeout(fitTerminal, 100);
return terminal as TerminalWithCore;
}, [fitTerminal]);
const setupSSHHandlers = useCallback(async () => {
if (!session || handlersSetRef.current) return;
const terminal = await initializeTerminal();
if (!terminal) return;
handlersSetRef.current = true;
// Setup terminal event handlers
terminal.onData((data: string) => session?.write?.(data));
terminal.onResize(({ cols, rows }: { cols: number; rows: number }) => {
session?.resize?.(cols, rows);
onResize?.(cols, rows);
});
// Setup SSH event handlers
session.ondata = (data: Uint8Array) => {
if (!terminal._core?._isDisposed) {
terminal.write(new Uint8Array(data));
}
};
const originalOnClose = session.onclose;
session.onclose = () => {
if (!terminal._core?._isDisposed) {
terminal.writeln("\r\n*** Connection closed ***");
}
handlersSetRef.current = false;
originalOnClose?.();
onClose?.();
};
// Final setup with proper sizing
setTimeout(() => {
if (
terminalInstanceRef.current?.fitAddon &&
!terminal._core?._isDisposed
) {
fitTerminal();
session?.resize?.(terminal.cols, terminal.rows);
terminal.focus();
}
}, 200);
}, [session, initializeTerminal, onResize, onClose, fitTerminal]);
// Handle window resize
useEffect(() => {
const handleResize = () => fitTerminal();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [fitTerminal]);
// Setup SSH handlers when session changes
useEffect(() => {
setupSSHHandlers().then();
}, [setupSSHHandlers]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (terminalInstanceRef.current?.terminal) {
const terminal = terminalInstanceRef.current.terminal;
if (!terminal._core?._isDisposed) {
terminal.dispose();
}
terminalInstanceRef.current = null;
}
handlersSetRef.current = false;
};
}, []);
return (
<div
ref={terminalRef}
className={cn("w-full h-full flex flex-col m-0 p-0", className)}
/>
);
};

View File

@@ -0,0 +1,85 @@
import { useCallback, useRef, useState } from "react";
interface SSHConfig {
hostname: string;
port: number;
username: string;
}
interface SSHConnection {
write: (data: string) => void;
resize: (cols: number, rows: number) => void;
close: () => void;
ondata: ((data: Uint8Array) => void) | null;
onclose: (() => void) | null;
}
export enum SSHStatus {
DISCONNECTED = 0,
CONNECTED = 1,
CONNECTING = 2,
}
export const SSH_DOCS_LINK = "https://docs.netbird.io/";
export const useSSH = (client: any) => {
const [status, setStatus] = useState(SSHStatus.DISCONNECTED);
const [config, setConfig] = useState<SSHConfig | null>(null);
const session = useRef<SSHConnection | null>(null);
const [error, setError] = useState("");
const connect = useCallback(
async (config: SSHConfig): Promise<SSHStatus> => {
if (status === SSHStatus.CONNECTED || status === SSHStatus.CONNECTING)
return status;
setStatus(SSHStatus.CONNECTING);
setConfig(config);
try {
const ssh = await client.createSSHConnection(
config.hostname,
config.port,
config.username,
);
ssh.onclose = () => {
setStatus(SSHStatus.DISCONNECTED);
setConfig(null);
session.current = null;
};
session.current = ssh;
setStatus(SSHStatus.CONNECTED);
return SSHStatus.CONNECTED;
} catch (err) {
console.error("SSH connection failed:", err);
session.current = null;
setStatus(SSHStatus.DISCONNECTED);
setError("SSH connection failed. Check the console for details.");
setConfig(null);
return SSHStatus.DISCONNECTED;
}
},
[client, status],
);
const disconnect = useCallback(() => {
if (session.current) {
session.current.close();
session.current = null;
setStatus(SSHStatus.DISCONNECTED);
setConfig(null);
}
}, []);
return {
connect,
error,
status,
config,
session: session.current,
disconnect,
};
};

View File

@@ -0,0 +1,70 @@
import { useLocalStorage } from "@hooks/useLocalStorage";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
interface SSHQueryParams {
peerId: string | null;
username: string | null;
port: string | null;
}
export function useSSHQueryParams() {
const searchParams = useSearchParams();
const router = useRouter();
const [params, setParams] = useState<SSHQueryParams>({
peerId: null,
username: null,
port: null,
});
const [, setLocalQueryParams] = useLocalStorage("netbird-query-params", "");
useEffect(() => {
const peerId = searchParams.get("id");
const username = searchParams.get("user");
const port = searchParams.get("port");
// If all params are present in URL, use them
if (peerId && username && port) {
setParams({ peerId, username, port });
return;
}
// Otherwise, try to restore from localStorage
const storedParams = localStorage.getItem("netbird-query-params");
if (!storedParams) return;
// Handle JSON encoded strings from localStorage
let paramsString = storedParams;
if (storedParams.startsWith('"') && storedParams.endsWith('"')) {
try {
paramsString = JSON.parse(storedParams);
} catch (e) {
return;
}
}
const urlParams = new URLSearchParams(paramsString);
const storedPeerId = urlParams.get("id");
const storedUsername = urlParams.get("user");
const storedPort = urlParams.get("port");
if (storedPeerId && storedUsername && storedPort) {
const newSearchParams = new URLSearchParams();
newSearchParams.set("id", storedPeerId);
newSearchParams.set("user", storedUsername);
newSearchParams.set("port", storedPort);
router.replace(`/peer/ssh?${newSearchParams.toString()}`);
setParams({
peerId: storedPeerId,
username: storedUsername,
port: storedPort,
});
// Clear stored params after restoring
setLocalQueryParams("");
}
}, [searchParams, router]);
return params;
}

View File

@@ -0,0 +1,306 @@
import { useApiCall } from "@utils/api";
import loadConfig from "@utils/config";
import { getBrowserInfo } from "@utils/helpers";
import { generateKeypair } from "@utils/wireguard";
import { trim } from "lodash";
import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
import { IronRDPInputHandler } from "@/modules/remote-access/rdp/ironrdp-input-handler";
import { IronRDPWASMBridge } from "@/modules/remote-access/rdp/ironrdp-wasm-bridge";
import { RDPCertificateHandler } from "@/modules/remote-access/rdp/rdp-certificate-handler";
import { installWebSocketProxy } from "@/modules/remote-access/rdp/websocket-proxy";
const config = loadConfig();
const WASM_CONFIG = {
SCRIPT_PATH: "/wasm_exec.js",
WASM_PATH: "https://pkgs.netbird.io/wasm/client",
INIT_TIMEOUT: 10000,
RETRY_DELAY: 100,
} as const;
export enum NetBirdStatus {
DISCONNECTED = 0,
CONNECTED = 1,
CONNECTING = 2,
}
export enum WASMStatus {
UNINITIALIZED,
INITIALIZED,
INITIALIZING,
}
type NetBirdState = {
status: NetBirdStatus;
wasmStatus: WASMStatus;
error: string;
};
class NetBirdStore {
private state: NetBirdState = {
status: NetBirdStatus.DISCONNECTED,
wasmStatus: WASMStatus.UNINITIALIZED,
error: "",
};
private listeners = new Set<() => void>();
getState = (): NetBirdState => this.state;
setState = (newState: Partial<NetBirdState>): void => {
this.state = { ...this.state, ...newState };
this.listeners.forEach((listener) => listener());
};
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
}
const netBirdStore = new NetBirdStore();
export const useNetBirdClient = () => {
const netBirdClient = useRef<any>(null);
const state = useSyncExternalStore(
netBirdStore.subscribe,
netBirdStore.getState,
netBirdStore.getState,
);
const { status, wasmStatus, error } = state;
const peerRequest = useApiCall(`/peers`);
const rdpComponents = useRef<{
bridge: IronRDPWASMBridge | null;
inputHandler: typeof IronRDPInputHandler | null;
certificateHandler: typeof RDPCertificateHandler | null;
}>({ bridge: null, inputHandler: null, certificateHandler: null });
const loadWASMRuntime = useCallback((): Promise<void> => {
if (document.querySelector(`script[src="${WASM_CONFIG.SCRIPT_PATH}"]`)) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = WASM_CONFIG.SCRIPT_PATH;
script.onload = () => resolve();
script.onerror = () => reject(new Error("Failed to load WASM runtime"));
document.head.appendChild(script);
});
}, []);
const loadGoClient = useCallback(async (): Promise<void> => {
if ((window as any).NetBirdClient) return;
const go = new (window as any).Go();
const wasmModule = await WebAssembly.instantiateStreaming(
fetch(WASM_CONFIG.WASM_PATH),
go.importObject,
);
go.run(wasmModule.instance);
const start = Date.now();
while (Date.now() - start < WASM_CONFIG.INIT_TIMEOUT) {
if ((window as any).NetBirdClient) return;
await new Promise((resolve) =>
setTimeout(resolve, WASM_CONFIG.RETRY_DELAY),
);
}
throw new Error("NetBird WASM failed to initialize in time");
}, []);
const initIronRDP = useCallback(() => {
if (rdpComponents.current.bridge) return;
installWebSocketProxy();
rdpComponents.current = {
bridge: new IronRDPWASMBridge(),
inputHandler: IronRDPInputHandler,
certificateHandler: RDPCertificateHandler,
};
}, []);
const initialize = useCallback(async (): Promise<WASMStatus> => {
const currentStatus = netBirdStore.getState().wasmStatus;
if (currentStatus === WASMStatus.INITIALIZED) return currentStatus;
if (currentStatus === WASMStatus.INITIALIZING) {
while (netBirdStore.getState().wasmStatus === WASMStatus.INITIALIZING) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
const finalStatus = netBirdStore.getState().wasmStatus;
if (finalStatus === WASMStatus.INITIALIZED) return finalStatus;
throw new Error("WASM initialization failed");
}
netBirdStore.setState({ wasmStatus: WASMStatus.INITIALIZING });
try {
await loadWASMRuntime();
await loadGoClient();
initIronRDP();
netBirdStore.setState({ wasmStatus: WASMStatus.INITIALIZED });
return WASMStatus.INITIALIZED;
} catch (error) {
netBirdStore.setState({
wasmStatus: WASMStatus.UNINITIALIZED,
error:
error instanceof Error ? error.message : "Failed to initialize WASM",
});
throw error;
}
}, [loadWASMRuntime, loadGoClient, initIronRDP]);
const initializeIronRDP = useCallback(async (): Promise<boolean> => {
if (!rdpComponents.current.bridge) return false;
try {
await rdpComponents.current.bridge.initialize();
return true;
} catch {
return false;
}
}, []);
const connect = useCallback(
async (privateKey: string): Promise<boolean> => {
await initialize();
if (typeof (window as any).NetBirdClient !== "function") {
netBirdStore.setState({
status: NetBirdStatus.DISCONNECTED,
error: "NetBirdClient is not available or not a function",
});
return false;
}
netBirdStore.setState({ status: NetBirdStatus.CONNECTING });
try {
netBirdClient.current = await (window as any).NetBirdClient({
privateKey,
logLevel: "warn",
managementURL: config.apiOrigin,
});
await netBirdClient.current.start();
netBirdStore.setState({ status: NetBirdStatus.CONNECTED });
return true;
} catch (error) {
netBirdStore.setState({
status: NetBirdStatus.DISCONNECTED,
error: error instanceof Error ? error.message : "Connection failed",
});
console.log(error);
return false;
}
},
[initialize],
);
const disconnect = useCallback(async (): Promise<void> => {
if (!netBirdClient.current?.stop) {
throw new Error("Go client not ready");
}
netBirdStore.setState({ status: NetBirdStatus.DISCONNECTED });
await netBirdClient.current.stop();
netBirdClient.current = null;
return Promise.resolve();
}, []);
const createSSHConnection = useCallback(
async (host: string, port: number, username: string): Promise<any> => {
if (!netBirdClient.current?.createSSHConnection) {
throw new Error("Go client not ready");
}
return netBirdClient.current.createSSHConnection(host, port, username);
},
[],
);
const makeRequest = useCallback(async (url: string): Promise<any> => {
if (!netBirdClient.current?.makeRequest) {
throw new Error("Go client not ready");
}
return netBirdClient.current.makeRequest(url);
}, []);
const proxyRequest = useCallback(async (request: any): Promise<any> => {
if (!netBirdClient.current?.proxyRequest) {
throw new Error("Go client not ready");
}
return netBirdClient.current.proxyRequest(request);
}, []);
const setupRDPProxy = useCallback(
async (hostname: string, port: string): Promise<string> => {
if (!netBirdClient.current?.setupRDPProxy) {
throw new Error("Go client not ready");
}
return netBirdClient.current.setupRDPProxy(hostname, port);
},
[],
);
const connectTemporary = useCallback(
async (peerId: string, rules?: string[]) => {
const currentStatus = netBirdStore.getState().status;
if (
currentStatus === NetBirdStatus.CONNECTING ||
currentStatus === NetBirdStatus.CONNECTED
) {
return currentStatus === NetBirdStatus.CONNECTED;
}
netBirdStore.setState({ status: NetBirdStatus.CONNECTING });
try {
const keyPairs = generateKeypair();
const browser = getBrowserInfo();
const name =
browser.name === ""
? "browser-client"
: trim(
`${browser.name.toLowerCase()}-${browser.version.toLowerCase()}-browser-client`,
);
await peerRequest.post(
{
name,
wg_pub_key: keyPairs.publicKey,
rules: rules ?? ["tcp/22", "tcp/3389", "tcp/44338"],
},
`/${peerId}/temporary-access`,
);
return await connect(keyPairs.privateKey);
} catch (error) {
netBirdStore.setState({ status: NetBirdStatus.DISCONNECTED });
throw error;
}
},
[connect, peerRequest],
);
useEffect(() => {
initialize().catch(console.error);
}, [initialize]);
return {
status,
wasmStatus,
error,
client: netBirdClient.current, // Expose the raw NetBird client
ironRDPBridge: rdpComponents.current.bridge,
ironRDPInputHandler: rdpComponents.current.inputHandler,
rdpCertificateHandler: rdpComponents.current.certificateHandler,
initialize,
initializeIronRDP,
connect,
connectTemporary,
disconnect,
createSSHConnection,
makeRequest,
proxyRequest,
setupRDPProxy,
};
};

View File

@@ -0,0 +1,53 @@
import { ToggleSwitch } from "@components/ToggleSwitch";
import React, { useMemo } from "react";
import { useSWRConfig } from "swr";
import { usePermissions } from "@/contexts/PermissionsProvider";
import { useRoutes } from "@/contexts/RoutesProvider";
import { Route } from "@/interfaces/Route";
type Props = {
route: Route;
};
export default function RouteAutoApplyCell({ route }: Readonly<Props>) {
const { permission } = usePermissions();
const { updateRoute } = useRoutes();
const { mutate } = useSWRConfig();
const isExitNode = useMemo(() => route.network === "0.0.0.0/0", [route]);
const isChecked = useMemo(() => {
// Checked means Auto Apply is ON, which maps to skip_auto_apply === false
return route.skip_auto_apply === false;
}, [route]);
const update = async (checked: boolean) => {
// When toggled ON (checked === true), we want skip_auto_apply = false
const nextSkipAutoApply = !checked;
updateRoute(
route,
{ skip_auto_apply: nextSkipAutoApply },
() => {
mutate("/routes");
},
checked
? "Auto Apply was enabled for the route"
: "Auto Apply was disabled for the route",
);
};
if (!isExitNode) return null;
return (
<div className={"flex items-center"}>
<ToggleSwitch
checked={isChecked}
size={"small"}
onClick={() => update(!isChecked)}
disabled={!permission.routes.update}
/>
</div>
);
}

View File

@@ -227,6 +227,7 @@ export function RouteModalContent({
const [enabled, setEnabled] = useState<boolean>(true);
const [metric, setMetric] = useState("9999");
const [masquerade, setMasquerade] = useState<boolean>(true);
const [isForced, setIsForced] = useState<boolean>(true);
const isNonLinuxRoutingPeer = useMemo(() => {
if (!routingPeer) return false;
@@ -304,6 +305,7 @@ export function RouteModalContent({
masquerade: useSinglePeer && isNonLinuxRoutingPeer ? true : masquerade,
groups: groupIds,
access_control_groups: accessControlGroupIds || undefined,
skip_auto_apply: !isForced,
},
onSuccess,
);
@@ -718,6 +720,20 @@ export function RouteModalContent({
helpText={"Use this switch to enable or disable the route."}
/>
{exitNode && (
<FancyToggleSwitch
value={isForced}
onChange={setIsForced}
label={
<>
<IconDirectionSign size={15} />
Auto Apply Route
</>
}
helpText={"Automatically apply this exit node to your distribution groups. This requires NetBird client v0.55.0 or higher."}
/>
)}
{!exitNode && (
<RoutingPeerMasqueradeSwitch
value={masquerade}

View File

@@ -7,6 +7,7 @@ import { GroupedRoute, Route } from "@/interfaces/Route";
import RouteAccessControlGroups from "@/modules/routes/RouteAccessControlGroups";
import RouteActionCell from "@/modules/routes/RouteActionCell";
import RouteActiveCell from "@/modules/routes/RouteActiveCell";
import RouteAutoApplyCell from "@/modules/routes/RouteAutoApplyCell";
import RouteDistributionGroupsCell from "@/modules/routes/RouteDistributionGroupsCell";
import RouteMetricCell from "@/modules/routes/RouteMetricCell";
import RoutePeerCell from "@/modules/routes/RoutePeerCell";
@@ -77,6 +78,15 @@ export const RouteTableColumns: ColumnDef<Route>[] = [
},
cell: ({ row }) => <RouteAccessControlGroups route={row.original} />,
},
{
id: "skipAutoApply",
accessorKey: "skip_auto_apply",
header: ({ column }) => {
return <DataTableHeader column={column}>Auto Apply</DataTableHeader>;
},
cell: ({ row }) => <RouteAutoApplyCell route={row.original} />,
sortingFn: "basic",
},
{
id: "group_names",
accessorFn: (row) => {
@@ -104,6 +114,10 @@ export default function RouteTable({ row }: Props) {
desc: true,
},
]);
const hasAtLeastOneExitNode = useMemo(() => {
return row.routes?.some((route) => route.network === "0.0.0.0/0");
}, [row.routes]);
const data = useMemo(() => {
if (!row.routes) return [];
@@ -144,6 +158,7 @@ export default function RouteTable({ row }: Props) {
domains: false,
domain_search: false,
network: false,
skipAutoApply: !!hasAtLeastOneExitNode,
}}
setSorting={setSorting}
columns={RouteTableColumns}

View File

@@ -20,6 +20,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@components/Tabs";
import { Textarea } from "@components/Textarea";
import { DomainsTooltip } from "@components/ui/DomainListBadge";
import { getOperatingSystem } from "@hooks/useOperatingSystem";
import { IconDirectionSign } from "@tabler/icons-react";
import { cn } from "@utils/helpers";
import { uniqBy } from "lodash";
import {
@@ -193,6 +194,7 @@ function RouteUpdateModalContent({ onSuccess, route, cell }: ModalProps) {
const [masquerade, setMasquerade] = useState<boolean>(
route?.masquerade ?? true,
);
const [isForced, setIsForced] = useState<boolean>(route?.skip_auto_apply === false);
// Refs to manage focus on tab change
const networkRangeRef = useRef<HTMLInputElement>(null);
@@ -257,6 +259,7 @@ function RouteUpdateModalContent({ onSuccess, route, cell }: ModalProps) {
masquerade: useSinglePeer && isNonLinuxRoutingPeer ? true : masquerade,
groups: groupIds,
access_control_groups: accessControlGroupIds || undefined,
skip_auto_apply: !isForced,
},
(r) => {
onSuccess && onSuccess(r);
@@ -456,6 +459,21 @@ function RouteUpdateModalContent({ onSuccess, route, cell }: ModalProps) {
}
helpText={"Use this switch to enable or disable the route."}
/>
{isExitNode && (
<FancyToggleSwitch
value={isForced}
onChange={setIsForced}
label={
<>
<IconDirectionSign size={15} />
Auto Apply Route
</>
}
helpText={"Automatically apply this exit node to your distribution groups. This requires NetBird client v0.55.0 or higher."}
/>
)}
{!isExitNode && (
<RoutingPeerMasqueradeSwitch
value={masquerade}

View File

@@ -23,6 +23,7 @@ import {
CalendarClock,
ExternalLinkIcon,
ShieldIcon,
ShieldUserIcon,
TimerResetIcon,
} from "lucide-react";
import React, { useState } from "react";
@@ -52,6 +53,19 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
}
});
/**
* User approval required
*/
const [userApprovalRequired, setUserApprovalRequired] = useState<boolean>(
() => {
try {
return account?.settings?.extra?.user_approval_required || false;
} catch (error) {
return false;
}
},
);
// Peer Expiration
const [
loginExpiration,
@@ -86,6 +100,7 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
const { hasChanges, updateRef } = useHasChanges([
peerApproval,
userApprovalRequired,
loginExpiration,
expiresIn,
expireInterval,
@@ -118,6 +133,7 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
extra: {
...account.settings?.extra,
peer_approval_enabled: peerApproval,
user_approval_required: userApprovalRequired,
},
},
} as Account)
@@ -125,6 +141,7 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
mutate("/accounts");
updateRef([
peerApproval,
userApprovalRequired,
loginExpiration,
expiresIn,
expireInterval,
@@ -181,6 +198,27 @@ export default function AuthenticationTab({ account }: Readonly<Props>) {
</div>
<div className={"flex flex-col gap-6 w-full mt-8 mb-3"}>
<div className={"flex flex-col"}>
<FancyToggleSwitch
value={userApprovalRequired}
onChange={setUserApprovalRequired}
dataCy={"user-approval-required"}
label={
<>
<ShieldUserIcon size={15} />
User Approval Required
</>
}
helpText={
<>
Require manual approval for new users joining via <br />
domain matching. Users will be blocked until approved.
</>
}
disabled={!permission.settings.update}
/>
</div>
<div className={"flex flex-col"}>
<FancyToggleSwitch
value={loginExpiration}

View File

@@ -3,7 +3,7 @@ import FullTooltip from "@components/FullTooltip";
import { notify } from "@components/Notification";
import { useApiCall } from "@utils/api";
import { Trash2 } from "lucide-react";
import React from "react";
import React, { useMemo } from "react";
import { useSWRConfig } from "swr";
import { useDialog } from "@/contexts/DialogProvider";
import { usePermissions } from "@/contexts/PermissionsProvider";
@@ -50,7 +50,12 @@ export default function GroupsActionCell({ group, in_use }: Readonly<Props>) {
issued: group?.issued,
});
const isDisabled = in_use || !isRegularGroup || !permission.groups.delete;
const isDisabled = useMemo(() => {
if (!permission.groups.delete) return true;
if (in_use) return true;
if (isJWTGroup) return false;
return !isRegularGroup;
}, [permission, in_use, isJWTGroup, isRegularGroup]);
const getDisabledText = () => {
if (isRegularGroup) {

View File

@@ -11,6 +11,7 @@ import * as Tabs from "@radix-ui/react-tabs";
import { useApiCall } from "@utils/api";
import { validator } from "@utils/helpers";
import { isNetBirdHosted } from "@utils/netbird";
import cidr from "ip-cidr";
import { ExternalLinkIcon, GlobeIcon, NetworkIcon } from "lucide-react";
import React, { useMemo, useState } from "react";
import { useSWRConfig } from "swr";
@@ -34,6 +35,9 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
const [customDNSDomain, setCustomDNSDomain] = useState(
account.settings.dns_domain || "",
);
const [networkRange, setNetworkRange] = useState(
account.settings.network_range || "",
);
const toggleNetworkDNSSetting = async (toggle: boolean) => {
notify({
@@ -57,25 +61,37 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
});
};
const { hasChanges, updateRef } = useHasChanges([customDNSDomain]);
const { hasChanges, updateRef } = useHasChanges([
customDNSDomain,
networkRange,
]);
const saveChanges = async () => {
const updatedSettings = {
...account.settings,
};
if (customDNSDomain !== "" || account.settings.dns_domain) {
updatedSettings.dns_domain = customDNSDomain;
}
if (networkRange !== "") {
updatedSettings.network_range = networkRange;
}
notify({
title: "Custom DNS Domain",
description: `Custom DNS Domain successfully updated.`,
title: "Network Settings",
description: `Network settings successfully updated.`,
promise: saveRequest
.put({
id: account.id,
settings: {
...account.settings,
dns_domain: customDNSDomain || "",
},
settings: updatedSettings,
})
.then(() => {
mutate("/accounts");
updateRef([customDNSDomain]);
updateRef([customDNSDomain, networkRange]);
}),
loadingMessage: "Updating Custom DNS domain...",
loadingMessage: "Updating network settings...",
});
};
@@ -90,6 +106,24 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
}
}, [customDNSDomain]);
const networkRangeError = useMemo(() => {
if (networkRange == "") {
if (account.settings.network_range) {
return "Network range cannot be empty";
}
return "";
}
try {
const validCIDR = cidr.isValidCIDR(networkRange);
if (!validCIDR) {
return "Please enter a valid IPv4 CIDR range, e.g. 100.64.0.0/16 or 192.168.1.0/24";
}
} catch (error) {
return "Please enter a valid IPv4 CIDR range, e.g. 100.64.0.0/16 or 192.168.1.0/24";
}
}, [networkRange, account.settings.network_range]);
return (
<Tabs.Content value={"networks"}>
<div className={"p-default py-6 max-w-2xl"}>
@@ -112,7 +146,12 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
</div>
<Button
variant={"primary"}
disabled={!hasChanges || !permission.settings.update}
disabled={
!hasChanges ||
!permission.settings.update ||
!!domainError ||
!!networkRangeError
}
onClick={saveChanges}
>
Save Changes
@@ -130,7 +169,8 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
<Label>DNS Domain</Label>
<HelpText>
Specify a custom peer DNS domain for your network. This should
not point to a domain that is already in use elsewhere, to avoid overriding DNS results.
not point to a domain that is already in use elsewhere, to
avoid overriding DNS results.
</HelpText>
</div>
<div className={"w-full"}>
@@ -149,6 +189,33 @@ export default function NetworkSettingsTab({ account }: Readonly<Props>) {
</div>
</div>
<div>
<div
className={
"flex flex-col gap-1 sm:flex-row w-full sm:gap-4 items-center"
}
>
<div className={"min-w-[330px]"}>
<Label>Network Range</Label>
<HelpText>
Specify a custom IPv4 range for your network in CIDR format.
All peer IPs will be re-allocated when changed.
</HelpText>
</div>
<div className={"w-full"}>
<Input
placeholder={"e.g. 100.64.0.0/16"}
errorTooltip={true}
errorTooltipPosition={"top"}
error={networkRangeError}
value={networkRange}
disabled={!permission.settings.update}
onChange={(e) => setNetworkRange(e.target.value)}
/>
</div>
</div>
</div>
<FancyToggleSwitch
value={routingPeerDNSSetting}
onChange={toggleNetworkDNSSetting}

View File

@@ -0,0 +1,52 @@
import Button from "@components/Button";
import { NotificationCountBadge } from "@components/ui/NotificationCountBadge";
import { Table } from "@tanstack/react-table";
import * as React from "react";
import { useEffect } from "react";
type Props<T> = {
table: Table<T>;
data?: T[];
count?: number;
};
export const PendingApprovalFilter = <T,>({ table, data, count }: Props<T>) => {
// Reset filter if there are no pending approvals
useEffect(() => {
if (
count == 0 &&
table.getColumn("approval_required")?.getFilterValue() === true
) {
table.setColumnFilters([]);
}
}, [count, table]);
if (!count) return;
return (
<Button
disabled={data?.length == 0}
onClick={() => {
table.setPageIndex(0);
let current =
table.getColumn("approval_required")?.getFilterValue() === undefined
? true
: undefined;
table.setColumnFilters([
{
id: "approval_required",
value: current,
},
]);
}}
variant={
table.getColumn("approval_required")?.getFilterValue() === true
? "tertiary"
: "secondary"
}
>
Pending Approvals
<NotificationCountBadge count={count} />
</Button>
);
};

Some files were not shown because too many files have changed in this diff Show More