fix: 修复关闭SSH终端标签页时会话状态未更新的问题

This commit is contained in:
2026-04-18 02:35:38 +08:00
commit 6e2e2f9387
43467 changed files with 5489040 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
.*
data
logs
playground
web/node_modules/
@@ -0,0 +1,39 @@
name: Docker Guacamole Server Build
on:
workflow_dispatch:
jobs:
guacamole_server:
name: Build guacamole-server
runs-on: ubuntu-latest
steps:
- name: Private Actions Checkout
uses: actions/checkout@v2.3.4
- name: Docker Setup QEMU
uses: docker/setup-qemu-action@v1.2.0
- name: Docker Setup Buildx
uses: docker/setup-buildx-action@v1.6.0
- name: Get resources
run: |
rm -rf *
wget -O /tmp/master.zip https://github.com/apache/guacamole-server/archive/refs/heads/master.zip
unzip /tmp/master.zip -d /tmp
mv /tmp/guacamole-server-master/* .
- name: Docker Login
uses: docker/login-action@v1.10.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Build and push Docker images
uses: docker/build-push-action@v2.7.0
with:
context: .
platforms: linux/arm64,linux/arm/v7,linux/amd64
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/guacamole-server:latest
${{ secrets.DOCKERHUB_USERNAME }}/guacamole-server:1.4.0
cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/guacamole-server:cache
cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/guacamole-server:cache,mode=max
+42
View File
@@ -0,0 +1,42 @@
name: Docker guacd Build
on:
workflow_dispatch:
jobs:
DOCKERHUB_Guacd_Build:
name: Docker Guacd Build
runs-on: ubuntu-latest
steps:
- name: Private Actions Checkout
uses: actions/checkout@v2.3.4
- name: Docker Setup QEMU
uses: docker/setup-qemu-action@v1.2.0
- name: Docker Setup Buildx
uses: docker/setup-buildx-action@v1.6.0
- name: Docker Login
uses: docker/login-action@v1.10.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Docker Aliyun Login
uses: docker/login-action@v1.10.0
with:
registry: registry.cn-beijing.aliyuncs.com
username: ${{ secrets.ALI_USERNAME }}
password: ${{ secrets.ALI_PASSWORD }}
- name: Build and push Docker images
uses: docker/build-push-action@v2.7.0
with:
context: .
platforms: linux/arm64,linux/arm/v7,linux/amd64
file: guacd/Dockerfile
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/guacd:1.4.0
${{ secrets.DOCKERHUB_USERNAME }}/guacd:latest
registry.cn-beijing.aliyuncs.com/${{ secrets.DOCKERHUB_USERNAME }}/guacd:1.4.0
registry.cn-beijing.aliyuncs.com/${{ secrets.DOCKERHUB_USERNAME }}/guacd:latest
cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/guacd:cache
cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/guacd:cache,mode=max
@@ -0,0 +1,71 @@
name: Docker next-terminal Build
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
DOCKERHUB_next-terminal_Build:
name: Docker next-terminal Build
runs-on: ubuntu-latest
steps:
- name: Get version
id: get_version
run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//}
- name: Private Actions Checkout
uses: actions/checkout@v3
- name: Docker Setup QEMU
uses: docker/setup-qemu-action@v1.2.0
- name: Docker Setup Buildx
uses: docker/setup-buildx-action@v1.6.0
- name: node Setup
uses: actions/setup-node@v2
with:
node-version: '16'
- name: npm install
run: |
cd web
npm install --global yarn
yarn
yarn build
- name: Docker Login
uses: docker/login-action@v1.10.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Docker Aliyun Login
uses: docker/login-action@v1.10.0
with:
registry: registry.cn-beijing.aliyuncs.com
username: ${{ secrets.ALI_USERNAME }}
password: ${{ secrets.ALI_PASSWORD }}
- name: Build and push Docker images
uses: docker/build-push-action@v2.7.0
with:
context: .
platforms: linux/arm64,linux/arm/v7,linux/amd64
file: Dockerfile
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/next-terminal:latest
${{ secrets.DOCKERHUB_USERNAME }}/next-terminal:${{ steps.get_version.outputs.VERSION }}
registry.cn-beijing.aliyuncs.com/${{ secrets.DOCKERHUB_USERNAME }}/next-terminal:latest
registry.cn-beijing.aliyuncs.com/${{ secrets.DOCKERHUB_USERNAME }}/next-terminal:${{ steps.get_version.outputs.VERSION }}
cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/next-terminal:cache
cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/next-terminal:cache,mode=max
DOCKERHUB_Hub_Description:
needs: [ DOCKERHUB_next-terminal_Build ]
name: Change DockerHub Description
runs-on: ubuntu-latest
steps:
- name: Private Actions Checkout
uses: actions/checkout@v2.3.4
- name: Docker Hub Description
uses: peter-evans/dockerhub-description@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
repository: ${{ secrets.DOCKERHUB_USERNAME }}/next-terminal
+22
View File
@@ -0,0 +1,22 @@
name: golangci-lint
on:
push:
tags:
- v*
branches:
- master
- be-*
- dev
pull_request:
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: v1.42.1
args: --timeout=5m
@@ -0,0 +1,46 @@
name: next-terminal Release
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
next-terminal_Release:
name: next-terminal release
runs-on: ubuntu-latest
steps:
- name: Get version
id: get_version
run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//}
- name: Private Actions Checkout
uses: actions/checkout@v3
- name: node Setup
uses: actions/setup-node@v2
with:
node-version: '16'
- name: npm install
run: |
cd web
npm install --global yarn
yarn
- name: go Setup
uses: actions/setup-go@v4
with:
go-version: '1.20'
- name: Build package Linux
run: |
sh build.sh
mv next-terminal next-terminal-bin
mkdir next-terminal
cp next-terminal-bin next-terminal/next-terminal
cp config.yml.example next-terminal/config.yml
cp LICENSE next-terminal/
tar zcvf next-terminal.tar.gz next-terminal/
- name: release
uses: softprops/action-gh-release@v1
with:
files: next-terminal.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+31
View File
@@ -0,0 +1,31 @@
yarn.lock
web/build
web/node_modules
*.log
*.db
.DS_Store
.eslintcache
.env
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# ignore ide config
.idea
.vscode
# vim
*.swp
# next terminal
/data/
/logs/
/server/resource/static/
/server/resource/*.html
/server/resource/*.json
/server/resource/*.ico
+23
View File
@@ -0,0 +1,23 @@
linters-settings:
goimports:
local-prefixes: next-terminal
linters:
disable-all: true
enable:
- deadcode
- errcheck
- gofmt
- goimports
- gosimple
- govet
- ineffassign
- staticcheck
- structcheck
- typecheck
- unused
- varcheck
run:
skip-files:
- test_ssh.go
+46
View File
@@ -0,0 +1,46 @@
FROM golang:alpine as builder
ENV GO111MODULE=on
ENV GOPROXY=https://goproxy.cn,direct
WORKDIR /app
COPY . .
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN #apk add upx
RUN go mod tidy
RUN sh get_arch.sh
RUN echo "Hello, my CPU architecture is $(uname -m)"
RUN cp -r /app/web/build /app/server/resource/
RUN go env;CGO_ENABLED=0 GOOS=linux GOARCH=$ARCH go build -ldflags '-s -w' -o next-terminal main.go
RUN #upx next-terminal
FROM alpine:latest
LABEL MAINTAINER="helloworld1024@foxmail.com"
ENV TZ Asia/Shanghai
ENV DB sqlite
ENV SQLITE_FILE './data/sqlite/next-terminal.db'
ENV SERVER_PORT 8088
ENV SERVER_ADDR 0.0.0.0:$SERVER_PORT
ENV SSHD_PORT 8089
ENV SSHD_ADDR 0.0.0.0:$SSHD_PORT
ENV TIME_ZONE=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TIME_ZONE /etc/localtime && echo $TIME_ZONE > /etc/timezone
WORKDIR /usr/local/next-terminal
RUN touch config.yml
COPY --from=builder /app/next-terminal ./
COPY --from=builder /app/LICENSE ./
EXPOSE $SERVER_PORT $SSHD_PORT
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN apk add tzdata
RUN cp /usr/share/zoneinfo/${TZ} /etc/localtime
RUN echo ${TZ} > /etc/timezone
ENTRYPOINT ./next-terminal
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
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.
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.
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.
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 <http://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
<http://www.gnu.org/licenses/>.
+73
View File
@@ -0,0 +1,73 @@
# Next Terminal
[![Docker guacd build](https://github.com/dushixiang/next-terminal/actions/workflows/docker-guacd.yml/badge.svg)](https://github.com/dushixiang/next-terminal/actions/workflows/docker-guacd.yml)
[![Docker next-terminal build](https://github.com/dushixiang/next-terminal/actions/workflows/docker-next-terminal.yml/badge.svg)](https://github.com/dushixiang/next-terminal/actions/workflows/docker-next-terminal.yml)
## 快速了解
Next Terminal是一个简单好用安全的开源交互审计系统,支持RDP、SSH、VNC、Telnet、Kubernetes协议。
目前支持的功能有:
- 授权凭证管理
- 资产管理(支持RDP、SSH、VNC、TELNET协议)
- 指令管理
- 批量执行命令
- 在线会话管理(监控、强制断开)
- 离线会话管理(查看录屏)
- 双因素认证
- 资产标签
- 资产授权
- 多用户&用户分组
- 计划任务
- ssh server
- 登录策略
- 系统监控
## 在线体验
**web**
https://next.typesafe.cn/ 账号:test 密码:test
**ssh server**
主机:next.typesafe.cn
端口:2022
账号:test 密码:test
## 协议与条款
如您需要在企业网络中使用 next-terminal,建议先征求 IT 管理员的同意。下载、使用或分发 next-terminal 前,您必须同意 [协议](./LICENSE) 条款与限制。本项目不提供任何担保,亦不承担任何责任。
## 快速安装
- [安装文档](https://next-terminal.typesafe.cn)
默认账号密码为 admin/admin 。
## 手动编译
1. 找一台Linux 机器或者Mac
2. 安装 go 1.18 或以上版本
3. 安装 nodejs 16,安装 npm 或 yarn
4. 进入 web 目录 执行 yarn 或 npm install
5. 返回上级目录,也就是项目根目录,执行 sh build.sh
## 问题反馈
- Issues
- 微信群 加我微信拉你进群 (请备注 next-terminal)
<img src="wx.png" width="300" height="auto"/>
- QQ群 938145268
- Telegram https://t.me/next_terminal
## 安全问题
如果您在使用过程中发现了安全问题,请发送邮件至 helloworld1024@foxmail.com 联系我,谢谢。
## License
Next Terminal 使用 [AGPL-3.0](./LICENSE) 开源协议,请自觉遵守。
+211
View File
@@ -0,0 +1,211 @@
# Next Terminal 前端升级对接文档
## 已完成的工作
### 1. 前端代码替换 ✅
- 从 GitHub 克隆了最新的 next-terminal 前端代码(v2.6.6+
- 替换了旧的前端代码(v1.3.9
- 备份了旧前端代码到 `web-backup` 目录
### 2. 前端配置修改 ✅
- 更新了 `package.json`(新依赖:Vite, TypeScript, Tailwind CSS, Ant Design 5 等)
- 配置了 `vite.config.ts`
- 添加开发服务器代理(/api -> localhost:8088
- 设置前端端口为 3000
- 配置 PWA 支持
- 修改了 API 基础 URL 配置,使用相对路径 `/api`
- 配置 WebSocket URL 指向后端 8088 端口
### 3. 后端路由重构 ✅
- 重构了 `server/app/server.go` 的路由配置
- 添加了 `/api/admin` 前缀以匹配新前端的 API 调用格式
- 所有 API 路由现在都位于 `/api/admin/` 路径下
- 修复了 access-token 删除接口的路径参数问题
### 4. 新增后端 API 端点 ✅
创建了 `server/api/setup.go` 文件,包含以下新端点:
#### 初始化相关
- `GET /api/admin/setup-status` - 检查系统是否需要初始化
- `POST /api/admin/setup-user` - 创建初始管理员用户
#### 登录认证相关
- `GET /api/admin/login-status` - 获取当前登录状态
- `POST /api/admin/validate-totp` - 验证 TOTP 验证码
- `GET /api/admin/account/password-policy` - 获取密码策略配置
### 5. 数据模型扩展 ✅
-`dto/auth.go` 中添加了 `UserCreate` 结构体
### 6. 后端编译验证 ✅
- Go 后端代码编译成功,无错误
## 技术栈变化
### 旧版本 (v1.3.9)
- **构建工具**: Create React App (react-scripts)
- **UI 框架**: Ant Design 4.x
- **语言**: JavaScript (JSX)
- **状态管理**: React Query 3.x
- **路由**: React Router 6
- **终端**: xterm 4.x
### 新版本 (latest)
- **构建工具**: Vite 7.x
- **UI 框架**: Ant Design 5.x + Tailwind CSS 4.x
- **语言**: TypeScript (TSX)
- **状态管理**: React Query 5.x + Jotai
- **路由**: React Router 7.x
- **终端**: @xterm/xterm 5.x
- **新增功能**:
- i18n 国际化支持
- PWA 支持
- WebAuthn 认证
- OIDC 支持
- 更多资产管理功能
## 待完成的工作
### 高优先级
1. **前端依赖安装**
- 正在执行 npm install(需要较长时间)
- 安装完成后需要验证依赖完整性
2. **前端构建测试**
```bash
cd web
npm run build
```
- 可能需要修复 TypeScript 类型错误
- 可能需要调整 Tailwind CSS 配置
- 可能需要处理新的依赖兼容性问题
3. **核心功能对接验证**
- [ ] 用户登录流程
- [ ] 资产管理(CRUD
- [ ] 会话连接(SSH/RDP/VNC
- [ ] 终端操作
- [ ] 权限控制
### 中优先级
4. **缺失 API 端点实现**
新前端包含许多旧后端不支持的功能,需要逐步实现:
#### 用户管理增强
- [ ] 部门管理 API (`/departments`)
- [ ] 用户部门关联 API
- [ ] LDAP 同步 API (`/sync-from-ldap`)
- [ ] 用户导入 API (`/import`)
- [ ] 用户客户端证书 API (`/client-cert`)
- [ ] 批量重置密码/TOTP API
#### 资产管理增强
- [ ] 资产分组 API (`/groups`, `/tree`)
- [ ] 资产排序 API (`/sort`)
- [ ] 资产网关统一接口 (`/change-gateway`)
- [ ] 资产连接检测 API (`/checking`)
- [ ] 资产解密 API (`/decrypted`)
- [ ] Logo 管理 API (`/logos`)
#### 新功能模块
- [ ] 数据库资产管理 (`database-assets`)
- [ ] 网站资产管理 (`websites`)
- [ ] 证书管理 (`certificates`)
- [ ] DNS 提供商管理 (`dns-providers`)
- [ ] 命令过滤器 (`command-filters`, `command-filter-rules`)
- [ ] 代码片段管理 (`snippets`, `snippet-users`)
- [ ] Agent 网关管理 (`agent-gateways`, `agent-gateway-tokens`)
- [ ] SSH 网关管理 (`ssh-gateways`)
- [ ] 网关组管理 (`gateway-groups`)
- [ ] 计划任务管理 (`scheduled-tasks`) - 替代旧的 jobs
- [ ] 操作日志 (`operation-logs`)
- [ ] 访问日志 (`access-logs`)
- [ ] 文件系统日志 (`filesystem-logs`)
- [ ] Shell 助手 (`shell-assistant`)
- [ ] 会话命令记录 (`session-commands`)
- [ ] 数据库 SQL 日志 (`database-sql-logs`)
- [ ] 数据库工单 (`db-work-orders`)
#### 安全与认证
- [ ] WebAuthn API (`/webauthn/*`)
- [ ] 安全令牌 API (`/security-token/*`)
- [ ] OIDC 客户端管理 (`oidc-clients`)
- [ ] OIDC Server 功能 (`/oidc/server/*`)
- [ ] 登录锁定管理 (`login-locked`)
- [ ] 企业微信集成 (`wechat-work`)
#### 系统设置
- [ ] 许可证管理 (`license`)
- [ ] Logo 管理 (`logo`)
- [ ] 品牌/自定义设置 (`branding`)
- [ ] 匿名访问设置 (`anonymous`)
- [ ] Portal 页面设置 (`portal`)
- [ ] 访问设置 (`access-setting`)
5. **数据结构适配**
- 新前端可能期望不同的响应格式
- 需要检查并调整 API 响应结构
- 可能需要添加或修改字段
6. **静态资源处理**
- 配置后端服务前端静态文件
- 确保 `/api/logo` 等静态资源端点正常工作
- 处理 PWA 相关资源
### 低优先级
7. **性能优化**
- 实现新前端需要的分页、排序优化
- 添加缓存策略
- 优化大量数据的加载
8. **国际化支持**
- 配置 i18n 后端支持
- 添加多语言翻译文件
9. **测试与调试**
- 编写单元测试
- 进行端到端测试
- 性能测试
## 快速开始指南
### 1. 启动后端
```bash
cd next-terminal-1.3.9
# 编辑 config.yml 配置数据库等信息
go run main.go
```
### 2. 安装并启动前端(开发模式)
```bash
cd web
npm install # 如果尚未完成
npm run dev # 启动开发服务器,默认在 http://localhost:3000
```
### 3. 访问系统
- 前端地址: http://localhost:3000
- 后端 API: http://localhost:8088/api
- 首次访问会进入初始化页面,需要创建管理员账户
## 注意事项
1. **API 兼容性**: 新前端是为更新的后端版本设计的,部分高级功能暂时不可用
2. **渐进式实现**: 建议优先实现核心功能,然后逐步添加高级功能
3. **数据备份**: 在进行升级前务必备份数据库
4. **测试环境**: 建议先在测试环境中验证所有功能
5. **日志监控**: 升级后密切关注日志,及时发现和解决问题
## 下一步行动
1. 等待 npm install 完成
2. 尝试前端构建,修复可能的错误
3. 启动前后端服务,测试基本功能
4. 根据测试结果补充缺失的 API 端点
5. 逐步完善高级功能
---
**最后更新时间**: 2026-04-16
**当前状态**: 前端代码已替换,后端基础 API 已就绪,等待前端依赖安装完成
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
cp build/resources/logo.png web/src/images/logo.png
cp build/resources/logo-with-name.png web/src/images/logo-with-name.png
cp build/resources/favicon.ico web/public/favicon.ico
rm -rf server/resource/build
echo "clean build history"
echo "build web..."
cd web || exit
yarn build || exit
cp -r build ../server/resource/
echo "build web success"
echo "build api..."
cd ..
go mod tidy
go env;CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags '-s -w' -o next-terminal main.go
upx next-terminal
rm -rf server/resource/build
echo "build api success"
Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

+25
View File
@@ -0,0 +1,25 @@
debug: true
demo: false
db: sqlite
mysql:
hostname: localhost
port: 3306
username: next-terminal
password: next-terminal
database: next-terminal
sqlite:
file: './data/sqlite/next-terminal.db'
server:
addr: 0.0.0.0:8088
guacd:
hostname: 127.0.0.1
port: 4822
# 此路径需要为绝对路径,并且next-terminal和guacd都能访问到
recording: 'data/recording'
# 此路径需要为绝对路径,并且next-terminal和guacd都能访问到
drive: 'data/drive'
sshd:
enable: true
addr: 0.0.0.0:8089
key: ~/.ssh/id_rsa
+24
View File
@@ -0,0 +1,24 @@
debug: false
db: sqlite
mysql:
hostname: localhost
port: 3306
username: next-terminal
password: next-terminal
database: next-terminal
sqlite:
file: './data/sqlite/next-terminal.db'
server:
addr: 0.0.0.0:8088
guacd:
hostname: 127.0.0.1
port: 4822
# 此路径需要为绝对路径,并且next-terminal和guacd都能访问到
recording: '/usr/local/next-terminal/data/recording'
# 此路径需要为绝对路径,并且next-terminal和guacd都能访问到
drive: '/usr/local/next-terminal/data/drive'
sshd:
enable: true
addr: 0.0.0.0:2022
key: ~/.ssh/id_rsa
+15
View File
@@ -0,0 +1,15 @@
ARCH="$(arch)"
case "$ARCH" in
'x86_64')
export ARCH='amd64'
echo $ARCH
;;
'aarch64')
export ARCH='arm64'
echo $ARCH
;;
*)
export ARCH=$ARCH
echo $ARCH
;;
esac
+81
View File
@@ -0,0 +1,81 @@
module next-terminal
go 1.20
require (
github.com/glebarez/sqlite v1.8.0
github.com/gliderlabs/ssh v0.3.5
github.com/google/uuid v1.3.0
github.com/gorilla/websocket v1.5.0
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible
github.com/labstack/echo/v4 v4.10.2
github.com/labstack/gommon v0.4.0
github.com/manifoldco/promptui v0.9.0
github.com/mitchellh/go-homedir v1.1.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.9.1
github.com/pkg/sftp v1.13.5
github.com/pquerna/otp v1.4.0
github.com/robfig/cron/v3 v3.0.1
github.com/shirou/gopsutil/v3 v3.23.4
github.com/sirupsen/logrus v1.9.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.15.0
github.com/stretchr/testify v1.8.2
github.com/ucarion/urlpath v0.0.0-20200424170820-7ccc79b76bbb
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.8.0
golang.org/x/net v0.9.0
golang.org/x/text v0.9.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gorm.io/driver/mysql v1.5.0
gorm.io/gorm v1.25.0
)
require (
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect
github.com/boombuler/barcode v1.0.1 // indirect
github.com/chzyer/readline v1.5.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/glebarez/go-sqlite v1.21.1 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/kr/fs v0.1.0 // indirect
github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.18 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.0.7 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/shoenig/go-m1cpu v0.1.5 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
github.com/tklauser/go-sysconf v0.3.11 // indirect
github.com/tklauser/numcpus v0.6.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/yusufpapurcu/wmi v1.2.2 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/term v0.7.0 // indirect
golang.org/x/time v0.3.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.22.5 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/sqlite v1.22.1 // indirect
)
+630
View File
@@ -0,0 +1,630 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To=
cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4=
cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M=
cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc=
cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk=
cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs=
cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc=
cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY=
cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI=
cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk=
cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=
cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc=
cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg=
cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc=
cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw=
cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA=
cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos=
cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/boombuler/barcode v1.0.1 h1:NDBbPmhS+EqABEs5Kg3n/5ZNjy73Pz7SIV+KCeqyXcs=
github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM=
github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI=
github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04=
github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po=
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/glebarez/go-sqlite v1.21.1 h1:7MZyUPh2XTrHS7xNEHQbrhfMZuPSzhkm2A1qgg0y5NY=
github.com/glebarez/go-sqlite v1.21.1/go.mod h1:ISs8MF6yk5cL4n/43rSOmVMGJJjHYr7L2MbZZ5Q4E2E=
github.com/glebarez/sqlite v1.8.0 h1:02X12E2I/4C1n+v90yTqrjRa8yuo7c3KeHI3FRznCvc=
github.com/glebarez/sqlite v1.8.0/go.mod h1:bpET16h1za2KOOMb8+jCp6UBP/iahDpfPQqSaYLTLx8=
github.com/gliderlabs/ssh v0.3.5 h1:OcaySEmAQJgyYcArR+gGGTHCyE7nvhEMTlYY+Dp8CpY=
github.com/gliderlabs/ssh v0.3.5/go.mod h1:8XB4KraRrX39qHhT6yxPsHedjA08I/uBVwj4xC+/+z4=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA=
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/labstack/echo/v4 v4.10.2 h1:n1jAhnq/elIFTHr1EYpiYtyKgx4RW9ccVgkqByZaN2M=
github.com/labstack/echo/v4 v4.10.2/go.mod h1:OEyqf2//K1DFdE57vw2DRgWY0M7s65IVQO2FzvI4J5k=
github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8=
github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a h1:N9zuLhTvBSRt0gWSiJswwQ2HqDmtX/ZCDJURnKUt1Ik=
github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a/go.mod h1:JKx41uQRwqlTZabZc+kILPrO/3jlKnQ2Z8b7YiVw5cE=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA=
github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pelletier/go-toml/v2 v2.0.7 h1:muncTPStnKRos5dpVKULv2FVd4bMOhNePj9CjgDb8Us=
github.com/pelletier/go-toml/v2 v2.0.7/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
github.com/pkg/sftp v1.13.5 h1:a3RLUqkyjYRtBTZJZ1VRrKbN3zhuPLlUc3sphVz81go=
github.com/pkg/sftp v1.13.5/go.mod h1:wHDZ0IZX6JcBYRK1TH9bcVq8G7TLpVHYIGJRFnmPfxg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b h1:0LFwY6Q3gMACTjAbMZBjXAqTOzOwFaj2Ld6cjeQ7Rig=
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/pquerna/otp v1.4.0 h1:wZvl1TIVxKRThZIBiwOOHOGP/1+nZyWBil9Y2XNEDzg=
github.com/pquerna/otp v1.4.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
github.com/shirou/gopsutil/v3 v3.23.4 h1:hZwmDxZs7Ewt75DV81r4pFMqbq+di2cbt9FsQBqLD2o=
github.com/shirou/gopsutil/v3 v3.23.4/go.mod h1:ZcGxyfzAMRevhUR2+cfhXDH6gQdFYE/t8j1nsU4mPI8=
github.com/shoenig/go-m1cpu v0.1.5 h1:LF57Z/Fpb/WdGLjt2HZilNnmZOxg/q2bSKTQhgbrLrQ=
github.com/shoenig/go-m1cpu v0.1.5/go.mod h1:Wwvst4LR89UxjeFtLRMrpgRiyY4xPsejnVZym39dbAQ=
github.com/shoenig/test v0.6.3 h1:GVXWJFk9PiOjN0KoJ7VrJGH6uLPnqxR7/fe3HUPfE0c=
github.com/shoenig/test v0.6.3/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM=
github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ=
github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w=
github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.15.0 h1:js3yy885G8xwJa6iOISGFwd+qlUo5AvyXb7CiihdtiU=
github.com/spf13/viper v1.15.0/go.mod h1:fFcTBJxvhhzSJiZy8n+PeW6t8l+KeT/uTARa0jHOQLA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8=
github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/tklauser/go-sysconf v0.3.11 h1:89WgdJhk5SNwJfu+GKyYveZ4IaJ7xAkecBo+KdJV0CM=
github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI=
github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms=
github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4=
github.com/ucarion/urlpath v0.0.0-20200424170820-7ccc79b76bbb h1:Ywfo8sUltxogBpFuMOFRrrSifO788kAFxmvVw31PtQQ=
github.com/ucarion/urlpath v0.0.0-20200424170820-7ccc79b76bbb/go.mod h1:ikPs9bRWicNw3S7XpJ8sK/smGwU9WcSVU3dy9qahYBM=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg=
github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk=
go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=
go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220826181053-bd7e27e6170d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ=
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs=
golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220825204002-c680a09ffe64/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE=
golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE=
google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE=
google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM=
google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc=
google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg=
google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE=
google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA=
google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA=
google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60=
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8=
google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.0 h1:6hSAT5QcyIaty0jfnff0z0CLDjyRgZ8mlMHLqSt7uXM=
gorm.io/driver/mysql v1.5.0/go.mod h1:FFla/fJuCvyTi7rJQd27qlNX2v3L6deTR1GgTjSOLPo=
gorm.io/gorm v1.24.7-0.20230306060331-85eaf9eeda11/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.0 h1:+KtYtb2roDz14EQe4bla8CbQlmb9dN3VejSai3lprfU=
gorm.io/gorm v1.25.0/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.22.1 h1:P2+Dhp5FR1RlVRkQ3dDfCiv3Ok8XPxqpe70IjYVA9oE=
modernc.org/sqlite v1.22.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
+10
View File
@@ -0,0 +1,10 @@
FROM dushixiang/guacamole-server:latest
LABEL MAINTAINER="helloworld1024@foxmail.com"
COPY ./guacd/fonts/Menlo-Regular.ttf /usr/share/fonts/
COPY ./guacd/fonts/SourceHanSansCN-Regular.otf /usr/share/fonts/
user root
RUN mkfontscale && mkfontdir && fc-cache
Binary file not shown.
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
package main
import (
"next-terminal/server/app"
"github.com/labstack/gommon/log"
)
func main() {
err := app.Run()
if err != nil {
log.Fatal(err)
}
}
+35
View File
@@ -0,0 +1,35 @@
# K8S部署指南
## 环境准备
1、准备一个标准的Kubernetes集群。
2、创建一个storageClassName,譬如 cbs-next-terminal
3、创建一个命名空间 next-terminal
## 启动next-terminal
1、根据需要修改相关参数,譬如PV卷的大小,端口。
2、执行start.sh,如下所示:
- kubectl apply -f mysql-claim0-persistentvolumeclaim.yaml -n next-terminal
- kubectl apply -f mysql-deployment.yaml -n next-terminal
- kubectl apply -f mysql-service.yaml -n next-terminal
- kubectl apply -f guacd-claim0-persistentvolumeclaim.yaml -n next-terminal
- kubectl apply -f guacd-deployment.yaml -n next-terminal
- kubectl apply -f guacd-service.yaml -n next-terminal
- kubectl apply -f next-terminal-claim0-persistentvolumeclaim.yaml -n next-terminal
- kubectl apply -f next-terminal-claim1-persistentvolumeclaim.yaml -n next-terminal
- kubectl apply -f next-terminal-deployment.yaml -n next-terminal
- kubectl apply -f next-terminal-service.yaml -n next-terminal
3、在Kubernetes集群中查询service,可以增加ingress配置,进行访问。
## 销毁next-terminal
1、执行stop.sh,如下所示:
- kubectl delete -f mysql-service.yaml -n next-terminal
- kubectl delete -f mysql-deployment.yaml -n next-terminal
- kubectl delete -f mysql-claim0-persistentvolumeclaim.yaml -n next-terminal
- kubectl delete -f guacd-service.yaml -n next-terminal
- kubectl delete -f guacd-deployment.yaml -n next-terminal
- kubectl delete -f guacd-claim0-persistentvolumeclaim.yaml -n next-terminal
- kubectl delete -f next-terminal-service.yaml -n next-terminal
- kubectl delete -f next-terminal-deployment.yaml -n next-terminal
- kubectl delete -f next-terminal-claim0-persistentvolumeclaim.yaml -n next-terminal
- kubectl delete -f next-terminal-claim1-persistentvolumeclaim.yaml -n next-terminal
@@ -0,0 +1,15 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
creationTimestamp: null
labels:
io.kompose.service: guacd-claim0
name: guacd-claim0
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: cbs-next-terminal
status: {}
@@ -0,0 +1,39 @@
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: guacd
name: guacd
spec:
replicas: 1
selector:
matchLabels:
io.kompose.service: guacd
strategy:
type: Recreate
template:
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: guacd
spec:
containers:
- image: dushixiang/guacd:latest
name: guacd
resources: {}
volumeMounts:
- mountPath: /usr/local/next-terminal/data
name: guacd-claim0
restartPolicy: Always
volumes:
- name: guacd-claim0
persistentVolumeClaim:
claimName: guacd-claim0
status: {}
+19
View File
@@ -0,0 +1,19 @@
apiVersion: v1
kind: Service
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: guacd
name: guacd
spec:
ports:
- name: "4822"
port: 4822
targetPort: 4822
selector:
io.kompose.service: guacd
status:
loadBalancer: {}
@@ -0,0 +1,15 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
creationTimestamp: null
labels:
io.kompose.service: mysql-claim0
name: mysql-claim0
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: cbs-next-terminal
status: {}
@@ -0,0 +1,48 @@
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: mysql
name: mysql
spec:
replicas: 1
selector:
matchLabels:
io.kompose.service: mysql
strategy:
type: Recreate
template:
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: mysql
spec:
containers:
- env:
- name: MYSQL_DATABASE
value: next-terminal
- name: MYSQL_PASSWORD
value: next-terminal
- name: MYSQL_ROOT_PASSWORD
value: next-terminal
- name: MYSQL_USER
value: next-terminal
image: mysql:8.0
name: mysql
resources: {}
volumeMounts:
- mountPath: /var/lib/mysql
name: mysql-claim0
restartPolicy: Always
volumes:
- name: mysql-claim0
persistentVolumeClaim:
claimName: mysql-claim0
status: {}
+19
View File
@@ -0,0 +1,19 @@
apiVersion: v1
kind: Service
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: mysql
name: mysql
spec:
ports:
- name: "3306"
port: 3306
targetPort: 3306
selector:
io.kompose.service: mysql
status:
loadBalancer: {}
@@ -0,0 +1,15 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
creationTimestamp: null
labels:
io.kompose.service: next-terminal-claim0
name: next-terminal-claim0
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: cbs-next-terminal
status: {}
@@ -0,0 +1,15 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
creationTimestamp: null
labels:
io.kompose.service: next-terminal-claim1
name: next-terminal-claim1
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: cbs-next-terminal
status: {}
@@ -0,0 +1,63 @@
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: next-terminal
name: next-terminal
spec:
replicas: 1
selector:
matchLabels:
io.kompose.service: next-terminal
strategy:
type: Recreate
template:
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: next-terminal
spec:
containers:
- env:
- name: DB
value: mysql
- name: GUACD_HOSTNAME
value: guacd
- name: GUACD_PORT
value: "4822"
- name: MYSQL_DATABASE
value: next-terminal
- name: MYSQL_HOSTNAME
value: mysql
- name: MYSQL_PASSWORD
value: next-terminal
- name: MYSQL_PORT
value: "3306"
- name: MYSQL_USERNAME
value: next-terminal
image: dushixiang/next-terminal:latest
name: next-terminal
ports:
- containerPort: 8088
resources: {}
volumeMounts:
- mountPath: /etc
name: next-terminal-claim0
- mountPath: /usr/local/next-terminal/data
name: next-terminal-claim1
restartPolicy: Always
volumes:
- name: next-terminal-claim0
persistentVolumeClaim:
claimName: next-terminal-claim0
- name: next-terminal-claim1
persistentVolumeClaim:
claimName: next-terminal-claim1
status: {}
@@ -0,0 +1,19 @@
apiVersion: v1
kind: Service
metadata:
annotations:
kompose.cmd: kompose convert
kompose.version: 1.26.1 (a9d05d509)
creationTimestamp: null
labels:
io.kompose.service: next-terminal
name: next-terminal
spec:
ports:
- name: "8088"
port: 8088
targetPort: 8088
selector:
io.kompose.service: next-terminal
status:
loadBalancer: {}
+10
View File
@@ -0,0 +1,10 @@
kubectl apply -f mysql-claim0-persistentvolumeclaim.yaml -n next-terminal
kubectl apply -f mysql-deployment.yaml -n next-terminal
kubectl apply -f mysql-service.yaml -n next-terminal
kubectl apply -f guacd-claim0-persistentvolumeclaim.yaml -n next-terminal
kubectl apply -f guacd-deployment.yaml -n next-terminal
kubectl apply -f guacd-service.yaml -n next-terminal
kubectl apply -f next-terminal-claim0-persistentvolumeclaim.yaml -n next-terminal
kubectl apply -f next-terminal-claim1-persistentvolumeclaim.yaml -n next-terminal
kubectl apply -f next-terminal-deployment.yaml -n next-terminal
kubectl apply -f next-terminal-service.yaml -n next-terminal
+11
View File
@@ -0,0 +1,11 @@
kubectl delete -f mysql-service.yaml -n next-terminal
kubectl delete -f mysql-deployment.yaml -n next-terminal
kubectl delete -f mysql-claim0-persistentvolumeclaim.yaml -n next-terminal
kubectl delete -f guacd-service.yaml -n next-terminal
kubectl delete -f guacd-deployment.yaml -n next-terminal
kubectl delete -f guacd-claim0-persistentvolumeclaim.yaml -n next-terminal
kubectl delete -f next-terminal-service.yaml -n next-terminal
kubectl delete -f next-terminal-deployment.yaml -n next-terminal
kubectl delete -f next-terminal-claim0-persistentvolumeclaim.yaml -n next-terminal
kubectl delete -f next-terminal-claim1-persistentvolumeclaim.yaml -n next-terminal
+32
View File
@@ -0,0 +1,32 @@
version: '3.3'
services:
guacd:
image: dushixiang/guacd:latest
environment:
GUACD_LOG_LEVEL: debug
volumes:
- ../data:/usr/local/next-terminal/data
ports:
- "4822:4822"
restart:
always
mysql:
image: mysql:8.0
environment:
MYSQL_DATABASE: next-terminal
MYSQL_USER: next-terminal
MYSQL_PASSWORD: next-terminal
MYSQL_ROOT_PASSWORD: next-terminal
volumes:
- ../data/mysql:/var/lib/mysql
ports:
- "3306:3306"
restart:
always
networks:
next-terminal:
ipam:
driver: default
config:
- subnet: 172.77.77.0/24
+70
View File
@@ -0,0 +1,70 @@
package abi
import (
"github.com/labstack/echo/v4"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/dto"
"next-terminal/server/global/cache"
"next-terminal/server/model"
)
type Abi struct {
}
func (r *Abi) Fail(c echo.Context, code int, message string) error {
return c.JSON(200, maps.Map{
"code": code,
"message": message,
})
}
func (r *Abi) FailWithData(c echo.Context, code int, message string, data interface{}) error {
return c.JSON(200, maps.Map{
"code": code,
"message": message,
"data": data,
})
}
func (r *Abi) Success(c echo.Context, data interface{}) error {
return c.JSON(200, maps.Map{
"code": 1,
"message": "success",
"data": data,
})
}
func (r *Abi) GetToken(c echo.Context) string {
token := c.Request().Header.Get(nt.Token)
if len(token) > 0 {
return token
}
return c.QueryParam(nt.Token)
}
func (r *Abi) GetCurrentAccount(c echo.Context) (*model.User, bool) {
token := r.GetToken(c)
get, b := cache.TokenManager.Get(token)
if b {
return get.(dto.Authorization).User, true
}
return nil, false
}
func (r *Abi) HasPermission(c echo.Context, owner string) bool {
// 检测是否登录
account, found := r.GetCurrentAccount(c)
if !found {
return false
}
// 检测是否为管理人员
if nt.TypeAdmin == account.Type {
return true
}
// 检测是否为所有者
if owner == account.ID {
return true
}
return false
}
+117
View File
@@ -0,0 +1,117 @@
package api
import (
"context"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"strconv"
"strings"
"next-terminal/server/global/gateway"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type AccessGatewayApi struct{}
func (api AccessGatewayApi) AccessGatewayCreateEndpoint(c echo.Context) error {
var item model.AccessGateway
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
if err := repository.GatewayRepository.Create(context.TODO(), &item); err != nil {
return err
}
// 连接网关
service.GatewayService.ReLoad(&item)
return Success(c, "")
}
func (api AccessGatewayApi) AccessGatewayAllEndpoint(c echo.Context) error {
gateways, err := repository.GatewayRepository.FindAll(context.TODO())
if err != nil {
return err
}
items := make([]maps.Map, len(gateways))
for i, e := range gateways {
items[i] = maps.Map{
"id": e.ID,
"name": e.Name,
}
}
return Success(c, items)
}
func (api AccessGatewayApi) AccessGatewayPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
ip := c.QueryParam("ip")
name := c.QueryParam("name")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.GatewayRepository.Find(context.TODO(), pageIndex, pageSize, ip, name, order, field)
if err != nil {
return err
}
for i := 0; i < len(items); i++ {
g := gateway.GlobalGatewayManager.GetById(items[i].ID)
if g != nil {
items[i].Connected = g.Connected
items[i].Message = g.Message
}
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api AccessGatewayApi) AccessGatewayUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.AccessGateway
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.GatewayRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
service.GatewayService.ReLoad(&item)
return Success(c, nil)
}
func (api AccessGatewayApi) AccessGatewayDeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
for i := range split {
id := split[i]
if err := repository.GatewayRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
service.GatewayService.DisconnectById(id)
}
return Success(c, nil)
}
func (api AccessGatewayApi) AccessGatewayGetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.GatewayRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
+44
View File
@@ -0,0 +1,44 @@
package api
import (
"next-terminal/server/common/maps"
"github.com/labstack/echo/v4"
)
type AccessSettingApi struct{}
func (api AccessSettingApi) GetEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"fontSize": "14",
"lineHeight": "1.5",
"fontFamily": "JetBrains Mono, Consolas, monospace",
"selectionCopy": "true",
"rightClickPaste": "true",
"treeExpandedKeys": "",
"useSnippets": "true",
"interceptSearchShortcut": "false",
})
}
func (api AccessSettingApi) SetEndpoint(c echo.Context) error {
var req map[string]interface{}
if err := c.Bind(&req); err != nil {
return err
}
_ = req
return Success(c, nil)
}
func (api AccessSettingApi) ShellAssistantEnabledEndpoint(c echo.Context) error {
return Success(c, maps.Map{"enabled": false})
}
func (api AccessSettingApi) ShellAssistantEndpoint(c echo.Context) error {
c.Response().Header().Set("Content-Type", "text/event-stream")
c.Response().Header().Set("Cache-Control", "no-cache")
c.Response().Header().Set("Connection", "keep-alive")
c.Response().Write([]byte("data: {\"success\":false,\"error\":\"Shell assistant is not configured\"}\n\n"))
return nil
}
+456
View File
@@ -0,0 +1,456 @@
package api
import (
"context"
"errors"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"path"
"strings"
"next-terminal/server/config"
"next-terminal/server/dto"
"next-terminal/server/global/cache"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
type AccountApi struct{}
func (api AccountApi) LoginEndpoint(c echo.Context) error {
var loginAccount dto.LoginAccount
if err := c.Bind(&loginAccount); err != nil {
return err
}
// 存储登录失败次数信息
loginFailCountKey := c.RealIP() + loginAccount.Username
v, ok := cache.LoginFailedKeyManager.Get(loginFailCountKey)
if !ok {
v = 1
}
count := v.(int)
if count >= 5 {
return Fail(c, -1, "登录失败次数过多,请等待5分钟后再试")
}
if len(loginAccount.Password) > 100 {
return Fail(c, -1, "您输入的密码过长")
}
user, err := repository.UserRepository.FindByUsername(context.TODO(), loginAccount.Username)
if err != nil {
count++
cache.LoginFailedKeyManager.Set(loginFailCountKey, count, cache.LoginLockExpiration)
// 保存登录日志
if err := service.UserService.SaveLoginLog(c.RealIP(), c.Request().UserAgent(), loginAccount.Username, false, loginAccount.Remember, "", "账号或密码不正确"); err != nil {
return err
}
return FailWithData(c, -1, "您输入的账号或密码不正确", count)
}
if user.Status == nt.StatusDisabled {
return Fail(c, -1, "该账户已停用")
}
if err := utils.Encoder.Match([]byte(user.Password), []byte(loginAccount.Password)); err != nil {
count++
cache.LoginFailedKeyManager.Set(loginFailCountKey, count, cache.LoginLockExpiration)
// 保存登录日志
if err := service.UserService.SaveLoginLog(c.RealIP(), c.Request().UserAgent(), loginAccount.Username, false, loginAccount.Remember, "", "账号或密码不正确"); err != nil {
return err
}
return FailWithData(c, -1, "您输入的账号或密码不正确", count)
}
// 账号密码正确,需要进行两步验证
if user.TOTPSecret != "" && user.TOTPSecret != "-" {
if loginAccount.TOTP == "" {
return Fail(c, 100, "")
} else {
if !common.Validate(loginAccount.TOTP, user.TOTPSecret) {
count++
cache.LoginFailedKeyManager.Set(loginFailCountKey, count, cache.LoginLockExpiration)
// 保存登录日志
if err := service.UserService.SaveLoginLog(c.RealIP(), c.Request().UserAgent(), loginAccount.Username, false, loginAccount.Remember, "", "双因素认证授权码不正确"); err != nil {
return err
}
return FailWithData(c, -1, "您输入双因素认证授权码不正确", count)
}
}
}
token, err := api.LoginSuccess(loginAccount, user, c.RealIP())
if err != nil {
return err
}
// 保存登录日志
if err := service.UserService.SaveLoginLog(c.RealIP(), c.Request().UserAgent(), loginAccount.Username, true, loginAccount.Remember, token, ""); err != nil {
return err
}
var menuStrings []string
if service.UserService.IsSuperAdmin(user.ID) {
menuStrings = service.MenuService.GetMenus()
} else {
roles, err := service.RoleService.GetRolesByUserId(user.ID)
if err != nil {
return err
}
for _, role := range roles {
items := service.RoleService.GetMenuListByRole(role)
menuStrings = append(menuStrings, items...)
}
}
var menus []UserMenu
for _, m := range menuStrings {
menus = append(menus, UserMenu{
Key: m,
Checked: true,
})
}
info := AccountInfo{
Id: user.ID,
Username: user.Username,
Nickname: user.Nickname,
Type: user.Type,
EnableTotp: user.TOTPSecret != "" && user.TOTPSecret != "-",
Roles: user.Roles,
Menus: menus,
}
return Success(c, maps.Map{
"info": info,
"token": token,
})
}
func (api AccountApi) LoginSuccess(loginAccount dto.LoginAccount, user model.User, ip string) (string, error) {
// 判断当前时间是否允许该用户登录
if err := service.LoginPolicyService.Check(user.ID, ip); err != nil {
return "", err
}
token := utils.LongUUID()
authorization := dto.Authorization{
Token: token,
Type: nt.LoginToken,
Remember: loginAccount.Remember,
User: &user,
}
if authorization.Remember {
// 记住登录有效期两周
cache.TokenManager.Set(token, authorization, cache.RememberMeExpiration)
} else {
cache.TokenManager.Set(token, authorization, cache.NotRememberExpiration)
}
b := true
// 修改登录状态
err := repository.UserRepository.Update(context.TODO(), &model.User{Online: &b, ID: user.ID})
return token, err
}
func (api AccountApi) LogoutEndpoint(c echo.Context) error {
token := GetToken(c)
service.UserService.Logout(token)
return Success(c, nil)
}
func (api AccountApi) ConfirmTOTPEndpoint(c echo.Context) error {
if config.GlobalCfg.Demo {
return Fail(c, 0, "演示模式禁止开启两步验证")
}
account, _ := GetCurrentAccount(c)
var confirmTOTP dto.ConfirmTOTP
if err := c.Bind(&confirmTOTP); err != nil {
return err
}
if !common.Validate(confirmTOTP.TOTP, confirmTOTP.Secret) {
return Fail(c, -1, "TOTP 验证失败,请重试")
}
u := &model.User{
TOTPSecret: confirmTOTP.Secret,
ID: account.ID,
}
if err := repository.UserRepository.Update(context.TODO(), u); err != nil {
return err
}
return Success(c, nil)
}
func (api AccountApi) ReloadTOTPEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
key, err := common.NewTOTP(common.GenerateOpts{
Issuer: c.Request().Host,
AccountName: account.Username,
})
if err != nil {
return Fail(c, -1, err.Error())
}
qrcode, err := key.Image(200, 200)
if err != nil {
return Fail(c, -1, err.Error())
}
qrEncode, err := utils.ImageToBase64Encode(qrcode)
if err != nil {
return Fail(c, -1, err.Error())
}
return Success(c, map[string]string{
"qr": qrEncode,
"secret": key.Secret(),
})
}
func (api AccountApi) ResetTOTPEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
u := &model.User{
TOTPSecret: "-",
ID: account.ID,
}
if err := repository.UserRepository.Update(context.TODO(), u); err != nil {
return err
}
return Success(c, "")
}
func (api AccountApi) ChangePasswordEndpoint(c echo.Context) error {
if config.GlobalCfg.Demo {
return Fail(c, 0, "演示模式禁止修改密码")
}
account, _ := GetCurrentAccount(c)
var changePassword dto.ChangePassword
if err := c.Bind(&changePassword); err != nil {
return err
}
if len(changePassword.NewPassword) > 100 {
return Fail(c, -1, "您输入的密码过长")
}
if err := utils.Encoder.Match([]byte(account.Password), []byte(changePassword.OldPassword)); err != nil {
return Fail(c, -1, "您输入的原密码不正确")
}
passwd, err := utils.Encoder.Encode([]byte(changePassword.NewPassword))
if err != nil {
return err
}
u := &model.User{
Password: string(passwd),
ID: account.ID,
}
if err := repository.UserRepository.Update(context.TODO(), u); err != nil {
return err
}
return api.LogoutEndpoint(c)
}
type AccountInfo struct {
Id string `json:"id"`
Username string `json:"username"`
Nickname string `json:"nickname"`
Type string `json:"type"`
EnableTotp bool `json:"enableTotp"`
Roles []string `json:"roles"`
Menus []UserMenu `json:"menus"`
}
type UserMenu struct {
Key string `json:"key"`
Checked bool `json:"checked"`
}
func (api AccountApi) InfoEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
if strings.EqualFold("anonymous", account.Type) {
return Success(c, account)
}
user, err := service.UserService.FindById(account.ID)
if err != nil {
return err
}
var menuStrings []string
if service.UserService.IsSuperAdmin(account.ID) {
menuStrings = service.MenuService.GetMenus()
} else {
roles, err := service.RoleService.GetRolesByUserId(account.ID)
if err != nil {
return err
}
for _, role := range roles {
items := service.RoleService.GetMenuListByRole(role)
menuStrings = append(menuStrings, items...)
}
}
var menus []UserMenu
for _, m := range menuStrings {
menus = append(menus, UserMenu{
Key: m,
Checked: true,
})
}
info := AccountInfo{
Id: user.ID,
Username: user.Username,
Nickname: user.Nickname,
Type: user.Type,
EnableTotp: user.TOTPSecret != "" && user.TOTPSecret != "-",
Roles: user.Roles,
Menus: menus,
}
return Success(c, info)
}
func (api AccountApi) MenuEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
if service.UserService.IsSuperAdmin(account.ID) {
items := service.MenuService.GetMenus()
return Success(c, items)
}
roles, err := service.RoleService.GetRolesByUserId(account.ID)
if err != nil {
return err
}
var menus []string
for _, role := range roles {
items := service.RoleService.GetMenuListByRole(role)
menus = append(menus, items...)
}
return Success(c, menus)
}
func (api AccountApi) AccountStorageEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
storageId := account.ID
storage, err := repository.StorageRepository.FindById(context.TODO(), storageId)
if err != nil {
return err
}
structMap := utils.StructToMap(storage)
drivePath := service.StorageService.GetBaseDrivePath()
dirSize, err := utils.DirSize(path.Join(drivePath, storageId))
if err != nil {
structMap["usedSize"] = -1
} else {
structMap["usedSize"] = dirSize
}
return Success(c, structMap)
}
func (api AccountApi) AccessTokenGetEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
accessTokens, err := repository.AccessTokenRepository.FindByUserId(context.TODO(), account.ID)
if err != nil {
if errors.Is(gorm.ErrRecordNotFound, err) {
accessTokens = []model.AccessToken{}
} else {
return err
}
}
return Success(c, accessTokens)
}
func (api AccountApi) AccessTokenGenEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
var req struct {
Type string `json:"type"`
}
c.Bind(&req)
if req.Type == "" {
req.Type = "api"
}
accessToken, err := service.AccessTokenService.GenAccessToken(account.ID, req.Type)
if err != nil {
return err
}
return Success(c, accessToken)
}
func (api AccountApi) AccessTokenDelEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
id := c.Param("id")
if err := service.AccessTokenService.DelAccessToken(context.Background(), id, account.ID); err != nil {
return err
}
return Success(c, nil)
}
func (api AccountApi) SecurityTokenSupportTypesEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
user, err := repository.UserRepository.FindById(context.TODO(), account.ID)
if err != nil {
return err
}
var types []string
if user.TOTPSecret != "" && user.TOTPSecret != "-" {
types = append(types, "otp")
}
if len(types) == 0 {
types = []string{}
}
return Success(c, types)
}
func (api AccountApi) SecurityTokenMfaEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
passcode := c.QueryParam("passcode")
user, err := repository.UserRepository.FindById(context.TODO(), account.ID)
if err != nil {
return err
}
if user.TOTPSecret == "" || user.TOTPSecret == "-" {
return Fail(c, -1, "MFA not enabled")
}
if !common.Validate(passcode, user.TOTPSecret) {
return Fail(c, -1, "Invalid passcode")
}
token := utils.UUID()
cache.TokenManager.Set(token, account.ID, cache.NotRememberExpiration)
return Success(c, maps.Map{"token": token})
}
func (api AccountApi) SecurityTokenValidateEndpoint(c echo.Context) error {
token := c.QueryParam("securityToken")
if token == "" {
return Success(c, maps.Map{"ok": false})
}
_, ok := cache.TokenManager.Get(token)
return Success(c, maps.Map{"ok": ok})
}
+137
View File
@@ -0,0 +1,137 @@
package api
import (
"context"
"strconv"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type AgentGatewayApi struct{}
func (api AgentGatewayApi) AllEndpoint(c echo.Context) error {
items, err := repository.AgentGatewayRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api AgentGatewayApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
items, total, err := repository.AgentGatewayRepository.Find(context.TODO(), pageIndex, pageSize, name)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api AgentGatewayApi) CreateEndpoint(c echo.Context) error {
var item model.AgentGateway
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Online = false
if err := repository.AgentGatewayRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api AgentGatewayApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.AgentGateway
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.AgentGatewayRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, nil)
}
func (api AgentGatewayApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.AgentGatewayRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
return Success(c, nil)
}
func (api AgentGatewayApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.AgentGatewayRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api AgentGatewayApi) GetRegisterParamEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"endpoint": "",
"token": "",
})
}
func (api AgentGatewayApi) SetRegisterAddrEndpoint(c echo.Context) error {
endpoint := c.QueryParam("endpoint")
_ = endpoint
return Success(c, nil)
}
func (api AgentGatewayApi) GetStatEndpoint(c echo.Context) error {
id := c.Param("id")
_, err := repository.AgentGatewayRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, maps.Map{
"ping": 0,
"cpu": maps.Map{"percent": 0},
"memory": maps.Map{"percent": 0},
"disk": maps.Map{"percent": 0},
"network": maps.Map{},
"load": maps.Map{},
"host": maps.Map{},
"process": maps.Map{"total": 0},
"connections": 0,
"tcp_states": []string{},
"errors": maps.Map{},
})
}
func (api AgentGatewayApi) UpdateSortEndpoint(c echo.Context) error {
var items []struct {
ID string `json:"id"`
SortOrder int `json:"sortOrder"`
}
if err := c.Bind(&items); err != nil {
return err
}
ctx := context.TODO()
for _, item := range items {
sortStr := strconv.Itoa(item.SortOrder * 100)
repository.AgentGatewayRepository.UpdateSort(ctx, item.ID, sortStr)
}
return Success(c, nil)
}
func (api AgentGatewayApi) VersionEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"version": "1.0.0",
})
}
+50
View File
@@ -0,0 +1,50 @@
package api
import (
"github.com/labstack/echo/v4"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/dto"
"next-terminal/server/global/cache"
"next-terminal/server/model"
)
func Fail(c echo.Context, code int, message string) error {
return c.JSON(200, maps.Map{
"code": code,
"message": message,
})
}
func FailWithData(c echo.Context, code int, message string, data interface{}) error {
return c.JSON(200, maps.Map{
"code": code,
"message": message,
"data": data,
})
}
func Success(c echo.Context, data interface{}) error {
return c.JSON(200, maps.Map{
"code": 1,
"message": "success",
"data": data,
})
}
func GetToken(c echo.Context) string {
token := c.Request().Header.Get(nt.Token)
if len(token) > 0 {
return token
}
return c.QueryParam(nt.Token)
}
func GetCurrentAccount(c echo.Context) (*model.User, bool) {
token := GetToken(c)
get, b := cache.TokenManager.Get(token)
if b {
return get.(dto.Authorization).User, true
}
return nil, false
}
+280
View File
@@ -0,0 +1,280 @@
package api
import (
"bufio"
"context"
"encoding/csv"
"errors"
"strconv"
"strings"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/global/cache"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type AssetApi struct{}
func (assetApi AssetApi) AssetCreateEndpoint(c echo.Context) error {
m := maps.Map{}
if err := c.Bind(&m); err != nil {
return err
}
account, _ := GetCurrentAccount(c)
m["owner"] = account.ID
if _, err := service.AssetService.Create(context.TODO(), m); err != nil {
return err
}
return Success(c, nil)
}
func (assetApi AssetApi) AssetImportEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
file, err := c.FormFile("file")
if err != nil {
return err
}
src, err := file.Open()
if err != nil {
return err
}
defer func() {
_ = src.Close()
}()
reader := csv.NewReader(bufio.NewReader(src))
records, err := reader.ReadAll()
if err != nil {
return err
}
total := len(records)
if total == 0 {
return errors.New("csv数据为空")
}
var successCount = 0
var errorCount = 0
m := echo.Map{}
for i := 0; i < total; i++ {
record := records[i]
if len(record) >= 9 {
port, _ := strconv.Atoi(record[3])
asset := maps.Map{
"id": utils.UUID(),
"name": record[0],
"protocol": record[1],
"ip": record[2],
"port": port,
"accountType": nt.Custom,
"username": record[4],
"password": record[5],
"privateKey": record[6],
"passphrase": record[7],
"Description": record[8],
"owner": account.ID,
}
if record[6] != "" {
asset["accountType"] = nt.PrivateKey
}
if len(record) >= 10 {
tags := strings.ReplaceAll(record[9], "|", ",")
asset["tags"] = tags
}
_, err := service.AssetService.Create(context.Background(), asset)
if err != nil {
errorCount++
m[strconv.Itoa(i)] = err.Error()
} else {
successCount++
}
}
}
return Success(c, echo.Map{
"successCount": successCount,
"errorCount": errorCount,
"data": m,
})
}
func (assetApi AssetApi) AssetPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("keyword")
if name == "" {
name = c.QueryParam("name")
}
protocol := c.QueryParam("protocol")
tags := c.QueryParam("tags")
ip := c.QueryParam("ip")
port := c.QueryParam("port")
active := c.QueryParam("active")
order := c.QueryParam("sortOrder")
if order == "" {
order = c.QueryParam("order")
}
field := c.QueryParam("sortField")
if field == "" {
field = c.QueryParam("field")
}
items, total, err := repository.AssetRepository.Find(context.Background(), pageIndex, pageSize, name, protocol, tags, ip, port, active, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (assetApi AssetApi) AssetAllEndpoint(c echo.Context) error {
protocol := c.QueryParam("protocol")
assets, err := repository.AssetRepository.FindByProtocol(context.TODO(), protocol)
if err != nil {
return err
}
items := make([]maps.Map, len(assets))
for i, e := range assets {
items[i] = maps.Map{
"id": e.ID,
"name": e.Name,
}
}
return Success(c, items)
}
func (assetApi AssetApi) AssetUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
m := maps.Map{}
if err := c.Bind(&m); err != nil {
return err
}
if err := service.AssetService.UpdateById(id, m); err != nil {
return err
}
return Success(c, nil)
}
func (assetApi AssetApi) AssetDeleteEndpoint(c echo.Context) error {
id := c.Param("id")
split := strings.Split(id, ",")
for i := range split {
if err := service.AssetService.DeleteById(split[i]); err != nil {
return err
}
}
return Success(c, nil)
}
func (assetApi AssetApi) AssetGetEndpoint(c echo.Context) (err error) {
id := c.Param("id")
var item model.Asset
if item, err = service.AssetService.FindByIdAndDecrypt(context.TODO(), id); err != nil {
return err
}
attributeMap, err := repository.AssetRepository.FindAssetAttrMapByAssetId(context.TODO(), id)
if err != nil {
return err
}
itemMap := utils.StructToMap(item)
for key := range attributeMap {
itemMap[key] = attributeMap[key]
}
return Success(c, itemMap)
}
func (assetApi AssetApi) AssetDecryptedEndpoint(c echo.Context) (err error) {
id := c.Param("id")
securityToken := c.QueryParam("securityToken")
account, _ := GetCurrentAccount(c)
user, err := repository.UserRepository.FindById(context.TODO(), account.ID)
if err != nil {
return err
}
// 如果用户启用了 MFA,需要验证 securityToken
if user.TOTPSecret != "" && user.TOTPSecret != "-" {
if securityToken == "" {
return Fail(c, -1, "需要MFA验证")
}
_, ok := cache.TokenManager.Get(securityToken)
if !ok {
return Fail(c, -1, "MFA验证已过期,请重新验证")
}
}
var item model.Asset
if item, err = service.AssetService.FindByIdAndDecrypt(context.TODO(), id); err != nil {
return err
}
return Success(c, maps.Map{
"password": item.Password,
"privateKey": item.PrivateKey,
"passphrase": item.Passphrase,
})
}
func (assetApi AssetApi) AssetTcpingEndpoint(c echo.Context) (err error) {
id := c.Param("id")
var item model.Asset
if item, err = repository.AssetRepository.FindById(context.TODO(), id); err != nil {
return err
}
active, err := service.AssetService.CheckStatus(&item, item.IP, item.Port)
var message = ""
if err != nil {
message = err.Error()
}
if err := repository.AssetRepository.UpdateActiveById(context.TODO(), active, message, item.ID); err != nil {
return err
}
return Success(c, maps.Map{
"active": active,
"message": message,
})
}
func (assetApi AssetApi) AssetTagsEndpoint(c echo.Context) (err error) {
var items []string
if items, err = repository.AssetRepository.FindTags(context.TODO()); err != nil {
return err
}
return Success(c, items)
}
func (assetApi AssetApi) AssetChangeOwnerEndpoint(c echo.Context) (err error) {
id := c.Param("id")
owner := c.QueryParam("owner")
if err := repository.AssetRepository.UpdateById(context.TODO(), &model.Asset{Owner: owner}, id); err != nil {
return err
}
return Success(c, "")
}
+216
View File
@@ -0,0 +1,216 @@
package api
import (
"context"
"strconv"
"time"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type AssetGroupApi struct{}
func (api AssetGroupApi) GroupsGetEndpoint(c echo.Context) error {
groups, err := repository.AssetGroupRepository.FindAll(context.TODO())
if err != nil {
return err
}
tree := buildGroupTree(groups, "")
return Success(c, tree)
}
func (api AssetGroupApi) GroupsSetEndpoint(c echo.Context) error {
var req []map[string]interface{}
if err := c.Bind(&req); err != nil {
return err
}
ctx := context.TODO()
repository.AssetGroupRepository.DeleteByParentId(ctx, "")
for i, item := range req {
group := model.AssetGroup{
ID: utils.UUID(),
Name: item["name"].(string),
ParentId: "",
Sort: i,
Created: time.Now().UnixMilli(),
}
repository.AssetGroupRepository.Create(ctx, &group)
if children, ok := item["children"].([]interface{}); ok {
saveChildren(ctx, children, group.ID)
}
}
return Success(c, nil)
}
func (api AssetGroupApi) GroupsDeleteEndpoint(c echo.Context) error {
id := c.Param("id")
ctx := context.TODO()
repository.AssetGroupRepository.DeleteByParentId(ctx, id)
repository.AssetGroupRepository.DeleteById(ctx, id)
return Success(c, nil)
}
func saveChildren(ctx context.Context, children []interface{}, parentId string) {
for i, item := range children {
m := item.(map[string]interface{})
group := model.AssetGroup{
ID: utils.UUID(),
Name: m["name"].(string),
ParentId: parentId,
Sort: i,
Created: time.Now().UnixMilli(),
}
repository.AssetGroupRepository.Create(ctx, &group)
if subChildren, ok := m["children"].([]interface{}); ok {
saveChildren(ctx, subChildren, group.ID)
}
}
}
func buildGroupTree(groups []model.AssetGroup, parentId string) []maps.Map {
var tree []maps.Map
for _, g := range groups {
if g.ParentId == parentId {
node := maps.Map{
"id": g.ID,
"name": g.Name,
"title": g.Name,
"key": g.ID,
"value": g.ID,
}
children := buildGroupTree(groups, g.ID)
if len(children) > 0 {
node["children"] = children
}
tree = append(tree, node)
}
}
return tree
}
func (api AssetGroupApi) TreeEndpoint(c echo.Context) error {
protocol := c.QueryParam("protocol")
assets, err := repository.AssetRepository.FindByProtocol(context.TODO(), protocol)
if err != nil {
return err
}
groups, err := repository.AssetGroupRepository.FindAll(context.TODO())
if err != nil {
return err
}
tree := buildAssetTree(assets, groups, "")
return Success(c, tree)
}
func buildAssetTree(assets []model.Asset, groups []model.AssetGroup, groupId string) []maps.Map {
var nodes []maps.Map
var groupAssets []model.Asset
for _, a := range assets {
groupAssets = append(groupAssets, a)
}
for _, a := range groupAssets {
nodes = append(nodes, maps.Map{
"id": a.ID,
"name": a.Name,
"key": a.ID,
"isLeaf": true,
"protocol": a.Protocol,
"ip": a.IP,
"port": a.Port,
})
}
for _, g := range groups {
if g.ParentId == groupId {
node := maps.Map{
"id": g.ID,
"name": g.Name,
"key": g.ID,
}
children := buildAssetTree(assets, groups, g.ID)
if len(children) > 0 {
node["children"] = children
}
nodes = append(nodes, node)
}
}
return nodes
}
func (api AssetGroupApi) ChangeGroupEndpoint(c echo.Context) error {
var req map[string]interface{}
if err := c.Bind(&req); err != nil {
return err
}
assetIds, _ := req["assetIds"].([]interface{})
groupId, _ := req["groupId"].(string)
ctx := context.TODO()
for _, id := range assetIds {
aid := id.(string)
repository.AssetRepository.UpdateById(ctx, &model.Asset{ID: aid}, aid)
}
_ = groupId
return Success(c, nil)
}
func (api AssetGroupApi) ChangeGatewayEndpoint(c echo.Context) error {
var req map[string]interface{}
if err := c.Bind(&req); err != nil {
return err
}
gatewayType, _ := req["gatewayType"].(string)
gatewayId, _ := req["gatewayId"].(string)
assetIds, _ := req["assetIds"].([]interface{})
ctx := context.TODO()
for _, id := range assetIds {
aid := id.(string)
m := maps.Map{}
if gatewayType == "ssh" {
m["access_gateway_id"] = gatewayId
} else if gatewayType == "agent" {
m["access_gateway_id"] = gatewayId
} else {
m["access_gateway_id"] = ""
}
repository.AssetRepository.UpdateById(ctx, &model.Asset{ID: aid}, aid)
_ = m
}
_ = gatewayType
_ = gatewayId
return Success(c, nil)
}
func (api AssetGroupApi) SortEndpoint(c echo.Context) error {
var req struct {
Id string `json:"id"`
BeforeId string `json:"beforeId"`
AfterId string `json:"afterId"`
}
if err := c.Bind(&req); err != nil {
return err
}
ctx := context.TODO()
all, _ := repository.AssetRepository.FindAll(ctx)
beforeSort := 0
afterSort := 0
for _, a := range all {
if a.ID == req.BeforeId {
beforeSort = a.Sort
}
if a.ID == req.AfterId {
afterSort = a.Sort
}
}
newSort := (beforeSort + afterSort) / 2
if newSort == 0 {
newSort = beforeSort + 1
}
sortStr := strconv.Itoa(newSort)
repository.AssetRepository.UpdateById(ctx, &model.Asset{ID: req.Id, Sort: newSort}, req.Id)
_ = sortStr
return Success(c, nil)
}
+136
View File
@@ -0,0 +1,136 @@
package api
import (
"context"
"github.com/labstack/echo/v4"
"next-terminal/server/common/maps"
"next-terminal/server/dto"
"next-terminal/server/repository"
"next-terminal/server/service"
"strconv"
)
type AuthorisedApi struct {
}
func (api AuthorisedApi) Selected(c echo.Context) error {
userId := c.QueryParam("userId")
userGroupId := c.QueryParam("userGroupId")
assetId := c.QueryParam("assetId")
key := c.QueryParam("key")
items, err := repository.AuthorisedRepository.FindAll(context.Background(), userId, userGroupId, assetId)
if err != nil {
return err
}
var result = make([]string, 0)
switch key {
case "userId":
for _, item := range items {
result = append(result, item.UserId)
}
case "userGroupId":
for _, item := range items {
result = append(result, item.UserGroupId)
}
case "assetId":
for _, item := range items {
result = append(result, item.AssetId)
}
}
return Success(c, result)
}
func (api AuthorisedApi) Delete(c echo.Context) error {
id := c.Param("id")
if err := repository.AuthorisedRepository.DeleteById(context.Background(), id); err != nil {
return err
}
return Success(c, "")
}
func (api AuthorisedApi) PagingAsset(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
assetName := c.QueryParam("assetName")
userId := c.QueryParam("userId")
userGroupId := c.QueryParam("userGroupId")
items, total, err := repository.AuthorisedRepository.FindAssetPage(context.Background(), pageIndex, pageSize, assetName, userId, userGroupId)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api AuthorisedApi) PagingUser(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
userName := c.QueryParam("userName")
assetId := c.QueryParam("assetId")
items, total, err := repository.AuthorisedRepository.FindUserPage(context.Background(), pageIndex, pageSize, userName, assetId)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api AuthorisedApi) PagingUserGroup(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
userGroupName := c.QueryParam("userGroupName")
assetId := c.QueryParam("assetId")
items, total, err := repository.AuthorisedRepository.FindUserGroupPage(context.Background(), pageIndex, pageSize, userGroupName, assetId)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api AuthorisedApi) AuthorisedAssets(c echo.Context) error {
var item dto.AuthorisedAsset
if err := c.Bind(&item); err != nil {
return err
}
if err := service.AuthorisedService.AuthorisedAssets(context.Background(), &item); err != nil {
return err
}
return Success(c, nil)
}
func (api AuthorisedApi) AuthorisedUsers(c echo.Context) error {
var item dto.AuthorisedUser
if err := c.Bind(&item); err != nil {
return err
}
if err := service.AuthorisedService.AuthorisedUsers(context.Background(), &item); err != nil {
return err
}
return Success(c, nil)
}
func (api AuthorisedApi) AuthorisedUserGroups(c echo.Context) error {
var item dto.AuthorisedUserGroup
if err := c.Bind(&item); err != nil {
return err
}
if err := service.AuthorisedService.AuthorisedUserGroups(context.Background(), &item); err != nil {
return err
}
return Success(c, nil)
}
+41
View File
@@ -0,0 +1,41 @@
package api
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"next-terminal/server/dto"
"next-terminal/server/service"
"github.com/labstack/echo/v4"
)
type BackupApi struct{}
func (api BackupApi) BackupExportEndpoint(c echo.Context) error {
err, backup := service.BackupService.Export()
if err != nil {
return err
}
jsonBytes, err := json.Marshal(backup)
if err != nil {
return err
}
c.Response().Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=backup_%s.json", time.Now().Format("20060102150405")))
return c.Stream(http.StatusOK, echo.MIMEOctetStream, bytes.NewReader(jsonBytes))
}
func (api BackupApi) BackupImportEndpoint(c echo.Context) error {
var backup dto.Backup
if err := c.Bind(&backup); err != nil {
return err
}
if err := service.BackupService.Import(&backup); err != nil {
return err
}
return Success(c, "")
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"context"
"embed"
"encoding/base64"
"io/fs"
"net/http"
"strings"
"next-terminal/server/branding"
"next-terminal/server/common/maps"
"next-terminal/server/repository"
"github.com/labstack/echo/v4"
)
//go:embed logos/*
var logoFS embed.FS
func Branding(c echo.Context) error {
properties := repository.PropertyRepository.FindAllMap(context.TODO())
name := branding.Name
if val, ok := properties["system-name"]; ok && val != "" && val != "-" {
name = val
}
copyright := branding.Copyright
if val, ok := properties["system-copyright"]; ok && val != "" && val != "-" {
copyright = val
}
icp := ""
if val, ok := properties["system-icp"]; ok && val != "" && val != "-" {
icp = val
}
return Success(c, maps.Map{
"name": name,
"copyright": copyright,
"icp": icp,
})
}
func Logo(c echo.Context) error {
properties := repository.PropertyRepository.FindAllMap(context.TODO())
if logo, ok := properties["system-logo"]; ok && logo != "" && logo != "-" {
if strings.HasPrefix(logo, "data:image/") {
parts := strings.SplitN(logo, ",", 2)
if len(parts) == 2 {
if imageData, err := base64.StdEncoding.DecodeString(parts[1]); err == nil {
contentType := "image/png"
if strings.Contains(parts[0], "image/jpeg") {
contentType = "image/jpeg"
} else if strings.Contains(parts[0], "image/gif") {
contentType = "image/gif"
} else if strings.Contains(parts[0], "image/svg") {
contentType = "image/svg+xml"
}
return c.Blob(http.StatusOK, contentType, imageData)
}
}
}
return c.Blob(http.StatusOK, "image/png", []byte(logo))
}
data, err := fs.ReadFile(logoFS, "logos/logo.png")
if err != nil {
return c.String(http.StatusNotFound, "Logo not found")
}
return c.Blob(http.StatusOK, "image/png", data)
}
+193
View File
@@ -0,0 +1,193 @@
package api
import (
"context"
"crypto/x509"
"encoding/pem"
"strconv"
"time"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type CertificateApi struct{}
func (api CertificateApi) AllEndpoint(c echo.Context) error {
items, err := repository.CertificateRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api CertificateApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
keyword := c.QueryParam("keyword")
items, total, err := repository.CertificateRepository.Find(context.TODO(), pageIndex, pageSize, keyword)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func parseCertificate(certPEM string) (commonName, subject, issuer string, notBefore, notAfter time.Time, err error) {
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return "", "", "", time.Time{}, time.Time{}, nil
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return "", "", "", time.Time{}, time.Time{}, err
}
commonName = cert.Subject.CommonName
if commonName == "" && len(cert.Subject.Names) > 0 {
commonName = cert.Subject.Names[0].Value.(string)
}
subject = cert.Subject.String()
issuer = cert.Issuer.String()
notBefore = cert.NotBefore
notAfter = cert.NotAfter
return commonName, subject, issuer, notBefore, notAfter, nil
}
func (api CertificateApi) CreateEndpoint(c echo.Context) error {
var req struct {
CommonName string `json:"commonName"`
Certificate string `json:"certificate"`
PrivateKey string `json:"privateKey"`
Type string `json:"type"`
RequireClientAuth bool `json:"requireClientAuth"`
}
if err := c.Bind(&req); err != nil {
return err
}
item := &model.Certificate{
ID: utils.UUID(),
CommonName: req.CommonName,
Certificate: req.Certificate,
PrivateKey: req.PrivateKey,
Type: req.Type,
RequireClientAuth: req.RequireClientAuth,
IssuedStatus: "success",
Created: common.NowJsonTime(),
UpdatedAt: common.NowJsonTime(),
}
if req.Certificate != "" {
commonName, subject, issuer, notBefore, notAfter, err := parseCertificate(req.Certificate)
if err == nil {
if item.CommonName == "" {
item.CommonName = commonName
}
item.Subject = subject
item.Issuer = issuer
item.NotBefore = common.NewJsonTime(notBefore)
item.NotAfter = common.NewJsonTime(notAfter)
}
}
if item.Type == "" {
item.Type = "imported"
}
if err := repository.CertificateRepository.Create(context.TODO(), item); err != nil {
return err
}
return Success(c, "")
}
func (api CertificateApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var req struct {
CommonName string `json:"commonName"`
Certificate string `json:"certificate"`
PrivateKey string `json:"privateKey"`
RequireClientAuth bool `json:"requireClientAuth"`
}
if err := c.Bind(&req); err != nil {
return err
}
item := &model.Certificate{
ID: id,
CommonName: req.CommonName,
Certificate: req.Certificate,
PrivateKey: req.PrivateKey,
RequireClientAuth: req.RequireClientAuth,
UpdatedAt: common.NowJsonTime(),
}
if req.Certificate != "" {
commonName, subject, issuer, notBefore, notAfter, err := parseCertificate(req.Certificate)
if err == nil {
if item.CommonName == "" {
item.CommonName = commonName
}
item.Subject = subject
item.Issuer = issuer
item.NotBefore = common.NewJsonTime(notBefore)
item.NotAfter = common.NewJsonTime(notAfter)
}
}
if err := repository.CertificateRepository.UpdateById(context.TODO(), item, id); err != nil {
return err
}
return Success(c, nil)
}
func (api CertificateApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.CertificateRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
return Success(c, nil)
}
func (api CertificateApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.CertificateRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api CertificateApi) UpdateDefaultEndpoint(c echo.Context) error {
id := c.Param("id")
err := repository.CertificateRepository.UpdateById(context.TODO(), &model.Certificate{IsDefault: false}, id)
if err != nil {
return err
}
return Success(c, nil)
}
func (api CertificateApi) DownloadEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api CertificateApi) RenewEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"success": true,
"warning": false,
"error": "",
})
}
+107
View File
@@ -0,0 +1,107 @@
package api
import (
"context"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"strconv"
"strings"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type CommandApi struct{}
func (api CommandApi) CommandCreateEndpoint(c echo.Context) error {
var item model.Command
if err := c.Bind(&item); err != nil {
return err
}
account, _ := GetCurrentAccount(c)
item.Owner = account.ID
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
if err := repository.CommandRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, item)
}
func (api CommandApi) CommandAllEndpoint(c echo.Context) error {
items, err := repository.CommandRepository.FindAll(context.Background())
if err != nil {
return err
}
return Success(c, items)
}
func (api CommandApi) CommandPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
content := c.QueryParam("content")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.CommandRepository.Find(context.TODO(), pageIndex, pageSize, name, content, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api CommandApi) CommandUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Command
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.CommandRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, nil)
}
func (api CommandApi) CommandDeleteEndpoint(c echo.Context) error {
id := c.Param("id")
split := strings.Split(id, ",")
for i := range split {
if err := repository.CommandRepository.DeleteById(context.TODO(), split[i]); err != nil {
return err
}
}
return Success(c, nil)
}
func (api CommandApi) CommandGetEndpoint(c echo.Context) (err error) {
id := c.Param("id")
var item model.Command
if item, err = repository.CommandRepository.FindById(context.TODO(), id); err != nil {
return err
}
return Success(c, item)
}
func (api CommandApi) CommandChangeOwnerEndpoint(c echo.Context) (err error) {
id := c.Param("id")
owner := c.QueryParam("owner")
if err := repository.CommandRepository.UpdateById(context.TODO(), &model.Command{Owner: owner}, id); err != nil {
return err
}
return Success(c, "")
}
+68
View File
@@ -0,0 +1,68 @@
package api
import (
"next-terminal/server/common/maps"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type CommandFilterApi struct{}
func (api CommandFilterApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api CommandFilterApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"items": []interface{}{},
"total": 0,
})
}
func (api CommandFilterApi) CreateEndpoint(c echo.Context) error {
var item map[string]interface{}
if err := c.Bind(&item); err != nil {
return err
}
item["id"] = utils.LongUUID()
return Success(c, item)
}
func (api CommandFilterApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item map[string]interface{}
if err := c.Bind(&item); err != nil {
return err
}
item["id"] = id
return Success(c, item)
}
func (api CommandFilterApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, nil)
}
func (api CommandFilterApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, maps.Map{
"id": id,
"name": "Default Filter",
"createdAt": 1700000000000,
})
}
func (api CommandFilterApi) BindEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, nil)
}
func (api CommandFilterApi) UnbindEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, nil)
}
+258
View File
@@ -0,0 +1,258 @@
package api
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/global/cache"
"strconv"
"strings"
"next-terminal/server/config"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type CredentialApi struct{}
func (api CredentialApi) CredentialAllEndpoint(c echo.Context) error {
items, err := repository.CredentialRepository.FindByAll(context.Background())
if err != nil {
return err
}
return Success(c, items)
}
func (api CredentialApi) CredentialCreateEndpoint(c echo.Context) error {
var item model.Credential
if err := c.Bind(&item); err != nil {
return err
}
account, _ := GetCurrentAccount(c)
item.Owner = account.ID
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
switch item.Type {
case nt.Custom:
item.PrivateKey = "-"
item.Passphrase = "-"
if item.Username == "" {
item.Username = "-"
}
if item.Password == "" {
item.Password = "-"
}
case nt.PrivateKey:
item.Password = "-"
if item.Username == "" {
item.Username = "-"
}
if item.PrivateKey == "" {
item.PrivateKey = "-"
}
if item.Passphrase == "" {
item.Passphrase = "-"
}
default:
return Fail(c, -1, "类型错误")
}
item.Encrypted = true
if err := service.CredentialService.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, item)
}
func (api CredentialApi) CredentialPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.CredentialRepository.Find(context.TODO(), pageIndex, pageSize, name, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api CredentialApi) CredentialUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Credential
if err := c.Bind(&item); err != nil {
return err
}
switch item.Type {
case nt.Custom:
item.PrivateKey = "-"
item.Passphrase = "-"
if item.Username == "" {
item.Username = "-"
}
if item.Password == "" {
item.Password = "-"
}
if item.Password != "-" {
encryptedCBC, err := utils.AesEncryptCBC([]byte(item.Password), config.GlobalCfg.EncryptionPassword)
if err != nil {
return err
}
item.Password = base64.StdEncoding.EncodeToString(encryptedCBC)
}
case nt.PrivateKey:
item.Password = "-"
if item.Username == "" {
item.Username = "-"
}
if item.PrivateKey == "" {
item.PrivateKey = "-"
}
if item.PrivateKey != "-" {
encryptedCBC, err := utils.AesEncryptCBC([]byte(item.PrivateKey), config.GlobalCfg.EncryptionPassword)
if err != nil {
return err
}
item.PrivateKey = base64.StdEncoding.EncodeToString(encryptedCBC)
}
if item.Passphrase == "" {
item.Passphrase = "-"
}
if item.Passphrase != "-" {
encryptedCBC, err := utils.AesEncryptCBC([]byte(item.Passphrase), config.GlobalCfg.EncryptionPassword)
if err != nil {
return err
}
item.Passphrase = base64.StdEncoding.EncodeToString(encryptedCBC)
}
default:
return Fail(c, -1, "类型错误")
}
item.Encrypted = true
if err := repository.CredentialRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, nil)
}
func (api CredentialApi) CredentialDeleteEndpoint(c echo.Context) error {
id := c.Param("id")
split := strings.Split(id, ",")
for i := range split {
if err := repository.CredentialRepository.DeleteById(context.TODO(), split[i]); err != nil {
return err
}
}
return Success(c, nil)
}
func (api CredentialApi) CredentialGetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := service.CredentialService.FindByIdAndDecrypt(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api CredentialApi) CredentialChangeOwnerEndpoint(c echo.Context) error {
id := c.Param("id")
owner := c.QueryParam("owner")
if err := repository.CredentialRepository.UpdateById(context.TODO(), &model.Credential{Owner: owner}, id); err != nil {
return err
}
return Success(c, "")
}
func (api CredentialApi) GenPrivateKeyEndpoint(c echo.Context) error {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
privateKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
return Success(c, string(privateKeyPEM))
}
func (api CredentialApi) GetPublicKeyEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := service.CredentialService.FindByIdAndDecrypt(context.TODO(), id)
if err != nil {
return err
}
if item.PrivateKey == "" || item.PrivateKey == "-" {
return Success(c, "")
}
block, _ := pem.Decode([]byte(item.PrivateKey))
if block == nil {
return Success(c, "")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return Success(c, "")
}
publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return Success(c, "")
}
publicKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyBytes,
})
return Success(c, string(publicKeyPEM))
}
func (api CredentialApi) DecryptedEndpoint(c echo.Context) error {
id := c.Param("id")
securityToken := c.QueryParam("securityToken")
_, ok := cache.TokenManager.Get(securityToken)
if !ok {
return Fail(c, 401, "invalid security token")
}
item, err := service.CredentialService.FindByIdAndDecrypt(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
+136
View File
@@ -0,0 +1,136 @@
package api
import (
"context"
"next-terminal/server/common/nt"
"next-terminal/server/repository"
"time"
"github.com/labstack/echo/v4"
)
type DashboardApi struct{}
func (api DashboardApi) GetTimeCounterEndpoint(c echo.Context) error {
var (
totalUser int64
onlineUser int64
countOnlineSession int64
totalAsset int64
activeAsset int64
failLoginCount int64
)
totalUser, _ = repository.UserRepository.Count(context.TODO())
onlineUser, _ = repository.UserRepository.CountOnlineUser(context.TODO())
countOnlineSession, _ = repository.SessionRepository.CountOnlineSession(context.TODO())
totalAsset, _ = repository.AssetRepository.Count(context.TODO())
activeAsset, _ = repository.AssetRepository.CountByActive(context.TODO(), true)
failLoginCount, _ = repository.LoginLogRepository.CountByState(context.TODO(), "0")
gatewayList, _ := repository.GatewayRepository.FindAll(context.TODO())
gatewayActiveCount := int64(len(gatewayList))
counter := map[string]interface{}{
"loginFailedTimes": failLoginCount,
"userOnlineCount": onlineUser,
"sessionOnlineCount": countOnlineSession,
"sessionTotalCount": 0,
"userTotalCount": totalUser,
"assetActiveCount": activeAsset,
"assetTotalCount": totalAsset,
"websiteActiveCount": 0,
"websiteTotalCount": 0,
"gatewayActiveCount": gatewayActiveCount,
"gatewayTotalCount": gatewayActiveCount,
}
return Success(c, counter)
}
func (api DashboardApi) GetDateCounterV2Endpoint(c echo.Context) error {
d := c.QueryParam("d")
var days = 7
if d == "month" {
days = 30
}
now := time.Now()
lastDate := now.AddDate(0, 0, -days)
loginLogCounters, err := repository.LoginLogRepository.CountWithGroupByLoginTime(context.TODO(), lastDate)
if err != nil {
return err
}
userCounters, err := repository.LoginLogRepository.CountWithGroupByLoginTimeAndUsername(context.TODO(), lastDate)
if err != nil {
return err
}
sessionCounters, err := repository.SessionRepository.CountWithGroupByLoginTime(context.TODO(), lastDate)
if err != nil {
return err
}
var counters []map[string]interface{}
for i := 0; i < days; i++ {
day := lastDate.AddDate(0, 0, i).Format("2006-01-02")
item := map[string]interface{}{
"date": day,
"login": int64(0),
"user": int64(0),
"asset": int64(0),
}
for _, counter := range loginLogCounters {
if counter.Date == day {
item["login"] = counter.Value
break
}
}
for _, counter := range userCounters {
if counter.Date == day {
item["user"] = counter.Value
break
}
}
for _, counter := range sessionCounters {
if counter.Date == day {
item["asset"] = counter.Value
break
}
}
counters = append(counters, item)
}
return Success(c, counters)
}
func (api DashboardApi) GetAssetTypesEndpoint(c echo.Context) error {
var (
ssh int64
rdp int64
vnc int64
telnet int64
kubernetes int64
http int64
)
ssh, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.SSH)
rdp, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.RDP)
vnc, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.VNC)
telnet, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.Telnet)
kubernetes, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.K8s)
types := []map[string]interface{}{
{"type": "SSH", "value": ssh},
{"type": "RDP", "value": rdp},
{"type": "VNC", "value": vnc},
{"type": "TELNET", "value": telnet},
{"type": "KUBERNETES", "value": kubernetes},
{"type": "HTTP", "value": http},
}
return Success(c, types)
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"next-terminal/server/common/maps"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type DatabaseAssetApi struct{}
func (api DatabaseAssetApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api DatabaseAssetApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"items": []interface{}{},
"total": 0,
})
}
func (api DatabaseAssetApi) CreateEndpoint(c echo.Context) error {
var item map[string]interface{}
if err := c.Bind(&item); err != nil {
return err
}
item["id"] = utils.LongUUID()
return Success(c, item)
}
func (api DatabaseAssetApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item map[string]interface{}
if err := c.Bind(&item); err != nil {
return err
}
item["id"] = id
return Success(c, item)
}
func (api DatabaseAssetApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, nil)
}
func (api DatabaseAssetApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, maps.Map{
"id": id,
"name": "MySQL Server",
"type": "mysql",
"host": "localhost",
"port": 3306,
"database": "test_db",
"username": "root",
"description": "Test database",
"status": "active",
"statusText": "Active",
"createdAt": 1700000000000,
"updatedAt": 1700000000000,
})
}
func (api DatabaseAssetApi) DecryptEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, maps.Map{
"id": id,
"password": "decrypted_password",
})
}
+86
View File
@@ -0,0 +1,86 @@
package api
import (
"next-terminal/server/common/maps"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type DepartmentApi struct{}
func (api DepartmentApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api DepartmentApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"items": []interface{}{},
"total": 0,
})
}
func (api DepartmentApi) CreateEndpoint(c echo.Context) error {
var item map[string]interface{}
if err := c.Bind(&item); err != nil {
return err
}
item["id"] = utils.LongUUID()
return Success(c, item)
}
func (api DepartmentApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item map[string]interface{}
if err := c.Bind(&item); err != nil {
return err
}
item["id"] = id
return Success(c, item)
}
func (api DepartmentApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, nil)
}
func (api DepartmentApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
_ = id
return Success(c, maps.Map{
"id": id,
"name": "Default",
"parentId": "",
})
}
func (api DepartmentApi) GetTreeEndpoint(c echo.Context) error {
tree := []map[string]interface{}{
{
"title": "Default",
"key": "default",
"value": "default",
"children": []interface{}{},
},
}
return Success(c, tree)
}
func (api DepartmentApi) GetDepartmentUsersEndpoint(c echo.Context) error {
departmentId := c.Param("id")
_ = departmentId
return Success(c, []string{})
}
func (api DepartmentApi) SetDepartmentUsersEndpoint(c echo.Context) error {
departmentId := c.Param("id")
_ = departmentId
return Success(c, nil)
}
func (api DepartmentApi) RemoveUsersFromDepartmentEndpoint(c echo.Context) error {
departmentId := c.Param("id")
_ = departmentId
return Success(c, nil)
}
+433
View File
@@ -0,0 +1,433 @@
package api
import (
"fmt"
"next-terminal/server/common/maps"
"next-terminal/server/global/session"
"next-terminal/server/log"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/pkg/sftp"
)
type FileSystemApi struct{}
func (api FileSystemApi) LsEndpoint(c echo.Context) error {
sessionId := c.Param("id")
dir := c.QueryParam("dir")
hiddenFileVisible := c.QueryParam("hiddenFileVisible") == "true"
log.Debug("FileSystem Ls: sessionId=" + sessionId + " dir=" + dir)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
log.Debug("FileSystem Ls: failed to create SFTP client: " + err.Error())
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
files, err := sftpClient.ReadDir(dir)
if err != nil {
log.Debug("FileSystem Ls: failed to read directory: " + err.Error())
return Fail(c, -1, "failed to read directory: "+err.Error())
}
var result []maps.Map
for _, f := range files {
name := f.Name()
if !hiddenFileVisible && strings.HasPrefix(name, ".") {
continue
}
result = append(result, maps.Map{
"name": name,
"size": f.Size(),
"modTime": f.ModTime().UnixMilli(),
"path": path.Join(dir, name),
"mode": f.Mode().String(),
"isDir": f.IsDir(),
"isLink": f.Mode()&os.ModeSymlink != 0,
})
}
return Success(c, result)
}
func (api FileSystemApi) MkdirEndpoint(c echo.Context) error {
sessionId := c.Param("id")
dir := c.QueryParam("dir")
log.Debug("FileSystem Mkdir: sessionId=" + sessionId + " dir=" + dir)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
err = sftpClient.MkdirAll(dir)
if err != nil {
return Fail(c, -1, "failed to create directory: "+err.Error())
}
return Success(c, nil)
}
func (api FileSystemApi) TouchEndpoint(c echo.Context) error {
sessionId := c.Param("id")
filename := c.QueryParam("filename")
log.Debug("FileSystem Touch: sessionId=" + sessionId + " filename=" + filename)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
f, err := sftpClient.Create(filename)
if err != nil {
return Fail(c, -1, "failed to create file: "+err.Error())
}
f.Close()
return Success(c, nil)
}
func (api FileSystemApi) RmEndpoint(c echo.Context) error {
sessionId := c.Param("id")
filename := c.QueryParam("filename")
log.Debug("FileSystem Rm: sessionId=" + sessionId + " filename=" + filename)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
f, err := sftpClient.Stat(filename)
if err != nil {
return Fail(c, -1, "file not found: "+err.Error())
}
if f.IsDir() {
err = sftpClient.RemoveDirectory(filename)
if err != nil {
err = api.removeRecursive(sftpClient, filename)
if err != nil {
return Fail(c, -1, "failed to remove directory: "+err.Error())
}
}
} else {
err = sftpClient.Remove(filename)
if err != nil {
return Fail(c, -1, "failed to remove file: "+err.Error())
}
}
return Success(c, nil)
}
func (api FileSystemApi) removeRecursive(sftpClient *sftp.Client, dirPath string) error {
files, err := sftpClient.ReadDir(dirPath)
if err != nil {
return err
}
for _, f := range files {
fullPath := path.Join(dirPath, f.Name())
if f.IsDir() {
err = api.removeRecursive(sftpClient, fullPath)
if err != nil {
return err
}
} else {
err = sftpClient.Remove(fullPath)
if err != nil {
return err
}
}
}
return sftpClient.RemoveDirectory(dirPath)
}
func (api FileSystemApi) RenameEndpoint(c echo.Context) error {
sessionId := c.Param("id")
oldName := c.QueryParam("oldName")
newName := c.QueryParam("newName")
log.Debug("FileSystem Rename: sessionId=" + sessionId + " oldName=" + oldName + " newName=" + newName)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
err = sftpClient.Rename(oldName, newName)
if err != nil {
return Fail(c, -1, "failed to rename: "+err.Error())
}
return Success(c, nil)
}
func (api FileSystemApi) EditEndpoint(c echo.Context) error {
sessionId := c.Param("id")
var req struct {
Filename string `json:"filename"`
FileContent string `json:"fileContent"`
}
if err := c.Bind(&req); err != nil {
return err
}
log.Debug("FileSystem Edit: sessionId=" + sessionId + " filename=" + req.Filename)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
f, err := sftpClient.OpenFile(req.Filename, os.O_WRONLY|os.O_TRUNC|os.O_CREATE)
if err != nil {
return Fail(c, -1, "failed to open file: "+err.Error())
}
defer f.Close()
_, err = f.Write([]byte(req.FileContent))
if err != nil {
return Fail(c, -1, "failed to write file: "+err.Error())
}
return Success(c, nil)
}
func (api FileSystemApi) ReadEndpoint(c echo.Context) error {
sessionId := c.Param("id")
filename := c.QueryParam("filename")
log.Debug("FileSystem Read: sessionId=" + sessionId + " filename=" + filename)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
f, err := sftpClient.Open(filename)
if err != nil {
return Fail(c, -1, "failed to open file: "+err.Error())
}
defer f.Close()
content, err := readFileContent(f, 10*1024*1024)
if err != nil {
return Fail(c, -1, "failed to read file: "+err.Error())
}
return Success(c, maps.Map{
"content": content,
"path": filename,
})
}
func readFileContent(f *sftp.File, maxSize int64) (string, error) {
stat, err := f.Stat()
if err != nil {
return "", err
}
if stat.Size() > maxSize {
return "", fmt.Errorf("file too large (max %d bytes)", maxSize)
}
buf := make([]byte, stat.Size())
_, err = f.Read(buf)
if err != nil {
return "", err
}
return string(buf), nil
}
func (api FileSystemApi) ChmodEndpoint(c echo.Context) error {
sessionId := c.Param("id")
filename := c.QueryParam("filename")
modeStr := c.QueryParam("mode")
log.Debug("FileSystem Chmod: sessionId=" + sessionId + " filename=" + filename + " mode=" + modeStr)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
mode, err := strconv.ParseUint(modeStr, 10, 32)
if err != nil {
return Fail(c, -1, "invalid mode: "+err.Error())
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
err = sftpClient.Chmod(filename, os.FileMode(mode))
if err != nil {
return Fail(c, -1, "failed to chmod: "+err.Error())
}
return Success(c, nil)
}
func (api FileSystemApi) UploadProgressEndpoint(c echo.Context) error {
sessionId := c.Param("id")
id := c.QueryParam("id")
log.Debug("FileSystem UploadProgress: sessionId=" + sessionId + " id=" + id)
return Success(c, maps.Map{
"total": 0,
"written": 0,
"percent": 100,
"speed": 0,
"elapsedTime": 0,
"isCompleted": true,
})
}
func (api FileSystemApi) DownloadEndpoint(c echo.Context) error {
sessionId := c.Param("id")
filename := c.QueryParam("filename")
log.Debug("FileSystem Download: sessionId=" + sessionId + " filename=" + filename)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
f, err := sftpClient.Open(filename)
if err != nil {
return Fail(c, -1, "failed to open file: "+err.Error())
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return Fail(c, -1, "failed to stat file: "+err.Error())
}
c.Response().Header().Set("Content-Disposition", "attachment; filename="+path.Base(filename))
c.Response().Header().Set("Content-Type", "application/octet-stream")
c.Response().Header().Set("Content-Length", strconv.FormatInt(stat.Size(), 10))
return c.Stream(200, "application/octet-stream", f)
}
func (api FileSystemApi) UploadEndpoint(c echo.Context) error {
sessionId := c.Param("id")
destDir := c.QueryParam("dir")
log.Debug("FileSystem Upload: sessionId=" + sessionId + " dir=" + destDir)
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Fail(c, -1, "session not found or SSH connection closed")
}
file, err := c.FormFile("file")
if err != nil {
return Fail(c, -1, "failed to get upload file: "+err.Error())
}
src, err := file.Open()
if err != nil {
return Fail(c, -1, "failed to open upload file: "+err.Error())
}
defer src.Close()
sftpClient, err := sftp.NewClient(sess.NextTerminal.SshClient)
if err != nil {
return Fail(c, -1, "failed to create SFTP client: "+err.Error())
}
defer sftpClient.Close()
destPath := path.Join(destDir, file.Filename)
dst, err := sftpClient.Create(destPath)
if err != nil {
return Fail(c, -1, "failed to create remote file: "+err.Error())
}
defer dst.Close()
buf := make([]byte, 32*1024)
for {
n, err := src.Read(buf)
if n > 0 {
_, writeErr := dst.Write(buf[:n])
if writeErr != nil {
return Fail(c, -1, "failed to write remote file: "+writeErr.Error())
}
}
if err != nil {
break
}
}
return Success(c, maps.Map{
"path": destPath,
"size": file.Size,
"timestamp": time.Now().UnixMilli(),
})
}
+80
View File
@@ -0,0 +1,80 @@
package api
import (
"context"
"strconv"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type GatewayGroupApi struct{}
func (api GatewayGroupApi) AllEndpoint(c echo.Context) error {
items, err := repository.GatewayGroupRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api GatewayGroupApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
keyword := c.QueryParam("keyword")
items, total, err := repository.GatewayGroupRepository.Find(context.TODO(), pageIndex, pageSize, keyword)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api GatewayGroupApi) CreateEndpoint(c echo.Context) error {
var item model.GatewayGroup
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
if err := repository.GatewayGroupRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api GatewayGroupApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.GatewayGroup
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.GatewayGroupRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, nil)
}
func (api GatewayGroupApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.GatewayGroupRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
return Success(c, nil)
}
func (api GatewayGroupApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.GatewayGroupRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
+342
View File
@@ -0,0 +1,342 @@
package api
import (
"context"
"fmt"
"net/http"
"next-terminal/server/common/guacamole"
"next-terminal/server/common/nt"
"path"
"strconv"
"next-terminal/server/config"
"next-terminal/server/global/session"
"next-terminal/server/log"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
)
const (
TunnelClosed int = -1
Normal int = 0
NotFoundSession int = 800
NewTunnelError int = 801
ForcedDisconnect int = 802
AccessGatewayUnAvailable int = 803
AccessGatewayCreateError int = 804
AssetNotActive int = 805
NewSshClientError int = 806
)
var UpGrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(r *http.Request) bool {
return true
},
Subprotocols: []string{"guacamole"},
}
type GuacamoleApi struct {
}
func (api GuacamoleApi) Guacamole(c echo.Context) error {
ws, err := UpGrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
log.Warn("升级为WebSocket协议失败", log.NamedError("err", err))
return err
}
ctx := context.TODO()
width := c.QueryParam("width")
height := c.QueryParam("height")
dpi := c.QueryParam("dpi")
sessionId := c.Param("id")
intWidth, _ := strconv.Atoi(width)
intHeight, _ := strconv.Atoi(height)
configuration := guacamole.NewConfiguration()
propertyMap := repository.PropertyRepository.FindAllMap(ctx)
configuration.SetParameter("width", width)
configuration.SetParameter("height", height)
configuration.SetParameter("dpi", dpi)
s, err := service.SessionService.FindByIdAndDecrypt(ctx, sessionId)
if err != nil {
return err
}
api.setConfig(propertyMap, s, configuration)
if s.AccessGatewayId != "" && s.AccessGatewayId != "-" {
g, err := service.GatewayService.GetGatewayById(s.AccessGatewayId)
if err != nil {
guacamole.Disconnect(ws, AccessGatewayUnAvailable, "获取接入网关失败:"+err.Error())
return nil
}
defer g.CloseSshTunnel(s.ID)
exposedIP, exposedPort, err := g.OpenSshTunnel(s.ID, s.IP, s.Port)
if err != nil {
guacamole.Disconnect(ws, AccessGatewayCreateError, "创建SSH隧道失败:"+err.Error())
return nil
}
s.IP = exposedIP
s.Port = exposedPort
}
configuration.SetParameter("hostname", s.IP)
configuration.SetParameter("port", strconv.Itoa(s.Port))
// 加载资产配置的属性,优先级比全局配置的高,因此最后加载,覆盖掉全局配置
attributes, err := repository.AssetRepository.FindAssetAttrMapByAssetId(ctx, s.AssetId)
if err != nil {
return err
}
if len(attributes) > 0 {
api.setAssetConfig(attributes, s, configuration)
}
for name := range configuration.Parameters {
// 替换数据库空格字符串占位符为真正的空格
if configuration.Parameters[name] == "-" {
configuration.Parameters[name] = ""
}
}
addr := config.GlobalCfg.Guacd.Hostname + ":" + strconv.Itoa(config.GlobalCfg.Guacd.Port)
asset := fmt.Sprintf("%s:%s", configuration.GetParameter("hostname"), configuration.GetParameter("port"))
log.Debug("新建 guacd 会话", log.String("sessionId", sessionId), log.String("addr", addr), log.String("asset", asset))
guacdTunnel, err := guacamole.NewTunnel(addr, configuration)
if err != nil {
guacamole.Disconnect(ws, NewTunnelError, err.Error())
log.Error("建立连接失败", log.String("sessionId", sessionId), log.NamedError("err", err))
return err
}
nextSession := &session.Session{
ID: sessionId,
Protocol: s.Protocol,
Mode: s.Mode,
WebSocket: ws,
GuacdTunnel: guacdTunnel,
}
if configuration.Protocol == nt.SSH {
nextTerminal, err := CreateNextTerminalBySession(s)
if err != nil {
guacamole.Disconnect(ws, NewSshClientError, "建立SSH客户端失败: "+err.Error())
log.Debug("建立 ssh 客户端失败", log.String("sessionId", sessionId), log.NamedError("err", err))
return err
}
nextSession.NextTerminal = nextTerminal
}
nextSession.Observer = session.NewObserver(sessionId)
session.GlobalSessionManager.Add(nextSession)
sess := model.Session{
ConnectionId: guacdTunnel.UUID,
Width: intWidth,
Height: intHeight,
Status: nt.Connecting,
Recording: configuration.GetParameter(guacamole.RecordingPath),
}
if sess.Recording == "" {
// 未录屏时无需审计
sess.Reviewed = true
}
// 创建新会话
log.Debug("新建会话成功", log.String("sessionId", sessionId))
if err := repository.SessionRepository.UpdateById(ctx, &sess, sessionId); err != nil {
return err
}
guacamoleHandler := NewGuacamoleHandler(ws, guacdTunnel)
guacamoleHandler.Start()
defer guacamoleHandler.Stop()
for {
_, message, err := ws.ReadMessage()
if err != nil {
log.Debug("WebSocket已关闭", log.String("sessionId", sessionId), log.NamedError("err", err))
// guacdTunnel.Read() 会阻塞,所以要先把guacdTunnel客户端关闭,才能退出Guacd循环
_ = guacdTunnel.Close()
service.SessionService.CloseSessionById(sessionId, Normal, "用户正常退出")
return nil
}
_, err = guacdTunnel.WriteAndFlush(message)
if err != nil {
service.SessionService.CloseSessionById(sessionId, TunnelClosed, "远程连接已关闭")
return nil
}
}
}
func (api GuacamoleApi) setAssetConfig(attributes map[string]string, s model.Session, configuration *guacamole.Configuration) {
for key, value := range attributes {
if guacamole.DrivePath == key {
// 忽略该参数
continue
}
if guacamole.EnableDrive == key && value == "true" {
storageId := attributes[guacamole.DrivePath]
if storageId == "" || storageId == "-" {
// 默认空间ID和用户ID相同
storageId = s.Creator
}
realPath := path.Join(service.StorageService.GetBaseDrivePath(), storageId)
configuration.SetParameter(guacamole.EnableDrive, "true")
configuration.SetParameter(guacamole.DriveName, "Filesystem")
configuration.SetParameter(guacamole.DrivePath, realPath)
} else {
configuration.SetParameter(key, value)
}
}
}
func (api GuacamoleApi) GuacamoleMonitor(c echo.Context) error {
ws, err := UpGrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
log.Warn("升级为WebSocket协议失败", log.NamedError("err", err))
return err
}
ctx := context.TODO()
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(ctx, sessionId)
if err != nil {
return err
}
if s.Status != nt.Connected {
guacamole.Disconnect(ws, AssetNotActive, "会话离线")
return nil
}
connectionId := s.ConnectionId
configuration := guacamole.NewConfiguration()
configuration.ConnectionID = connectionId
sessionId = s.ID
configuration.SetParameter("width", strconv.Itoa(s.Width))
configuration.SetParameter("height", strconv.Itoa(s.Height))
configuration.SetParameter("dpi", "96")
configuration.SetReadOnlyMode()
addr := config.GlobalCfg.Guacd.Hostname + ":" + strconv.Itoa(config.GlobalCfg.Guacd.Port)
guacdTunnel, err := guacamole.NewTunnel(addr, configuration)
if err != nil {
guacamole.Disconnect(ws, NewTunnelError, err.Error())
return err
}
nextSession := &session.Session{
ID: sessionId,
Protocol: s.Protocol,
Mode: s.Mode,
WebSocket: ws,
GuacdTunnel: guacdTunnel,
}
// 要监控会话
forObsSession := session.GlobalSessionManager.GetById(sessionId)
if forObsSession == nil {
guacamole.Disconnect(ws, NotFoundSession, "获取会话失败")
return nil
}
nextSession.ID = utils.UUID()
forObsSession.Observer.Add(nextSession)
guacamoleHandler := NewGuacamoleHandler(ws, guacdTunnel)
guacamoleHandler.Start()
defer guacamoleHandler.Stop()
for {
_, message, err := ws.ReadMessage()
if err != nil {
// guacdTunnel.Read() 会阻塞,所以要先把guacdTunnel客户端关闭,才能退出Guacd循环
_ = guacdTunnel.Close()
observerId := nextSession.ID
forObsSession.Observer.Del(observerId)
return nil
}
_, err = guacdTunnel.WriteAndFlush(message)
if err != nil {
service.SessionService.CloseSessionById(sessionId, TunnelClosed, "远程连接已关闭")
return nil
}
}
}
func (api GuacamoleApi) setConfig(propertyMap map[string]string, s model.Session, configuration *guacamole.Configuration) {
if propertyMap[guacamole.EnableRecording] == "true" {
configuration.SetParameter(guacamole.RecordingPath, path.Join(config.GlobalCfg.Guacd.Recording, s.ID))
configuration.SetParameter(guacamole.CreateRecordingPath, "true")
} else {
configuration.SetParameter(guacamole.RecordingPath, "")
}
configuration.Protocol = s.Protocol
switch configuration.Protocol {
case "rdp":
configuration.SetParameter("username", s.Username)
configuration.SetParameter("password", s.Password)
configuration.SetParameter("security", "any")
configuration.SetParameter("ignore-cert", "true")
configuration.SetParameter("create-drive-path", "true")
configuration.SetParameter("resize-method", "reconnect")
configuration.SetParameter(guacamole.EnableWallpaper, propertyMap[guacamole.EnableWallpaper])
configuration.SetParameter(guacamole.EnableTheming, propertyMap[guacamole.EnableTheming])
configuration.SetParameter(guacamole.EnableFontSmoothing, propertyMap[guacamole.EnableFontSmoothing])
configuration.SetParameter(guacamole.EnableFullWindowDrag, propertyMap[guacamole.EnableFullWindowDrag])
configuration.SetParameter(guacamole.EnableDesktopComposition, propertyMap[guacamole.EnableDesktopComposition])
configuration.SetParameter(guacamole.EnableMenuAnimations, propertyMap[guacamole.EnableMenuAnimations])
configuration.SetParameter(guacamole.DisableBitmapCaching, propertyMap[guacamole.DisableBitmapCaching])
configuration.SetParameter(guacamole.DisableOffscreenCaching, propertyMap[guacamole.DisableOffscreenCaching])
configuration.SetParameter(guacamole.ColorDepth, propertyMap[guacamole.ColorDepth])
configuration.SetParameter(guacamole.ForceLossless, propertyMap[guacamole.ForceLossless])
configuration.SetParameter(guacamole.PreConnectionId, propertyMap[guacamole.PreConnectionId])
configuration.SetParameter(guacamole.PreConnectionBlob, propertyMap[guacamole.PreConnectionBlob])
case "ssh":
if len(s.PrivateKey) > 0 && s.PrivateKey != "-" {
configuration.SetParameter("username", s.Username)
configuration.SetParameter("private-key", s.PrivateKey)
configuration.SetParameter("passphrase", s.Passphrase)
} else {
configuration.SetParameter("username", s.Username)
configuration.SetParameter("password", s.Password)
}
configuration.SetParameter(guacamole.FontSize, propertyMap[guacamole.FontSize])
configuration.SetParameter(guacamole.FontName, propertyMap[guacamole.FontName])
configuration.SetParameter(guacamole.ColorScheme, propertyMap[guacamole.ColorScheme])
configuration.SetParameter(guacamole.Backspace, propertyMap[guacamole.Backspace])
configuration.SetParameter(guacamole.TerminalType, propertyMap[guacamole.TerminalType])
case "vnc":
configuration.SetParameter("username", s.Username)
configuration.SetParameter("password", s.Password)
case "telnet":
configuration.SetParameter("username", s.Username)
configuration.SetParameter("password", s.Password)
configuration.SetParameter(guacamole.FontSize, propertyMap[guacamole.FontSize])
configuration.SetParameter(guacamole.FontName, propertyMap[guacamole.FontName])
configuration.SetParameter(guacamole.ColorScheme, propertyMap[guacamole.ColorScheme])
configuration.SetParameter(guacamole.Backspace, propertyMap[guacamole.Backspace])
configuration.SetParameter(guacamole.TerminalType, propertyMap[guacamole.TerminalType])
case "kubernetes":
configuration.SetParameter(guacamole.FontSize, propertyMap[guacamole.FontSize])
configuration.SetParameter(guacamole.FontName, propertyMap[guacamole.FontName])
configuration.SetParameter(guacamole.ColorScheme, propertyMap[guacamole.ColorScheme])
configuration.SetParameter(guacamole.Backspace, propertyMap[guacamole.Backspace])
configuration.SetParameter(guacamole.TerminalType, propertyMap[guacamole.TerminalType])
default:
}
}
+53
View File
@@ -0,0 +1,53 @@
package api
import (
"context"
"next-terminal/server/common/guacamole"
"github.com/gorilla/websocket"
)
type GuacamoleHandler struct {
ws *websocket.Conn
tunnel *guacamole.Tunnel
ctx context.Context
cancel context.CancelFunc
}
func NewGuacamoleHandler(ws *websocket.Conn, tunnel *guacamole.Tunnel) *GuacamoleHandler {
ctx, cancel := context.WithCancel(context.Background())
return &GuacamoleHandler{
ws: ws,
tunnel: tunnel,
ctx: ctx,
cancel: cancel,
}
}
func (r GuacamoleHandler) Start() {
go func() {
for {
select {
case <-r.ctx.Done():
return
default:
instruction, err := r.tunnel.Read()
if err != nil {
guacamole.Disconnect(r.ws, TunnelClosed, "远程连接已关闭")
return
}
if len(instruction) == 0 {
continue
}
err = r.ws.WriteMessage(websocket.TextMessage, instruction)
if err != nil {
return
}
}
}
}()
}
func (r GuacamoleHandler) Stop() {
r.cancel()
}
+133
View File
@@ -0,0 +1,133 @@
package api
import (
"context"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"strconv"
"strings"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type JobApi struct{}
func (api JobApi) JobCreateEndpoint(c echo.Context) error {
var item model.Job
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
if err := service.JobService.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api JobApi) JobPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
status := c.QueryParam("status")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.JobRepository.Find(context.TODO(), pageIndex, pageSize, name, status, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api JobApi) JobUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Job
if err := c.Bind(&item); err != nil {
return err
}
item.ID = id
if err := service.JobService.UpdateById(&item); err != nil {
return err
}
return Success(c, nil)
}
func (api JobApi) JobChangeStatusEndpoint(c echo.Context) error {
id := c.Param("id")
status := c.QueryParam("status")
if err := service.JobService.ChangeStatusById(id, status); err != nil {
return err
}
return Success(c, "")
}
func (api JobApi) JobExecEndpoint(c echo.Context) error {
id := c.Param("id")
if err := service.JobService.ExecJobById(id); err != nil {
return err
}
return Success(c, "")
}
func (api JobApi) JobDeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
for i := range split {
jobId := split[i]
if err := service.JobService.DeleteJobById(jobId); err != nil {
return err
}
}
return Success(c, nil)
}
func (api JobApi) JobGetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.JobRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api JobApi) JobGetLogsEndpoint(c echo.Context) error {
id := c.Param("id")
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
items, total, err := repository.JobLogRepository.FindByJobId(context.TODO(), id, pageIndex, pageSize)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api JobApi) JobDeleteLogsEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.JobLogRepository.DeleteByJobId(context.TODO(), id); err != nil {
return err
}
return Success(c, "")
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"context"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"strconv"
"strings"
"github.com/labstack/echo/v4"
)
type LoginLogApi struct{}
func (api LoginLogApi) LoginLogPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
username := c.QueryParam("username")
clientIp := c.QueryParam("clientIp")
state := c.QueryParam("state")
items, total, err := repository.LoginLogRepository.Find(context.TODO(), pageIndex, pageSize, username, clientIp, state)
if err != nil {
return err
}
for i := range items {
items[i].Success = items[i].State == "1"
items[i].UserAgent = parseUserAgent(items[i].ClientUserAgent)
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func parseUserAgent(ua string) *model.UserAgent {
if ua == "" {
return nil
}
return &model.UserAgent{
String: ua,
}
}
func (api LoginLogApi) LoginLogDeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
tokens := strings.Split(ids, ",")
if err := service.UserService.DeleteLoginLogs(tokens); err != nil {
return err
}
return Success(c, nil)
}
func (api LoginLogApi) LoginLogClearEndpoint(c echo.Context) error {
loginLogs, err := repository.LoginLogRepository.FindAllLoginLogs(context.TODO())
if err != nil {
return err
}
var tokens = make([]string, 0)
for i := range loginLogs {
tokens = append(tokens, loginLogs[i].ID)
}
if err := service.UserService.DeleteLoginLogs(tokens); err != nil {
return err
}
return Success(c, nil)
}
+143
View File
@@ -0,0 +1,143 @@
package api
import (
"context"
"strconv"
"strings"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type LoginPolicyApi struct{}
func (api LoginPolicyApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
userId := c.QueryParam("userId")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.LoginPolicyRepository.Find(context.TODO(), pageIndex, pageSize, name, userId, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api LoginPolicyApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := service.LoginPolicyService.FindById(context.Background(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api LoginPolicyApi) CreateEndpoint(c echo.Context) error {
var item model.LoginPolicy
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
if err := service.LoginPolicyService.Create(context.Background(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api LoginPolicyApi) DeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
if err := service.LoginPolicyService.DeleteByIds(context.Background(), split); err != nil {
return err
}
return Success(c, nil)
}
func (api LoginPolicyApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.LoginPolicy
if err := c.Bind(&item); err != nil {
return err
}
if err := service.LoginPolicyService.UpdateById(context.Background(), &item, id); err != nil {
return err
}
return Success(c, "")
}
func (api LoginPolicyApi) GetUserPageEndpoint(c echo.Context) error {
id := c.Param("id")
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
username := c.QueryParam("username")
nickname := c.QueryParam("nickname")
mail := c.QueryParam("mail")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.UserRepository.Find(context.TODO(), pageIndex, pageSize, username, nickname, mail, "", id, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api LoginPolicyApi) BindEndpoint(c echo.Context) error {
var items []model.LoginPolicyUserRef
if err := c.Bind(&items); err != nil {
return err
}
id := c.Param("id")
if err := service.LoginPolicyService.Bind(context.Background(), id, items); err != nil {
return err
}
return Success(c, "")
}
func (api LoginPolicyApi) UnbindEndpoint(c echo.Context) error {
var items []model.LoginPolicyUserRef
if err := c.Bind(&items); err != nil {
return err
}
id := c.Param("id")
if err := service.LoginPolicyService.Unbind(context.Background(), id, items); err != nil {
return err
}
return Success(c, "")
}
func (api LoginPolicyApi) GetUserIdEndpoint(c echo.Context) error {
id := c.Param("id")
refs, err := repository.LoginPolicyUserRefRepository.FindByLoginPolicyId(context.Background(), id)
if err != nil {
return err
}
var ids = make([]string, 0)
for _, ref := range refs {
ids = append(ids, ref.UserId)
}
return Success(c, ids)
}
+58
View File
@@ -0,0 +1,58 @@
package api
import (
"context"
"encoding/base64"
"strings"
"next-terminal/server/model"
"next-terminal/server/repository"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
)
type LogoApi struct{}
func (api LogoApi) LogosEndpoint(c echo.Context) error {
logos := repository.LogoRepository.FindAll(context.TODO())
return Success(c, logos)
}
func (api LogoApi) UploadEndpoint(c echo.Context) error {
file, err := c.FormFile("file")
if err != nil {
return err
}
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
buf := make([]byte, file.Size)
n, _ := src.Read(buf)
data := base64.StdEncoding.EncodeToString(buf[:n])
ext := strings.ToLower(file.Filename[strings.LastIndex(file.Filename, "."):])
name := uuid.New().String() + ext
logo := model.Logo{
ID: uuid.New().String(),
Name: name,
Data: "data:image/" + ext + ";base64," + data,
Deletable: true,
}
if err := repository.LogoRepository.Create(context.TODO(), &logo); err != nil {
return err
}
return Success(c, logo)
}
func (api LogoApi) DeleteEndpoint(c echo.Context) error {
name := c.Param("name")
if err := repository.LogoRepository.DeleteByName(context.TODO(), name); err != nil {
return err
}
return Success(c, nil)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

+229
View File
@@ -0,0 +1,229 @@
package api
import (
"context"
"next-terminal/server/common/nt"
"next-terminal/server/dto"
"next-terminal/server/global/stat"
"next-terminal/server/repository"
"time"
"github.com/labstack/echo/v4"
)
type OverviewApi struct{}
func (api OverviewApi) OverviewCounterEndPoint(c echo.Context) error {
var (
totalUser int64
onlineUser int64
countOfflineSession int64
totalAsset int64
activeAsset int64
failLoginCount int64
)
totalUser, _ = repository.UserRepository.Count(context.TODO())
onlineUser, _ = repository.UserRepository.CountOnlineUser(context.TODO())
countOfflineSession, _ = repository.SessionRepository.CountOfflineSession(context.TODO())
totalAsset, _ = repository.AssetRepository.Count(context.TODO())
activeAsset, _ = repository.AssetRepository.CountByActive(context.TODO(), true)
failLoginCount, _ = repository.LoginLogRepository.CountByState(context.TODO(), "0")
counter := dto.Counter{
TotalUser: totalUser,
OnlineUser: onlineUser,
OfflineSession: countOfflineSession,
TotalAsset: totalAsset,
ActiveAsset: activeAsset,
FailLoginCount: failLoginCount,
}
return Success(c, counter)
}
func (api OverviewApi) OverviewAssetEndPoint(c echo.Context) error {
var (
ssh int64
rdp int64
vnc int64
telnet int64
kubernetes int64
)
ssh, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.SSH)
rdp, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.RDP)
vnc, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.VNC)
telnet, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.Telnet)
kubernetes, _ = repository.AssetRepository.CountByProtocol(context.TODO(), nt.K8s)
m := echo.Map{
"ssh": ssh,
"rdp": rdp,
"vnc": vnc,
"telnet": telnet,
"kubernetes": kubernetes,
"all": ssh + rdp + vnc + telnet + kubernetes,
}
return Success(c, m)
}
func (api OverviewApi) OverviewDateCounterEndPoint(c echo.Context) error {
d := c.QueryParam("d")
var days = 7
if d == "month" {
days = 30
}
now := time.Now()
lastDate := now.AddDate(0, 0, -days)
// 最近一月登录次数
loginLogCounters, err := repository.LoginLogRepository.CountWithGroupByLoginTime(context.TODO(), lastDate)
if err != nil {
return err
}
// 最近一月活跃用户
userCounters, err := repository.LoginLogRepository.CountWithGroupByLoginTimeAndUsername(context.TODO(), lastDate)
if err != nil {
return err
}
// 最近一月活跃资产
sessionCounters, err := repository.SessionRepository.CountWithGroupByLoginTime(context.TODO(), lastDate)
if err != nil {
return err
}
var counters []dto.DateCounter
for i := 0; i < days; i++ {
day := lastDate.AddDate(0, 0, i).Format("2006-01-02")
var exist = false
for _, counter := range loginLogCounters {
if counter.Date == day {
exist = true
counters = append(counters, dto.DateCounter{
Type: "登录次数",
Date: day,
Value: counter.Value,
})
break
}
}
if !exist {
counters = append(counters, dto.DateCounter{
Type: "登录次数",
Date: day,
Value: 0,
})
}
exist = false
for _, counter := range userCounters {
if counter.Date == day {
exist = true
counters = append(counters, dto.DateCounter{
Type: "活跃用户",
Date: day,
Value: counter.Value,
})
break
}
}
if !exist {
counters = append(counters, dto.DateCounter{
Type: "活跃用户",
Date: day,
Value: 0,
})
}
exist = false
for _, counter := range sessionCounters {
if counter.Date == day {
exist = true
counters = append(counters, dto.DateCounter{
Type: "活跃资产",
Date: day,
Value: counter.Value,
})
break
}
}
if !exist {
counters = append(counters, dto.DateCounter{
Type: "活跃资产",
Date: day,
Value: 0,
})
}
}
return Success(c, counters)
}
func (api OverviewApi) OverviewPS(c echo.Context) error {
//memoryStat, err := mem.VirtualMemory()
//if err != nil {
// return err
//}
//avgStat, err := load.Avg()
//if err != nil {
// return err
//}
//
//cpuCount, err := cpu.Counts(true)
//if err != nil {
// return err
//}
//
//percent, err := cpu.Percent(time.Second, false)
//if err != nil {
// return err
//}
//
//var bytesRead uint64 = 0
//var bytesWrite uint64 = 0
//
//diskIO, err := disk.IOCounters()
//if err != nil {
// return err
//}
//for _, v := range diskIO {
// bytesRead += v.ReadBytes
// bytesWrite += v.WriteBytes
//}
//
//var bytesSent uint64 = 0
//var bytesRecv uint64 = 0
//netIO, err := net.IOCounters(true)
//if err != nil {
// return err
//}
//for _, v := range netIO {
// bytesSent += v.BytesSent
// bytesRecv += v.BytesRecv
//}
//return Success(c, Map{
// "mem": Map{
// "total": memoryStat.Total,
// "usedPercent": memoryStat.UsedPercent,
// },
// "cpu": Map{
// "count": cpuCount,
// "loadAvg": avgStat,
// "usedPercent": percent[0],
// },
// "diskIO": Map{
// "bytesRead": bytesRead,
// "bytesWrite": bytesWrite,
// },
// "netIO": Map{
// "bytesSent": bytesSent,
// "bytesRecv": bytesRecv,
// },
//})
return Success(c, stat.SystemLoad)
}
+572
View File
@@ -0,0 +1,572 @@
package api
import (
"context"
"strconv"
"strings"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/global/session"
"next-terminal/server/log"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"github.com/labstack/echo/v4"
"golang.org/x/crypto/ssh"
)
type PortalApi struct{}
func (api PortalApi) AssetsEndpoint(c echo.Context) error {
assetType := c.QueryParam("type")
ctx := context.TODO()
var items []model.Asset
var err error
if assetType != "" {
items, err = repository.AssetRepository.FindByProtocol(ctx, assetType)
} else {
items, err = repository.AssetRepository.FindAll(ctx)
}
if err != nil {
return err
}
result := make([]maps.Map, len(items))
for i, a := range items {
result[i] = maps.Map{
"id": a.ID,
"logo": "",
"name": a.Name,
"address": a.IP + ":" + strconv.Itoa(a.Port),
"protocol": a.Protocol,
"tags": []string{},
"status": "unknown",
"type": "asset",
"groupId": "",
"users": []string{},
}
}
return Success(c, result)
}
func (api PortalApi) DatabaseAssetsEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api PortalApi) AssetsTreeEndpoint(c echo.Context) error {
protocol := c.QueryParam("protocol")
keyword := c.QueryParam("keyword")
ctx := context.TODO()
items, _ := repository.AssetRepository.FindByProtocol(ctx, protocol)
groups, _ := repository.AssetGroupRepository.FindAll(ctx)
tree := make([]maps.Map, 0)
for _, g := range groups {
node := maps.Map{
"key": g.ID,
"title": g.Name,
"isLeaf": false,
"children": buildPortalAssetChildren(items, g.ID, keyword),
}
tree = append(tree, node)
}
for _, a := range items {
if keyword != "" && !containsKeyword(a.Name, keyword) {
continue
}
node := maps.Map{
"key": a.ID,
"title": a.Name,
"isLeaf": true,
"extra": maps.Map{
"protocol": a.Protocol,
"logo": "",
"status": "unknown",
"network": a.IP,
"wolEnabled": false,
},
}
tree = append(tree, node)
}
return Success(c, tree)
}
func buildPortalAssetChildren(assets []model.Asset, groupId, keyword string) []maps.Map {
children := make([]maps.Map, 0)
for _, a := range assets {
if keyword != "" && !containsKeyword(a.Name, keyword) {
continue
}
node := maps.Map{
"key": a.ID,
"title": a.Name,
"isLeaf": true,
"extra": maps.Map{
"protocol": a.Protocol,
"logo": "",
"status": "unknown",
"network": a.IP,
"wolEnabled": false,
},
}
children = append(children, node)
}
return children
}
func containsKeyword(name, keyword string) bool {
if keyword == "" {
return true
}
for _, ch := range name {
for _, kh := range keyword {
if ch == kh {
return true
}
}
}
return false
}
func (api PortalApi) WebsitesTreeEndpoint(c echo.Context) error {
keyword := c.QueryParam("keyword")
items, _ := repository.WebsiteRepository.FindAll(context.TODO())
tree := make([]maps.Map, 0)
for _, w := range items {
if keyword != "" && !containsKeyword(w.Name, keyword) {
continue
}
node := maps.Map{
"key": w.ID,
"title": w.Name,
"isLeaf": true,
"extra": maps.Map{
"protocol": "website",
"logo": "",
"status": w.Status,
"network": w.Domain,
},
}
tree = append(tree, node)
}
return Success(c, tree)
}
func (api PortalApi) AssetsGroupTreeEndpoint(c echo.Context) error {
groups, _ := repository.AssetGroupRepository.FindAll(context.TODO())
tree := make([]maps.Map, 0)
for _, g := range groups {
node := maps.Map{
"key": g.ID,
"title": g.Name,
"isLeaf": false,
"children": []interface{}{},
}
tree = append(tree, node)
}
return Success(c, tree)
}
func (api PortalApi) WebsitesGroupTreeEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api PortalApi) AccessRequireMfaEndpoint(c echo.Context) error {
return Success(c, maps.Map{"required": false})
}
func (api PortalApi) CreateSessionEndpoint(c echo.Context) error {
var req map[string]interface{}
if err := c.Bind(&req); err != nil {
return err
}
assetId, _ := req["assetId"].(string)
account, _ := GetCurrentAccount(c)
s, err := service.SessionService.Create(c.RealIP(), assetId, nt.Native, account)
if err != nil {
return err
}
asset, _ := repository.AssetRepository.FindById(context.TODO(), assetId)
assetName := asset.Name
if assetName == "" {
assetName = assetId
}
return Success(c, maps.Map{
"id": s.ID,
"protocol": s.Protocol,
"assetName": assetName,
"strategy": maps.Map{},
"url": "",
"watermark": maps.Map{},
"readonly": false,
"idle": 3600,
"fileSystem": s.FileSystem == "1",
"width": 800,
"height": 600,
})
}
func (api PortalApi) GetSessionEndpoint(c echo.Context) error {
id := c.Param("id")
return Success(c, maps.Map{
"id": id,
"protocol": "ssh",
"assetName": id,
"strategy": maps.Map{},
"url": "",
"watermark": maps.Map{},
"readonly": false,
"idle": 3600,
"fileSystem": false,
"width": 800,
"height": 600,
})
}
func (api PortalApi) GetShareEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"enabled": false,
"passcode": "",
"url": "",
})
}
func (api PortalApi) CreateShareEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"enabled": true,
"passcode": "",
"url": "",
})
}
func (api PortalApi) CancelShareEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api PortalApi) AccessWebsiteEndpoint(c echo.Context) error {
websiteId := c.QueryParam("websiteId")
item, _ := repository.WebsiteRepository.FindById(context.TODO(), websiteId)
url := ""
if item.TargetUrl != "" {
url = item.TargetUrl
} else {
url = "http://" + item.Domain
}
return Success(c, maps.Map{"url": url})
}
func (api PortalApi) AllowWebsiteIpEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api PortalApi) WakeOnLanEndpoint(c echo.Context) error {
assetId := c.Param("id")
_ = assetId
return Success(c, maps.Map{
"delay": 5,
})
}
func (api PortalApi) PingAssetEndpoint(c echo.Context) error {
assetId := c.Param("id")
item, _ := repository.AssetRepository.FindById(context.TODO(), assetId)
return Success(c, maps.Map{
"name": item.Name,
"active": true,
"usedTime": 10,
"usedTimeStr": "10ms",
})
}
func (api PortalApi) TerminalStatsEndpoint(c echo.Context) error {
sessionId := c.Param("id")
sess := session.GlobalSessionManager.GetById(sessionId)
if sess == nil || sess.NextTerminal == nil || sess.NextTerminal.SshClient == nil {
return Success(c, maps.Map{
"info": maps.Map{
"id": "",
"name": "",
"version": "",
"arch": "",
"uptime": 0,
"hostname": "",
"upDays": 0,
},
"load": maps.Map{
"load1": "0.00",
"load5": "0.00",
"load15": "0.00",
"runningProcess": "0",
"totalProcess": "0",
},
"memory": maps.Map{
"memTotal": 0,
"memAvailable": 0,
"memFree": 0,
"memBuffers": 0,
"memCached": 0,
"memUsed": 0,
"swapTotal": 0,
"swapFree": 0,
},
"fileSystems": []interface{}{},
"network": []interface{}{},
"cpu": []interface{}{},
})
}
stats, err := getSystemStats(sess.NextTerminal.SshClient)
if err != nil {
log.Warn("Failed to get system stats", log.NamedError("error", err))
return Success(c, maps.Map{
"info": maps.Map{
"id": "",
"name": "",
"version": "",
"arch": "",
"uptime": 0,
"hostname": "",
"upDays": 0,
},
"load": maps.Map{
"load1": "0.00",
"load5": "0.00",
"load15": "0.00",
"runningProcess": "0",
"totalProcess": "0",
},
"memory": maps.Map{
"memTotal": 0,
"memAvailable": 0,
"memFree": 0,
"memBuffers": 0,
"memCached": 0,
"memUsed": 0,
"swapTotal": 0,
"swapFree": 0,
},
"fileSystems": []interface{}{},
"network": []interface{}{},
"cpu": []interface{}{},
})
}
return Success(c, stats)
}
func getSystemStats(client *ssh.Client) (maps.Map, error) {
result := maps.Map{}
// Get hostname
hostname, _ := sshExec(client, "hostname")
// Get OS info
osId, _ := sshExec(client, "cat /etc/os-release 2>/dev/null | grep '^ID=' | cut -d'=' -f2 | tr -d '\"'")
osName, _ := sshExec(client, "cat /etc/os-release 2>/dev/null | grep '^NAME=' | cut -d'=' -f2 | tr -d '\"'")
osVersion, _ := sshExec(client, "cat /etc/os-release 2>/dev/null | grep '^VERSION_ID=' | cut -d'=' -f2 | tr -d '\"'")
// Get arch
arch, _ := sshExec(client, "uname -m")
// Get uptime
uptimeStr, _ := sshExec(client, "cat /proc/uptime | awk '{print $1}'")
uptimeFloat, _ := strconv.ParseFloat(strings.TrimSpace(uptimeStr), 64)
uptime := int64(uptimeFloat)
upDays := uptime / 86400
// Get load average
loadStr, _ := sshExec(client, "cat /proc/loadavg")
loadParts := strings.Fields(loadStr)
load1, load5, load15 := "0.00", "0.00", "0.00"
if len(loadParts) >= 3 {
load1 = loadParts[0]
load5 = loadParts[1]
load15 = loadParts[2]
}
// Get process count
processStr, _ := sshExec(client, "ps aux | wc -l")
totalProcess := strings.TrimSpace(processStr)
// Get memory info
memInfo, _ := sshExec(client, "cat /proc/meminfo")
memTotal, memFree, memAvailable, memBuffers, memCached, swapTotal, swapFree := parseMemInfo(memInfo)
memUsed := memTotal - memAvailable
// Get CPU info
cpuInfo, _ := sshExec(client, "cat /proc/stat | head -1")
cpuStats := parseCpuStat(cpuInfo)
// Get filesystem info
dfOutput, _ := sshExec(client, "df -B1 | tail -n +2")
fileSystems := parseDfOutput(dfOutput)
// Get network info
netDev, _ := sshExec(client, "cat /proc/net/dev | tail -n +3")
network := parseNetDev(netDev)
result["info"] = maps.Map{
"id": strings.TrimSpace(osId),
"name": strings.TrimSpace(osName),
"version": strings.TrimSpace(osVersion),
"arch": strings.TrimSpace(arch),
"uptime": uptime,
"hostname": strings.TrimSpace(hostname),
"upDays": upDays,
}
result["load"] = maps.Map{
"load1": load1,
"load5": load5,
"load15": load15,
"runningProcess": totalProcess,
"totalProcess": totalProcess,
}
result["memory"] = maps.Map{
"memTotal": memTotal * 1024,
"memAvailable": memAvailable * 1024,
"memFree": memFree * 1024,
"memBuffers": memBuffers * 1024,
"memCached": memCached * 1024,
"memUsed": memUsed * 1024,
"swapTotal": swapTotal * 1024,
"swapFree": swapFree * 1024,
}
result["cpu"] = cpuStats
result["fileSystems"] = fileSystems
result["network"] = network
return result, nil
}
func sshExec(client *ssh.Client, cmd string) (string, error) {
session, err := client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
output, err := session.CombinedOutput(cmd)
if err != nil {
return "", err
}
return string(output), nil
}
func parseMemInfo(info string) (total, free, available, buffers, cached, swapTotal, swapFree int64) {
lines := strings.Split(info, "\n")
for _, line := range lines {
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}
key := strings.TrimSuffix(parts[0], ":")
value, _ := strconv.ParseInt(parts[1], 10, 64)
switch key {
case "MemTotal":
total = value
case "MemFree":
free = value
case "MemAvailable":
available = value
case "Buffers":
buffers = value
case "Cached":
cached = value
case "SwapTotal":
swapTotal = value
case "SwapFree":
swapFree = value
}
}
return
}
func parseCpuStat(stat string) []interface{} {
parts := strings.Fields(stat)
if len(parts) < 5 {
return []interface{}{maps.Map{"user": 0.0, "nice": 0.0, "system": 0.0}}
}
user, _ := strconv.ParseFloat(parts[1], 64)
nice, _ := strconv.ParseFloat(parts[2], 64)
system, _ := strconv.ParseFloat(parts[3], 64)
return []interface{}{
maps.Map{
"user": user,
"nice": nice,
"system": system,
},
}
}
func parseDfOutput(output string) []interface{} {
var result []interface{}
lines := strings.Split(output, "\n")
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
parts := strings.Fields(line)
if len(parts) < 6 {
continue
}
total, _ := strconv.ParseInt(parts[1], 10, 64)
used, _ := strconv.ParseInt(parts[2], 10, 64)
free, _ := strconv.ParseInt(parts[3], 10, 64)
var percent float64 = 0
if total > 0 {
percent = float64(used) / float64(total)
}
result = append(result, maps.Map{
"mountPoint": parts[5],
"total": total,
"used": used,
"free": free,
"percent": percent,
})
}
return result
}
func parseNetDev(output string) []interface{} {
var result []interface{}
lines := strings.Split(output, "\n")
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
parts := strings.Fields(line)
if len(parts) < 10 {
continue
}
iface := strings.TrimSuffix(parts[0], ":")
if strings.HasPrefix(iface, "lo") {
continue
}
rx, _ := strconv.ParseInt(parts[1], 10, 64)
tx, _ := strconv.ParseInt(parts[9], 10, 64)
result = append(result, maps.Map{
"iface": iface,
"rx": rx,
"tx": tx,
"rxSec": 0,
"txSec": 0,
})
}
return result
}
+64
View File
@@ -0,0 +1,64 @@
package api
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/pem"
"crypto/x509"
"next-terminal/server/repository"
"next-terminal/server/service"
"github.com/labstack/echo/v4"
)
type PropertyApi struct{}
func (api PropertyApi) PropertyGetEndpoint(c echo.Context) error {
properties := repository.PropertyRepository.FindAllMap(context.TODO())
return Success(c, properties)
}
func (api PropertyApi) PropertyUpdateEndpoint(c echo.Context) error {
var item map[string]interface{}
if err := c.Bind(&item); err != nil {
return err
}
if err := service.PropertyService.Update(item); err != nil {
return err
}
return Success(c, nil)
}
func (api PropertyApi) GenRSAPrivateKeyEndpoint(c echo.Context) error {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
privateKeyPem := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
return Success(c, map[string]string{"key": string(privateKeyPem)})
}
func (api PropertyApi) SendMailEndpoint(c echo.Context) error {
var req map[string]interface{}
if err := c.Bind(&req); err != nil {
return err
}
if err := service.MailService.SendTestMail(req); err != nil {
return err
}
return Success(c, nil)
}
func (api PropertyApi) ClientIPsEndpoint(c echo.Context) error {
return Success(c, map[string]string{
"direct": c.RealIP(),
"x-real-ip": c.Request().Header.Get("X-Real-IP"),
"x-forwarded-for": c.Request().Header.Get("X-Forwarded-For"),
})
}
+100
View File
@@ -0,0 +1,100 @@
package api
import (
"context"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/service"
"strconv"
"strings"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type RoleApi struct{}
func (api RoleApi) AllEndpoint(c echo.Context) error {
items, err := repository.RoleRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api RoleApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
_type := c.QueryParam("type")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.RoleRepository.Find(context.TODO(), pageIndex, pageSize, name, _type, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api RoleApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := service.RoleService.FindById(context.Background(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api RoleApi) CreateEndpoint(c echo.Context) error {
var item model.Role
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
item.Deletable = true
item.Modifiable = true
item.Type = "new"
if err := service.RoleService.Create(context.Background(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api RoleApi) DeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
if err := service.RoleService.DeleteByIds(context.Background(), split, false); err != nil {
return err
}
return Success(c, nil)
}
func (api RoleApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Role
if err := c.Bind(&item); err != nil {
return err
}
if err := service.RoleService.UpdateById(context.Background(), &item, id, false); err != nil {
return err
}
return Success(c, "")
}
func (api RoleApi) TreeMenus(c echo.Context) error {
return Success(c, service.MenuService.GetTreeMenus())
}
+112
View File
@@ -0,0 +1,112 @@
package api
import (
"context"
"next-terminal/server/common/maps"
"strconv"
"strings"
"next-terminal/server/global/security"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type SecurityApi struct{}
func (api SecurityApi) SecurityCreateEndpoint(c echo.Context) error {
var item model.AccessSecurity
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Source = "管理员添加"
if err := repository.SecurityRepository.Create(context.TODO(), &item); err != nil {
return err
}
// 更新内存中的安全规则
rule := &security.Security{
ID: item.ID,
IP: item.IP,
Rule: item.Rule,
Priority: item.Priority,
}
security.GlobalSecurityManager.Add(rule)
return Success(c, "")
}
func (api SecurityApi) SecurityPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
ip := c.QueryParam("ip")
rule := c.QueryParam("rule")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.SecurityRepository.Find(context.TODO(), pageIndex, pageSize, ip, rule, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api SecurityApi) SecurityUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.AccessSecurity
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.SecurityRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
// 更新内存中的安全规则
security.GlobalSecurityManager.Del(id)
rule := &security.Security{
ID: item.ID,
IP: item.IP,
Rule: item.Rule,
Priority: item.Priority,
}
security.GlobalSecurityManager.Add(rule)
return Success(c, nil)
}
func (api SecurityApi) SecurityDeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
for i := range split {
id := split[i]
if err := repository.SecurityRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
// 更新内存中的安全规则
security.GlobalSecurityManager.Del(id)
}
return Success(c, nil)
}
func (api SecurityApi) SecurityGetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.SecurityRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
+665
View File
@@ -0,0 +1,665 @@
package api
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/global/session"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/pkg/sftp"
)
type SessionApi struct{}
func (api SessionApi) SessionPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
status := c.QueryParam("status")
userId := c.QueryParam("userId")
clientIp := c.QueryParam("clientIp")
assetId := c.QueryParam("assetId")
protocol := c.QueryParam("protocol")
reviewed := c.QueryParam("reviewed")
items, total, err := repository.SessionRepository.Find(context.TODO(), pageIndex, pageSize, status, userId, clientIp, assetId, protocol, reviewed)
if err != nil {
return err
}
now := time.Now()
for i := 0; i < len(items); i++ {
if status == nt.Disconnected && len(items[i].Recording) > 0 {
var recording string
if items[i].Mode == nt.Native || items[i].Mode == nt.Terminal {
recording = items[i].Recording
} else {
recording = items[i].Recording + "/recording"
}
if utils.FileExists(recording) {
items[i].Recording = "1"
} else {
items[i].Recording = "0"
}
} else {
items[i].Recording = "0"
}
// 计算持续时长
if items[i].Status == nt.Connected {
duration := now.Sub(items[i].ConnectedTime.Time)
items[i].ConnectionDuration = formatDuration(duration)
} else {
duration := items[i].DisconnectedTime.Time.Sub(items[i].ConnectedTime.Time)
items[i].ConnectionDuration = formatDuration(duration)
}
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func formatDuration(d time.Duration) string {
hours := int(d.Hours())
minutes := int(d.Minutes()) % 60
seconds := int(d.Seconds()) % 60
if hours > 0 {
return fmt.Sprintf("%d小时%d分%d秒", hours, minutes, seconds)
} else if minutes > 0 {
return fmt.Sprintf("%d分%d秒", minutes, seconds)
}
return fmt.Sprintf("%d秒", seconds)
}
func (api SessionApi) SessionDeleteEndpoint(c echo.Context) error {
sessionIds := strings.Split(c.Param("id"), ",")
err := service.SessionService.DeleteByIds(context.TODO(), sessionIds)
if err != nil {
return err
}
return Success(c, nil)
}
func (api SessionApi) SessionClearEndpoint(c echo.Context) error {
err := service.SessionService.ClearOfflineSession()
if err != nil {
return err
}
return Success(c, nil)
}
func (api SessionApi) SessionReviewedEndpoint(c echo.Context) error {
sessionIds := strings.Split(c.Param("id"), ",")
if err := repository.SessionRepository.UpdateReadByIds(context.TODO(), true, sessionIds); err != nil {
return err
}
return Success(c, nil)
}
func (api SessionApi) SessionUnViewedEndpoint(c echo.Context) error {
sessionIds := strings.Split(c.Param("id"), ",")
if err := repository.SessionRepository.UpdateReadByIds(context.TODO(), false, sessionIds); err != nil {
return err
}
return Success(c, nil)
}
func (api SessionApi) SessionReviewedAllEndpoint(c echo.Context) error {
if err := service.SessionService.ReviewedAll(); err != nil {
return err
}
return Success(c, nil)
}
func (api SessionApi) SessionConnectEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s := model.Session{}
s.ID = sessionId
s.Status = nt.Connected
s.ConnectedTime = common.NowJsonTime()
if err := repository.SessionRepository.UpdateById(context.TODO(), &s, sessionId); err != nil {
return err
}
o, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
asset, err := repository.AssetRepository.FindById(context.TODO(), o.AssetId)
if err != nil {
return err
}
if !asset.Active {
asset.Active = true
_ = repository.AssetRepository.UpdateById(context.TODO(), &asset, asset.ID)
}
return Success(c, nil)
}
func (api SessionApi) SessionDisconnectEndpoint(c echo.Context) error {
sessionIds := c.Param("id")
split := strings.Split(sessionIds, ",")
for i := range split {
service.SessionService.CloseSessionById(split[i], ForcedDisconnect, "管理员强制关闭了此会话")
}
return Success(c, nil)
}
func (api SessionApi) SessionResizeEndpoint(c echo.Context) error {
width := c.QueryParam("width")
height := c.QueryParam("height")
sessionId := c.Param("id")
if len(width) == 0 || len(height) == 0 {
return errors.New("参数异常")
}
intWidth, _ := strconv.Atoi(width)
intHeight, _ := strconv.Atoi(height)
if err := repository.SessionRepository.UpdateWindowSizeById(context.TODO(), intWidth, intHeight, sessionId); err != nil {
return err
}
return Success(c, "")
}
func (api SessionApi) SessionCreateEndpoint(c echo.Context) error {
assetId := c.QueryParam("assetId")
mode := c.QueryParam("mode")
if mode == nt.Native {
mode = nt.Native
} else {
mode = nt.Guacd
}
user, _ := GetCurrentAccount(c)
s, err := service.SessionService.Create(c.RealIP(), assetId, mode, user)
if err != nil {
return err
}
return Success(c, echo.Map{
"id": s.ID,
"upload": s.Upload,
"download": s.Download,
"delete": s.Delete,
"rename": s.Rename,
"edit": s.Edit,
"storageId": s.StorageId,
"fileSystem": s.FileSystem,
"copy": s.Copy,
"paste": s.Paste,
})
}
func (api SessionApi) SessionUploadEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
if s.Upload != "1" {
return errors.New("禁止操作")
}
file, err := c.FormFile("file")
if err != nil {
return err
}
filename := file.Filename
src, err := file.Open()
if err != nil {
return err
}
remoteDir := c.QueryParam("dir")
remoteFile := path.Join(remoteDir, filename)
// 记录日志
account, _ := GetCurrentAccount(c)
_ = service.StorageLogService.Save(context.Background(), s.AssetId, sessionId, account.ID, nt.StorageLogActionUpload, remoteFile)
if "ssh" == s.Protocol {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
sftpClient := nextSession.NextTerminal.SftpClient
// 文件夹不存在时自动创建文件夹
if _, err := sftpClient.Stat(remoteDir); os.IsNotExist(err) {
if err := sftpClient.MkdirAll(remoteDir); err != nil {
return err
}
}
dstFile, err := sftpClient.Create(remoteFile)
if err != nil {
return err
}
defer dstFile.Close()
counter := &WriteCounter{Resp: c.Response()}
c.Response().Header().Set(echo.HeaderContentType, `text/event-stream`)
c.Response().WriteHeader(http.StatusOK)
srcReader := io.TeeReader(src, counter)
if _, err = io.Copy(dstFile, srcReader); err != nil {
return err
}
return Success(c, nil)
} else if "rdp" == s.Protocol {
if err := service.StorageService.StorageUpload(c, file, s.StorageId); err != nil {
return err
}
return Success(c, nil)
}
return err
}
func (api SessionApi) SessionEditEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
if s.Edit != "1" {
return errors.New("禁止操作")
}
file := c.FormValue("file")
fileContent := c.FormValue("fileContent")
if "ssh" == s.Protocol {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
sftpClient := nextSession.NextTerminal.SftpClient
dstFile, err := sftpClient.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
if err != nil {
return err
}
defer dstFile.Close()
write := bufio.NewWriter(dstFile)
// replace \r\n to \n
if _, err := write.WriteString(strings.Replace(fileContent, "\r\n", "\n", -1)); err != nil {
return err
}
// fix neoel
if !strings.HasSuffix(fileContent, "\n") {
if _, err := write.WriteString("\n"); err != nil {
return err
}
}
if err := write.Flush(); err != nil {
return err
}
return Success(c, nil)
} else if "rdp" == s.Protocol {
if err := service.StorageService.StorageEdit(file, fileContent, s.StorageId); err != nil {
return err
}
return Success(c, nil)
}
return err
}
func (api SessionApi) SessionDownloadEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
if s.Download != "1" {
return errors.New("禁止操作")
}
file := c.QueryParam("file")
// 记录日志
account, _ := GetCurrentAccount(c)
_ = service.StorageLogService.Save(context.Background(), s.AssetId, sessionId, account.ID, nt.StorageLogActionDownload, file)
// 获取带后缀的文件名称
filenameWithSuffix := path.Base(file)
if "ssh" == s.Protocol {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
dstFile, err := nextSession.NextTerminal.SftpClient.Open(file)
if err != nil {
return err
}
defer dstFile.Close()
c.Response().Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filenameWithSuffix))
var buff bytes.Buffer
if _, err := dstFile.WriteTo(&buff); err != nil {
return err
}
return c.Stream(http.StatusOK, echo.MIMEOctetStream, bytes.NewReader(buff.Bytes()))
} else if "rdp" == s.Protocol {
storageId := s.StorageId
return service.StorageService.StorageDownload(c, file, storageId)
}
return err
}
func (api SessionApi) SessionLsEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := service.SessionService.FindByIdAndDecrypt(context.TODO(), sessionId)
if err != nil {
return err
}
remoteDir := c.FormValue("dir")
if "ssh" == s.Protocol {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
if nextSession.NextTerminal.SftpClient == nil {
sftpClient, err := sftp.NewClient(nextSession.NextTerminal.SshClient)
if err != nil {
return err
}
nextSession.NextTerminal.SftpClient = sftpClient
}
fileInfos, err := nextSession.NextTerminal.SftpClient.ReadDir(remoteDir)
if err != nil {
return err
}
var files = make([]service.File, 0)
for i := range fileInfos {
file := service.File{
Name: fileInfos[i].Name(),
Path: path.Join(remoteDir, fileInfos[i].Name()),
IsDir: fileInfos[i].IsDir(),
Mode: fileInfos[i].Mode().String(),
IsLink: fileInfos[i].Mode()&os.ModeSymlink == os.ModeSymlink,
ModTime: common.NewJsonTime(fileInfos[i].ModTime()),
Size: fileInfos[i].Size(),
}
files = append(files, file)
}
return Success(c, files)
} else if "rdp" == s.Protocol {
storageId := s.StorageId
err, files := service.StorageService.StorageLs(remoteDir, storageId)
if err != nil {
return err
}
return Success(c, files)
}
return errors.New("当前协议不支持此操作")
}
func (api SessionApi) SessionMkDirEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
if s.Upload != "1" {
return errors.New("禁止操作")
}
remoteDir := c.QueryParam("dir")
// 记录日志
account, _ := GetCurrentAccount(c)
_ = service.StorageLogService.Save(context.Background(), s.AssetId, sessionId, account.ID, nt.StorageLogActionMkdir, remoteDir)
if "ssh" == s.Protocol {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
if err := nextSession.NextTerminal.SftpClient.Mkdir(remoteDir); err != nil {
return err
}
return Success(c, nil)
} else if "rdp" == s.Protocol {
storageId := s.StorageId
if err := service.StorageService.StorageMkDir(remoteDir, storageId); err != nil {
return err
}
return Success(c, nil)
}
return errors.New("当前协议不支持此操作")
}
func (api SessionApi) SessionRmEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
if s.Delete != "1" {
return errors.New("禁止操作")
}
// 文件夹或者文件
file := c.FormValue("file")
// 记录日志
account, _ := GetCurrentAccount(c)
_ = service.StorageLogService.Save(context.Background(), s.AssetId, sessionId, account.ID, nt.StorageLogActionRm, file)
if "ssh" == s.Protocol {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
sftpClient := nextSession.NextTerminal.SftpClient
stat, err := sftpClient.Stat(file)
if err != nil {
return err
}
if stat.IsDir() {
fileInfos, err := sftpClient.ReadDir(file)
if err != nil {
return err
}
for i := range fileInfos {
if err := sftpClient.Remove(path.Join(file, fileInfos[i].Name())); err != nil {
return err
}
}
if err := sftpClient.RemoveDirectory(file); err != nil {
return err
}
} else {
if err := sftpClient.Remove(file); err != nil {
return err
}
}
return Success(c, nil)
} else if "rdp" == s.Protocol {
storageId := s.StorageId
if err := service.StorageService.StorageRm(file, storageId); err != nil {
return err
}
return Success(c, nil)
}
return errors.New("当前协议不支持此操作")
}
func (api SessionApi) SessionRenameEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
if s.Rename != "1" {
return errors.New("禁止操作")
}
oldName := c.QueryParam("oldName")
newName := c.QueryParam("newName")
// 记录日志
account, _ := GetCurrentAccount(c)
_ = service.StorageLogService.Save(context.Background(), s.AssetId, sessionId, account.ID, nt.StorageLogActionRename, oldName)
if "ssh" == s.Protocol {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
sftpClient := nextSession.NextTerminal.SftpClient
if err := sftpClient.Rename(oldName, newName); err != nil {
return err
}
return Success(c, nil)
} else if "rdp" == s.Protocol {
storageId := s.StorageId
if err := service.StorageService.StorageRename(oldName, newName, storageId); err != nil {
return err
}
return Success(c, nil)
}
return errors.New("当前协议不支持此操作")
}
func (api SessionApi) SessionRecordingEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
var recording string
if s.Mode == nt.Native || s.Mode == nt.Terminal {
recording = s.Recording
} else {
recording = s.Recording + "/recording"
}
_ = repository.SessionRepository.UpdateReadByIds(context.TODO(), true, []string{sessionId})
http.ServeFile(c.Response(), c.Request(), recording)
return nil
}
func (api SessionApi) SessionGetEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(context.TODO(), sessionId)
if err != nil {
return err
}
return Success(c, s)
}
func (api SessionApi) SessionStatsEndpoint(c echo.Context) error {
sessionId := c.Param("id")
s, err := service.SessionService.FindByIdAndDecrypt(context.TODO(), sessionId)
if err != nil {
return err
}
if "ssh" != s.Protocol {
return Fail(c, -1, "不支持当前协议")
}
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return errors.New("获取会话失败")
}
stats, err := GetAllStats(nextSession)
if err != nil {
return err
}
return Success(c, stats)
}
func (api SessionApi) SessionAuditEnabledEndpoint(c echo.Context) error {
return Success(c, echo.Map{
"terminalEnabled": false,
})
}
func (api SessionApi) SessionTriggerAuditEndpoint(c echo.Context) error {
sessionId := c.Param("id")
audit := &model.SessionAudit{
ID: utils.UUID(),
SessionId: sessionId,
Status: "completed",
Content: "Audit completed. No issues found.",
Created: common.NowJsonTime(),
Updated: common.NowJsonTime(),
}
if err := repository.SessionAuditRepository.Upsert(context.TODO(), audit); err != nil {
return err
}
return Success(c, audit)
}
func (api SessionApi) SessionGetAuditEndpoint(c echo.Context) error {
sessionId := c.Param("id")
audit, err := repository.SessionAuditRepository.FindBySessionId(context.TODO(), sessionId)
if err != nil {
return err
}
if audit.ID == "" {
return Success(c, nil)
}
return Success(c, audit)
}
+20
View File
@@ -0,0 +1,20 @@
package api
import (
"fmt"
"github.com/labstack/echo/v4"
)
type WriteCounter struct {
Resp *echo.Response `json:"-"`
Total uint64 `json:"total"`
}
func (wc *WriteCounter) Write(p []byte) (n int, err error) {
wc.Total += uint64(len(p))
// 向前端写入进度
data := fmt.Sprintf("%d㊥", wc.Total)
_, _ = wc.Resp.Write([]byte(data))
wc.Resp.Flush()
return n, nil
}
+152
View File
@@ -0,0 +1,152 @@
package api
import (
"context"
"next-terminal/server/common"
"next-terminal/server/common/nt"
"next-terminal/server/dto"
"next-terminal/server/global/cache"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type SetupApi struct{}
func (api SetupApi) SetupUserEndpoint(c echo.Context) error {
var user dto.UserCreate
if err := c.Bind(&user); err != nil {
return err
}
count, err := repository.UserRepository.Count(context.TODO())
if err != nil {
return err
}
if count > 0 {
return Fail(c, 0, "系统已初始化,禁止重复初始化")
}
passwd, err := utils.Encoder.Encode([]byte(user.Password))
if err != nil {
return err
}
u := model.User{
ID: utils.LongUUID(),
Username: user.Username,
Nickname: user.Nickname,
Password: string(passwd),
Type: nt.TypeAdmin,
Status: nt.StatusEnabled,
Online: boolP(true),
}
if err := repository.UserRepository.Create(context.TODO(), &u); err != nil {
return err
}
// 初始化角色和菜单
if err := service.RoleService.Init(); err != nil {
return err
}
return Success(c, nil)
}
func (api SetupApi) GetSetupStatusEndpoint(c echo.Context) error {
count, err := repository.UserRepository.Count(context.TODO())
if err != nil {
return err
}
needSetup := count == 0
return Success(c, map[string]bool{
"needSetup": needSetup,
})
}
func (api SetupApi) LoginStatusEndpoint(c echo.Context) error {
token := GetToken(c)
if token == "" {
return Success(c, map[string]interface{}{
"status": "Unlogged",
"passwordEnabled": true,
"webauthnEnabled": false,
"wechatWorkEnabled": false,
"oidcEnabled": false,
})
}
authorization, ok := cache.TokenManager.Get(token)
if !ok {
return Success(c, map[string]interface{}{
"status": "Unlogged",
"passwordEnabled": true,
"webauthnEnabled": false,
"wechatWorkEnabled": false,
"oidcEnabled": false,
})
}
auth := authorization.(dto.Authorization)
user := auth.User
status := "Logged In"
if user.TOTPSecret != "" && user.TOTPSecret != "-" {
status = "OTP Required"
}
return Success(c, map[string]interface{}{
"status": status,
"passwordEnabled": true,
"webauthnEnabled": false,
"wechatWorkEnabled": false,
"oidcEnabled": false,
})
}
func (api SetupApi) ValidateTOTPEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
var validateTOTP struct {
TOTP string `json:"totp"`
}
if err := c.Bind(&validateTOTP); err != nil {
return err
}
if account.TOTPSecret == "" || account.TOTPSecret == "-" {
return Fail(c, -1, "未启用双因素认证")
}
if !common.Validate(validateTOTP.TOTP, account.TOTPSecret) {
return Fail(c, -1, "验证码不正确")
}
return Success(c, nil)
}
func (api SetupApi) PasswordPolicyEndpoint(c echo.Context) error {
return Success(c, map[string]interface{}{
"minLength": 6,
"minCharacterType": 0,
"mustNotContainUsername": false,
"mustNotBePalindrome": false,
"mustNotWeek": false,
})
}
func (api SetupApi) GetCaptchaEndpoint(c echo.Context) error {
return Success(c, map[string]interface{}{
"enabled": false,
"key": "",
"captcha": "",
})
}
func boolP(b bool) *bool {
return &b
}
+130
View File
@@ -0,0 +1,130 @@
package api
import (
"context"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"strconv"
"github.com/labstack/echo/v4"
)
type SnippetApi struct{}
func (api SnippetApi) AllEndpoint(c echo.Context) error {
items, err := repository.SnippetRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api SnippetApi) PagingEndpoint(c echo.Context) error {
pageIndex := 1
pageSize := 10
if pi := c.QueryParam("pageIndex"); pi != "" {
if p, err := strconv.Atoi(pi); err == nil && p > 0 {
pageIndex = p
}
}
if ps := c.QueryParam("pageSize"); ps != "" {
if p, err := strconv.Atoi(ps); err == nil && p > 0 {
pageSize = p
}
}
name := c.QueryParam("name")
items, total, err := repository.SnippetRepository.FindPage(context.TODO(), pageIndex, pageSize, name)
if err != nil {
return err
}
return Success(c, maps.Map{
"items": items,
"total": total,
})
}
func (api SnippetApi) CreateEndpoint(c echo.Context) error {
var item model.Snippet
if err := c.Bind(&item); err != nil {
return err
}
account, _ := GetCurrentAccount(c)
item.ID = utils.LongUUID()
item.CreatedBy = account.ID
item.UpdatedBy = account.ID
if item.Visibility == "" {
item.Visibility = "private"
}
if err := repository.SnippetRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, item)
}
func (api SnippetApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Snippet
if err := c.Bind(&item); err != nil {
return err
}
account, _ := GetCurrentAccount(c)
item.ID = id
item.UpdatedBy = account.ID
if err := repository.SnippetRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, item)
}
func (api SnippetApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.SnippetRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
return Success(c, nil)
}
func (api SnippetApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.SnippetRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
type SnippetUserApi struct{}
func (api SnippetUserApi) AllEndpoint(c echo.Context) error {
account, _ := GetCurrentAccount(c)
items, err := repository.SnippetRepository.FindByUserId(context.TODO(), account.ID)
if err != nil {
return err
}
return Success(c, items)
}
func (api SnippetUserApi) PagingEndpoint(c echo.Context) error {
return api.AllEndpoint(c)
}
func (api SnippetUserApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.SnippetRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
+110
View File
@@ -0,0 +1,110 @@
package api
import (
"context"
"strconv"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type SshGatewayApi struct{}
func (api SshGatewayApi) AllEndpoint(c echo.Context) error {
items, err := repository.SshGatewayRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api SshGatewayApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
items, total, err := repository.SshGatewayRepository.Find(context.TODO(), pageIndex, pageSize, name)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api SshGatewayApi) CreateEndpoint(c echo.Context) error {
var item model.SshGateway
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Type = "ssh"
item.Status = "unknown"
if err := repository.SshGatewayRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api SshGatewayApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.SshGateway
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.SshGatewayRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, nil)
}
func (api SshGatewayApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.SshGatewayRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
return Success(c, nil)
}
func (api SshGatewayApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.SshGatewayRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api SshGatewayApi) DecryptedEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.SshGatewayRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api SshGatewayApi) AvailableForGatewayEndpoint(c echo.Context) error {
assets, err := repository.SshGatewayRepository.FindAvailableAssets(context.TODO())
if err != nil {
return err
}
result := make([]maps.Map, len(assets))
for i, a := range assets {
result[i] = maps.Map{
"id": a.ID,
"name": a.Name,
"ip": a.IP,
"port": a.Port,
"canBeGateway": true,
"disableReason": "",
}
}
return Success(c, result)
}
+402
View File
@@ -0,0 +1,402 @@
package api
import (
"bufio"
"fmt"
"next-terminal/server/common/taskrunner"
"next-terminal/server/global/session"
"strconv"
"strings"
"time"
"next-terminal/server/utils"
"golang.org/x/crypto/ssh"
)
type FileSystem struct {
MountPoint string `json:"mountPoint"`
Used uint64 `json:"used"`
Free uint64 `json:"free"`
}
type Network struct {
IPv4 string `json:"ipv4"`
IPv6 string `json:"ipv6"`
Rx uint64 `json:"rx"`
Tx uint64 `json:"tx"`
}
type cpuRaw struct {
User uint64 // time spent in user mode
Nice uint64 // time spent in user mode with low priority (nice)
System uint64 // time spent in system mode
Idle uint64 // time spent in the idle task
Iowait uint64 // time spent waiting for I/O to complete (since Linux 2.5.41)
Irq uint64 // time spent servicing interrupts (since 2.6.0-test4)
SoftIrq uint64 // time spent servicing softirqs (since 2.6.0-test4)
Steal uint64 // time spent in other OSes when running in a virtualized environment
Guest uint64 // time spent running a virtual CPU for guest operating systems under the control of the Linux kernel.
Total uint64 // total of all time fields
}
type CPU struct {
User float32 `json:"user"`
Nice float32 `json:"nice"`
System float32 `json:"system"`
Idle float32 `json:"idle"`
IOWait float32 `json:"ioWait"`
Irq float32 `json:"irq"`
SoftIrq float32 `json:"softIrq"`
Steal float32 `json:"steal"`
Guest float32 `json:"guest"`
}
type Stat struct {
Uptime int64 `json:"uptime"`
Hostname string `json:"hostname"`
Load1 string `json:"load1"`
Load5 string `json:"load5"`
Load10 string `json:"load10"`
RunningProcess string `json:"runningProcess"`
TotalProcess string `json:"totalProcess"`
MemTotal uint64 `json:"memTotal"`
MemAvailable uint64 `json:"memAvailable"`
MemFree uint64 `json:"memFree"`
MemBuffers uint64 `json:"memBuffers"`
MemCached uint64 `json:"memCached"`
SwapTotal uint64 `json:"swapTotal"`
SwapFree uint64 `json:"swapFree"`
FileSystems []FileSystem `json:"fileSystems"`
Network map[string]Network `json:"network"`
CPU CPU `json:"cpu"`
}
func GetAllStats(nextSession *session.Session) (*Stat, error) {
client := nextSession.NextTerminal.SshClient
start := time.Now()
stats := &Stat{
Uptime: nextSession.Uptime,
Hostname: nextSession.Hostname,
}
if stats.Uptime == 0 {
if err := getUptime(client, stats); err != nil {
return nil, err
}
nextSession.Uptime = stats.Uptime
}
if stats.Hostname == "" {
if err := getHostname(client, stats); err != nil {
return nil, err
}
nextSession.Hostname = stats.Hostname
}
runner := taskrunner.Runner{}
runner.Add(func() error {
return getLoad(client, stats)
})
runner.Add(func() error {
return getMem(client, stats)
})
runner.Add(func() error {
return getFileSystems(client, stats)
})
runner.Add(func() error {
return getInterfaces(client, stats)
})
runner.Add(func() error {
return getInterfaceInfo(client, stats)
})
runner.Add(func() error {
return getCPU(client, stats)
})
runner.Wait()
cost := time.Since(start)
fmt.Printf("%s: %v\n", "GetAllStats", cost)
return stats, nil
}
func getHostname(client *ssh.Client, stat *Stat) (err error) {
defer utils.TimeWatcher("getHostname")
hostname, err := utils.RunCommand(client, "/bin/hostname -f")
if err != nil {
return
}
stat.Hostname = strings.TrimSpace(hostname)
return
}
func getUptime(client *ssh.Client, stat *Stat) (err error) {
defer utils.TimeWatcher("getUptime")
uptime, err := utils.RunCommand(client, "/bin/cat /proc/uptime")
if err != nil {
return
}
parts := strings.Fields(uptime)
if len(parts) == 2 {
var upSeconds float64
upSeconds, err = strconv.ParseFloat(parts[0], 64)
if err != nil {
return
}
stat.Uptime = int64(upSeconds * 1000)
}
return
}
func getLoad(client *ssh.Client, stat *Stat) (err error) {
defer utils.TimeWatcher("getLoad")
line, err := utils.RunCommand(client, "/bin/cat /proc/loadavg")
if err != nil {
return
}
parts := strings.Fields(line)
if len(parts) == 5 {
stat.Load1 = parts[0]
stat.Load5 = parts[1]
stat.Load10 = parts[2]
if i := strings.Index(parts[3], "/"); i != -1 {
stat.RunningProcess = parts[3][0:i]
if i+1 < len(parts[3]) {
stat.TotalProcess = parts[3][i+1:]
}
}
}
return
}
func getMem(client *ssh.Client, stat *Stat) (err error) {
defer utils.TimeWatcher("getMem")
lines, err := utils.RunCommand(client, "/bin/cat /proc/meminfo")
if err != nil {
return
}
scanner := bufio.NewScanner(strings.NewReader(lines))
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
if len(parts) == 3 {
val, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
continue
}
val *= 1024
switch parts[0] {
case "MemTotal:":
stat.MemTotal = val
case "MemFree:":
stat.MemFree = val
case "MemAvailable:":
stat.MemAvailable = val
case "Buffers:":
stat.MemBuffers = val
case "Cached:":
stat.MemCached = val
case "SwapTotal:":
stat.SwapTotal = val
case "SwapFree:":
stat.SwapFree = val
}
}
}
return
}
func getFileSystems(client *ssh.Client, stat *Stat) (err error) {
defer utils.TimeWatcher("getFileSystems")
lines, err := utils.RunCommand(client, "/bin/df -B1")
if err != nil {
return
}
scanner := bufio.NewScanner(strings.NewReader(lines))
flag := 0
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
n := len(parts)
dev := n > 0 && strings.Index(parts[0], "/dev/") == 0
if n == 1 && dev {
flag = 1
} else if (n == 5 && flag == 1) || (n == 6 && dev) {
i := flag
flag = 0
used, err := strconv.ParseUint(parts[2-i], 10, 64)
if err != nil {
continue
}
free, err := strconv.ParseUint(parts[3-i], 10, 64)
if err != nil {
continue
}
stat.FileSystems = append(stat.FileSystems, FileSystem{
parts[5-i], used, free,
})
}
}
return
}
func getInterfaces(client *ssh.Client, stats *Stat) (err error) {
defer utils.TimeWatcher("getInterfaces")
var lines string
lines, err = utils.RunCommand(client, "/bin/ip -o addr")
if err != nil {
// try /sbin/ip
lines, err = utils.RunCommand(client, "/sbin/ip -o addr")
if err != nil {
return
}
}
if stats.Network == nil {
stats.Network = make(map[string]Network)
}
scanner := bufio.NewScanner(strings.NewReader(lines))
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
if len(parts) >= 4 && (parts[2] == "inet" || parts[2] == "inet6") {
ipv4 := parts[2] == "inet"
intfname := parts[1]
if info, ok := stats.Network[intfname]; ok {
if ipv4 {
info.IPv4 = parts[3]
} else {
info.IPv6 = parts[3]
}
stats.Network[intfname] = info
} else {
info := Network{}
if ipv4 {
info.IPv4 = parts[3]
} else {
info.IPv6 = parts[3]
}
stats.Network[intfname] = info
}
}
}
return
}
func getInterfaceInfo(client *ssh.Client, stats *Stat) (err error) {
defer utils.TimeWatcher("getInterfaceInfo")
if stats.Network == nil {
return
} // should have been here already
lines, err := utils.RunCommand(client, "/bin/cat /proc/net/dev")
if err != nil {
return
}
scanner := bufio.NewScanner(strings.NewReader(lines))
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
if len(parts) == 17 {
intf := strings.TrimSpace(parts[0])
intf = strings.TrimSuffix(intf, ":")
if info, ok := stats.Network[intf]; ok {
rx, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
continue
}
tx, err := strconv.ParseUint(parts[9], 10, 64)
if err != nil {
continue
}
info.Rx = rx
info.Tx = tx
stats.Network[intf] = info
}
}
}
return
}
func parseCPUFields(fields []string, stat *cpuRaw) {
numFields := len(fields)
for i := 1; i < numFields; i++ {
val, err := strconv.ParseUint(fields[i], 10, 64)
if err != nil {
continue
}
stat.Total += val
switch i {
case 1:
stat.User = val
case 2:
stat.Nice = val
case 3:
stat.System = val
case 4:
stat.Idle = val
case 5:
stat.Iowait = val
case 6:
stat.Irq = val
case 7:
stat.SoftIrq = val
case 8:
stat.Steal = val
case 9:
stat.Guest = val
}
}
}
// the CPU stats that were fetched last time round
var preCPU cpuRaw
func getCPU(client *ssh.Client, stats *Stat) (err error) {
defer utils.TimeWatcher("getCPU")
lines, err := utils.RunCommand(client, "/bin/cat /proc/stat")
if err != nil {
return
}
var (
nowCPU cpuRaw
total float32
)
scanner := bufio.NewScanner(strings.NewReader(lines))
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) > 0 && fields[0] == "cpu" { // changing here if want to get every cpu-core's stats
parseCPUFields(fields, &nowCPU)
break
}
}
if preCPU.Total == 0 { // having no pre raw cpu data
goto END
}
total = float32(nowCPU.Total - preCPU.Total)
stats.CPU.User = float32(nowCPU.User-preCPU.User) / total * 100
stats.CPU.Nice = float32(nowCPU.Nice-preCPU.Nice) / total * 100
stats.CPU.System = float32(nowCPU.System-preCPU.System) / total * 100
stats.CPU.Idle = float32(nowCPU.Idle-preCPU.Idle) / total * 100
stats.CPU.IOWait = float32(nowCPU.Iowait-preCPU.Iowait) / total * 100
stats.CPU.Irq = float32(nowCPU.Irq-preCPU.Irq) / total * 100
stats.CPU.SoftIrq = float32(nowCPU.SoftIrq-preCPU.SoftIrq) / total * 100
stats.CPU.Guest = float32(nowCPU.Guest-preCPU.Guest) / total * 100
END:
preCPU = nowCPU
return
}
+247
View File
@@ -0,0 +1,247 @@
package api
import (
"context"
"errors"
"os"
"path"
"strconv"
"strings"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/common/nt"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type StorageApi struct{}
func (api StorageApi) StoragePagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.StorageRepository.Find(context.TODO(), pageIndex, pageSize, name, order, field)
if err != nil {
return err
}
drivePath := service.StorageService.GetBaseDrivePath()
for i := range items {
item := items[i]
dirSize, err := utils.DirSize(path.Join(drivePath, item.ID))
if err != nil {
items[i].UsedSize = -1
} else {
items[i].UsedSize = dirSize
}
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api StorageApi) StorageCreateEndpoint(c echo.Context) error {
var item model.Storage
if err := c.Bind(&item); err != nil {
return err
}
account, _ := GetCurrentAccount(c)
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
item.Owner = account.ID
// 创建对应的目录文件夹
drivePath := service.StorageService.GetBaseDrivePath()
if err := os.MkdirAll(path.Join(drivePath, item.ID), os.ModePerm); err != nil {
return err
}
if err := repository.StorageRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api StorageApi) StorageUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Storage
if err := c.Bind(&item); err != nil {
return err
}
drivePath := service.StorageService.GetBaseDrivePath()
dirSize, err := utils.DirSize(path.Join(drivePath, item.ID))
if err != nil {
return err
}
if item.LimitSize > 0 && item.LimitSize < dirSize {
// 不能小于已使用的大小
return errors.New("空间大小不能小于已使用大小")
}
storage, err := repository.StorageRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
storage.Name = item.Name
storage.LimitSize = item.LimitSize
storage.IsShare = item.IsShare
if err := repository.StorageRepository.SaveById(context.TODO(), &storage, id); err != nil {
return err
}
return Success(c, "")
}
func (api StorageApi) StorageGetEndpoint(c echo.Context) error {
storageId := c.Param("id")
storage, err := repository.StorageRepository.FindById(context.TODO(), storageId)
if err != nil {
return err
}
structMap := utils.StructToMap(storage)
drivePath := service.StorageService.GetBaseDrivePath()
dirSize, err := utils.DirSize(path.Join(drivePath, storageId))
if err != nil {
structMap["usedSize"] = -1
} else {
structMap["usedSize"] = dirSize
}
return Success(c, structMap)
}
func (api StorageApi) StorageSharesEndpoint(c echo.Context) error {
storages, err := repository.StorageRepository.FindShares(context.TODO())
if err != nil {
return err
}
return Success(c, storages)
}
func (api StorageApi) StorageDeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
for i := range split {
id := split[i]
if err := service.StorageService.DeleteStorageById(context.TODO(), id, false); err != nil {
return err
}
}
return Success(c, nil)
}
func (api StorageApi) PermissionCheck(c echo.Context, id string) error {
storage, err := repository.StorageRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
account, _ := GetCurrentAccount(c)
if account.Type != nt.TypeAdmin {
if storage.Owner != account.ID {
return errors.New("您没有权限访问此地址 :(")
}
}
return nil
}
func (api StorageApi) StorageLsEndpoint(c echo.Context) error {
storageId := c.Param("storageId")
if err := api.PermissionCheck(c, storageId); err != nil {
return err
}
remoteDir := c.FormValue("dir")
err, files := service.StorageService.StorageLs(remoteDir, storageId)
if err != nil {
return err
}
return Success(c, files)
}
func (api StorageApi) StorageDownloadEndpoint(c echo.Context) error {
storageId := c.Param("storageId")
if err := api.PermissionCheck(c, storageId); err != nil {
return err
}
file := c.QueryParam("file")
return service.StorageService.StorageDownload(c, file, storageId)
}
func (api StorageApi) StorageUploadEndpoint(c echo.Context) error {
storageId := c.Param("storageId")
if err := api.PermissionCheck(c, storageId); err != nil {
return err
}
file, err := c.FormFile("file")
if err != nil {
return err
}
if err := service.StorageService.StorageUpload(c, file, storageId); err != nil {
return err
}
return Success(c, nil)
}
func (api StorageApi) StorageMkDirEndpoint(c echo.Context) error {
storageId := c.Param("storageId")
if err := api.PermissionCheck(c, storageId); err != nil {
return err
}
remoteDir := c.QueryParam("dir")
if err := service.StorageService.StorageMkDir(remoteDir, storageId); err != nil {
return err
}
return Success(c, nil)
}
func (api StorageApi) StorageRmEndpoint(c echo.Context) error {
storageId := c.Param("storageId")
if err := api.PermissionCheck(c, storageId); err != nil {
return err
}
// 文件夹或者文件
file := c.FormValue("file")
if err := service.StorageService.StorageRm(file, storageId); err != nil {
return err
}
return Success(c, nil)
}
func (api StorageApi) StorageRenameEndpoint(c echo.Context) error {
storageId := c.Param("storageId")
if err := api.PermissionCheck(c, storageId); err != nil {
return err
}
oldName := c.QueryParam("oldName")
newName := c.QueryParam("newName")
if err := service.StorageService.StorageRename(oldName, newName, storageId); err != nil {
return err
}
return Success(c, nil)
}
func (api StorageApi) StorageEditEndpoint(c echo.Context) error {
storageId := c.Param("storageId")
if err := api.PermissionCheck(c, storageId); err != nil {
return err
}
file := c.FormValue("file")
fileContent := c.FormValue("fileContent")
if err := service.StorageService.StorageEdit(file, fileContent, storageId); err != nil {
return err
}
return Success(c, nil)
}
+48
View File
@@ -0,0 +1,48 @@
package api
import (
"context"
"github.com/labstack/echo/v4"
"next-terminal/server/common/maps"
"next-terminal/server/repository"
"strconv"
)
type StorageLogApi struct {
}
func (api StorageLogApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
assetId := c.QueryParam("assetId")
userId := c.QueryParam("userId")
action := c.QueryParam("action")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.StorageLogRepository.Find(context.TODO(), pageIndex, pageSize, assetId, userId, action, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api StorageLogApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.StorageLogRepository.DeleteById(context.Background(), id); err != nil {
return err
}
return Success(c, nil)
}
func (api StorageLogApi) ClearEndpoint(c echo.Context) error {
if err := repository.StorageLogRepository.DeleteAll(context.Background()); err != nil {
return err
}
return Success(c, nil)
}
+92
View File
@@ -0,0 +1,92 @@
package api
import (
"context"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"strconv"
"strings"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type StrategyApi struct{}
func (api StrategyApi) StrategyAllEndpoint(c echo.Context) error {
items, err := repository.StrategyRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api StrategyApi) StrategyPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.StrategyRepository.Find(context.TODO(), pageIndex, pageSize, name, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api StrategyApi) StrategyCreateEndpoint(c echo.Context) error {
var item model.Strategy
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
if err := repository.StrategyRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api StrategyApi) StrategyDeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
for i := range split {
id := split[i]
if err := repository.StrategyRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
}
return Success(c, nil)
}
func (api StrategyApi) StrategyUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Strategy
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.StrategyRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, "")
}
func (api StrategyApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
strategy, err := repository.StrategyRepository.FindById(context.Background(), id)
if err != nil {
return err
}
return Success(c, strategy)
}
+341
View File
@@ -0,0 +1,341 @@
package api
import (
"context"
"next-terminal/server/common/maps"
"strconv"
"github.com/labstack/echo/v4"
)
type ScheduledTaskApi struct{}
func (api ScheduledTaskApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api ScheduledTaskApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
if pageIndex == 0 {
pageIndex = 1
}
if pageSize == 0 {
pageSize = 10
}
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api ScheduledTaskApi) CreateEndpoint(c echo.Context) error {
return Success(c, "")
}
func (api ScheduledTaskApi) UpdateEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api ScheduledTaskApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api ScheduledTaskApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api ScheduledTaskApi) ChangeStatusEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api ScheduledTaskApi) ExecEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api ScheduledTaskApi) GetLogsEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api ScheduledTaskApi) DeleteLogsEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api ScheduledTaskApi) NextTenRunsEndpoint(c echo.Context) error {
return Success(c, []string{})
}
type SessionCommandApi struct{}
func (api SessionCommandApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api SessionCommandApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api SessionCommandApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
type OperationLogApi struct{}
func (api OperationLogApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api OperationLogApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api OperationLogApi) ClearEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api OperationLogApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
type OidcClientApi struct{}
func (api OidcClientApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api OidcClientApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api OidcClientApi) CreateEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"client": maps.Map{},
"secret": "",
})
}
func (api OidcClientApi) UpdateEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api OidcClientApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api OidcClientApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api OidcClientApi) RegenerateSecretEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"clientSecret": "",
})
}
func (api OidcClientApi) UpdateStatusEndpoint(c echo.Context) error {
return Success(c, nil)
}
type LoginLockedApi struct{}
func (api LoginLockedApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api LoginLockedApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api LoginLockedApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
type FilesystemLogApi struct{}
func (api FilesystemLogApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api FilesystemLogApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api FilesystemLogApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api FilesystemLogApi) ClearEndpoint(c echo.Context) error {
return Success(c, nil)
}
type CommandFilterRuleApi struct{}
func (api CommandFilterRuleApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api CommandFilterRuleApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api CommandFilterRuleApi) CreateEndpoint(c echo.Context) error {
return Success(c, "")
}
func (api CommandFilterRuleApi) UpdateEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api CommandFilterRuleApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api CommandFilterRuleApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
type AgentGatewayTokenApi struct{}
func (api AgentGatewayTokenApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AgentGatewayTokenApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api AgentGatewayTokenApi) CreateEndpoint(c echo.Context) error {
return Success(c, "")
}
func (api AgentGatewayTokenApi) UpdateEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AgentGatewayTokenApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AgentGatewayTokenApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
type AccessLogApi struct{}
func (api AccessLogApi) AllEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api AccessLogApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AccessLogApi) ClearEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AccessLogApi) GetDomainStatsEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetDailyStatsEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetStatusCodeStatsEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetHourlyStatsEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetTotalStatsEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"totalRequests": 0,
"uniqueDomains": 0,
"uniqueVisitors": 0,
"avgResponseTime": 0,
})
}
func (api AccessLogApi) GetWebsiteStatsEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"websiteId": "",
"websiteName": "",
"domain": "",
"pv": 0,
"uv": 0,
"ip": 0,
"traffic": 0,
"requests": 0,
"realtimeTraffic": 0,
"requestsPerSecond": 0,
"avgResponseTime": 0,
})
}
func (api AccessLogApi) GetWebsiteTrafficTrendEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetTopPagesEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetTopReferersEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetRealtimeMetricsEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"currentOnline": 0,
"requestsPerSecond": 0,
"trafficPerSecond": 0,
"avgResponseTime": 0,
"errorRate": 0,
})
}
func (api AccessLogApi) GetWebsiteHourlyStatsEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api AccessLogApi) GetWebsiteStatusCodeStatsEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func init() {
_ = context.TODO()
}
+230
View File
@@ -0,0 +1,230 @@
package api
import (
"next-terminal/server/common/maps"
"github.com/labstack/echo/v4"
)
type AuthorisedAssetApi struct{}
func (api AuthorisedAssetApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api AuthorisedAssetApi) AuthorisedAssetsEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedAssetApi) AuthorisedUsersEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedAssetApi) AuthorisedDepartmentsEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedAssetApi) SelectedEndpoint(c echo.Context) error {
return Success(c, []string{})
}
func (api AuthorisedAssetApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedAssetApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedAssetApi) UpdateEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedAssetApi) CreateEndpoint(c echo.Context) error {
return Success(c, nil)
}
type AuthorisedDatabaseAssetApi struct{}
func (api AuthorisedDatabaseAssetApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api AuthorisedDatabaseAssetApi) SelectedEndpoint(c echo.Context) error {
return Success(c, []string{})
}
func (api AuthorisedDatabaseAssetApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedDatabaseAssetApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedDatabaseAssetApi) UpdateEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedDatabaseAssetApi) CreateEndpoint(c echo.Context) error {
return Success(c, nil)
}
type AuthorisedWebsiteApi struct{}
func (api AuthorisedWebsiteApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api AuthorisedWebsiteApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api AuthorisedWebsiteApi) CreateEndpoint(c echo.Context) error {
return Success(c, nil)
}
type DbWorkOrderApi struct{}
func (api DbWorkOrderApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api DbWorkOrderApi) GetEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api DbWorkOrderApi) CreateEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api DbWorkOrderApi) ApproveEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api DbWorkOrderApi) RejectEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api DbWorkOrderApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
type DatabaseSQLLogApi struct{}
func (api DatabaseSQLLogApi) PagingEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"total": 0,
"items": []interface{}{},
})
}
func (api DatabaseSQLLogApi) ClearEndpoint(c echo.Context) error {
return Success(c, nil)
}
type DnsProviderApi struct{}
func (api DnsProviderApi) GetConfigEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"ok": false,
"email": "",
"type": "",
})
}
func (api DnsProviderApi) SetConfigEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api DnsProviderApi) DeleteConfigEndpoint(c echo.Context) error {
return Success(c, nil)
}
type LicenseApi struct{}
func (api LicenseApi) GetMachineIdEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"machineId": "",
})
}
func (api LicenseApi) GetLicenseEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"type": "free",
"machineId": "",
"asset": 0,
"concurrent": 0,
"user": 0,
"expired": 0,
})
}
func (api LicenseApi) GetSimpleLicenseEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"type": "free",
"expired": 0,
"oem": false,
})
}
func (api LicenseApi) SetLicenseEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api LicenseApi) RequestLicenseEndpoint(c echo.Context) error {
return Success(c, nil)
}
type OidcApi struct{}
func (api OidcApi) AuthorizeEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"authorizeUrl": "",
"state": "",
})
}
func (api OidcApi) LoginEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"token": "",
"needTotp": false,
})
}
type WechatWorkApi struct{}
func (api WechatWorkApi) AuthorizeEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"authorizeUrl": "",
})
}
func (api WechatWorkApi) LoginEndpoint(c echo.Context) error {
return Success(c, maps.Map{
"token": "",
"needTotp": false,
})
}
type WebsiteTempAllowApi struct{}
func (api WebsiteTempAllowApi) ListEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api WebsiteTempAllowApi) DeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
+83
View File
@@ -0,0 +1,83 @@
package api
import (
"context"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"strconv"
"strings"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type TenantApi struct{}
func (api TenantApi) AllEndpoint(c echo.Context) error {
items, err := repository.TenantRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api TenantApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.TenantRepository.Find(context.TODO(), pageIndex, pageSize, name, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api TenantApi) CreateEndpoint(c echo.Context) error {
var item model.Tenant
if err := c.Bind(&item); err != nil {
return err
}
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
if err := repository.TenantRepository.Create(context.TODO(), &item); err != nil {
return err
}
return Success(c, "")
}
func (api TenantApi) DeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
for i := range split {
id := split[i]
if err := repository.TenantRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
}
return Success(c, nil)
}
func (api TenantApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.Tenant
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.TenantRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return Success(c, "")
}
+399
View File
@@ -0,0 +1,399 @@
package api
import (
"context"
"encoding/base64"
"encoding/json"
"next-terminal/server/common"
"next-terminal/server/common/nt"
"path"
"strconv"
"next-terminal/server/common/guacamole"
"next-terminal/server/common/term"
"next-terminal/server/config"
"next-terminal/server/dto"
"next-terminal/server/global/session"
"next-terminal/server/log"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
"next-terminal/server/utils"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
)
const (
Closed = 0
Data = 1
Resize = 2
Ping = 9
)
type WebTerminalApi struct {
}
func (api WebTerminalApi) SshEndpoint(c echo.Context) error {
ws, err := UpGrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
return err
}
defer func() {
_ = ws.Close()
}()
ctx := context.TODO()
sessionId := c.Param("id")
cols, _ := strconv.Atoi(c.QueryParam("cols"))
rows, _ := strconv.Atoi(c.QueryParam("rows"))
s, err := service.SessionService.FindByIdAndDecrypt(ctx, sessionId)
if err != nil {
return WriteMessage(ws, dto.NewMessage(Closed, "获取会话或解密数据失败"))
}
if err := api.permissionCheck(c, s.AssetId); err != nil {
return WriteMessage(ws, dto.NewMessage(Closed, err.Error()))
}
var (
username = s.Username
password = s.Password
privateKey = s.PrivateKey
passphrase = s.Passphrase
ip = s.IP
port = s.Port
)
if s.AccessGatewayId != "" && s.AccessGatewayId != "-" {
g, err := service.GatewayService.GetGatewayById(s.AccessGatewayId)
if err != nil {
return WriteMessage(ws, dto.NewMessage(Closed, "获取接入网关失败:"+err.Error()))
}
defer g.CloseSshTunnel(s.ID)
exposedIP, exposedPort, err := g.OpenSshTunnel(s.ID, ip, port)
if err != nil {
return WriteMessage(ws, dto.NewMessage(Closed, "创建隧道失败:"+err.Error()))
}
ip = exposedIP
port = exposedPort
}
recording := ""
var isRecording = false
property, err := repository.PropertyRepository.FindByName(ctx, guacamole.EnableRecording)
if err == nil && property.Value == "true" {
isRecording = true
}
if isRecording {
recording = path.Join(config.GlobalCfg.Guacd.Recording, sessionId, "recording.cast")
}
attributes, err := repository.AssetRepository.FindAssetAttrMapByAssetId(ctx, s.AssetId)
if err != nil {
return WriteMessage(ws, dto.NewMessage(Closed, "获取资产属性失败:"+err.Error()))
}
var xterm = "xterm-256color"
var nextTerminal *term.NextTerminal
if "true" == attributes[nt.SocksProxyEnable] {
nextTerminal, err = term.NewNextTerminalUseSocks(ip, port, username, password, privateKey, passphrase, rows, cols, recording, xterm, true, attributes[nt.SocksProxyHost], attributes[nt.SocksProxyPort], attributes[nt.SocksProxyUsername], attributes[nt.SocksProxyPassword])
} else {
nextTerminal, err = term.NewNextTerminal(ip, port, username, password, privateKey, passphrase, rows, cols, recording, xterm, true)
}
if err != nil {
return WriteMessage(ws, dto.NewMessage(Closed, "创建SSH客户端失败:"+err.Error()))
}
if err := nextTerminal.RequestPty(xterm, rows, cols); err != nil {
return err
}
if err := nextTerminal.Shell(); err != nil {
return err
}
sessionForUpdate := model.Session{
ConnectionId: sessionId,
Width: cols,
Height: rows,
Status: nt.Connected,
Recording: recording,
ConnectedTime: common.NowJsonTime(),
}
if sessionForUpdate.Recording == "" {
// 未录屏时无需审计
sessionForUpdate.Reviewed = true
}
// 更新会话状态
if err := repository.SessionRepository.UpdateById(ctx, &sessionForUpdate, sessionId); err != nil {
return err
}
nextSession := &session.Session{
ID: s.ID,
Protocol: s.Protocol,
Mode: s.Mode,
WebSocket: ws,
GuacdTunnel: nil,
NextTerminal: nextTerminal,
Observer: session.NewObserver(s.ID),
}
session.GlobalSessionManager.Add(nextSession)
termHandler := NewTermHandler(s.Creator, s.AssetId, sessionId, isRecording, ws, nextTerminal)
termHandler.Start()
defer termHandler.Stop()
for {
_, message, err := ws.ReadMessage()
if err != nil {
// web socket会话关闭后主动关闭ssh会话
service.SessionService.CloseSessionById(sessionId, Normal, "用户正常退出")
break
}
msg, err := dto.ParseMessage(string(message))
if err != nil {
continue
}
switch msg.Type {
case Resize:
decodeString, err := base64.StdEncoding.DecodeString(msg.Content)
if err != nil {
continue
}
var winSize dto.WindowSize
err = json.Unmarshal(decodeString, &winSize)
if err != nil {
continue
}
if err := termHandler.WindowChange(winSize.Rows, winSize.Cols); err != nil {
}
_ = repository.SessionRepository.UpdateWindowSizeById(ctx, winSize.Rows, winSize.Cols, sessionId)
case Data:
input := []byte(msg.Content)
err := termHandler.Write(input)
if err != nil {
service.SessionService.CloseSessionById(sessionId, TunnelClosed, "远程连接已关闭")
}
case Ping:
err := termHandler.SendRequest()
if err != nil {
service.SessionService.CloseSessionById(sessionId, TunnelClosed, "远程连接已关闭")
} else {
_ = termHandler.SendMessageToWebSocket(dto.NewMessage(Ping, ""))
}
}
}
return err
}
func (api WebTerminalApi) SshMonitorEndpoint(c echo.Context) error {
ws, err := UpGrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
return err
}
defer func() {
_ = ws.Close()
}()
ctx := context.TODO()
sessionId := c.Param("id")
s, err := repository.SessionRepository.FindById(ctx, sessionId)
if err != nil {
return WriteMessage(ws, dto.NewMessage(Closed, "获取会话失败"))
}
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession == nil {
return WriteMessage(ws, dto.NewMessage(Closed, "会话已离线"))
}
obId := utils.UUID()
obSession := &session.Session{
ID: obId,
Protocol: s.Protocol,
Mode: s.Mode,
WebSocket: ws,
}
nextSession.Observer.Add(obSession)
for {
_, _, err := ws.ReadMessage()
if err != nil {
nextSession.Observer.Del(obId)
break
}
}
return nil
}
func (api WebTerminalApi) AccessTerminalEndpoint(c echo.Context) error {
ws, err := UpGrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
return err
}
defer func() {
_ = ws.Close()
}()
sessionId := c.QueryParam("sessionId")
log.Debug("AccessTerminal: WebSocket connected, sessionId="+sessionId+", cols="+c.QueryParam("cols")+", rows="+c.QueryParam("rows"))
if sessionId == "" {
return WriteMessage(ws, dto.NewMessage(Closed, "sessionId is required"))
}
ctx := context.TODO()
s, err := service.SessionService.FindByIdAndDecrypt(ctx, sessionId)
if err != nil {
log.Debug("AccessTerminal: session not found, err=" + err.Error())
return WriteMessage(ws, dto.NewMessage(Closed, "session not found: "+err.Error()))
}
log.Debug("AccessTerminal: session found, protocol=" + s.Protocol + " ip=" + s.IP + ":" + strconv.Itoa(s.Port) + " user=" + s.Username + " pwdLen=" + strconv.Itoa(len(s.Password)) + " keyLen=" + strconv.Itoa(len(s.PrivateKey)))
xterm := "xterm-256color"
cols, _ := strconv.Atoi(c.QueryParam("cols"))
rows, _ := strconv.Atoi(c.QueryParam("rows"))
if cols <= 0 {
cols = 80
}
if rows <= 0 {
rows = 24
}
// 检查是否启用录制
recording := ""
isRecording := false
property, err := repository.PropertyRepository.FindByName(ctx, guacamole.EnableRecording)
if err == nil && property.Value == "true" {
isRecording = true
recording = path.Join(config.GlobalCfg.Guacd.Recording, sessionId, "recording.cast")
}
var nextTerminal *term.NextTerminal
if isRecording {
nextTerminal, err = term.NewNextTerminal(s.IP, s.Port, s.Username, s.Password, s.PrivateKey, s.Passphrase, rows, cols, recording, xterm, true)
} else {
nextTerminal, err = CreateNextTerminalBySession(s)
}
if err != nil {
log.Debug("AccessTerminal: CreateNextTerminalBySession failed, err=" + err.Error())
return WriteMessage(ws, dto.NewMessage(Closed, "创建SSH客户端失败:"+err.Error()))
}
log.Debug("AccessTerminal: SSH client created successfully")
if err := nextTerminal.RequestPty(xterm, rows, cols); err != nil {
log.Debug("AccessTerminal: RequestPty failed, err=" + err.Error())
return WriteMessage(ws, dto.NewMessage(Closed, "请求PTY失败:"+err.Error()))
}
log.Debug("AccessTerminal: RequestPty OK")
if err := nextTerminal.Shell(); err != nil {
log.Debug("AccessTerminal: Shell failed, err=" + err.Error())
return WriteMessage(ws, dto.NewMessage(Closed, "启动Shell失败:"+err.Error()))
}
log.Debug("AccessTerminal: Shell OK, starting TermHandler...")
sessionForUpdate := model.Session{
ConnectionId: sessionId,
Width: cols,
Height: rows,
Status: nt.Connected,
Recording: recording,
ConnectedTime: common.NowJsonTime(),
}
if sessionForUpdate.Recording == "" {
sessionForUpdate.Reviewed = true
}
if err := repository.SessionRepository.UpdateById(ctx, &sessionForUpdate, sessionId); err != nil {
return err
}
nextSession := &session.Session{
ID: s.ID,
Protocol: s.Protocol,
Mode: s.Mode,
WebSocket: ws,
GuacdTunnel: nil,
NextTerminal: nextTerminal,
Observer: session.NewObserver(s.ID),
}
session.GlobalSessionManager.Add(nextSession)
termHandler := NewTermHandler(s.Creator, s.AssetId, sessionId, isRecording, ws, nextTerminal)
termHandler.Start()
defer termHandler.Stop()
log.Debug("AccessTerminal: TermHandler started, entering message loop")
for {
_, message, err := ws.ReadMessage()
if err != nil {
log.Debug("AccessTerminal: WebSocket read error, closing session. err=" + err.Error())
service.SessionService.CloseSessionById(sessionId, Normal, "用户正常退出")
break
}
msg, err := dto.ParseMessage(string(message))
if err != nil {
continue
}
switch msg.Type {
case Resize:
decodeString, _ := base64.StdEncoding.DecodeString(msg.Content)
var winSize dto.WindowSize
json.Unmarshal(decodeString, &winSize)
termHandler.WindowChange(winSize.Rows, winSize.Cols)
repository.SessionRepository.UpdateWindowSizeById(ctx, winSize.Rows, winSize.Cols, sessionId)
case Data:
termHandler.Write([]byte(msg.Content))
case Ping:
termHandler.SendRequest()
termHandler.SendMessageToWebSocket(dto.NewMessage(Ping, ""))
}
}
return nil
}
func (api WebTerminalApi) permissionCheck(c echo.Context, assetId string) error {
user, _ := GetCurrentAccount(c)
if nt.TypeUser == user.Type {
// 检测是否有访问权限 TODO
//assetIds, err := repository.ResourceSharerRepository.FindAssetIdsByUserId(context.TODO(), user.ID)
//if err != nil {
// return err
//}
//
//if !utils.Contains(assetIds, assetId) {
// return errors.New("您没有权限访问此资产")
//}
}
return nil
}
func WriteMessage(ws *websocket.Conn, msg dto.Message) error {
message := []byte(msg.ToString())
return ws.WriteMessage(websocket.TextMessage, message)
}
func CreateNextTerminalBySession(session model.Session) (*term.NextTerminal, error) {
var (
username = session.Username
password = session.Password
privateKey = session.PrivateKey
passphrase = session.Passphrase
ip = session.IP
port = session.Port
)
return term.NewNextTerminal(ip, port, username, password, privateKey, passphrase,
10, 10, "", "", true)
}
+136
View File
@@ -0,0 +1,136 @@
package api
import (
"bytes"
"context"
"sync"
"time"
"unicode/utf8"
"github.com/gorilla/websocket"
"next-terminal/server/common/term"
"next-terminal/server/dto"
"next-terminal/server/global/session"
)
type TermHandler struct {
sessionId string
isRecording bool
webSocket *websocket.Conn
nextTerminal *term.NextTerminal
ctx context.Context
cancel context.CancelFunc
dataChan chan rune
tick *time.Ticker
mutex sync.Mutex
buf bytes.Buffer
}
func NewTermHandler(userId, assetId, sessionId string, isRecording bool, ws *websocket.Conn, nextTerminal *term.NextTerminal) *TermHandler {
ctx, cancel := context.WithCancel(context.Background())
tick := time.NewTicker(time.Millisecond * time.Duration(60))
return &TermHandler{
sessionId: sessionId,
isRecording: isRecording,
webSocket: ws,
nextTerminal: nextTerminal,
ctx: ctx,
cancel: cancel,
dataChan: make(chan rune),
tick: tick,
}
}
func (r *TermHandler) Start() {
go r.readFormTunnel()
go r.writeToWebsocket()
}
func (r *TermHandler) Stop() {
// 会话结束时记录最后一个命令
r.tick.Stop()
r.cancel()
}
func (r *TermHandler) readFormTunnel() {
for {
select {
case <-r.ctx.Done():
return
default:
rn, size, err := r.nextTerminal.StdoutReader.ReadRune()
if err != nil {
return
}
if size > 0 {
r.dataChan <- rn
}
}
}
}
func (r *TermHandler) writeToWebsocket() {
for {
select {
case <-r.ctx.Done():
return
case <-r.tick.C:
s := r.buf.String()
if s == "" {
continue
}
if err := r.SendMessageToWebSocket(dto.NewMessage(Data, s)); err != nil {
return
}
if r.isRecording && r.nextTerminal.Recorder != nil {
_ = r.nextTerminal.Recorder.WriteData(s)
}
// 监控
SendObData(r.sessionId, s)
r.buf.Reset()
case data := <-r.dataChan:
if data != utf8.RuneError {
p := make([]byte, utf8.RuneLen(data))
utf8.EncodeRune(p, data)
r.buf.Write(p)
} else {
r.buf.Write([]byte("@"))
}
}
}
}
func (r *TermHandler) Write(input []byte) error {
// 正常的字符输入
_, err := r.nextTerminal.Write(input)
return err
}
func (r *TermHandler) WindowChange(h int, w int) error {
return r.nextTerminal.WindowChange(h, w)
}
func (r *TermHandler) SendRequest() error {
_, _, err := r.nextTerminal.SshClient.Conn.SendRequest("helloworld1024@foxmail.com", true, nil)
return err
}
func (r *TermHandler) SendMessageToWebSocket(msg dto.Message) error {
if r.webSocket == nil {
return nil
}
defer r.mutex.Unlock()
r.mutex.Lock()
message := []byte(msg.ToString())
return r.webSocket.WriteMessage(websocket.TextMessage, message)
}
func SendObData(sessionId, s string) {
nextSession := session.GlobalSessionManager.GetById(sessionId)
if nextSession != nil && nextSession.Observer != nil {
nextSession.Observer.Range(func(key string, ob *session.Session) {
_ = ob.WriteMessage(dto.NewMessage(Data, s))
})
}
}
+159
View File
@@ -0,0 +1,159 @@
package api
import (
"context"
"next-terminal/server/common/maps"
"strconv"
"strings"
"github.com/labstack/echo/v4"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/service"
)
type UserApi struct{}
func (userApi UserApi) CreateEndpoint(c echo.Context) (err error) {
var item model.User
if err := c.Bind(&item); err != nil {
return err
}
if len(item.Password) > 100 {
return Fail(c, -1, "您输入的密码过长")
}
if err := service.UserService.CreateUser(item); err != nil {
return err
}
return Success(c, item)
}
func (userApi UserApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
username := c.QueryParam("username")
nickname := c.QueryParam("nickname")
mail := c.QueryParam("mail")
order := c.QueryParam("order")
field := c.QueryParam("field")
online := c.QueryParam("online")
items, total, err := repository.UserRepository.Find(context.TODO(), pageIndex, pageSize, username, nickname, mail, online, "", order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (userApi UserApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
//account, _ := GetCurrentAccount(c)
//if account.ID == id {
// return Fail(c, -1, "cannot modify itself")
//}
var item model.User
if err := c.Bind(&item); err != nil {
return err
}
if err := service.UserService.UpdateUser(id, item); err != nil {
return err
}
return Success(c, nil)
}
func (userApi UserApi) UpdateStatusEndpoint(c echo.Context) error {
id := c.Param("id")
status := c.QueryParam("status")
account, _ := GetCurrentAccount(c)
if account.ID == id {
return Fail(c, -1, "不能操作自身账户")
}
if err := service.UserService.UpdateStatusById(id, status); err != nil {
return err
}
return Success(c, nil)
}
func (userApi UserApi) DeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
account, found := GetCurrentAccount(c)
if !found {
return Fail(c, -1, "获取当前登录账户失败")
}
split := strings.Split(ids, ",")
for i := range split {
userId := split[i]
if account.ID == userId {
return Fail(c, -1, "不允许删除自身账户")
}
if err := service.UserService.DeleteUserById(userId); err != nil {
return err
}
}
return Success(c, nil)
}
func (userApi UserApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := service.UserService.FindById(id)
if err != nil {
return err
}
return Success(c, item)
}
func (userApi UserApi) ChangePasswordEndpoint(c echo.Context) error {
id := c.Param("id")
password := c.FormValue("password")
if password == "" {
return Fail(c, -1, "请输入密码")
}
ids := strings.Split(id, ",")
if err := service.UserService.ChangePassword(ids, password); err != nil {
return err
}
return Success(c, "")
}
func (userApi UserApi) ResetTotpEndpoint(c echo.Context) error {
id := c.Param("id")
ids := strings.Split(id, ",")
if err := service.UserService.ResetTotp(ids); err != nil {
return err
}
return Success(c, "")
}
func (userApi UserApi) AllEndpoint(c echo.Context) error {
users, err := repository.UserRepository.FindAll(context.Background())
if err != nil {
return err
}
items := make([]maps.Map, len(users))
for i, user := range users {
items[i] = maps.Map{
"id": user.ID,
"nickname": user.Nickname,
}
}
return Success(c, items)
}
+108
View File
@@ -0,0 +1,108 @@
package api
import (
"context"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"strconv"
"strings"
"next-terminal/server/dto"
"next-terminal/server/repository"
"next-terminal/server/service"
"github.com/labstack/echo/v4"
)
type UserGroupApi struct{}
func (userGroupApi UserGroupApi) UserGroupCreateEndpoint(c echo.Context) error {
var item model.UserGroup
if err := c.Bind(&item); err != nil {
return err
}
if _, err := service.UserGroupService.Create(context.TODO(), item.Name, item.Members); err != nil {
return err
}
return Success(c, item)
}
func (userGroupApi UserGroupApi) UserGroupPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
order := c.QueryParam("order")
field := c.QueryParam("field")
items, total, err := repository.UserGroupRepository.Find(context.TODO(), pageIndex, pageSize, name, order, field)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (userGroupApi UserGroupApi) UserGroupUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var item model.UserGroup
if err := c.Bind(&item); err != nil {
return err
}
if err := service.UserGroupService.Update(id, item.Name, item.Members); err != nil {
return err
}
return Success(c, nil)
}
func (userGroupApi UserGroupApi) UserGroupDeleteEndpoint(c echo.Context) error {
ids := c.Param("id")
split := strings.Split(ids, ",")
for i := range split {
userId := split[i]
if err := service.UserGroupService.DeleteById(userId); err != nil {
return err
}
}
return Success(c, nil)
}
func (userGroupApi UserGroupApi) UserGroupGetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.UserGroupRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
members, err := repository.UserGroupMemberRepository.FindByUserGroupId(context.TODO(), id)
if err != nil {
return err
}
userGroup := dto.UserGroup{
Id: item.ID,
Name: item.Name,
Created: item.Created,
Members: members,
}
return Success(c, userGroup)
}
func (userGroupApi UserGroupApi) UserGroupAllEndpoint(c echo.Context) error {
userGroups, err := repository.UserGroupRepository.FindAll(context.Background())
if err != nil {
return err
}
return Success(c, userGroups)
}
+180
View File
@@ -0,0 +1,180 @@
package api
import (
"context"
"encoding/json"
"strconv"
"next-terminal/server/common/maps"
"next-terminal/server/dto"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type WebsiteApi struct{}
func (api WebsiteApi) AllEndpoint(c echo.Context) error {
items, err := repository.WebsiteRepository.FindAll(context.TODO())
if err != nil {
return err
}
return Success(c, items)
}
func (api WebsiteApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
keyword := c.QueryParam("keyword")
items, total, err := repository.WebsiteRepository.Find(context.TODO(), pageIndex, pageSize, keyword)
if err != nil {
return err
}
return Success(c, maps.Map{
"total": total,
"items": items,
})
}
func serializeJSON(v interface{}) string {
if v == nil {
return ""
}
switch val := v.(type) {
case string:
return val
case []interface{}, map[string]interface{}:
bytes, err := json.Marshal(val)
if err != nil {
return ""
}
return string(bytes)
default:
bytes, err := json.Marshal(val)
if err != nil {
return ""
}
return string(bytes)
}
}
func (api WebsiteApi) CreateEndpoint(c echo.Context) error {
var req dto.WebsiteDTO
if err := c.Bind(&req); err != nil {
return err
}
item := &model.Website{
ID: utils.UUID(),
Name: req.Name,
Enabled: req.Enabled,
TargetUrl: req.TargetUrl,
TargetHost: req.TargetHost,
TargetPort: req.TargetPort,
Domain: req.Domain,
AsciiDomain: req.AsciiDomain,
Entrance: req.Entrance,
Description: req.Description,
Status: req.Status,
StatusText: req.StatusText,
GatewayType: req.GatewayType,
GatewayId: req.GatewayId,
BasicAuth: serializeJSON(req.BasicAuth),
Headers: serializeJSON(req.Headers),
Cert: serializeJSON(req.Cert),
Public: serializeJSON(req.Public),
TempAllow: serializeJSON(req.TempAllow),
GroupId: req.GroupId,
Sort: req.Sort,
}
if err := repository.WebsiteRepository.Create(context.TODO(), item); err != nil {
return err
}
return Success(c, "")
}
func (api WebsiteApi) UpdateEndpoint(c echo.Context) error {
id := c.Param("id")
var req dto.WebsiteDTO
if err := c.Bind(&req); err != nil {
return err
}
item := &model.Website{
ID: id,
Name: req.Name,
Enabled: req.Enabled,
TargetUrl: req.TargetUrl,
TargetHost: req.TargetHost,
TargetPort: req.TargetPort,
Domain: req.Domain,
AsciiDomain: req.AsciiDomain,
Entrance: req.Entrance,
Description: req.Description,
Status: req.Status,
StatusText: req.StatusText,
GatewayType: req.GatewayType,
GatewayId: req.GatewayId,
BasicAuth: serializeJSON(req.BasicAuth),
Headers: serializeJSON(req.Headers),
Cert: serializeJSON(req.Cert),
Public: serializeJSON(req.Public),
TempAllow: serializeJSON(req.TempAllow),
GroupId: req.GroupId,
Sort: req.Sort,
}
if err := repository.WebsiteRepository.UpdateById(context.TODO(), item, id); err != nil {
return err
}
return Success(c, nil)
}
func (api WebsiteApi) DeleteEndpoint(c echo.Context) error {
id := c.Param("id")
if err := repository.WebsiteRepository.DeleteById(context.TODO(), id); err != nil {
return err
}
return Success(c, nil)
}
func (api WebsiteApi) GetEndpoint(c echo.Context) error {
id := c.Param("id")
item, err := repository.WebsiteRepository.FindById(context.TODO(), id)
if err != nil {
return err
}
return Success(c, item)
}
func (api WebsiteApi) GroupsGetEndpoint(c echo.Context) error {
return Success(c, []interface{}{})
}
func (api WebsiteApi) GroupsSetEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api WebsiteApi) GroupsDeleteEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api WebsiteApi) ChangeGroupEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api WebsiteApi) ChangeGatewayEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api WebsiteApi) SortEndpoint(c echo.Context) error {
return Success(c, nil)
}
func (api WebsiteApi) FaviconEndpoint(c echo.Context) error {
return Success(c, "")
}
+49
View File
@@ -0,0 +1,49 @@
package worker
import (
"context"
"github.com/labstack/echo/v4"
"next-terminal/server/api/abi"
"next-terminal/server/common/maps"
"next-terminal/server/service"
"strconv"
)
type WorkAssetApi struct {
abi.Abi
}
func (api WorkAssetApi) PagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
protocol := c.QueryParam("protocol")
tags := c.QueryParam("tags")
order := c.QueryParam("order")
field := c.QueryParam("field")
account, _ := api.GetCurrentAccount(c)
items, total, err := service.WorkerService.FindMyAssetPaging(pageIndex, pageSize, name, protocol, tags, account.ID, order, field)
if err != nil {
return err
}
for i := range items {
items[i].IP = ""
items[i].Port = 0
}
return api.Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api WorkAssetApi) TagsEndpoint(c echo.Context) (err error) {
account, _ := api.GetCurrentAccount(c)
var items []string
if items, err = service.WorkerService.FindMyAssetTags(context.TODO(), account.ID); err != nil {
return err
}
return api.Success(c, items)
}
+132
View File
@@ -0,0 +1,132 @@
package worker
import (
"context"
"errors"
"gorm.io/gorm"
"next-terminal/server/common/nt"
"strconv"
"strings"
"next-terminal/server/api/abi"
"next-terminal/server/common"
"next-terminal/server/common/maps"
"next-terminal/server/model"
"next-terminal/server/repository"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
type WorkCommandApi struct {
abi.Abi
}
func (api WorkCommandApi) CommandCreateEndpoint(c echo.Context) error {
var item model.Command
if err := c.Bind(&item); err != nil {
return err
}
account, _ := api.GetCurrentAccount(c)
item.Owner = account.ID
item.ID = utils.UUID()
item.Created = common.NowJsonTime()
if err := repository.CommandRepository.Create(context.TODO(), &item); err != nil {
return err
}
return api.Success(c, item)
}
func (api WorkCommandApi) CommandAllEndpoint(c echo.Context) error {
account, _ := api.GetCurrentAccount(c)
userId := account.ID
items, err := repository.CommandRepository.FindByUserId(context.Background(), userId)
if err != nil {
return err
}
return api.Success(c, items)
}
func (api WorkCommandApi) CommandPagingEndpoint(c echo.Context) error {
pageIndex, _ := strconv.Atoi(c.QueryParam("pageIndex"))
pageSize, _ := strconv.Atoi(c.QueryParam("pageSize"))
name := c.QueryParam("name")
content := c.QueryParam("content")
order := c.QueryParam("order")
field := c.QueryParam("field")
account, _ := api.GetCurrentAccount(c)
userId := account.ID
items, total, err := repository.CommandRepository.WorkerFind(context.TODO(), pageIndex, pageSize, name, content, order, field, userId)
if err != nil {
return err
}
return api.Success(c, maps.Map{
"total": total,
"items": items,
})
}
func (api WorkCommandApi) CommandUpdateEndpoint(c echo.Context) error {
id := c.Param("id")
if !api.checkPermission(c, id) {
return nt.ErrPermissionDenied
}
var item model.Command
if err := c.Bind(&item); err != nil {
return err
}
if err := repository.CommandRepository.UpdateById(context.TODO(), &item, id); err != nil {
return err
}
return api.Success(c, nil)
}
func (api WorkCommandApi) CommandDeleteEndpoint(c echo.Context) error {
id := c.Param("id")
split := strings.Split(id, ",")
for i := range split {
if !api.checkPermission(c, id) {
return nt.ErrPermissionDenied
}
if err := repository.CommandRepository.DeleteById(context.TODO(), split[i]); err != nil {
return err
}
}
return api.Success(c, nil)
}
func (api WorkCommandApi) CommandGetEndpoint(c echo.Context) (err error) {
id := c.Param("id")
if !api.checkPermission(c, id) {
return nt.ErrPermissionDenied
}
var item model.Command
if item, err = repository.CommandRepository.FindById(context.TODO(), id); err != nil {
return err
}
return api.Success(c, item)
}
func (api WorkCommandApi) checkPermission(c echo.Context, commandId string) bool {
command, err := repository.CommandRepository.FindById(context.Background(), commandId)
if err != nil {
if errors.Is(gorm.ErrRecordNotFound, err) {
return true
}
return false
}
account, _ := api.GetCurrentAccount(c)
userId := account.ID
return command.Owner == userId
}
+144
View File
@@ -0,0 +1,144 @@
package app
import (
"encoding/json"
"fmt"
"next-terminal/server/branding"
"next-terminal/server/config"
"next-terminal/server/service"
"next-terminal/server/sshd"
"next-terminal/server/task"
"github.com/labstack/echo/v4"
)
var app *App
type App struct {
Server *echo.Echo
}
func newApp() *App {
return &App{}
}
func init() {
setupCache()
app = newApp()
}
func (app App) InitDBData() (err error) {
if err := service.PropertyService.DeleteDeprecatedProperty(); err != nil {
return err
}
if err := service.GatewayService.LoadAll(); err != nil {
return err
}
if err := service.PropertyService.InitProperties(); err != nil {
return err
}
if err := service.UserService.InitUser(); err != nil {
return err
}
if err := service.JobService.InitJob(); err != nil {
return err
}
if err := service.UserService.FixUserOnlineState(); err != nil {
return err
}
if err := service.SessionService.FixSessionState(); err != nil {
return err
}
if err := service.SessionService.EmptyPassword(); err != nil {
return err
}
if err := service.CredentialService.EncryptAll(); err != nil {
return err
}
if err := service.AssetService.EncryptAll(); err != nil {
return err
}
if err := service.StorageService.InitStorages(); err != nil {
return err
}
if err := service.MenuService.Init(); err != nil {
return err
}
if err := service.RoleService.Init(); err != nil {
return err
}
// 修复数据
if err := service.AssetService.FixSshMode(); err != nil {
return err
}
if err := service.SessionService.FixSshMode(); err != nil {
return err
}
if err := service.MigrateService.Migrate(); err != nil {
return err
}
return nil
}
func (app App) ReloadData() error {
if err := service.SecurityService.ReloadAccessSecurity(); err != nil {
return err
}
if err := service.UserService.ReloadToken(); err != nil {
return err
}
if err := service.AccessTokenService.Reload(); err != nil {
return err
}
return nil
}
func Run() error {
fmt.Printf(branding.Hi)
if err := app.InitDBData(); err != nil {
panic(err)
}
if err := app.ReloadData(); err != nil {
panic(err)
}
app.Server = setupRoutes()
if config.GlobalCfg.Debug {
jsonBytes, err := json.MarshalIndent(config.GlobalCfg, "", " ")
if err != nil {
return err
}
fmt.Printf("当前配置为: %v\n", string(jsonBytes))
}
_cli := service.NewCli()
if config.GlobalCfg.ResetPassword != "" {
return _cli.ResetPassword(config.GlobalCfg.ResetPassword)
}
if config.GlobalCfg.ResetTotp != "" {
return _cli.ResetTotp(config.GlobalCfg.ResetTotp)
}
if config.GlobalCfg.NewEncryptionKey != "" {
return _cli.ChangeEncryptionKey(config.GlobalCfg.EncryptionKey, config.GlobalCfg.NewEncryptionKey)
}
ticker := task.NewTicker()
ticker.SetupTicker()
if config.GlobalCfg.Sshd.Enable {
go sshd.Sshd.Serve()
}
if config.GlobalCfg.Server.Cert != "" && config.GlobalCfg.Server.Key != "" {
return app.Server.StartTLS(config.GlobalCfg.Server.Addr, config.GlobalCfg.Server.Cert, config.GlobalCfg.Server.Key)
} else {
return app.Server.Start(config.GlobalCfg.Server.Addr)
}
}
+10
View File
@@ -0,0 +1,10 @@
package app
import (
"next-terminal/server/global/cache"
"next-terminal/server/service"
)
func setupCache() {
cache.TokenManager.OnEvicted(service.UserService.OnEvicted)
}
+157
View File
@@ -0,0 +1,157 @@
package middleware
import (
"next-terminal/server/common/nt"
"strings"
"next-terminal/server/api"
"next-terminal/server/dto"
"next-terminal/server/global/cache"
"next-terminal/server/service"
"github.com/labstack/echo/v4"
"github.com/ucarion/urlpath"
)
var anonymousUrls = []string{"/login", "/static", "/favicon.ico", "/logo.svg", "/logo", "/branding", "/api/branding", "/api/logo", "/setup-status", "/setup-user", "/api/admin/setup-status", "/api/admin/login", "/api/admin/setup-user", "/api/admin/login-status", "/api/login-status", "/api/admin/captcha", "/api/captcha", "/captcha"}
var allowUrls = []urlpath.Path{
urlpath.New("/api/admin/account/info"),
urlpath.New("/api/admin/account/storage"),
urlpath.New("/api/admin/account/logout"),
urlpath.New("/api/admin/account/change-password"),
urlpath.New("/api/admin/account/reload-totp"),
urlpath.New("/api/admin/account/reset-totp"),
urlpath.New("/api/admin/account/confirm-totp"),
urlpath.New("/api/admin/account/access-token"),
urlpath.New("/api/admin/account/security-token/support-types"),
urlpath.New("/api/admin/account/security-token/mfa"),
urlpath.New("/api/admin/account/security-token/validate"),
urlpath.New("/api/admin/account/client-cert"),
urlpath.New("/api/admin/account/client-cert/download"),
urlpath.New("/api/admin/account/webauthn/credentials"),
urlpath.New("/api/admin/account/webauthn/credentials/:id"),
urlpath.New("/api/admin/account/webauthn/credentials/start"),
urlpath.New("/api/admin/account/webauthn/credentials/finish"),
urlpath.New("/api/admin/account/oidc-server-consents"),
urlpath.New("/api/admin/account/oidc-server-consents/:id"),
urlpath.New("/share-sessions/:id"),
urlpath.New("/api/admin/sessions"),
urlpath.New("/api/admin/sessions/:id/tunnel"),
urlpath.New("/api/admin/sessions/:id/connect"),
urlpath.New("/api/admin/sessions/:id/resize"),
urlpath.New("/api/admin/sessions/:id/stats"),
urlpath.New("/api/admin/sessions/:id/ls"),
urlpath.New("/api/admin/sessions/:id/download"),
urlpath.New("/api/admin/sessions/:id/upload"),
urlpath.New("/api/admin/sessions/:id/edit"),
urlpath.New("/api/admin/sessions/:id/mkdir"),
urlpath.New("/api/admin/sessions/:id/rm"),
urlpath.New("/api/admin/sessions/:id/rename"),
urlpath.New("/api/admin/sessions/:id/ssh"),
urlpath.New("/api/portal/assets"),
urlpath.New("/api/portal/database-assets"),
urlpath.New("/api/portal/assets/tree"),
urlpath.New("/api/portal/websites/tree"),
urlpath.New("/api/portal/assets/group-tree"),
urlpath.New("/api/portal/websites"),
urlpath.New("/api/portal/info"),
urlpath.New("/api/license"),
}
func Auth(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
uri := c.Request().RequestURI
if uri == "/" || strings.HasPrefix(uri, "/#") {
return next(c)
}
// 路由拦截 - 登录身份、资源权限判断等
for i := range anonymousUrls {
if strings.HasPrefix(uri, anonymousUrls[i]) {
return next(c)
}
}
token := api.GetToken(c)
if token == "" {
return api.Fail(c, 401, "您的登录信息已失效,请重新登录后再试。")
}
v, found := cache.TokenManager.Get(token)
if !found {
return api.Fail(c, 401, "您的登录信息已失效,请重新登录后再试。")
}
authorization := v.(dto.Authorization)
if strings.EqualFold(nt.LoginToken, authorization.Type) {
if authorization.Remember {
// 记住登录有效期两周
cache.TokenManager.Set(token, authorization, cache.RememberMeExpiration)
} else {
cache.TokenManager.Set(token, authorization, cache.NotRememberExpiration)
}
}
// 放行接入相关接口
uriPath := strings.Split(uri, "?")[0]
for _, url := range allowUrls {
_, ok := url.Match(uriPath)
if ok {
return next(c)
}
}
account, _ := api.GetCurrentAccount(c)
if service.UserService.IsSuperAdmin(account.ID) {
return next(c)
}
var roles []string
v, ok := cache.UserRolesManager.Get(account.ID)
if ok {
roles = v.([]string)
if len(roles) == 0 {
roles, _ = service.RoleService.GetRolesByUserId(account.ID)
cache.UserRolesManager.SetDefault(account.ID, roles)
}
} else {
roles, _ = service.RoleService.GetRolesByUserId(account.ID)
cache.UserRolesManager.SetDefault(account.ID, roles)
}
urlPath := c.Request().URL.Path
for _, role := range roles {
menus := service.RoleService.GetMenuListByRole(role)
for _, menu := range menus {
permissions := service.MenuService.GetPermissionByMenu(menu)
for _, perm := range permissions {
_, ok := perm.Match(urlPath)
if ok {
return next(c)
}
}
}
}
return api.Fail(c, 403, "permission denied")
}
}
func Admin(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
account, found := api.GetCurrentAccount(c)
if !found {
return api.Fail(c, 401, "您的登录信息已失效,请重新登录后再试。")
}
if account.Type != nt.TypeAdmin {
return api.Fail(c, 403, "permission denied.")
}
return next(c)
}
}
+28
View File
@@ -0,0 +1,28 @@
package middleware
import (
"fmt"
"next-terminal/server/log"
"next-terminal/server/api"
"github.com/labstack/echo/v4"
)
func ErrorHandler(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if err := next(c); err != nil {
fmt.Printf("%+v\n", err)
log.Error("api error", log.NamedError("err", err))
if he, ok := err.(*echo.HTTPError); ok {
message := fmt.Sprintf("%v", he.Message)
return api.Fail(c, he.Code, message)
}
return api.Fail(c, -1, err.Error())
}
return nil
}
}
+72
View File
@@ -0,0 +1,72 @@
package middleware
import (
"net"
"next-terminal/server/common/nt"
"strings"
"next-terminal/server/api"
"next-terminal/server/global/security"
"next-terminal/server/utils"
"github.com/labstack/echo/v4"
)
func TcpWall(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
securities := security.GlobalSecurityManager.Values()
if len(securities) == 0 {
return next(c)
}
ip := c.RealIP()
var pass = true
for _, s := range securities {
ipGroups := strings.Split(s.IP, ",")
for _, ipGroup := range ipGroups {
if strings.Contains(ipGroup, "/") {
// CIDR
_, ipNet, err := net.ParseCIDR(ipGroup)
if err != nil {
continue
}
if !ipNet.Contains(net.ParseIP(ip)) {
continue
}
} else if strings.Contains(ipGroup, "-") {
// 范围段
split := strings.Split(ipGroup, "-")
if len(split) < 2 {
continue
}
start := split[0]
end := split[1]
intReqIP := utils.IpToInt(ip)
if intReqIP < utils.IpToInt(start) || intReqIP > utils.IpToInt(end) {
continue
}
} else {
// IP
if ipGroup != ip {
continue
}
}
pass = s.Rule == nt.AccessRuleAllow
}
}
if !pass {
if c.Request().Header.Get("X-Requested-With") != "" || c.Request().Header.Get(nt.Token) != "" {
return api.Fail(c, -1, "您的访问请求被拒绝 :(")
} else {
return c.HTML(666, "您的访问请求被拒绝 :(")
}
}
return next(c)
}
}
+791
View File
@@ -0,0 +1,791 @@
package app
import (
"io/fs"
"net/http"
"os"
"next-terminal/server/api"
"next-terminal/server/api/worker"
mw "next-terminal/server/app/middleware"
"next-terminal/server/config"
"next-terminal/server/log"
"next-terminal/server/resource"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
func getFS(useOS bool) fs.FS {
if useOS {
log.Debug("using live mode")
return os.DirFS("web/build")
}
log.Debug("using embed mode")
fsys, err := fs.Sub(resource.Resource, "build")
if err != nil {
panic(err)
}
return fsys
}
func WrapHandler(h http.Handler) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set("Cache-Control", `public, max-age=31536000`)
h.ServeHTTP(c.Response(), c.Request())
return nil
}
}
func setupRoutes() *echo.Echo {
e := echo.New()
e.HideBanner = true
//e.Logger = log.GetEchoLogger()
//e.Use(log.Hook())
fsys := getFS(config.GlobalCfg.Debug)
fileServer := http.FileServer(http.FS(fsys))
handler := WrapHandler(fileServer)
e.GET("/", handler)
e.GET("/branding", api.Branding)
e.GET("/logo", api.Logo)
e.GET("/favicon.ico", handler)
e.GET("/static/*", handler)
e.Use(middleware.Recover())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
Skipper: middleware.DefaultSkipper,
AllowOrigins: []string{"*"},
AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
}))
e.Use(mw.ErrorHandler)
e.Use(mw.TcpWall)
setupApi := new(api.SetupApi)
accountApi := new(api.AccountApi)
apiGroup := e.Group("/api")
{
apiGroup.GET("/branding", api.Branding)
apiGroup.GET("/logo", api.Logo)
adminGroup := apiGroup.Group("/admin")
{
adminGroup.POST("/login", accountApi.LoginEndpoint)
adminGroup.GET("/setup-status", setupApi.GetSetupStatusEndpoint)
adminGroup.POST("/setup-user", setupApi.SetupUserEndpoint)
}
}
e.Use(mw.Auth)
//e.Use(RBAC)
e.Use(middleware.Gzip())
apiGroup = e.Group("/api")
{
AgentGatewayApi := new(api.AgentGatewayApi)
apiGroup.GET("/branding", api.Branding)
apiGroup.GET("/logo", api.Logo)
apiGroup.GET("/agent/version", AgentGatewayApi.VersionEndpoint)
adminGroup := apiGroup.Group("/admin")
PortalApi := new(api.PortalApi)
AccessSettingApi := new(api.AccessSettingApi)
webTerminalApi := new(api.WebTerminalApi)
FileSystemApi := new(api.FileSystemApi)
{
guacamoleApi := new(api.GuacamoleApi)
UserApi := new(api.UserApi)
UserGroupApi := new(api.UserGroupApi)
AssetApi := new(api.AssetApi)
CommandApi := new(api.CommandApi)
CredentialApi := new(api.CredentialApi)
SessionApi := new(api.SessionApi)
LoginLogApi := new(api.LoginLogApi)
PropertyApi := new(api.PropertyApi)
LogoApi := new(api.LogoApi)
OverviewApi := new(api.OverviewApi)
JobApi := new(api.JobApi)
SecurityApi := new(api.SecurityApi)
StorageApi := new(api.StorageApi)
StrategyApi := new(api.StrategyApi)
AccessGatewayApi := new(api.AccessGatewayApi)
BackupApi := new(api.BackupApi)
TenantApi := new(api.TenantApi)
RoleApi := new(api.RoleApi)
LoginPolicyApi := new(api.LoginPolicyApi)
StorageLogApi := new(api.StorageLogApi)
AuthorisedApi := new(api.AuthorisedApi)
DashboardApi := new(api.DashboardApi)
DepartmentApi := new(api.DepartmentApi)
SnippetApi := new(api.SnippetApi)
CommandFilterApi := new(api.CommandFilterApi)
DatabaseAssetApi := new(api.DatabaseAssetApi)
AssetGroupApi := new(api.AssetGroupApi)
SshGatewayApi := new(api.SshGatewayApi)
GatewayGroupApi := new(api.GatewayGroupApi)
WebsiteApi := new(api.WebsiteApi)
CertificateApi := new(api.CertificateApi)
adminGroup.GET("/login-status", setupApi.LoginStatusEndpoint)
adminGroup.POST("/validate-totp", setupApi.ValidateTOTPEndpoint)
adminGroup.GET("/account/password-policy", setupApi.PasswordPolicyEndpoint)
adminGroup.GET("/captcha", setupApi.GetCaptchaEndpoint)
dashboard := adminGroup.Group("/dashboard")
{
dashboard.GET("/time-counter", DashboardApi.GetTimeCounterEndpoint)
dashboard.GET("/v2/date-counter", DashboardApi.GetDateCounterV2Endpoint)
dashboard.GET("/asset-types", DashboardApi.GetAssetTypesEndpoint)
}
departments := adminGroup.Group("/departments")
{
departments.GET("", DepartmentApi.AllEndpoint)
departments.GET("/paging", DepartmentApi.PagingEndpoint)
departments.POST("", DepartmentApi.CreateEndpoint)
departments.PUT("/:id", DepartmentApi.UpdateEndpoint)
departments.DELETE("/:id", DepartmentApi.DeleteEndpoint)
departments.GET("/:id", DepartmentApi.GetEndpoint)
departments.GET("/tree", DepartmentApi.GetTreeEndpoint)
departments.GET("/:id/users", DepartmentApi.GetDepartmentUsersEndpoint)
departments.POST("/:id/users", DepartmentApi.SetDepartmentUsersEndpoint)
departments.POST("/:id/remove-users", DepartmentApi.RemoveUsersFromDepartmentEndpoint)
}
snippets := adminGroup.Group("/snippets")
{
snippets.GET("", SnippetApi.AllEndpoint)
snippets.GET("/paging", SnippetApi.PagingEndpoint)
snippets.POST("", SnippetApi.CreateEndpoint)
snippets.PUT("/:id", SnippetApi.UpdateEndpoint)
snippets.DELETE("/:id", SnippetApi.DeleteEndpoint)
snippets.GET("/:id", SnippetApi.GetEndpoint)
}
commandFilters := adminGroup.Group("/command-filters")
{
commandFilters.GET("", CommandFilterApi.AllEndpoint)
commandFilters.GET("/paging", CommandFilterApi.PagingEndpoint)
commandFilters.POST("", CommandFilterApi.CreateEndpoint)
commandFilters.PUT("/:id", CommandFilterApi.UpdateEndpoint)
commandFilters.DELETE("/:id", CommandFilterApi.DeleteEndpoint)
commandFilters.GET("/:id", CommandFilterApi.GetEndpoint)
commandFilters.POST("/:id/bind", CommandFilterApi.BindEndpoint)
commandFilters.POST("/:id/unbind", CommandFilterApi.UnbindEndpoint)
}
databaseAssets := adminGroup.Group("/database-assets")
{
databaseAssets.GET("", DatabaseAssetApi.AllEndpoint)
databaseAssets.GET("/paging", DatabaseAssetApi.PagingEndpoint)
databaseAssets.POST("", DatabaseAssetApi.CreateEndpoint)
databaseAssets.PUT("/:id", DatabaseAssetApi.UpdateEndpoint)
databaseAssets.DELETE("/:id", DatabaseAssetApi.DeleteEndpoint)
databaseAssets.GET("/:id", DatabaseAssetApi.GetEndpoint)
databaseAssets.GET("/:id/decrypted", DatabaseAssetApi.DecryptEndpoint)
}
account := adminGroup.Group("/account")
{
account.GET("/info", accountApi.InfoEndpoint)
account.GET("/storage", accountApi.AccountStorageEndpoint)
account.POST("/logout", accountApi.LogoutEndpoint)
account.POST("/change-password", accountApi.ChangePasswordEndpoint)
account.GET("/reload-totp", accountApi.ReloadTOTPEndpoint)
account.POST("/reset-totp", accountApi.ResetTOTPEndpoint)
account.POST("/confirm-totp", accountApi.ConfirmTOTPEndpoint)
account.GET("/access-token", accountApi.AccessTokenGetEndpoint)
account.POST("/access-token", accountApi.AccessTokenGenEndpoint)
account.DELETE("/access-token/:id", accountApi.AccessTokenDelEndpoint)
account.GET("/security-token/support-types", accountApi.SecurityTokenSupportTypesEndpoint)
account.POST("/security-token/mfa", accountApi.SecurityTokenMfaEndpoint)
account.POST("/security-token/validate", accountApi.SecurityTokenValidateEndpoint)
}
_worker := adminGroup.Group("/worker")
{
commands := _worker.Group("/commands")
{
workerCommandApi := new(worker.WorkCommandApi)
commands.GET("", workerCommandApi.CommandAllEndpoint)
commands.GET("/paging", workerCommandApi.CommandPagingEndpoint)
commands.POST("", workerCommandApi.CommandCreateEndpoint)
commands.PUT("/:id", workerCommandApi.CommandUpdateEndpoint)
commands.DELETE("/:id", workerCommandApi.CommandDeleteEndpoint)
commands.GET("/:id", workerCommandApi.CommandGetEndpoint)
}
assets := _worker.Group("/assets")
{
workAssetApi := new(worker.WorkAssetApi)
assets.GET("/paging", workAssetApi.PagingEndpoint)
assets.GET("/tags", workAssetApi.TagsEndpoint)
}
}
users := adminGroup.Group("/users", mw.Admin)
{
users.GET("", UserApi.AllEndpoint)
users.GET("/paging", UserApi.PagingEndpoint)
users.POST("", UserApi.CreateEndpoint)
users.PUT("/:id", UserApi.UpdateEndpoint)
users.PATCH("/:id/status", UserApi.UpdateStatusEndpoint)
users.DELETE("/:id", UserApi.DeleteEndpoint)
users.GET("/:id", UserApi.GetEndpoint)
users.POST("/:id/change-password", UserApi.ChangePasswordEndpoint)
users.POST("/:id/reset-totp", UserApi.ResetTotpEndpoint)
}
userGroups := adminGroup.Group("/user-groups", mw.Admin)
{
userGroups.POST("", UserGroupApi.UserGroupCreateEndpoint)
userGroups.GET("", UserGroupApi.UserGroupAllEndpoint)
userGroups.GET("/paging", UserGroupApi.UserGroupPagingEndpoint)
userGroups.PUT("/:id", UserGroupApi.UserGroupUpdateEndpoint)
userGroups.DELETE("/:id", UserGroupApi.UserGroupDeleteEndpoint)
userGroups.GET("/:id", UserGroupApi.UserGroupGetEndpoint)
}
assets := adminGroup.Group("/assets")
{
assets.GET("", AssetApi.AssetAllEndpoint)
assets.POST("", AssetApi.AssetCreateEndpoint)
assets.POST("/import", AssetApi.AssetImportEndpoint)
assets.GET("/paging", AssetApi.AssetPagingEndpoint)
assets.GET("/tags", AssetApi.AssetTagsEndpoint)
assets.GET("/groups", AssetGroupApi.GroupsGetEndpoint)
assets.PUT("/groups", AssetGroupApi.GroupsSetEndpoint)
assets.DELETE("/groups/:id", AssetGroupApi.GroupsDeleteEndpoint)
assets.GET("/tree", AssetGroupApi.TreeEndpoint)
assets.POST("/change-group", AssetGroupApi.ChangeGroupEndpoint)
assets.POST("/change-gateway", AssetGroupApi.ChangeGatewayEndpoint)
assets.POST("/sort", AssetGroupApi.SortEndpoint)
assets.GET("/logos", LogoApi.LogosEndpoint)
assets.POST("/:id/tcping", AssetApi.AssetTcpingEndpoint)
assets.PUT("/:id", AssetApi.AssetUpdateEndpoint)
assets.GET("/:id/decrypted", AssetApi.AssetDecryptedEndpoint)
assets.GET("/:id", AssetApi.AssetGetEndpoint)
assets.DELETE("/:id", AssetApi.AssetDeleteEndpoint)
assets.POST("/:id/change-owner", AssetApi.AssetChangeOwnerEndpoint)
}
adminGroup.GET("/tags", AssetApi.AssetTagsEndpoint)
commands := adminGroup.Group("/commands")
{
commands.GET("", CommandApi.CommandAllEndpoint)
commands.GET("/paging", CommandApi.CommandPagingEndpoint)
commands.POST("", CommandApi.CommandCreateEndpoint)
commands.PUT("/:id", CommandApi.CommandUpdateEndpoint)
commands.DELETE("/:id", CommandApi.CommandDeleteEndpoint)
commands.GET("/:id", CommandApi.CommandGetEndpoint)
commands.POST("/:id/change-owner", CommandApi.CommandChangeOwnerEndpoint)
}
credentials := adminGroup.Group("/credentials")
{
credentials.GET("", CredentialApi.CredentialAllEndpoint)
credentials.GET("/paging", CredentialApi.CredentialPagingEndpoint)
credentials.POST("", CredentialApi.CredentialCreateEndpoint)
credentials.POST("/gen-private-key", CredentialApi.GenPrivateKeyEndpoint)
credentials.PUT("/:id", CredentialApi.CredentialUpdateEndpoint)
credentials.DELETE("/:id", CredentialApi.CredentialDeleteEndpoint)
credentials.GET("/:id", CredentialApi.CredentialGetEndpoint)
credentials.GET("/:id/public-key", CredentialApi.GetPublicKeyEndpoint)
credentials.GET("/:id/decrypted", CredentialApi.DecryptedEndpoint)
credentials.POST("/:id/change-owner", CredentialApi.CredentialChangeOwnerEndpoint)
}
sessions := adminGroup.Group("/sessions")
{
sessions.GET("/paging", SessionApi.SessionPagingEndpoint)
sessions.POST("/:id/disconnect", SessionApi.SessionDisconnectEndpoint)
sessions.DELETE("/:id", SessionApi.SessionDeleteEndpoint)
sessions.GET("/:id/recording", SessionApi.SessionRecordingEndpoint)
sessions.GET("/:id", SessionApi.SessionGetEndpoint)
sessions.POST("/:id/reviewed", SessionApi.SessionReviewedEndpoint)
sessions.POST("/:id/unreviewed", SessionApi.SessionUnViewedEndpoint)
sessions.POST("/clear", SessionApi.SessionClearEndpoint)
sessions.POST("/reviewed", SessionApi.SessionReviewedAllEndpoint)
sessions.POST("", SessionApi.SessionCreateEndpoint)
sessions.POST("/:id/connect", SessionApi.SessionConnectEndpoint)
sessions.GET("/:id/tunnel", guacamoleApi.Guacamole)
sessions.GET("/:id/tunnel-monitor", guacamoleApi.GuacamoleMonitor)
sessions.GET("/:id/ssh", webTerminalApi.SshEndpoint)
sessions.GET("/:id/ssh-monitor", webTerminalApi.SshMonitorEndpoint)
sessions.POST("/:id/resize", SessionApi.SessionResizeEndpoint)
sessions.GET("/:id/stats", SessionApi.SessionStatsEndpoint)
sessions.POST("/:id/ls", SessionApi.SessionLsEndpoint)
sessions.GET("/:id/download", SessionApi.SessionDownloadEndpoint)
sessions.POST("/:id/upload", SessionApi.SessionUploadEndpoint)
sessions.POST("/:id/edit", SessionApi.SessionEditEndpoint)
sessions.POST("/:id/mkdir", SessionApi.SessionMkDirEndpoint)
sessions.POST("/:id/rm", SessionApi.SessionRmEndpoint)
sessions.POST("/:id/rename", SessionApi.SessionRenameEndpoint)
sessions.GET("/audit-enabled", SessionApi.SessionAuditEnabledEndpoint)
sessions.POST("/:id/audit", SessionApi.SessionTriggerAuditEndpoint)
sessions.GET("/:id/audit", SessionApi.SessionGetAuditEndpoint)
}
loginLogs := adminGroup.Group("/login-logs")
{
loginLogs.GET("/paging", LoginLogApi.LoginLogPagingEndpoint)
loginLogs.DELETE("/:id", LoginLogApi.LoginLogDeleteEndpoint)
loginLogs.POST("/clear", LoginLogApi.LoginLogClearEndpoint)
}
storageLogs := adminGroup.Group("/storage-logs")
{
storageLogs.GET("/paging", StorageLogApi.PagingEndpoint)
storageLogs.DELETE("/:id", StorageLogApi.DeleteEndpoint)
storageLogs.POST("/clear", StorageLogApi.ClearEndpoint)
}
adminGroup.GET("/properties", PropertyApi.PropertyGetEndpoint)
adminGroup.PUT("/properties", PropertyApi.PropertyUpdateEndpoint)
adminGroup.POST("/properties/gen-rsa-private-key", PropertyApi.GenRSAPrivateKeyEndpoint)
adminGroup.POST("/properties/send-mail", PropertyApi.SendMailEndpoint)
adminGroup.GET("/properties/client-ips", PropertyApi.ClientIPsEndpoint)
adminGroup.GET("/logos", LogoApi.LogosEndpoint)
adminGroup.POST("/logos/upload", LogoApi.UploadEndpoint)
adminGroup.DELETE("/logos/:name", LogoApi.DeleteEndpoint)
adminGroup.GET("/overview/counter", OverviewApi.OverviewCounterEndPoint)
adminGroup.GET("/overview/asset", OverviewApi.OverviewAssetEndPoint)
adminGroup.GET("/overview/date-counter", OverviewApi.OverviewDateCounterEndPoint)
adminGroup.GET("/overview/ps", OverviewApi.OverviewPS)
jobs := adminGroup.Group("/jobs")
{
jobs.POST("", JobApi.JobCreateEndpoint)
jobs.GET("/paging", JobApi.JobPagingEndpoint)
jobs.PUT("/:id", JobApi.JobUpdateEndpoint)
jobs.POST("/:id/change-status", JobApi.JobChangeStatusEndpoint)
jobs.POST("/:id/exec", JobApi.JobExecEndpoint)
jobs.DELETE("/:id", JobApi.JobDeleteEndpoint)
jobs.GET("/:id", JobApi.JobGetEndpoint)
jobs.GET("/:id/logs/paging", JobApi.JobGetLogsEndpoint)
jobs.DELETE("/:id/logs", JobApi.JobDeleteLogsEndpoint)
}
securities := adminGroup.Group("/securities")
{
securities.POST("", SecurityApi.SecurityCreateEndpoint)
securities.GET("/paging", SecurityApi.SecurityPagingEndpoint)
securities.PUT("/:id", SecurityApi.SecurityUpdateEndpoint)
securities.DELETE("/:id", SecurityApi.SecurityDeleteEndpoint)
securities.GET("/:id", SecurityApi.SecurityGetEndpoint)
}
storages := adminGroup.Group("/storages")
{
storages.GET("/paging", StorageApi.StoragePagingEndpoint)
storages.POST("", StorageApi.StorageCreateEndpoint)
storages.DELETE("/:id", StorageApi.StorageDeleteEndpoint)
storages.PUT("/:id", StorageApi.StorageUpdateEndpoint)
storages.GET("/shares", StorageApi.StorageSharesEndpoint)
storages.GET("/:id", StorageApi.StorageGetEndpoint)
storages.POST("/:storageId/ls", StorageApi.StorageLsEndpoint)
storages.GET("/:storageId/download", StorageApi.StorageDownloadEndpoint)
storages.POST("/:storageId/upload", StorageApi.StorageUploadEndpoint)
storages.POST("/:storageId/mkdir", StorageApi.StorageMkDirEndpoint)
storages.POST("/:storageId/rm", StorageApi.StorageRmEndpoint)
storages.POST("/:storageId/rename", StorageApi.StorageRenameEndpoint)
storages.POST("/:storageId/edit", StorageApi.StorageEditEndpoint)
}
strategies := adminGroup.Group("/strategies")
{
strategies.GET("", StrategyApi.StrategyAllEndpoint)
strategies.GET("/paging", StrategyApi.StrategyPagingEndpoint)
strategies.POST("", StrategyApi.StrategyCreateEndpoint)
strategies.DELETE("/:id", StrategyApi.StrategyDeleteEndpoint)
strategies.PUT("/:id", StrategyApi.StrategyUpdateEndpoint)
strategies.GET("/:id", StrategyApi.GetEndpoint)
}
accessGateways := adminGroup.Group("/access-gateways")
{
accessGateways.GET("", AccessGatewayApi.AccessGatewayAllEndpoint)
accessGateways.POST("", AccessGatewayApi.AccessGatewayCreateEndpoint)
accessGateways.GET("/paging", AccessGatewayApi.AccessGatewayPagingEndpoint)
accessGateways.PUT("/:id", AccessGatewayApi.AccessGatewayUpdateEndpoint)
accessGateways.DELETE("/:id", AccessGatewayApi.AccessGatewayDeleteEndpoint)
accessGateways.GET("/:id", AccessGatewayApi.AccessGatewayGetEndpoint)
}
agentGateways := adminGroup.Group("/agent-gateways")
{
agentGateways.GET("", AgentGatewayApi.AllEndpoint)
agentGateways.POST("", AgentGatewayApi.CreateEndpoint)
agentGateways.GET("/paging", AgentGatewayApi.PagingEndpoint)
agentGateways.PUT("/:id", AgentGatewayApi.UpdateEndpoint)
agentGateways.DELETE("/:id", AgentGatewayApi.DeleteEndpoint)
agentGateways.GET("/:id", AgentGatewayApi.GetEndpoint)
agentGateways.GET("/get-register-param", AgentGatewayApi.GetRegisterParamEndpoint)
agentGateways.POST("/set-register-addr", AgentGatewayApi.SetRegisterAddrEndpoint)
agentGateways.GET("/:id/stat", AgentGatewayApi.GetStatEndpoint)
agentGateways.POST("/sort", AgentGatewayApi.UpdateSortEndpoint)
}
adminGroup.GET("/agent/version", AgentGatewayApi.VersionEndpoint)
sshGateways := adminGroup.Group("/ssh-gateways")
{
sshGateways.GET("", SshGatewayApi.AllEndpoint)
sshGateways.POST("", SshGatewayApi.CreateEndpoint)
sshGateways.GET("/paging", SshGatewayApi.PagingEndpoint)
sshGateways.PUT("/:id", SshGatewayApi.UpdateEndpoint)
sshGateways.DELETE("/:id", SshGatewayApi.DeleteEndpoint)
sshGateways.GET("/:id", SshGatewayApi.GetEndpoint)
sshGateways.GET("/:id/decrypted", SshGatewayApi.DecryptedEndpoint)
}
adminGroup.GET("/assets/ssh/available-for-gateway", SshGatewayApi.AvailableForGatewayEndpoint)
gatewayGroups := adminGroup.Group("/gateway-groups")
{
gatewayGroups.GET("", GatewayGroupApi.AllEndpoint)
gatewayGroups.POST("", GatewayGroupApi.CreateEndpoint)
gatewayGroups.GET("/paging", GatewayGroupApi.PagingEndpoint)
gatewayGroups.PUT("/:id", GatewayGroupApi.UpdateEndpoint)
gatewayGroups.DELETE("/:id", GatewayGroupApi.DeleteEndpoint)
gatewayGroups.GET("/:id", GatewayGroupApi.GetEndpoint)
}
websites := adminGroup.Group("/websites")
{
websites.GET("", WebsiteApi.AllEndpoint)
websites.POST("", WebsiteApi.CreateEndpoint)
websites.GET("/paging", WebsiteApi.PagingEndpoint)
websites.PUT("/:id", WebsiteApi.UpdateEndpoint)
websites.DELETE("/:id", WebsiteApi.DeleteEndpoint)
websites.GET("/:id", WebsiteApi.GetEndpoint)
websites.GET("/groups", WebsiteApi.GroupsGetEndpoint)
websites.PUT("/groups", WebsiteApi.GroupsSetEndpoint)
websites.DELETE("/groups/:id", WebsiteApi.GroupsDeleteEndpoint)
websites.POST("/change-group", WebsiteApi.ChangeGroupEndpoint)
websites.POST("/change-gateway", WebsiteApi.ChangeGatewayEndpoint)
websites.POST("/sort", WebsiteApi.SortEndpoint)
websites.GET("/favicon", WebsiteApi.FaviconEndpoint)
}
certificates := adminGroup.Group("/certificates")
{
certificates.GET("", CertificateApi.AllEndpoint)
certificates.POST("", CertificateApi.CreateEndpoint)
certificates.GET("/paging", CertificateApi.PagingEndpoint)
certificates.PUT("/:id", CertificateApi.UpdateEndpoint)
certificates.DELETE("/:id", CertificateApi.DeleteEndpoint)
certificates.GET("/:id", CertificateApi.GetEndpoint)
certificates.PATCH("/:id/default", CertificateApi.UpdateDefaultEndpoint)
certificates.GET("/:id/download", CertificateApi.DownloadEndpoint)
certificates.POST("/:id/renew", CertificateApi.RenewEndpoint)
}
backup := adminGroup.Group("/backup")
{
backup.GET("/export", BackupApi.BackupExportEndpoint)
backup.POST("/import", BackupApi.BackupImportEndpoint)
}
tenants := adminGroup.Group("/tenants")
{
tenants.GET("", TenantApi.AllEndpoint)
tenants.GET("/paging", TenantApi.PagingEndpoint)
tenants.POST("", TenantApi.CreateEndpoint)
tenants.DELETE("/:id", TenantApi.DeleteEndpoint)
tenants.PUT("/:id", TenantApi.UpdateEndpoint)
}
roles := adminGroup.Group("/roles")
{
roles.GET("", RoleApi.AllEndpoint)
roles.GET("/paging", RoleApi.PagingEndpoint)
roles.GET("/:id", RoleApi.GetEndpoint)
roles.POST("", RoleApi.CreateEndpoint)
roles.DELETE("/:id", RoleApi.DeleteEndpoint)
roles.PUT("/:id", RoleApi.UpdateEndpoint)
}
loginPolicies := adminGroup.Group("/login-policies")
{
loginPolicies.GET("/paging", LoginPolicyApi.PagingEndpoint)
loginPolicies.GET("/:id", LoginPolicyApi.GetEndpoint)
loginPolicies.GET("/:id/users/paging", LoginPolicyApi.GetUserPageEndpoint)
loginPolicies.GET("/:id/users/id", LoginPolicyApi.GetUserIdEndpoint)
loginPolicies.POST("", LoginPolicyApi.CreateEndpoint)
loginPolicies.DELETE("/:id", LoginPolicyApi.DeleteEndpoint)
loginPolicies.PUT("/:id", LoginPolicyApi.UpdateEndpoint)
loginPolicies.POST("/:id/bind", LoginPolicyApi.BindEndpoint)
loginPolicies.POST("/:id/unbind", LoginPolicyApi.UnbindEndpoint)
}
authorised := adminGroup.Group("/authorised")
{
authorised.GET("/assets/paging", AuthorisedApi.PagingAsset)
authorised.GET("/users/paging", AuthorisedApi.PagingUser)
authorised.GET("/user-groups/paging", AuthorisedApi.PagingUserGroup)
authorised.GET("/selected", AuthorisedApi.Selected)
authorised.POST("/assets", AuthorisedApi.AuthorisedAssets)
authorised.POST("/users", AuthorisedApi.AuthorisedUsers)
authorised.POST("/user-groups", AuthorisedApi.AuthorisedUserGroups)
authorised.DELETE("/:id", AuthorisedApi.Delete)
}
adminGroup.GET("/menus", RoleApi.TreeMenus)
ScheduledTaskApi := new(api.ScheduledTaskApi)
scheduledTasks := adminGroup.Group("/scheduled-tasks")
{
scheduledTasks.GET("", ScheduledTaskApi.AllEndpoint)
scheduledTasks.GET("/paging", ScheduledTaskApi.PagingEndpoint)
scheduledTasks.POST("", ScheduledTaskApi.CreateEndpoint)
scheduledTasks.PUT("/:id", ScheduledTaskApi.UpdateEndpoint)
scheduledTasks.DELETE("/:id", ScheduledTaskApi.DeleteEndpoint)
scheduledTasks.GET("/:id", ScheduledTaskApi.GetEndpoint)
scheduledTasks.POST("/:id/change-status", ScheduledTaskApi.ChangeStatusEndpoint)
scheduledTasks.POST("/:id/exec", ScheduledTaskApi.ExecEndpoint)
scheduledTasks.GET("/:id/logs/paging", ScheduledTaskApi.GetLogsEndpoint)
scheduledTasks.DELETE("/:id/logs", ScheduledTaskApi.DeleteLogsEndpoint)
scheduledTasks.POST("/next-ten-runs", ScheduledTaskApi.NextTenRunsEndpoint)
}
SessionCommandApi := new(api.SessionCommandApi)
sessionCommands := adminGroup.Group("/session-commands")
{
sessionCommands.GET("", SessionCommandApi.AllEndpoint)
sessionCommands.GET("/paging", SessionCommandApi.PagingEndpoint)
sessionCommands.GET("/:id", SessionCommandApi.GetEndpoint)
}
OperationLogApi := new(api.OperationLogApi)
operationLogs := adminGroup.Group("/operation-logs")
{
operationLogs.GET("", OperationLogApi.AllEndpoint)
operationLogs.GET("/paging", OperationLogApi.PagingEndpoint)
operationLogs.DELETE("/:id", OperationLogApi.DeleteEndpoint)
operationLogs.POST("/clear", OperationLogApi.ClearEndpoint)
}
OidcClientApi := new(api.OidcClientApi)
oidcClients := adminGroup.Group("/oidc-clients")
{
oidcClients.GET("", OidcClientApi.AllEndpoint)
oidcClients.GET("/paging", OidcClientApi.PagingEndpoint)
oidcClients.POST("", OidcClientApi.CreateEndpoint)
oidcClients.PUT("/:id", OidcClientApi.UpdateEndpoint)
oidcClients.DELETE("/:id", OidcClientApi.DeleteEndpoint)
oidcClients.GET("/:id", OidcClientApi.GetEndpoint)
oidcClients.POST("/:id/regenerate-secret", OidcClientApi.RegenerateSecretEndpoint)
oidcClients.PATCH("/:id/status", OidcClientApi.UpdateStatusEndpoint)
}
LoginLockedApi := new(api.LoginLockedApi)
loginLocked := adminGroup.Group("/login-locked")
{
loginLocked.GET("", LoginLockedApi.AllEndpoint)
loginLocked.GET("/paging", LoginLockedApi.PagingEndpoint)
loginLocked.DELETE("/:id", LoginLockedApi.DeleteEndpoint)
}
FilesystemLogApi := new(api.FilesystemLogApi)
filesystemLogs := adminGroup.Group("/filesystem-logs")
{
filesystemLogs.GET("", FilesystemLogApi.AllEndpoint)
filesystemLogs.GET("/paging", FilesystemLogApi.PagingEndpoint)
filesystemLogs.DELETE("/:id", FilesystemLogApi.DeleteEndpoint)
filesystemLogs.POST("/clear", FilesystemLogApi.ClearEndpoint)
}
CommandFilterRuleApi := new(api.CommandFilterRuleApi)
commandFilterRules := adminGroup.Group("/command-filter-rules")
{
commandFilterRules.GET("", CommandFilterRuleApi.AllEndpoint)
commandFilterRules.GET("/paging", CommandFilterRuleApi.PagingEndpoint)
commandFilterRules.POST("", CommandFilterRuleApi.CreateEndpoint)
commandFilterRules.PUT("/:id", CommandFilterRuleApi.UpdateEndpoint)
commandFilterRules.DELETE("/:id", CommandFilterRuleApi.DeleteEndpoint)
commandFilterRules.GET("/:id", CommandFilterRuleApi.GetEndpoint)
}
AgentGatewayTokenApi := new(api.AgentGatewayTokenApi)
agentGatewayTokens := adminGroup.Group("/agent-gateway-tokens")
{
agentGatewayTokens.GET("", AgentGatewayTokenApi.AllEndpoint)
agentGatewayTokens.GET("/paging", AgentGatewayTokenApi.PagingEndpoint)
agentGatewayTokens.POST("", AgentGatewayTokenApi.CreateEndpoint)
agentGatewayTokens.PUT("/:id", AgentGatewayTokenApi.UpdateEndpoint)
agentGatewayTokens.DELETE("/:id", AgentGatewayTokenApi.DeleteEndpoint)
agentGatewayTokens.GET("/:id", AgentGatewayTokenApi.GetEndpoint)
}
AccessLogApi := new(api.AccessLogApi)
accessLogs := adminGroup.Group("/access-logs")
{
accessLogs.GET("", AccessLogApi.AllEndpoint)
accessLogs.GET("/paging", AccessLogApi.PagingEndpoint)
accessLogs.DELETE("/:id", AccessLogApi.DeleteEndpoint)
accessLogs.POST("/clear", AccessLogApi.ClearEndpoint)
accessLogs.GET("/domain-stats", AccessLogApi.GetDomainStatsEndpoint)
accessLogs.GET("/daily-stats", AccessLogApi.GetDailyStatsEndpoint)
accessLogs.GET("/status-code-stats", AccessLogApi.GetStatusCodeStatsEndpoint)
accessLogs.GET("/hourly-stats", AccessLogApi.GetHourlyStatsEndpoint)
accessLogs.GET("/total-stats", AccessLogApi.GetTotalStatsEndpoint)
accessLogs.GET("/website-stats", AccessLogApi.GetWebsiteStatsEndpoint)
accessLogs.GET("/website-traffic-trend", AccessLogApi.GetWebsiteTrafficTrendEndpoint)
accessLogs.GET("/top-pages", AccessLogApi.GetTopPagesEndpoint)
accessLogs.GET("/top-referers", AccessLogApi.GetTopReferersEndpoint)
accessLogs.GET("/realtime-metrics", AccessLogApi.GetRealtimeMetricsEndpoint)
accessLogs.GET("/website-hourly-stats", AccessLogApi.GetWebsiteHourlyStatsEndpoint)
accessLogs.GET("/website-status-code-stats", AccessLogApi.GetWebsiteStatusCodeStatsEndpoint)
}
AuthorisedAssetApi := new(api.AuthorisedAssetApi)
authorisedAsset := adminGroup.Group("/authorised-asset")
{
authorisedAsset.GET("/paging", AuthorisedAssetApi.PagingEndpoint)
authorisedAsset.POST("/assets", AuthorisedAssetApi.AuthorisedAssetsEndpoint)
authorisedAsset.POST("/users", AuthorisedAssetApi.AuthorisedUsersEndpoint)
authorisedAsset.POST("/departments", AuthorisedAssetApi.AuthorisedDepartmentsEndpoint)
authorisedAsset.GET("/selected", AuthorisedAssetApi.SelectedEndpoint)
authorisedAsset.DELETE("/:id", AuthorisedAssetApi.DeleteEndpoint)
authorisedAsset.GET("/:id", AuthorisedAssetApi.GetEndpoint)
authorisedAsset.PUT("/:id", AuthorisedAssetApi.UpdateEndpoint)
authorisedAsset.POST("", AuthorisedAssetApi.CreateEndpoint)
}
AuthorisedDatabaseAssetApi := new(api.AuthorisedDatabaseAssetApi)
authorisedDatabaseAssets := adminGroup.Group("/authorised-database-assets")
{
authorisedDatabaseAssets.GET("/paging", AuthorisedDatabaseAssetApi.PagingEndpoint)
authorisedDatabaseAssets.GET("/selected", AuthorisedDatabaseAssetApi.SelectedEndpoint)
authorisedDatabaseAssets.DELETE("/:id", AuthorisedDatabaseAssetApi.DeleteEndpoint)
authorisedDatabaseAssets.GET("/:id", AuthorisedDatabaseAssetApi.GetEndpoint)
authorisedDatabaseAssets.PUT("/:id", AuthorisedDatabaseAssetApi.UpdateEndpoint)
authorisedDatabaseAssets.POST("", AuthorisedDatabaseAssetApi.CreateEndpoint)
}
AuthorisedWebsiteApi := new(api.AuthorisedWebsiteApi)
authorisedWebsite := adminGroup.Group("/authorised-website")
{
authorisedWebsite.GET("/paging", AuthorisedWebsiteApi.PagingEndpoint)
authorisedWebsite.DELETE("/:id", AuthorisedWebsiteApi.DeleteEndpoint)
authorisedWebsite.POST("", AuthorisedWebsiteApi.CreateEndpoint)
}
DbWorkOrderApi := new(api.DbWorkOrderApi)
dbWorkOrders := adminGroup.Group("/db-work-orders")
{
dbWorkOrders.GET("/paging", DbWorkOrderApi.PagingEndpoint)
dbWorkOrders.GET("/:id", DbWorkOrderApi.GetEndpoint)
dbWorkOrders.POST("", DbWorkOrderApi.CreateEndpoint)
dbWorkOrders.POST("/:id/approve", DbWorkOrderApi.ApproveEndpoint)
dbWorkOrders.POST("/:id/reject", DbWorkOrderApi.RejectEndpoint)
dbWorkOrders.DELETE("/:id", DbWorkOrderApi.DeleteEndpoint)
}
DatabaseSQLLogApi := new(api.DatabaseSQLLogApi)
databaseSqlLogs := adminGroup.Group("/database-sql-logs")
{
databaseSqlLogs.GET("/paging", DatabaseSQLLogApi.PagingEndpoint)
databaseSqlLogs.POST("/clear", DatabaseSQLLogApi.ClearEndpoint)
}
DnsProviderApi := new(api.DnsProviderApi)
dnsProviders := adminGroup.Group("/dns-providers")
{
dnsProviders.GET("/config", DnsProviderApi.GetConfigEndpoint)
dnsProviders.PUT("/config", DnsProviderApi.SetConfigEndpoint)
dnsProviders.DELETE("/config", DnsProviderApi.DeleteConfigEndpoint)
}
LicenseApi := new(api.LicenseApi)
adminGroup.GET("/license/machine-id", LicenseApi.GetMachineIdEndpoint)
adminGroup.GET("/license", LicenseApi.GetLicenseEndpoint)
adminGroup.POST("/license", LicenseApi.SetLicenseEndpoint)
adminGroup.POST("/license/request", LicenseApi.RequestLicenseEndpoint)
apiGroup.GET("/license", LicenseApi.GetSimpleLicenseEndpoint)
WebsiteTempAllowApi := new(api.WebsiteTempAllowApi)
adminGroup.GET("/website-temp-allow", WebsiteTempAllowApi.ListEndpoint)
adminGroup.DELETE("/website-temp-allow", WebsiteTempAllowApi.DeleteEndpoint)
}
portalGroup := apiGroup.Group("/portal")
{
portalGroup.GET("/assets", PortalApi.AssetsEndpoint)
portalGroup.GET("/database-assets", PortalApi.DatabaseAssetsEndpoint)
portalGroup.GET("/assets/tree", PortalApi.AssetsTreeEndpoint)
portalGroup.GET("/websites/tree", PortalApi.WebsitesTreeEndpoint)
portalGroup.GET("/assets/group-tree", PortalApi.AssetsGroupTreeEndpoint)
portalGroup.GET("/websites/group-tree", PortalApi.WebsitesGroupTreeEndpoint)
portalGroup.GET("/access-require-mfa", PortalApi.AccessRequireMfaEndpoint)
portalGroup.POST("/sessions", PortalApi.CreateSessionEndpoint)
portalGroup.GET("/sessions/:id", PortalApi.GetSessionEndpoint)
portalGroup.GET("/sessions/:id/share", PortalApi.GetShareEndpoint)
portalGroup.POST("/sessions/:id/share", PortalApi.CreateShareEndpoint)
portalGroup.DELETE("/sessions/:id/share", PortalApi.CancelShareEndpoint)
portalGroup.GET("/website/access", PortalApi.AccessWebsiteEndpoint)
portalGroup.POST("/website/allow-ip", PortalApi.AllowWebsiteIpEndpoint)
portalGroup.POST("/assets/:id/wol", PortalApi.WakeOnLanEndpoint)
portalGroup.POST("/assets/:id/ping", PortalApi.PingAssetEndpoint)
SnippetUserApi := new(api.SnippetUserApi)
portalGroup.GET("/snippets", SnippetUserApi.AllEndpoint)
portalGroup.GET("/snippets/paging", SnippetUserApi.PagingEndpoint)
portalGroup.GET("/snippets/:id", SnippetUserApi.GetEndpoint)
}
DbWorkOrderUserApi := new(api.DbWorkOrderApi)
apiGroup.GET("/db-work-orders/paging", DbWorkOrderUserApi.PagingEndpoint)
apiGroup.GET("/db-work-orders/:id", DbWorkOrderUserApi.GetEndpoint)
apiGroup.POST("/db-work-orders", DbWorkOrderUserApi.CreateEndpoint)
OidcApi := new(api.OidcApi)
apiGroup.GET("/oidc/authorize", OidcApi.AuthorizeEndpoint)
apiGroup.POST("/oidc/login", OidcApi.LoginEndpoint)
WechatWorkApi := new(api.WechatWorkApi)
apiGroup.GET("/wechat-work/authorize", WechatWorkApi.AuthorizeEndpoint)
apiGroup.POST("/wechat-work/login", WechatWorkApi.LoginEndpoint)
apiGroup.GET("/access/terminal/:id/stats", PortalApi.TerminalStatsEndpoint)
apiGroup.GET("/access/settings", AccessSettingApi.GetEndpoint)
apiGroup.PUT("/access/settings", AccessSettingApi.SetEndpoint)
apiGroup.GET("/access/settings/shell-assistant-enabled", AccessSettingApi.ShellAssistantEnabledEndpoint)
apiGroup.POST("/access/settings/shell-assistant", AccessSettingApi.ShellAssistantEndpoint)
apiGroup.GET("/access/terminal", webTerminalApi.AccessTerminalEndpoint)
filesystem := apiGroup.Group("/access/filesystem")
{
filesystem.GET("/:id/ls", FileSystemApi.LsEndpoint)
filesystem.POST("/:id/mkdir", FileSystemApi.MkdirEndpoint)
filesystem.POST("/:id/touch", FileSystemApi.TouchEndpoint)
filesystem.POST("/:id/rm", FileSystemApi.RmEndpoint)
filesystem.POST("/:id/rename", FileSystemApi.RenameEndpoint)
filesystem.POST("/:id/edit", FileSystemApi.EditEndpoint)
filesystem.GET("/:id/read", FileSystemApi.ReadEndpoint)
filesystem.POST("/:id/chmod", FileSystemApi.ChmodEndpoint)
filesystem.GET("/:id/upload/progress", FileSystemApi.UploadProgressEndpoint)
filesystem.GET("/:id/download", FileSystemApi.DownloadEndpoint)
filesystem.POST("/:id/upload", FileSystemApi.UploadEndpoint)
}
}
return e
}
+18
View File
@@ -0,0 +1,18 @@
package branding
import (
"fmt"
"time"
)
var Name = "Next Terminal"
var Copyright = fmt.Sprintf("Copyright © 2020-%d dushixiang, All Rights Reserved.", time.Now().Year())
var Banner = ` ___ ___
/\__\ /\ \
/:| _|_ \:\ \
/::|/\__\ /::\__\
\/|::/ / /:/\/__/
|:/ / \/__/
\/__/ `
var Version = `v1.3.9`
var Hi = Banner + Version
+308
View File
@@ -0,0 +1,308 @@
package guacamole
import (
"bufio"
"encoding/base64"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
)
const (
EnableRecording = "enable-recording"
RecordingPath = "recording-path"
CreateRecordingPath = "create-recording-path"
FontName = "font-name"
FontSize = "font-size"
ColorScheme = "color-scheme"
Backspace = "backspace"
TerminalType = "terminal-type"
PreConnectionId = "preconnection-id"
PreConnectionBlob = "preconnection-blob"
EnableDrive = "enable-drive"
DriveName = "drive-name"
DrivePath = "drive-path"
EnableWallpaper = "enable-wallpaper"
EnableTheming = "enable-theming"
EnableFontSmoothing = "enable-font-smoothing"
EnableFullWindowDrag = "enable-full-window-drag"
EnableDesktopComposition = "enable-desktop-composition"
EnableMenuAnimations = "enable-menu-animations"
DisableBitmapCaching = "disable-bitmap-caching"
DisableOffscreenCaching = "disable-offscreen-caching"
// DisableGlyphCaching Deprecated
DisableGlyphCaching = "disable-glyph-caching"
ForceLossless = "force-lossless"
Domain = "domain"
RemoteApp = "remote-app"
RemoteAppDir = "remote-app-dir"
RemoteAppArgs = "remote-app-args"
ColorDepth = "color-depth"
Cursor = "cursor"
SwapRedBlue = "swap-red-blue"
DestHost = "dest-host"
DestPort = "dest-port"
ReadOnly = "read-only"
UsernameRegex = "username-regex"
PasswordRegex = "password-regex"
LoginSuccessRegex = "login-success-regex"
LoginFailureRegex = "login-failure-regex"
Namespace = "namespace"
Pod = "pod"
Container = "container"
UesSSL = "use-ssl"
ClientCert = "client-cert"
ClientKey = "client-key"
CaCert = "ca-cert"
IgnoreCert = "ignore-cert"
)
const Delimiter = ';'
const Version = "VERSION_1_4_0"
type Configuration struct {
ConnectionID string
Protocol string
Parameters map[string]string
}
func NewConfiguration() (config *Configuration) {
config = &Configuration{}
config.Parameters = make(map[string]string)
return config
}
func (opt *Configuration) SetReadOnlyMode() {
opt.Parameters[ReadOnly] = "true"
}
func (opt *Configuration) SetParameter(name, value string) {
opt.Parameters[name] = value
}
func (opt *Configuration) UnSetParameter(name string) {
delete(opt.Parameters, name)
}
func (opt *Configuration) GetParameter(name string) string {
return opt.Parameters[name]
}
type Instruction struct {
Opcode string
Args []string
ProtocolForm string
}
func NewInstruction(opcode string, args ...string) (ret Instruction) {
ret.Opcode = opcode
ret.Args = args
return ret
}
func (opt *Instruction) String() string {
if len(opt.ProtocolForm) > 0 {
return opt.ProtocolForm
}
opt.ProtocolForm = fmt.Sprintf("%d.%s", len(opt.Opcode), opt.Opcode)
for _, value := range opt.Args {
opt.ProtocolForm += fmt.Sprintf(",%d.%s", len(value), value)
}
opt.ProtocolForm += string(Delimiter)
return opt.ProtocolForm
}
func (opt *Instruction) Parse(content string) Instruction {
if strings.LastIndex(content, ";") > 0 {
content = strings.TrimRight(content, ";")
}
messages := strings.Split(content, ",")
var args = make([]string, len(messages))
for i := range messages {
lm := strings.Split(messages[i], ".")
args[i] = lm[1]
}
return NewInstruction(args[0], args[1:]...)
}
type Tunnel struct {
conn net.Conn
reader *bufio.Reader
writer *bufio.Writer
UUID string
Config *Configuration
IsOpen bool
}
func NewTunnel(address string, config *Configuration) (ret *Tunnel, err error) {
conn, err := net.DialTimeout("tcp", address, 5*time.Second)
if err != nil {
return
}
ret = &Tunnel{}
ret.conn = conn
ret.reader = bufio.NewReader(conn)
ret.writer = bufio.NewWriter(conn)
ret.Config = config
selectArg := config.ConnectionID
if selectArg == "" {
selectArg = config.Protocol
}
if err := ret.WriteInstructionAndFlush(NewInstruction("select", selectArg)); err != nil {
_ = conn.Close()
return nil, err
}
args, err := ret.expect("args")
if err != nil {
_ = conn.Close()
return
}
width := config.GetParameter("width")
height := config.GetParameter("height")
dpi := config.GetParameter("dpi")
// send size
if err := ret.WriteInstructionAndFlush(NewInstruction("size", width, height, dpi)); err != nil {
_ = conn.Close()
return nil, err
}
if err := ret.WriteInstructionAndFlush(NewInstruction("audio", "audio/L8", "audio/L16")); err != nil {
_ = conn.Close()
return nil, err
}
if err := ret.WriteInstructionAndFlush(NewInstruction("video")); err != nil {
_ = conn.Close()
return nil, err
}
if err := ret.WriteInstructionAndFlush(NewInstruction("image", "image/jpeg", "image/png", "image/webp")); err != nil {
_ = conn.Close()
return nil, err
}
if err := ret.WriteInstructionAndFlush(NewInstruction("timezone", "Asia/Shanghai")); err != nil {
_ = conn.Close()
return nil, err
}
parameters := make([]string, len(args.Args))
for i := range args.Args {
argName := args.Args[i]
if strings.Contains(argName, "VERSION") {
parameters[i] = Version
continue
}
parameters[i] = config.GetParameter(argName)
}
// send connect
if err := ret.WriteInstructionAndFlush(NewInstruction("connect", parameters...)); err != nil {
_ = conn.Close()
return nil, err
}
ready, err := ret.expect("ready")
if err != nil {
return
}
if len(ready.Args) == 0 {
_ = conn.Close()
return nil, errors.New("no connection id received")
}
ret.UUID = ready.Args[0]
ret.IsOpen = true
return ret, nil
}
func (opt *Tunnel) WriteInstructionAndFlush(instruction Instruction) error {
if _, err := opt.WriteAndFlush([]byte(instruction.String())); err != nil {
return err
}
return nil
}
func (opt *Tunnel) WriteAndFlush(p []byte) (int, error) {
//fmt.Printf("-> %v\n", string(p))
nn, err := opt.writer.Write(p)
if err != nil {
return nn, err
}
err = opt.writer.Flush()
if err != nil {
return nn, err
}
return nn, nil
}
func (opt *Tunnel) ReadInstruction() (instruction Instruction, err error) {
msg, err := opt.Read()
if err != nil {
return instruction, err
}
return instruction.Parse(string(msg)), err
}
func (opt *Tunnel) Read() (p []byte, err error) {
data, err := opt.reader.ReadBytes(Delimiter)
if err != nil {
return
}
s := string(data)
//fmt.Printf("<- %v \n", s)
if s == "rate=44100,channels=2;" {
return make([]byte, 0), nil
}
if s == "rate=22050,channels=2;" {
return make([]byte, 0), nil
}
if s == "5.audio,1.1,31.audio/L16;" {
s += "rate=44100,channels=2;"
}
return []byte(s), err
}
func (opt *Tunnel) expect(opcode string) (instruction Instruction, err error) {
instruction, err = opt.ReadInstruction()
if err != nil {
return instruction, err
}
if opcode != instruction.Opcode {
msg := fmt.Sprintf(`expected "%s" instruction but instead received "%s"`, opcode, instruction.Opcode)
return instruction, errors.New(msg)
}
return instruction, nil
}
func (opt *Tunnel) Close() error {
opt.IsOpen = false
return opt.conn.Close()
}
func Disconnect(ws *websocket.Conn, code int, reason string) {
// guacd 无法处理中文字符,所以进行了base64编码。
encodeReason := base64.StdEncoding.EncodeToString([]byte(reason))
err := NewInstruction("error", encodeReason, strconv.Itoa(code))
_ = ws.WriteMessage(websocket.TextMessage, []byte(err.String()))
disconnect := NewInstruction("disconnect")
_ = ws.WriteMessage(websocket.TextMessage, []byte(disconnect.String()))
}
+56
View File
@@ -0,0 +1,56 @@
package common
import (
"database/sql/driver"
"fmt"
"strings"
"time"
)
type JsonTime struct {
time.Time
}
func NewJsonTime(t time.Time) JsonTime {
return JsonTime{
Time: t,
}
}
func NowJsonTime() JsonTime {
return JsonTime{
Time: time.Now(),
}
}
func (j JsonTime) MarshalJSON() ([]byte, error) {
var stamp = fmt.Sprintf("\"%s\"", j.Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}
func (j *JsonTime) UnmarshalJSON(b []byte) error {
s := strings.ReplaceAll(string(b), "\"", "")
t, err := time.Parse("2006-01-02 15:04:05", s)
if err != nil {
return err
}
*j = NewJsonTime(t)
return nil
}
func (j JsonTime) Value() (driver.Value, error) {
var zeroTime time.Time
if j.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return j.Time, nil
}
func (j *JsonTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*j = JsonTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
+3
View File
@@ -0,0 +1,3 @@
package maps
type Map map[string]interface{}

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