Compare commits

..

No commits in common. 'dev' and 'v1' have entirely different histories.
dev ... v1

@ -7,15 +7,15 @@ tmp_dir = "tmp"
[build] [build]
# Just plain old shell command. You could use `make` as well. # Just plain old shell command. You could use `make` as well.
cmd = "CGO_ENABLED=1 go build -tags=jsoniter -ldflags=\"-X 'github.com/0xJacky/Nginx-UI/settings.buildTime=$(date +%s)'\" -v -o ./tmp/main ." cmd = "CGO_ENABLED=1 go build -ldflags=\"-X 'github.com/0xJacky/Nginx-UI/server/settings.buildTime=$(date +%s)'\" -o ./tmp/main ."
# Binary file yields from `cmd`. # Binary file yields from `cmd`.
bin = "tmp/main" bin = "tmp/main"
# Customize binary. # Customize binary.
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main" full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# Watch these filename extensions. # Watch these filename extensions.
include_ext = ["go", "tpl", "tmpl", "html", "toml", "po"] include_ext = ["go", "tpl", "tmpl", "html", "conf", "ini", "toml"]
# Ignore these filename extensions or directories. # Ignore these filename extensions or directories.
exclude_dir = ["assets", "tmp", "vendor", "app/node_modules", "upload", "docs", "resources", ".idea"] exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules", "upload"]
# Watch these directories if you specified. # Watch these directories if you specified.
include_dir = [] include_dir = []
# Exclude files. # Exclude files.
@ -51,6 +51,3 @@ runner = "green"
[misc] [misc]
# Delete tmp directory on exit # Delete tmp directory on exit
clean_on_exit = true clean_on_exit = true
[screen]
keep_scroll = true

@ -1,4 +0,0 @@
.git
app/node_modules
.idea
tmp

@ -1,16 +1,15 @@
root = true root = true
[*] [*]
block_comment_start = /*
block_comment_end = */
charset = utf-8 charset = utf-8
indent_style = space indent_style = space
indent_size = 2 indent_size = 4
end_of_line = lf end_of_line = lf
insert_final_newline = true insert_final_newline = true
trim_trailing_whitespace = true trim_trailing_whitespace = true
[*.go]
indent_size = 4
[README.md] [README.md]
indent_style = space indent_style = space
indent_size = 4 indent_size = 4

@ -1,18 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "npm"
directory: "/app"
target-branch: "dev"
schedule:
interval: "weekly"
- package-ecosystem: "gomod"
directory: "/"
target-branch: "dev"
schedule:
interval: "weekly"

@ -1,266 +1,255 @@
name: Build name: Build
on: on:
push: push:
branches: branches:
- '*' - '*'
- '!weblate' paths:
paths: - "**/*.js"
- "app/**/*.js" - "**/*.vue"
- "app/**/*.vue" - "frontend/package.json"
- "app/src/language/**/*.po" - "frontend/.env*"
- "app/i18n.json" - "**/*.go"
- "app/package.json" - "go.mod"
- "app/.env*" - "go.sum"
- "**/*.go" - ".github/workflows/*.yml"
- "go.mod" - "resources/*"
- "go.sum" pull_request:
- ".github/workflows/build*.yml" types: [ opened, synchronize, reopened ]
- "resources/docker/docker/*" paths:
- "resources/development/*" - "**/*.js"
- "resources/demo/*" - "**/*.vue"
- "Dockerfile" - "frontend/package.json"
- "demo.Dockerfile" - "frontend/.env*"
pull_request: - "**/*.go"
types: [ opened, synchronize, reopened ] - "go.mod"
paths: - "go.sum"
- "**/*.js" - ".github/workflows/*.yml"
- "**/*.vue" release:
- "app/package.json" types:
- "app/.env*" - published
- "**/*.go"
- "go.mod"
- "go.sum"
- ".github/workflows/*.yml"
- "resources/docker/docker/*"
- "resources/development/*"
- "resources/demo/*"
release:
types:
- published
jobs: jobs:
build_app: build_frontend:
runs-on: macos-14 runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Set up nodejs - name: Set up nodejs
uses: actions/setup-node@v4 uses: actions/setup-node@v3
with: with:
node-version: current node-version: 18.x
cache: 'yarn'
- name: Install dependencies cache-dependency-path: 'frontend/yarn.lock'
run: |
corepack enable - name: Install dependencies
corepack prepare pnpm@latest --activate run: yarn install
pnpm install working-directory: frontend
working-directory: app
- name: Update translations
- name: Check frontend code style run: yarn gettext:compile
run: | working-directory: frontend
pnpm run lint
working-directory: app - name: Build
run: |
- name: Check frontend types npx browserslist@latest --update-db
run: | yarn build
pnpm run typecheck working-directory: frontend
working-directory: app
- name: Archive frontend artifacts
- name: Build uses: actions/upload-artifact@v3
run: | with:
npx browserslist@latest --update-db name: frontend-dist
pnpm build path: frontend/dist
working-directory: app
- name: Prepare publish
- name: Archive app artifacts if: github.event_name == 'release'
uses: actions/upload-artifact@v4 run: |
with: cp README*.md frontend/dist
name: app-dist find frontend/dist -printf '%P\n' | tar -C frontend/dist --no-recursion -zcvf frontend-dist.tar.gz -T -
path: app/dist
- name: Publish
- name: Prepare publish uses: softprops/action-gh-release@v1
if: github.event_name == 'release' if: github.event_name == 'release'
run: | with:
cp README*.md app/dist files: frontend-dist.tar.gz
find app/dist -printf '%P\n' | tar -C app/dist --no-recursion -zcvf app-dist.tar.gz -T -
build:
- name: Publish runs-on: ubuntu-latest
uses: softprops/action-gh-release@v2 needs: build_frontend
if: github.event_name == 'release' strategy:
with: matrix:
files: app-dist.tar.gz goos: [ linux, darwin ]
goarch: [ amd64, 386, arm64 ]
build: exclude:
runs-on: ubuntu-latest # Exclude i386 on darwin.
needs: build_app - goarch: 386
strategy: goos: darwin
matrix: include:
goos: [ linux, darwin ] # BEGIN Linux ARM 5 6 7
goarch: [ amd64, 386, arm64 ] - goos: linux
exclude: goarch: arm
# Exclude i386 on darwin. goarm: 7
- goarch: 386 - goos: linux
goos: darwin goarch: arm
include: goarm: 6
# BEGIN Linux ARM 5 6 7 - goos: linux
- goos: linux goarch: arm
goarch: arm goarm: 5
goarm: 7 # END Linux ARM 5 6 7
- goos: linux env:
goarch: arm CGO_ENABLED: 1
goarm: 6 GOOS: ${{ matrix.goos }}
- goos: linux GOARCH: ${{ matrix.goarch }}
goarch: arm GOARM: ${{ matrix.goarm }}
goarm: 5 steps:
# END Linux ARM 5 6 7 - name: Checkout
env: uses: actions/checkout@v3
CGO_ENABLED: 1
GOOS: ${{ matrix.goos }} - name: Set up Go
GOARCH: ${{ matrix.goarch }} uses: actions/setup-go@v3
GOARM: ${{ matrix.goarm }} with:
steps: go-version: ^1.20.1
- name: Checkout
uses: actions/checkout@v4 - name: Set up cache
uses: actions/cache@v3
- name: Set up Go with:
uses: actions/setup-go@v5 path: |
with: ~/.cache/go-build
go-version: ^1.23.0 ~/go/pkg/mod
key: ${{ runner.os }}-${{ env.GOOS }}-${{ env.GOARCH }}${{ env.GOARM }}-go-${{ hashFiles('**/go.sum') }}
- name: Setup compiler environment restore-keys: |
id: info ${{ runner.os }}-${{ env.GOOS }}-${{ env.GOARCH }}${{ env.GOARM }}-go-
run: |
export _NAME=nginx-ui-$(jq ".$GOOS[\"$GOARCH$GOARM\"].name" -r < .github/build/build_info.json) - name: Setup compiler environment
export _ARCH=$(jq ".$GOOS[\"$GOARCH$GOARM\"].arch" -r < .github/build/build_info.json) id: info
export _ABI=$(jq ".$GOOS[\"$GOARCH$GOARM\"].abi // \"\"" -r < .github/build/build_info.json) run: |
export _ARTIFACT=nginx-ui-$GOOS-$GOARCH$(if [[ "$GOARM" ]]; then echo "v$GOARM"; fi) export _NAME=nginx-ui-$(jq ".$GOOS[\"$GOARCH$GOARM\"].name" -r < .github/build/build_info.json)
echo "GOOS: $GOOS, GOARCH: $GOARCH, GOARM: $GOARM, ABI: $_ABI, RELEASE_NAME: $_NAME, ARTIFACT_NAME: $_ARTIFACT" export _ARCH=$(jq ".$GOOS[\"$GOARCH$GOARM\"].arch" -r < .github/build/build_info.json)
echo "ARCH_NAME=$_ARCH" >> $GITHUB_ENV export _ABI=$(jq ".$GOOS[\"$GOARCH$GOARM\"].abi // \"\"" -r < .github/build/build_info.json)
echo "ABI=$_ABI" >> $GITHUB_ENV export _ARTIFACT=nginx-ui-$GOOS-$GOARCH$(if [[ "$GOARM" ]]; then echo "v$GOARM"; fi)
echo "DIST=$_NAME" >> $GITHUB_ENV echo "GOOS: $GOOS, GOARCH: $GOARCH, GOARM: $GOARM, ABI: $_ABI, RELEASE_NAME: $_NAME, ARTIFACT_NAME: $_ARTIFACT"
echo "ARTIFACT=$_ARTIFACT" >> $GITHUB_ENV echo "ARCH_NAME=$_ARCH" >> $GITHUB_ENV
echo "ABI=$_ABI" >> $GITHUB_ENV
- name: Install musl cross compiler echo "DIST=$_NAME" >> $GITHUB_ENV
if: env.GOOS == 'linux' echo "ARTIFACT=$_ARTIFACT" >> $GITHUB_ENV
uses: 0xJacky/musl-cross-compilers@v0.6.6
id: musl - name: Install musl cross compiler
with: if: env.GOOS == 'linux'
target: ${{ env.ARCH_NAME }}-linux-musl${{ env.ABI }} uses: 0xJacky/musl-cross-compilers@v0.6.5
id: musl
- name: Post install musl cross compiler with:
if: env.GOOS == 'linux' target: ${{ env.ARCH_NAME }}-linux-musl${{ env.ABI }}
run: |
echo "PATH=${{ steps.musl.outputs.path }}:$PATH" >> $GITHUB_ENV - name: Post install musl cross compiler
echo "CC=${{ env.ARCH_NAME }}-linux-musl${{ env.ABI }}-gcc" >> $GITHUB_ENV if: env.GOOS == 'linux'
echo "CXX=${{ env.ARCH_NAME }}-linux-musl${{ env.ABI }}-g++" >> $GITHUB_ENV run: |
echo "LD_FLAGS=-w --extldflags '-static'" >> $GITHUB_ENV echo "PATH=${{ steps.musl.outputs.path }}:$PATH" >> $GITHUB_ENV
echo "CC=${{ env.ARCH_NAME }}-linux-musl${{ env.ABI }}-gcc" >> $GITHUB_ENV
- name: Install darwin cross compiler echo "CXX=${{ env.ARCH_NAME }}-linux-musl${{ env.ABI }}-g++" >> $GITHUB_ENV
if: env.GOOS == 'darwin' echo "LD_FLAGS=--extldflags '-static'" >> $GITHUB_ENV
run: |
curl -L https://github.com/Hintay/crossosx/releases/latest/download/crossosx.tar.zst -o crossosx.tar.zst - name: Install darwin cross compiler
tar xvaf crossosx.tar.zst if: env.GOOS == 'darwin'
echo "LD_LIBRARY_PATH=$(pwd)/crossosx/lib/" >> $GITHUB_ENV run: |
echo "PATH=$(pwd)/crossosx/bin/:$PATH" >> $GITHUB_ENV curl -L https://github.com/Hintay/crossosx/releases/latest/download/crossosx.tar.zst -o crossosx.tar.zst
echo "CC=${{ env.ARCH_NAME }}-clang" >> $GITHUB_ENV tar xvaf crossosx.tar.zst
echo "CXX=${{ env.ARCH_NAME }}-clang++" >> $GITHUB_ENV echo "LD_LIBRARY_PATH=$(pwd)/crossosx/lib/" >> $GITHUB_ENV
echo "LD_FLAGS=-w" >> $GITHUB_ENV echo "PATH=$(pwd)/crossosx/bin/:$PATH" >> $GITHUB_ENV
echo "CC=${{ env.ARCH_NAME }}-clang" >> $GITHUB_ENV
- name: Download app artifacts echo "CXX=${{ env.ARCH_NAME }}-clang++" >> $GITHUB_ENV
uses: actions/download-artifact@v4 echo "LD_FLAGS=-s -w" >> $GITHUB_ENV
with:
name: app-dist - name: Download frontend artifacts
path: app/dist uses: actions/download-artifact@v3
with:
- name: Build name: frontend-dist
run: | path: frontend/dist
mkdir -p dist
go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/settings.buildTime=$(date +%s)'" -o dist/nginx-ui -v main.go - name: Build
run: |
- name: Archive backend artifacts mkdir -p dist
uses: actions/upload-artifact@v4 go build -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/server/settings.buildTime=$(date +%s)'" -o dist/nginx-ui -v main.go
with:
name: ${{ env.ARTIFACT }} - name: Archive backend artifacts
path: dist/nginx-ui uses: actions/upload-artifact@v3
with:
- name: Prepare publish name: ${{ env.ARTIFACT }}
if: github.event_name == 'release' path: dist/nginx-ui
run: |
cp README*.md ./dist - name: Prepare publish
find dist -printf '%P\n' | tar -C dist --no-recursion -zcvf ${{ env.DIST }}.tar.gz -T - if: github.event_name == 'release'
openssl dgst -sha512 ${{ env.DIST }}.tar.gz | sed 's/([^)]*)//g' | awk '{print $NF}' >> ${{ env.DIST }}.tar.gz.digest run: |
cp README*.md ./dist
- name: Publish find dist -printf '%P\n' | tar -C dist --no-recursion -zcvf ${{ env.DIST }}.tar.gz -T -
uses: softprops/action-gh-release@v2
if: github.event_name == 'release' - name: Publish
with: uses: softprops/action-gh-release@v1
files: | if: github.event_name == 'release'
${{ env.DIST }}.tar.gz with:
${{ env.DIST }}.tar.gz.digest files: ${{ env.DIST }}.tar.gz
docker-build: docker-build:
if: github.event_name != 'pull_request' runs-on: ubuntu-latest
runs-on: ubuntu-latest needs: build
needs: build env:
env: PLATFORMS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6,linux/arm/v5
PLATFORMS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6,linux/arm/v5 steps:
steps: - name: Checkout
- name: Checkout uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Get the version
- name: Get the version id: get_version
id: get_version run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT
run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT
- name: Download artifacts
- name: Download artifacts uses: actions/download-artifact@v3
uses: actions/download-artifact@v4 with:
with: path: ./dist
path: ./dist
- name: Prepare Artifacts
- name: Prepare Artifacts run: chmod +x ./dist/nginx-ui-*/nginx-ui
run: chmod +x ./dist/nginx-ui-*/nginx-ui
- name: Set up Docker Buildx
- name: Set up Docker Buildx id: buildx
id: buildx uses: docker/setup-buildx-action@v2
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
- name: Login to DockerHub uses: docker/login-action@v2
uses: docker/login-action@v3 with:
with: username: ${{ secrets.DOCKERHUB_USER }}
username: ${{ secrets.DOCKERHUB_USER }} password: ${{ secrets.DOCKERHUB_TOKEN }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Prepare Dockerfile
- name: Prepare Dockerfile if: github.event_name == 'release'
if: github.event_name == 'release' run: |
run: | cp ./Dockerfile ./dist
cp ./Dockerfile ./dist cp -rp ./resources ./dist
cp -rp ./resources ./dist
- name: Build and push
- name: Build and push if: github.event_name == 'release'
if: github.event_name == 'release' uses: docker/build-push-action@v3
uses: docker/build-push-action@v5 with:
with: context: ./dist
context: ./dist file: ./dist/Dockerfile
file: ./dist/Dockerfile platforms: ${{ env.PLATFORMS }}
platforms: ${{ env.PLATFORMS }} push: ${{ github.event_name != 'pull_request' }}
push: ${{ github.event_name != 'pull_request' }} tags: |
tags: | uozi/nginx-ui:latest
uozi/nginx-ui:latest uozi/nginx-ui:${{ steps.get_version.outputs.VERSION }}
uozi/nginx-ui:${{ steps.get_version.outputs.VERSION }}
- name: Prepare Demo Dockerfile
- name: Prepare Demo Dockerfile run: |
run: | cp ./demo.Dockerfile ./dist
cp ./demo.Dockerfile ./dist cp -rp ./resources ./dist
cp -rp ./resources ./dist
- name: Build and push demo
- name: Build and push demo uses: docker/build-push-action@v3
uses: docker/build-push-action@v5 with:
with: context: ./dist
context: ./dist file: ./dist/demo.Dockerfile
file: ./dist/demo.Dockerfile platforms: ${{ env.PLATFORMS }}
platforms: ${{ env.PLATFORMS }} push: ${{ github.event_name != 'pull_request' }}
push: ${{ github.event_name != 'pull_request' }} tags: |
tags: | uozi/nginx-ui-demo:latest
uozi/nginx-ui-demo:latest

@ -1,99 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ "dev" ]
pull_request:
branches: [ "dev" ]
paths-ignore:
- '**/*.md'
- '**/*.ini'
schedule:
- cron: '34 6 * * *'
jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
# required for all workflows
security-events: write
# required to fetch internal or private CodeQL packs
packages: read
# only required for workflows in private repositories
actions: read
contents: read
strategy:
fail-fast: false
matrix:
include:
- language: go
build-mode: autobuild
- language: javascript-typescript
build-mode: none
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"

@ -1,64 +0,0 @@
name: Build Documents
on:
push:
branches:
- '*'
paths:
- "docs/**/*.js"
- "docs/**/*.ts"
- "docs/**/*.vue"
- "docs/package.json"
- "docs/.env*"
- "docs/**/*.md"
- ".github/workflows/doc*.yml"
pull_request:
types: [ opened, synchronize, reopened ]
paths:
- "docs/**/*.js"
- "docs/**/*.ts"
- "docs/**/*.vue"
- "docs/package.json"
- "docs/.env*"
- "docs/**/*.md"
- ".github/workflows/doc*.yml"
jobs:
build:
runs-on: macos-14
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up nodejs
uses: actions/setup-node@v4
with:
node-version: 21.x
- name: Install dependencies
run: |
corepack enable
corepack prepare pnpm@latest --activate
pnpm install
working-directory: docs
- name: Build
run: COMMIT_REF=$(git rev-parse HEAD) pnpm docs:build
working-directory: docs
- name: Archive artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: docs/.vitepress/dist
- name: Deploy to server
if: github.event_name != 'pull_request'
uses: easingthemes/ssh-deploy@main
env:
REMOTE_HOST: ${{ secrets.REMOTE_HOST }}
REMOTE_USER: ${{ secrets.REMOTE_USER }}
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
TARGET: ${{ secrets.REMOTE_TARGET }}
SOURCE: "docs/.vitepress/dist/"
ARGS: "-rlgoDzvc -i --delete"

@ -1,32 +0,0 @@
name: Weblate Pull Branch
on:
workflow_dispatch:
pull_request_target:
branches:
- 'dev'
types: [ closed ]
release:
types:
- published
jobs:
weblate:
runs-on: ubuntu-latest
if: github.event.pull_request.merged == true || github.event.action == 'published' || github.event_name == 'workflow_dispatch'
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Install wlc
run: pip install wlc
- name: Update Repository
env:
WEBLATE_TOKEN: ${{ secrets.WEBLATE_TOKEN }}
run: wlc --key $WEBLATE_TOKEN pull

@ -1,86 +0,0 @@
name: Synchronize Weblate Branch
on:
workflow_dispatch:
schedule:
- cron: '15 18 * * *'
env:
DEVELOP_BRANCH: dev
WEBLATE_BRANCH: weblate
jobs:
check:
name: Check Branches
runs-on: ubuntu-latest
outputs:
behind: ${{ steps.check.outputs.behind }}
ahead: ${{ steps.check.outputs.ahead }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ env.DEVELOP_BRANCH }}
clean: false
fetch-depth: 0
- name: Check branches
id: check
run: |
git fetch --all
git branch $WEBLATE_BRANCH origin/$WEBLATE_BRANCH
echo "behind=$(git rev-list --count $WEBLATE_BRANCH..$DEVELOP_BRANCH)" >> $GITHUB_OUTPUT
echo "ahead=$(git rev-list --count $DEVELOP_BRANCH..$WEBLATE_BRANCH)" >> $GITHUB_OUTPUT
- name: Echo outputs
run: |
echo "behind: ${{ steps.check.outputs.behind }}"
echo "ahead: ${{ steps.check.outputs.ahead }}"
force-update:
name: Force Update Weblate Status
runs-on: ubuntu-latest
needs: check
if: ${{ needs.check.outputs.behind > 0 }}
env:
WEBLATE_TOKEN: ${{ secrets.WEBLATE_TOKEN }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Install wlc
run: pip install wlc
- name: Update weblate repository
run: wlc --key $WEBLATE_TOKEN pull
- name: Push weblate branch
run: wlc --key $WEBLATE_TOKEN push
sync-branch:
name: Sync Weblate Branch
runs-on: ubuntu-latest
needs: [check, force-update]
if: ${{ needs.check.outputs.ahead > 0 && always() }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ env.DEVELOP_BRANCH }}
fetch-depth: 0
- name: Set up git
run: |
git config --global user.name 'Weblate'
git config --global user.email 'weblate@nginxui.com'
- name: Push changes of weblate branch to develop branch
run: |
git fetch origin
git merge --ff-only -- origin/${{ env.WEBLATE_BRANCH }}
git push origin ${{ env.DEVELOP_BRANCH }}

7
.gitignore vendored

@ -1,13 +1,10 @@
.DS_Store .DS_Store
.idea
database.db database.db
tmp tmp
node_modules node_modules
.pnpm-store /app.ini
app.ini
dist dist
*.exe *.exe
*.po~ *.po~
nginx-ui nginx-ui
resources/development/nginx
app/.env
app/.status_hash

10
.idea/.gitignore vendored

@ -1,10 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# GitHub Copilot persisted chat sessions
/copilot/chatSessions

@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/nginx-ui.iml" filepath="$PROJECT_DIR$/.idea/nginx-ui.iml" />
</modules>
</component>
</project>

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

@ -1,3 +0,0 @@
[weblate]
url = https://weblate.nginxui.com/api/
translation = nginx-ui

@ -2,28 +2,17 @@ FROM --platform=$TARGETPLATFORM uozi/nginx-ui-base:latest
ARG TARGETOS ARG TARGETOS
ARG TARGETARCH ARG TARGETARCH
ARG TARGETVARIANT ARG TARGETVARIANT
WORKDIR /app
EXPOSE 80 443 EXPOSE 80 443
ENV NGINX_UI_OFFICIAL_DOCKER=true COPY resources/docker/start.sh /app/start.sh
COPY resources/docker/nginx.conf /usr/etc/nginx/nginx.conf
COPY resources/docker/nginx-ui.conf /usr/etc/nginx/conf.d/nginx-ui.conf
COPY resources/docker/nginx-ui.conf /etc/nginx/conf.d/nginx-ui.conf
COPY nginx-ui-$TARGETOS-$TARGETARCH$TARGETVARIANT/nginx-ui /app/nginx-ui
# register nginx-ui service RUN cd /app && chmod a+x /app/start.sh \
COPY resources/docker/nginx-ui.run /etc/s6-overlay/s6-rc.d/nginx-ui/run && rm -f /etc/nginx/conf.d/default.conf \
RUN echo 'longrun' > /etc/s6-overlay/s6-rc.d/nginx-ui/type && \ && rm -f /usr/etc/nginx/conf.d/default.conf
touch /etc/s6-overlay/s6-rc.d/user/contents.d/nginx-ui
# copy nginx config ENTRYPOINT ["./start.sh"]
COPY resources/docker/nginx.conf /usr/local/etc/nginx/nginx.conf
COPY resources/docker/nginx-ui.conf /usr/local/etc/nginx/conf.d/nginx-ui.conf
# copy nginx-ui executable binary
COPY nginx-ui-$TARGETOS-$TARGETARCH$TARGETVARIANT/nginx-ui /usr/local/bin/nginx-ui
# remove default nginx config
RUN rm -f /etc/nginx/conf.d/default.conf \
&& rm -f /usr/local/etc/nginx/conf.d/default.conf
# recreate access.log and error.log
RUN rm -f /var/log/nginx/access.log && \
touch /var/log/nginx/access.log && \
rm -f /var/log/nginx/error.log && \
touch /var/log/nginx/error.log

@ -1,319 +0,0 @@
<div align="center">
<img src="resources/logo.png" alt="Logotipo de la interfaz de usuario de Nginx">
</div>
# Interfaz de usuario (UI) de Nginx
Otra UI web de Nginx, desarrollada por [0xJacky](https://jackyu.cn/) y [Hintay](https://blog.kugeek.com/).
[![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml)
## Documentación
Para consultar la documentación, visite [nginxui.com](https://nginxui.com).
## Stargazers en el tiempo
[![Stargazers over time](https://starchart.cc/0xJacky/nginx-ui.svg)](https://starchart.cc/0xJacky/nginx-ui)
[English](README.md) | Español | [简体中文](README-zh_CN.md) | [繁體中文](README-zh_TW.md)
<details>
<summary>Tabla de Contenidos</summary>
<ol>
<li>
<a href="#about-the-project">Sobre el proyecto</a>
<ul>
<li><a href="#demo">Demostración</a></li>
<li><a href="#features">Características</a></li>
<li><a href="#internationalization">Internacionalización</a></li>
<li><a href="#built-with">Desarrollado con</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Cómo empezar</a>
<ul>
<li><a href="#before-use">Antes de usar</a></li>
<li><a href="#installation">Instalación</a></li>
<li>
<a href="#usage">Uso</a>
<ul>
<li><a href="#from-executable">Desde el ejecutable</a></li>
<li><a href="#with-systemd">Con Systemd</a></li>
<li><a href="#with-docker">Con Docker</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#manual-build">Compilación manual</a>
<ul>
<li><a href="#prerequisites">Prerequisitos</a></li>
<li><a href="#build-app">Compilación del Frontend</a></li>
<li><a href="#build-backend">Compilación del Backend</a></li>
</ul>
</li>
<li>
<a href="#script-for-linux">Script para Linux</a>
<ul>
<li><a href="#basic-usage">Uso Básico</a></li>
<li><a href="#more-usage">Uso Avanzado</a></li>
</ul>
</li>
<li><a href="#example-of-nginx-reverse-proxy-configuration">Ejemplo de configuración de proxy reverso de Nginx</a></li>
<li><a href="#contributing">Contribuir</a></li>
<li><a href="#license">Licencia</a></li>
</ol>
</details>
## Sobre el proyecto
![Dashboard](resources/screenshots/dashboard_es.png)
### Demostración
URL:[https://demo.nginxui.com](https://demo.nginxui.com)
- Nombre de usuario: admin
- Contraseña: admin
### Características
- Estadísticas en línea para los indicadores del servidor, como el uso de la CPU, el uso de la memoria, el promedio de carga y el uso del disco.
- Asistente de ChatGPT en línea
- Despliegue con un solo clic y renovación automática de certificados Let's Encrypt.
- Edición de las configuraciones de sitios web con nuestro **NgxConfigEditor** de diseño propio, que es un editor de bloques fácil de usar para configuraciones de nginx o con el **Editor de código Ace** que admite resaltar la sintaxis de configuración de nginx.
- Visualización en línea los registros de Nginx
- Escrito en Go y Vue, distribuído en un único binario ejecutable.
- Prueba automática del archivo de configuración y recarga de nginx después de guardar la configuración.
- Terminal Web
- Modo oscuro
- Diseño web adaptable
### Internacionalización
- Inglés
- Chino Simplificado
- Chino Tradicional
Aceptamos traducciones a cualquier idioma.
### Desarrollado con
- [El lenguaje de programación Go](https://go.dev)
- [Gin Web Framework](https://gin-gonic.com)
- [GORM](http://gorm.io)
- [Vue 3](https://v3.vuejs.org)
- [Vite](https://vitejs.dev)
- [TypeScript](https://www.typescriptlang.org/)
- [Ant Design Vue](https://antdv.com)
- [vue3-gettext](https://github.com/jshmrtn/vue3-gettext)
- [vue3-ace-editor](https://github.com/CarterLi/vue3-ace-editor)
- [Gonginx](https://github.com/tufanbarisyildirim/gonginx)
## Cómo empezar
### Antes de usar
La UI de Nginx sigue la configuración estándar de archivos de un servidor web de Debian. Los archivos de configuración del sitio creados se colocarán en la carpeta `sites-available` que se encuentra dentro de la carpeta de configuración de Nginx (detectada automáticamente). Los archivos de configuración para un sitio habilitado crearán un soft link en la carpeta `sites-enabled`. Es posible que deba ajustar la forma en que se organizan los archivos de configuración.
Para sistemas que no sean Debian (y Ubuntu), es posible que deba cambiar el contenido del archivo de configuración `nginx.conf` al estilo Debian como se muestra a continuación.
```nginx
http {
# ...
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
```
Para más información: [debian/conf/nginx.conf](https://salsa.debian.org/nginx-team/nginx/-/blob/master/debian/conf/nginx.conf#L59-L60)
### Instalación
La UI de Nginx está disponible en las siguientes plataformas:
- macOS 11 Big Sur y posterior (amd64 / arm64)
- Linux 2.6.23 and later (x86 / amd64 / arm64 / armv5 / armv6 / armv7)
- Incluyendo pero no limitado a Debian 7 / 8, Ubuntu 12.04 / 14.04 and later, CentOS 6 / 7, Arch Linux
- FreeBSD
- OpenBSD
- Dragonfly BSD
- Openwrt
Puede visitar [latest release](https://github.com/0xJacky/nginx-ui/releases/latest) para descargar la última distribución, o simplemente usar los [scripts de instalación para Linux](#script-for-linux).
### Uso
Al ejecutar por primera vez la UI de Nginx, visite en su navegador `http://<your_server_ip>:<listen_port>` para completar las configuraciones posteriores.
#### Desde el ejecutable
**Ejecutar UI Nginx en la terminal**
```shell
nginx-ui -config app.ini
```
Presione `Control+C` en la terminal para salir de la UI de Nginx.
**Ejecutar UI Nginx en Segundo plano**
```shell
nohup ./nginx-ui -config app.ini &
```
Detenga la UI de Nginx con el siguiente comando.
```shell
kill -9 $(ps -aux | grep nginx-ui | grep -v grep | awk '{print $2}')
```
#### Con Systemd
Si está utilizando el [script de instalación para Linux](#script-for-linux), la UI de Nginx se instalará como el servicio `nginx-ui` en systemd. Utilice el comando `systemctl` para controlarlo.
**Iniciar UI Nginx**
```shell
systemctl start nginx-ui
```
**Detener UI Nginx**
```shell
systemctl stop nginx-ui
```
**Reiniciar UI Nginx**
```shell
systemctl restart nginx-ui
```
#### Con Docker
Nuestra imagen dpcker [uozi/nginx-ui:latest](https://hub.docker.com/r/uozi/nginx-ui) se basa en la última imagen nginx y se puede usar para reemplazar Nginx en el host. Puede realizar el cambio fácilmente publicando los puertos 80 y 443 del contenedor en el host.
##### Nota
1. Cuando utilice este contenedor por primera vez, asegúrese de que el volumen mapeado a /etc/nginx esté vacío.
2. Si desea incluir archivos estáticos, puede mapear directorios al contenedor.
**Ejemplo de desplegado Docker**
```bash
docker run -dit \
--name=nginx-ui \
--restart=always \
-e TZ=Asia/Shanghai \
-v /mnt/user/appdata/nginx:/etc/nginx \
-v /mnt/user/appdata/nginx-ui:/etc/nginx-ui \
-v /var/www:/var/www \
-p 8080:80 -p 8443:443 \
uozi/nginx-ui:latest
```
## Compilación manual
En plataformas que no tienen una versión de compilación oficial, pueden compilarse manualmente.
### Prerequisitos
- Make
- Golang 1.23+
- node.js 21+
```shell
npx browserslist@latest --update-db
```
### Compilación del Frontend
Ejecute el siguiente comando en el directorio `app`.
```shell
pnpm install
pnpm build
```
### Compilación del Backend
Primero compile la interfaz y luego ejecute el siguiente comando en el directorio raíz del proyecto.
```shell
go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/settings.buildTime=$(date +%s)'" -o nginx-ui -v main.go
```
## Script para Linux
### Uso básico
**Instalar and Actualizar**
```shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) install
```
El puerto de escucha predeterminado es `9000` y el puerto de Desafío HTTP predeterminado es `9180`.
Si hay un conflicto de puertos, modifique manualmente `/usr/local/etc/nginx-ui/app.ini`,
luego use `systemctl restart nginx-ui` para recargar el servicio de UI de Nginx.
**Eliminar UI Nginx UI, excepto los archivos de configuración y la base de datos**
```shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) remove
```
### Uso avanzado
````shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) help
````
## Ejemplo de configuración de proxy reverso de Nginx
```nginx
server {
listen 80;
listen [::]:80;
server_name <your_server_name>;
rewrite ^(.*)$ https://$host$1 permanent;
}
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name <your_server_name>;
ssl_certificate /path/to/ssl_cert;
ssl_certificate_key /path/to/ssl_cert_key;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_pass http://127.0.0.1:9000/;
}
}
```
## Contribuir
Las contribuciones son lo que hace que la comunidad de código abierto sea un lugar increíble para aprender, inspirar y crear. Cualquier contribución que hagas es **muy apreciada**.
Si tiene una sugerencia que mejoraría este proyecto, bifurque el repositorio y cree un pull request. También puede simplemente abrir un issue con la etiqueta "enhancement". ¡No olvides darle una estrella al proyecto! ¡Gracias de nuevo!
1. Bifurcar el proyecto
2. Crea un branch de mejora (`git checkout -b feature/AmazingFeature`)
3. Commit de tus cambios (`git commit -m 'Add some AmazingFeature'`)
4. Push al branch (`git push origin feature/AmazingFeature`)
5. Abrir un Pull Request
## Licencia
Este proyecto se proporciona bajo una licencia GNU Affero General Public License v3.0 que se puede encontrar en el archivo [LICENCIA](LICENSE). Al usar, distribuir o contribuir a este proyecto, acepta los términos y condiciones de esta licencia.

@ -1,388 +0,0 @@
<div align="center">
<img src="resources/logo.png" alt="Nginx UI Logo">
</div>
# Nginx UI
Yet another Nginx Web UI, được phát triển bởi [0xJacky](https://jackyu.cn/) và [Hintay](https://blog.kugeek.com/).
[![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml)
[![GitHub license](https://img.shields.io/github/license/0xJacky/nginx-ui?label=License&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![Release Version](https://img.shields.io/github/release/0xJacky/nginx-ui?include_prereleases&label=Release&logo=github)](https://github.com/0xJacky/nginx-ui/releases/latest "Click to view the repo on Github")
[![GitHub Star](https://img.shields.io/github/stars/0xJacky/nginx-ui?label=Stars&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![GitHub Fork](https://img.shields.io/github/forks/0xJacky/nginx-ui?label=Forks&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![Repo Size](https://img.shields.io/github/repo-size/0xJacky/nginx-ui?label=Size&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![GitHub Fork](https://img.shields.io/github/issues-closed-raw/0xJacky/nginx-ui?label=Closed%20Issue&logo=github)](https://github.com/0xJacky/nginx-ui/issue "Click to view the repo on Github")
[![Docker Stars](https://img.shields.io/docker/stars/uozi/nginx-ui?label=Stars&logo=docker)](https://hub.docker.com/r/uozi/nginx-ui "Click to view the image on Docker Hub")
[![Docker Pulls](https://img.shields.io/docker/pulls/uozi/nginx-ui?label=Pulls&logo=docker)](https://hub.docker.com/r/uozi/nginx-ui "Click to view the image on Docker Hub")
[![Image Size](https://img.shields.io/docker/image-size/uozi/nginx-ui/latest?label=Image%20Size&logo=docker)](https://hub.docker.com/r/uozi/nginx-ui "Click to view the image on Docker Hub")
## Tài liệu
Để xem tài liệu, hãy truy cập [nginxui.com](https://nginxui.com).
## Stargazers over time
[![Stargazers over time](https://starchart.cc/0xJacky/nginx-ui.svg)](https://starchart.cc/0xJacky/nginx-ui)
English | [Español](README-es.md) | [简体中文](README-zh_CN.md) | [繁體中文](README-zh_TW.md) | [Tiếng Việt](README-vi_VN.md)
<details>
<summary>Mục lục</summary>
<ol>
<li>
<a href="#about-the-project">Thông tin dự án</a>
<ul>
<li><a href="#demo">Demo</a></li>
<li><a href="#features">Tính năng</a></li>
<li><a href="#internationalization">Ngôn ngữ hiển thị</a></li>
<li><a href="#built-with">Được xây dựng với</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Bắt đầu</a>
<ul>
<li><a href="#before-use">Lưu ý trước khi sử dụng</a></li>
<li><a href="#installation">Cài đặt</a></li>
<li>
<a href="#usage">Cách dùng</a>
<ul>
<li><a href="#from-executable">Sử dụng với Executable</a></li>
<li><a href="#with-systemd">Sử dụng với Systemd</a></li>
<li><a href="#with-docker">Sử dụng với Docker</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#manual-build">Build từ mã nguồn</a>
<ul>
<li><a href="#prerequisites">Điều kiện cần</a></li>
<li><a href="#build-app">Build Frontend</a></li>
<li><a href="#build-backend">Build Backend</a></li>
</ul>
</li>
<li>
<a href="#script-for-linux">Script cho Linux</a>
<ul>
<li><a href="#basic-usage">Sử dụng cơ bản</a></li>
<li><a href="#more-usage">Sử dụng nâng cao</a></li>
</ul>
</li>
<li><a href="#example-of-nginx-reverse-proxy-configuration">Ví dụ về cấu hình Nginx Reverse Proxy</a></li>
<li><a href="#contributing">Đóng góp</a></li>
<li><a href="#license">Giấy phép</a></li>
</ol>
</details>
## Về dự án
![Dashboard](resources/screenshots/dashboard_en.png)
### Demo
URL:[https://demo.nginxui.com](https://demo.nginxui.com)
- Username:admin
- Password:admin
### Tính năng
- Thống kê trực tuyến cho các chỉ số máy chủ như mức sử dụng CPU, mức sử dụng bộ nhớ, mức tải trung bình và mức sử dụng ổ đĩa.
- Chat với trợ lý ChatGPT
- Triển khai bằng một cú nhấp chuột và tự động gia hạn chứng chỉ Let's Encrypt.
- Chỉnh sửa cấu hình Nginx từ UI với **NgxConfigEditor** tự thiết kế của chúng tôi, một trình chỉnh sửa khối thân thiện với người dùng cho cấu hình nginx hoặc **Ace Code Editor** hỗ trợ làm nổi bật cú pháp cấu hình nginx.
- Xem Nginx logs
- Được viết bằng Go và Vue, và được phân phối với một tệp nhị phân thực thi duy nhất.
- Tự động kiểm tra file cấu hình và tải lại nginx sau khi lưu cấu hình.
- Web Terminal
- Dark Mode
- Responsive Web Design
### Ngôn ngữ hiển thị
- Tiếng Việt
- Tiếng Anh
- Tiếng Nga
- Tiếng Pháp
- Tiếng Tây Ban Nha
- Tiếng Trung giản thể
- Tiếng Trung phồn thể
Chúng tôi hoan nghênh bản dịch sang bất kỳ ngôn ngữ nào.
### Được xây dựng với
- [The Go Programming Language](https://go.dev)
- [Gin Web Framework](https://gin-gonic.com)
- [GORM](http://gorm.io)
- [Vue 3](https://v3.vuejs.org)
- [Vite](https://vitejs.dev)
- [TypeScript](https://www.typescriptlang.org/)
- [Ant Design Vue](https://antdv.com)
- [vue3-gettext](https://github.com/jshmrtn/vue3-gettext)
- [vue3-ace-editor](https://github.com/CarterLi/vue3-ace-editor)
- [Gonginx](https://github.com/tufanbarisyildirim/gonginx)
## Bắt đầu
### Lưu ý trước khi sử dụng
Máy chủ của bạn sẽ cần phải cài Nginx trước khi cài đặt Nginx UI
Nginx UI tuân theo tiêu chuẩn tệp cấu hình máy chủ web Debian. Các tệp cấu hình trang web đã tạo sẽ được đặt trong thư mục /etc/nginx/sites-available (được phát hiện tự động). Các tệp cấu hình cho một trang web được kích hoạt sẽ tạo một symlink đến thư mục /etc/nginx/sites-enabled. Bạn có thể cần điều chỉnh cách sắp xếp các tệp cấu hình của mình.
Đối với các hệ thống không phải Debian (và Ubuntu), bạn có thể cần thay đổi nội dung của tệp cấu hình nginx.conf thành kiểu Debian như hiển thị bên dưới.
```nginx
http {
# ...
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
```
Để biết thêm thông tin: [debian/conf/nginx.conf](https://salsa.debian.org/nginx-team/nginx/-/blob/master/debian/conf/nginx.conf#L59-L60)
### Cài đặt
Giao diện người dùng Nginx có sẵn trên các nền tảng sau:
- macOS 11 Big Sur and later (amd64 / arm64)
- Linux 2.6.23 and later (x86 / amd64 / arm64 / armv5 / armv6 / armv7)
- Bao gồm nhưng không giới hạn Debian 7/8, Ubuntu 12.04/14.04 trở lên, CentOS 6/7, Arch Linux
- FreeBSD
- OpenBSD
- Dragonfly BSD
- Openwrt
Bạn có thể truy cập [latest release](https://github.com/0xJacky/nginx-ui/releases/latest) để tải xuống bản phân phối mới nhất hoặc sử dụng [Tập lệnh cài đặt cho Linux](#script-for-linux).
### Sử dụng
Trong lần chạy đầu tiên, vui lòng truy cập `http://<your_server_ip>:<listen_port>` bằng trình duyệt của bạn để hoàn tất các cấu hình.
#### Chạy với Executable
**Chạy giao diện người dùng Nginx trong Terminal**
```shell
nginx-ui -config app.ini
```
Bấm `Ctrl + C` vào terminal để thoát Nginx UI.
**Chạy nền (Background)**
```shell
nohup ./nginx-ui -config app.ini &
```
Dừng Nginx UI bằng lệnh sau.
```shell
kill -9 $(ps -aux | grep nginx-ui | grep -v grep | awk '{print $2}')
```
#### Chạy với Systemd
Nếu bạn sử dụng [tập lệnh cài đặt cho Linux](#script-for-linux), Nginx UI sẽ được cài đặt dưới dạng `nginx-ui` service trong systemd. Hãy sử dụng `systemctl` để điều khiển nó.
**Start Nginx UI**
```shell
systemctl start nginx-ui
```
**Stop Nginx UI**
```shell
systemctl stop nginx-ui
```
**Restart Nginx UI**
```shell
systemctl restart nginx-ui
```
#### Sử dụng với Docker
Docker image của chúng tôi [uozi/nginx-ui:latest](https://hub.docker.com/r/uozi/nginx-ui) dựa trên nginx image mới nhất và có thể được sử dụng để thay thế Nginx trên máy chủ. Bằng cách xuất bản cổng 80 và 443 của container, bạn có thể dễ dàng thực hiện chuyển đổi.
##### Ghi chú
1. Khi khởi chạy container lần đầu tiên, hãy chắc chắn thư mục /etc/nginx trên máy host là rỗng.
2. Nếu bạn muốn lưu trữ các tệp tĩnh, bạn có thể mount các thư mục vào container.
<details>
<summary><b>Triển khai với Docker</b></summary>
1. [Cài đặt Docker.](https://docs.docker.com/install/)
2. Sau đó triển khai nginx-ui như thế sau:
```bash
docker run -dit \
--name=nginx-ui \
--restart=always \
-e TZ=Asia/Shanghai \
-v /mnt/user/appdata/nginx:/etc/nginx \
-v /mnt/user/appdata/nginx-ui:/etc/nginx-ui \
-p 8080:80 -p 8443:443 \
uozi/nginx-ui:latest
```
3. Khi container đã hoạt động, truy cập vào trang quản trị nginx-ui theo liên kết `http://<your_server_ip>:8080/install`.
</details>
<details>
<summary><b>Triển khai với Docker-Compose</b></summary>
1. [Cài đặt Docker-Compose.](https://docs.docker.com/compose/install/)
2. Tạo tệp docker-compose.yml:
```yml
version: '3.3'
services:
nginx-ui:
stdin_open: true
tty: true
container_name: nginx-ui
restart: always
environment:
- TZ=Asia/Shanghai
volumes:
- '/mnt/user/appdata/nginx:/etc/nginx'
- '/mnt/user/appdata/nginx-ui:/etc/nginx-ui'
- '/var/www:/var/www'
ports:
- 8080:80
- 8443:443
image: 'uozi/nginx-ui:latest'
```
3. Sau đó tạo container bằng lệnh:
```bash
docker-compose up -d
```
Nếu bạn sử dụng docker-compose-plugin, lệnh sẽ như sau
```bash
docker compose up -d
```
4. Khi container đã hoạt động, truy cập vào trang quản trị nginx-ui theo liên kết `http://<your_server_ip>:8080/install`.
</details>
## Xây dựng thủ công
Trên các nền tảng không có phiên bản xây dựng chính thức, chúng có thể được xây dựng thủ công.
### Điều kiện cần
- Make
- Golang 1.23+
- node.js 21+
```shell
npx browserslist@latest --update-db
```
### Build Frontend
Vui lòng thực hiện lệnh sau trong thư mục `app`.
```shell
pnpm install
pnpm build
```
### Build Backend
Vui lòng build Frontend trước, sau đó thực hiện lệnh sau trong thư mục gốc của dự án.
```shell
go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/settings.buildTime=$(date +%s)'" -o nginx-ui -v main.go
```
## Tập lệnh cho Linux
### Cách sử dụng cơ bản
**Cài đặt và nâng cấp**
```shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) install
```
Port mặc định để truy cập UI là `9000`, port HTTP Challenge mặc định để xác thực SSL là `9180`.
Nếu có xung đột port, vui lòng sửa đổi trong file `/usr/local/etc/nginx-ui/app.ini`,
hãy nhớ restart nginx-ui bằng lệnh `systemctl restart nginx-ui` mỗi khi bạn sửa đổi file app.ini.
**Gỡ bỏ Nginx UI nhưng giữ lại các tệp cấu hình và cơ sở dữ liệu**
```shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) remove
```
**Gỡ bỏ Nginx UI đồng thời xoá các tệp cấu hình, cơ sở dữ liệu**
```shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) remove --purge
```
### Trợ giúp
````shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) help
````
## Ví dụ về cấu hình Nginx Reverse Proxy
```nginx
server {
listen 80;
listen [::]:80;
server_name <your_server_name>;
rewrite ^(.*)$ https://$host$1 permanent;
}
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name <your_server_name>;
ssl_certificate /path/to/ssl_cert;
ssl_certificate_key /path/to/ssl_cert_key;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_pass http://127.0.0.1:9000/;
}
}
```
## Đóng góp
Đóng góp là điều khiến cộng đồng nguồn mở trở thành một nơi tuyệt vời để học hỏi, truyền cảm hứng và sáng tạo. Bất kỳ đóng góp nào bạn thực hiện đều được **đánh giá cao**.
Nếu bạn có đề xuất giúp dự án tốt hơn, vui lòng phân nhánh repo và tạo pull request. Bạn cũng có thể mở một issue mới với thẻ "enhancement" để đề xuất tính năng. Đừng quên cho dự án một Star! Cảm ơn một lần nữa!
1. Fork dự án
2. Tạo Branch (`git checkout -b feature/AmazingFeature`)
3. Commit thay đổi (`git commit -m 'Add some AmazingFeature'`)
4. Đẩy code lên Branch (`git push origin feature/AmazingFeature`)
5. Mở một Pull Request
## Giấy phép
Dự án này được cung cấp theo giấy phép GNU Affero General Public License v3.0 có thể tìm thấy trong tệp [LICENSE](LICENSE). Bằng cách sử dụng, phân phối hoặc đóng góp cho dự án này, bạn đồng ý với các điều khoản và điều kiện của giấy phép này.

@ -10,7 +10,7 @@ Nginx 网络管理界面,由 [0xJacky](https://jackyu.cn/) 与 [Hintay](https
[![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml) [![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml)
[English](README.md) | [Español](README-es.md) | 简体中文 | [繁體中文](README-zh_TW.md) [English](README.md) | 简体中文 | [繁體中文](README-zh_TW.md)
<details> <details>
<summary>目录</summary> <summary>目录</summary>
@ -125,7 +125,7 @@ http {
Nginx UI 可在以下平台中使用: Nginx UI 可在以下平台中使用:
- macOS 11 Big Sur 及之后版本(amd64 / arm64) - Mac OS X 10.10 Yosemite 及之后版本(amd64 / arm64)
- Linux 2.6.23 及之后版本(x86 / amd64 / arm64 / armv5 / armv6 / armv7) - Linux 2.6.23 及之后版本(x86 / amd64 / arm64 / armv5 / armv6 / armv7)
- 包括但不限于 Debian 7 / 8、Ubuntu 12.04 / 14.04 及后续版本、CentOS 6 / 7、Arch Linux - 包括但不限于 Debian 7 / 8、Ubuntu 12.04 / 14.04 及后续版本、CentOS 6 / 7、Arch Linux
- FreeBSD - FreeBSD
@ -137,7 +137,7 @@ Nginx UI 可在以下平台中使用:
### 使用方法 ### 使用方法
第一次运行 Nginx UI 时,请在浏览器中访问 `http://<your_server_ip>:<listen_port>` 完成后续配置。 第一次运行 Nginx UI 时,请在浏览器中访问 `http://<your_server_ip>:<listen_port>/install` 完成后续配置。
#### 通过执行文件运行 #### 通过执行文件运行
**在终端中运行 Nginx UI** **在终端中运行 Nginx UI**
@ -207,9 +207,9 @@ docker run -dit \
- Make - Make
- Golang 1.23+ - Golang 1.19+
- node.js 21+ - node.js 18+
```shell ```shell
npx browserslist@latest --update-db npx browserslist@latest --update-db
@ -217,11 +217,12 @@ docker run -dit \
### 构建前端 ### 构建前端
请在 `app` 目录中执行以下命令。 请在 `frontend` 目录中执行以下命令。
```shell ```shell
pnpm install yarn install
pnpm build make translations
yarn build
``` ```
### 构建后端 ### 构建后端
@ -229,7 +230,7 @@ pnpm build
请先完成前端编译,再回到项目的根目录执行以下命令。 请先完成前端编译,再回到项目的根目录执行以下命令。
```shell ```shell
go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/settings.buildTime=$(date +%s)'" -o nginx-ui -v main.go go build -o nginx-ui -v main.go
``` ```
## Linux 安装脚本 ## Linux 安装脚本
@ -239,20 +240,20 @@ go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/sett
**安装或升级** **安装或升级**
```shell ```shell
bash <(curl -L -s https://mirror.ghproxy.com/https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) install -r https://mirror.ghproxy.com/ bash <(curl -L -s https://ghproxy.com/https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) install -r https://ghproxy.com/
``` ```
一键安装脚本默认设置的监听端口为 `9000`,HTTP Challenge 端口默认为 `9180`,如果出现端口冲突请进入 `/usr/local/etc/nginx-ui/app.ini` 修改,并使用 `systemctl restart nginx-ui` 重启 Nginx UI 服务。 一键安装脚本默认设置的监听端口为 `9000`,HTTP Challenge 端口默认为 `9180`,如果出现端口冲突请进入 `/usr/local/etc/nginx-ui/app.ini` 修改,并使用 `systemctl restart nginx-ui` 重启 Nginx UI 服务。
**卸载 Nginx UI 但保留配置和数据库文件** **卸载 Nginx UI 但保留配置和数据库文件**
```shell ```shell
bash <(curl -L -s https://mirror.ghproxy.com/https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) remove bash <(curl -L -s https://ghproxy.com/https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) remove
``` ```
### 更多用法 ### 更多用法
````shell ````shell
bash <(curl -L -s https://mirror.ghproxy.com/https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) help bash <(curl -L -s https://ghproxy.com/https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) help
```` ````
## Nginx 反向代理配置示例 ## Nginx 反向代理配置示例
@ -272,9 +273,8 @@ map $http_upgrade $connection_upgrade {
} }
server { server {
listen 443 ssl; listen 443 ssl http2;
listen [::]:443 ssl; listen [::]:443 ssl http2;
http2 on;
server_name <your_server_name>; server_name <your_server_name>;

@ -6,11 +6,11 @@
Yet another Nginx Web UI Yet another Nginx Web UI
Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https://blog.kugeek.com/) 開發。 Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https://blog.kugeek.com/) 開發。
[![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml) [![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml)
[English](README.md) | [Español](README-es.md) | [简体中文](README-zh_CN.md) | 繁體中文 [English](README.md) | [简体中文](README-zh_CN.md) | 繁體中文
<details> <details>
<summary>目錄</summary> <summary>目錄</summary>
@ -21,7 +21,7 @@ Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https:
<li><a href="#線上預覽">線上預覽</a></li> <li><a href="#線上預覽">線上預覽</a></li>
<li><a href="#特色">特色</a></li> <li><a href="#特色">特色</a></li>
<li><a href="#國際化">國際化</a></li> <li><a href="#國際化">國際化</a></li>
<li><a href="#建置基於">建置基於</a></li> <li><a href="#構建基於">構建基於</a></li>
</ul> </ul>
</li> </li>
<li> <li>
@ -40,21 +40,21 @@ Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https:
</ul> </ul>
</li> </li>
<li> <li>
<a href="#手動建置">手動建置</a> <a href="#手動構建">手動構建</a>
<ul> <ul>
<li><a href="#相依性">相依性</a></li> <li><a href="#依賴">依賴</a></li>
<li><a href="#建置前端">建置前端</a></li> <li><a href="#構建前端">構建前端</a></li>
<li><a href="#建置後端">建置後端</a></li> <li><a href="#構建後端">構建後端</a></li>
</ul> </ul>
</li> </li>
<li> <li>
<a href="#linux-安裝指令">Linux 安裝指令</a> <a href="#linux-安裝指令碼">Linux 安裝指令碼</a>
<ul> <ul>
<li><a href="#基本用法">基本用法</a></li> <li><a href="#基本用法">基本用法</a></li>
<li><a href="#更多用法">更多用法</a></li> <li><a href="#更多用法">更多用法</a></li>
</ul> </ul>
</li> </li>
<li><a href="#nginx-反向代理設定範例">Nginx 反向代理設定範例</a></li> <li><a href="#nginx-反向代理配置示例">Nginx 反向代理配置示例</a></li>
<li><a href="#貢獻">貢獻</a></li> <li><a href="#貢獻">貢獻</a></li>
<li><a href="#開源軟體授權條款">開源軟體授權條款</a></li> <li><a href="#開源軟體授權條款">開源軟體授權條款</a></li>
</ol> </ol>
@ -67,7 +67,7 @@ Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https:
### 線上預覽 ### 線上預覽
網址:[https://demo.nginxui.com](https://demo.nginxui.com) 位址:[https://demo.nginxui.com](https://demo.nginxui.com)
- 使用者:admin - 使用者:admin
- 密碼:admin - 密碼:admin
@ -77,11 +77,11 @@ Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https:
- 線上檢視伺服器 CPU、記憶體、系統負載、磁碟使用率等指標 - 線上檢視伺服器 CPU、記憶體、系統負載、磁碟使用率等指標
- 線上 ChatGPT 助理 - 線上 ChatGPT 助理
- 一鍵申請和自動續簽 Let's encrypt 憑證 - 一鍵申請和自動續簽 Let's encrypt 憑證
- 線上編輯 Nginx 設定檔,編輯器支援 Nginx 設定語法醒目提示 - 線上編輯 Nginx 配置檔案,編輯器支援 Nginx 配置語法突顯
- 線上檢視 Nginx 日誌 - 線上查看 Nginx 日誌
- 使用 Go 和 Vue 開發,發行版本為單個可執行檔案 - 使用 Go 和 Vue 開發,發行版本為單個可執行檔案
- 儲存設定後自動測試設定檔並重新載入 Nginx - 保存配置後自動測試配置檔案並重載 Nginx
- 基於網頁瀏覽器的高階命令列終端 - 基於網頁瀏覽器的高級命令行終端
- 支援暗黑模式 - 支援暗黑模式
- 自適應網頁設計 - 自適應網頁設計
@ -93,8 +93,7 @@ Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https:
我們歡迎您將專案翻譯成任何語言。 我們歡迎您將專案翻譯成任何語言。
### 建置基於 ### 構建基於
- [The Go Programming Language](https://go.dev) - [The Go Programming Language](https://go.dev)
- [Gin Web Framework](https://gin-gonic.com) - [Gin Web Framework](https://gin-gonic.com)
- [GORM](http://gorm.io) - [GORM](http://gorm.io)
@ -110,9 +109,9 @@ Nginx 網路管理介面,由 [0xJacky](https://jackyu.cn/) 與 [Hintay](https:
### 使用前注意 ### 使用前注意
Nginx UI 遵循 Debian 的網頁伺服器設定檔標準。建立的網站設定檔將會放置於 Nginx 設定資料夾(自動檢測)下的 `sites-available` 中,啟用後的網站將會建立一份設定檔軟連結檔到 `sites-enabled` 資料夾。您可能需要提前調整設定檔的組織方式。 Nginx UI 遵循 Debian 的網頁伺服器配置檔案標準。建立的網站配置檔案將會放置於 Nginx 配置資料夾(自動檢測)下的 `sites-available` 中,啟用後的網站將會建立一份配置檔案軟連結檔到 `sites-enabled` 資料夾。您可能需要提前調整配置檔案的組織方式。
對於非 Debian (及 Ubuntu) 作業系統,您可能需要將 `nginx.conf` 設定檔中的內容修改為如下所示的 Debian 風格。 對於非 Debian (及 Ubuntu) 作業系統,您可能需要將 `nginx.conf` 配置檔案中的內容修改為如下所示的 Debian 風格。
```nginx ```nginx
http { http {
@ -128,7 +127,7 @@ http {
Nginx UI 可在以下作業系統中使用: Nginx UI 可在以下作業系統中使用:
- macOS 11 Big Sur 及之後版本(amd64 / arm64) - Mac OS X 10.10 Yosemite 及之後版本(amd64 / arm64)
- Linux 2.6.23 及之後版本(x86 / amd64 / arm64 / armv5 / armv6 / armv7) - Linux 2.6.23 及之後版本(x86 / amd64 / arm64 / armv5 / armv6 / armv7)
- 包括但不限於 Debian 7 / 8、Ubuntu 12.04 / 14.04 及後續版本、CentOS 6 / 7、Arch Linux - 包括但不限於 Debian 7 / 8、Ubuntu 12.04 / 14.04 及後續版本、CentOS 6 / 7、Arch Linux
- FreeBSD - FreeBSD
@ -136,14 +135,13 @@ Nginx UI 可在以下作業系統中使用:
- Dragonfly BSD - Dragonfly BSD
- Openwrt - Openwrt
您可以在 [最新釋出 (latest release)](https://github.com/0xJacky/nginx-ui/releases/latest) 中下載最新版本,或使用 [Linux 安裝指令](#linux-安裝指令)。 您可以在 [最新释出 (latest release)](https://github.com/0xJacky/nginx-ui/releases/latest) 中下載最新版本,或使用 [Linux 安裝指令碼](#linux-安裝指令碼)。
### 使用方法 ### 使用方法
第一次執行 Nginx UI 時,請在網頁瀏覽器中訪問 `http://<your_server_ip>:<listen_port>` 完成後續設定。 第一次執行 Nginx UI 時,請在網頁瀏覽器中訪問 `http://<your_server_ip>:<listen_port>/install` 完成後續配置。
#### 透過執行檔案執行 #### 透過執行檔案執行
**在終端中執行 Nginx UI** **在終端中執行 Nginx UI**
```shell ```shell
@ -156,29 +154,24 @@ nginx-ui -config app.ini
```shell ```shell
nohup ./nginx-ui -config app.ini & nohup ./nginx-ui -config app.ini &
``` ```
使用以下命令停止 Nginx UI。 使用以下命令停止 Nginx UI。
```shell ```shell
kill -9 $(ps -aux | grep nginx-ui | grep -v grep | awk '{print $2}') kill -9 $(ps -aux | grep nginx-ui | grep -v grep | awk '{print $2}')
``` ```
#### 使用 Systemd #### 使用 Systemd
如果你使用的是 [Linux 安裝指令碼](#linux-安裝指令碼),Nginx UI 將作為 `nginx-ui` 守護行程安裝在 systemd 中。請使用 `systemctl` 指令控制。
如果你使用的是 [Linux 安裝指令](#linux-安裝指令),Nginx UI 將作為 `nginx-ui` 守護行程安裝在 systemd 中。請使用 `systemctl` 指令控制。
**啟動 Nginx UI** **啟動 Nginx UI**
```shell ```shell
systemctl start nginx-ui systemctl start nginx-ui
``` ```
**停止 Nginx UI** **停止 Nginx UI**
```shell ```shell
systemctl stop nginx-ui systemctl stop nginx-ui
``` ```
**重啟 Nginx UI** **重啟 Nginx UI**
```shell ```shell
@ -187,11 +180,11 @@ systemctl restart nginx-ui
#### 使用 Docker #### 使用 Docker
您可以在 docker 中使用我們提供的 `uozi/nginx-ui:latest` [映象](https://hub.docker.com/r/uozi/nginx-ui),此映象基於 `nginx:latest` 建置。您可以直接將其監聽到 80 和 443 埠以取代宿主機上的 Nginx。 您可以在 docker 中使用我們提供的 `uozi/nginx-ui:latest` [鏡像](https://hub.docker.com/r/uozi/nginx-ui),此鏡像基於 `nginx:latest` 構建。您可以直接將其監聽到 80 和 443 埠以取代宿主機上的 Nginx。
注意:對映到 `/etc/nginx` 的資料夾應是一個空資料夾。 注意:映射到 `/etc/nginx` 的資料夾應是一個空資料夾。
**Docker 範例** **Docker 示例**
```bash ```bash
docker run -dit \ docker run -dit \
@ -204,40 +197,41 @@ docker run -dit \
uozi/nginx-ui:latest uozi/nginx-ui:latest
``` ```
## 手動建置 ## 手動構建
對於沒有官方建置版本的作業系統,可以嘗試手動建置。 對於沒有官方構建版本的作業系統,可以嘗試手動構建。
### 相依性 ### 依賴
- Make - Make
- Golang 1.23+ - Golang 1.18+
- node.js 21+ - node.js 14+
```shell ```shell
npx browserslist@latest --update-db npx browserslist@latest --update-db
``` ```
### 建置前端 ### 構建前端
請在 `app` 資料夾中執行以下命令。 請在 `frontend` 資料夾中執行以下命令。
```shell ```shell
pnpm install yarn install
pnpm build make translations
yarn build
``` ```
### 建置後端 ### 構建後端
請先完成前端編譯,再回到專案的根目錄執行以下命令。 請先完成前端編譯,再回到專案的根目錄執行以下命令。
```shell ```shell
go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/settings.buildTime=$(date +%s)'" -o nginx-ui -v main.go go build -o nginx-ui -v main.go
``` ```
## Linux 安裝指令 ## Linux 安裝指令碼
### 基本用法 ### 基本用法
@ -246,10 +240,9 @@ go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/sett
```shell ```shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) install bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) install
``` ```
一鍵安裝指令碼預設的監聽埠為 `9000`,HTTP Challenge 埠預設為 `9180`,如果出現埠衝突請修改 `/usr/local/etc/nginx-ui/app.ini`,並使用 `systemctl restart nginx-ui` 重啟 Nginx UI 守護行程。
一鍵安裝指令預設的監聽連接埠為 `9000`,HTTP Challenge 埠預設為 `9180`,如果出現連接埠衝突請修改 `/usr/local/etc/nginx-ui/app.ini`,並使用 `systemctl restart nginx-ui` 重啟 Nginx UI 守護行程。 **解除安裝 Nginx UI 但保留配置和資料庫檔案**
**解除安裝 Nginx UI 但保留設定和資料庫檔案**
```shell ```shell
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) remove bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) remove
@ -261,7 +254,7 @@ bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/inst
bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) help bash <(curl -L -s https://raw.githubusercontent.com/0xJacky/nginx-ui/master/install.sh) help
```` ````
## Nginx 反向代理設定範例 ## Nginx 反向代理配置示例
```nginx ```nginx
server { server {
@ -278,9 +271,8 @@ map $http_upgrade $connection_upgrade {
} }
server { server {
listen 443 ssl; listen 443 ssl http2;
listen [::]:443 ssl; listen [::]:443 ssl http2;
http2 on;
server_name <your_server_name>; server_name <your_server_name>;
@ -314,4 +306,4 @@ server {
## 開源軟體授權條款 ## 開源軟體授權條款
此專案基於 GNU Affero Public License v3.0 (AGPLv3) 授權條款,請參閱 [LICENSE](LICENSE) 檔案。透過使用、散佈或對本專案做出貢獻,表明您已同意本授權條款的條款和條件。 此專案基於 GNU Affero Public License v3.0 (AGPLv3) 授權條款,請參閱 [LICENSE](LICENSE) 檔案。透過使用、分發或對本專案做出貢獻,表明您已同意本許可證的條款和條件。

@ -7,18 +7,6 @@
Yet another Nginx Web UI, developed by [0xJacky](https://jackyu.cn/) and [Hintay](https://blog.kugeek.com/). Yet another Nginx Web UI, developed by [0xJacky](https://jackyu.cn/) and [Hintay](https://blog.kugeek.com/).
[![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml) [![Build and Publish](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml/badge.svg)](https://github.com/0xJacky/nginx-ui/actions/workflows/build.yml)
[![GitHub license](https://img.shields.io/github/license/0xJacky/nginx-ui?label=License&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![Release Version](https://img.shields.io/github/release/0xJacky/nginx-ui?include_prereleases&label=Release&logo=github)](https://github.com/0xJacky/nginx-ui/releases/latest "Click to view the repo on Github")
[![GitHub Star](https://img.shields.io/github/stars/0xJacky/nginx-ui?label=Stars&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![GitHub Fork](https://img.shields.io/github/forks/0xJacky/nginx-ui?label=Forks&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![Repo Size](https://img.shields.io/github/repo-size/0xJacky/nginx-ui?label=Size&logo=github)](https://github.com/0xJacky/nginx-ui "Click to view the repo on Github")
[![GitHub Fork](https://img.shields.io/github/issues-closed-raw/0xJacky/nginx-ui?label=Closed%20Issue&logo=github)](https://github.com/0xJacky/nginx-ui/issue "Click to view the repo on Github")
[![Docker Stars](https://img.shields.io/docker/stars/uozi/nginx-ui?label=Stars&logo=docker)](https://hub.docker.com/r/uozi/nginx-ui "Click to view the image on Docker Hub")
[![Docker Pulls](https://img.shields.io/docker/pulls/uozi/nginx-ui?label=Pulls&logo=docker)](https://hub.docker.com/r/uozi/nginx-ui "Click to view the image on Docker Hub")
[![Image Size](https://img.shields.io/docker/image-size/uozi/nginx-ui/latest?label=Image%20Size&logo=docker)](https://hub.docker.com/r/uozi/nginx-ui "Click to view the image on Docker Hub")
[![Translated Status](https://weblate.nginxui.com/widget/nginx-ui/frontend/svg-badge.svg)](https://weblate.nginxui.com/engage/nginx-ui/)
## Documentation ## Documentation
To check out docs, visit [nginxui.com](https://nginxui.com). To check out docs, visit [nginxui.com](https://nginxui.com).
@ -27,7 +15,8 @@ To check out docs, visit [nginxui.com](https://nginxui.com).
[![Stargazers over time](https://starchart.cc/0xJacky/nginx-ui.svg)](https://starchart.cc/0xJacky/nginx-ui) [![Stargazers over time](https://starchart.cc/0xJacky/nginx-ui.svg)](https://starchart.cc/0xJacky/nginx-ui)
English | [Español](README-es.md) | [简体中文](README-zh_CN.md) | [繁體中文](README-zh_TW.md) | [Tiếng Việt](README-vi_VN.md)
English | [简体中文](README-zh_CN.md) | [繁體中文](README-zh_TW.md)
<details> <details>
<summary>Table of Contents</summary> <summary>Table of Contents</summary>
@ -60,7 +49,7 @@ English | [Español](README-es.md) | [简体中文](README-zh_CN.md) | [繁體
<a href="#manual-build">Manual Build</a> <a href="#manual-build">Manual Build</a>
<ul> <ul>
<li><a href="#prerequisites">Prerequisites</a></li> <li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#build-app">Build Frontend</a></li> <li><a href="#build-frontend">Build Frontend</a></li>
<li><a href="#build-backend">Build Backend</a></li> <li><a href="#build-backend">Build Backend</a></li>
</ul> </ul>
</li> </li>
@ -77,6 +66,7 @@ English | [Español](README-es.md) | [简体中文](README-zh_CN.md) | [繁體
</ol> </ol>
</details> </details>
## About The Project ## About The Project
![Dashboard](resources/screenshots/dashboard_en.png) ![Dashboard](resources/screenshots/dashboard_en.png)
@ -142,7 +132,7 @@ For more information: [debian/conf/nginx.conf](https://salsa.debian.org/nginx-te
Nginx UI is available on the following platforms: Nginx UI is available on the following platforms:
- macOS 11 Big Sur and later (amd64 / arm64) - Mac OS X 10.10 Yosemite and later (amd64 / arm64)
- Linux 2.6.23 and later (x86 / amd64 / arm64 / armv5 / armv6 / armv7) - Linux 2.6.23 and later (x86 / amd64 / arm64 / armv5 / armv6 / armv7)
- Including but not limited to Debian 7 / 8, Ubuntu 12.04 / 14.04 and later, CentOS 6 / 7, Arch Linux - Including but not limited to Debian 7 / 8, Ubuntu 12.04 / 14.04 and later, CentOS 6 / 7, Arch Linux
- FreeBSD - FreeBSD
@ -154,7 +144,7 @@ You can visit [latest release](https://github.com/0xJacky/nginx-ui/releases/late
### Usage ### Usage
In the first runtime of Nginx UI, please visit `http://<your_server_ip>:<listen_port>` In the first runtime of Nginx UI, please visit `http://<your_server_ip>:<listen_port>/install`
in your browser to complete the follow-up configurations. in your browser to complete the follow-up configurations.
#### From Executable #### From Executable
@ -170,12 +160,11 @@ Press `Control+C` in the terminal to exit Nginx UI.
```shell ```shell
nohup ./nginx-ui -config app.ini & nohup ./nginx-ui -config app.ini &
``` ```
Stop Nginx UI with the follow command. Stop Nginx UI with the follow commond.
```shell ```shell
kill -9 $(ps -aux | grep nginx-ui | grep -v grep | awk '{print $2}') kill -9 $(ps -aux | grep nginx-ui | grep -v grep | awk '{print $2}')
``` ```
#### With Systemd #### With Systemd
If you are using the [installation script for Linux](#script-for-linux), the Nginx UI will be installed as `nginx-ui` service in systemd. Please use the `systemctl` command to control it. If you are using the [installation script for Linux](#script-for-linux), the Nginx UI will be installed as `nginx-ui` service in systemd. Please use the `systemctl` command to control it.
@ -204,12 +193,7 @@ you can easily make the switch.
1. When using this container for the first time, ensure that the volume mapped to /etc/nginx is empty. 1. When using this container for the first time, ensure that the volume mapped to /etc/nginx is empty.
2. If you want to host static files, you can map directories to container. 2. If you want to host static files, you can map directories to container.
<details> **Docker Deploy Example**
<summary><b>Deploy with Docker</b></summary>
1. [Install Docker.](https://docs.docker.com/install/)
2. Then deploy nginx-ui like this:
```bash ```bash
docker run -dit \ docker run -dit \
@ -218,55 +202,11 @@ docker run -dit \
-e TZ=Asia/Shanghai \ -e TZ=Asia/Shanghai \
-v /mnt/user/appdata/nginx:/etc/nginx \ -v /mnt/user/appdata/nginx:/etc/nginx \
-v /mnt/user/appdata/nginx-ui:/etc/nginx-ui \ -v /mnt/user/appdata/nginx-ui:/etc/nginx-ui \
-v /var/www:/var/www \
-p 8080:80 -p 8443:443 \ -p 8080:80 -p 8443:443 \
uozi/nginx-ui:latest uozi/nginx-ui:latest
``` ```
3. When your docker container is running, Log in to nginx-ui panel with `http://<your_server_ip>:8080/install`.
</details>
<details>
<summary><b>Deploy with Docker-Compose</b></summary>
1. [Install Docker-Compose.](https://docs.docker.com/compose/install/)
2. Create a docker-compose.yml file like this:
```yml
version: '3.3'
services:
nginx-ui:
stdin_open: true
tty: true
container_name: nginx-ui
restart: always
environment:
- TZ=Asia/Shanghai
volumes:
- '/mnt/user/appdata/nginx:/etc/nginx'
- '/mnt/user/appdata/nginx-ui:/etc/nginx-ui'
- '/var/www:/var/www'
ports:
- 8080:80
- 8443:443
image: 'uozi/nginx-ui:latest'
```
3. Then creat your container by:
```bash
docker-compose up -d
```
```bash
# If using docker-compose-plugin
docker compose up -d
```
4. When your docker container is running, Log in to nginx-ui panel with `http://<your_server_ip>:8080/install`.
</details>
## Manual Build ## Manual Build
On platforms that do not have an official build version, they can be built manually. On platforms that do not have an official build version, they can be built manually.
@ -275,9 +215,9 @@ On platforms that do not have an official build version, they can be built manua
- Make - Make
- Golang 1.23+ - Golang 1.19+
- node.js 21+ - node.js 18+
```shell ```shell
npx browserslist@latest --update-db npx browserslist@latest --update-db
@ -285,19 +225,19 @@ On platforms that do not have an official build version, they can be built manua
### Build Frontend ### Build Frontend
Please execute the following command in `app` directory. Please execute the following command in `frontend` directory.
```shell ```shell
pnpm install yarn install
pnpm build yarn build
``` ```
### Build Backend ### Build Backend
Please build the app first, and then execute the following command in the project root directory. Please build the frontend first, and then execute the following command in the project root directory.
```shell ```shell
go build -tags=jsoniter -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/settings.buildTime=$(date +%s)'" -o nginx-ui -v main.go go build -o nginx-ui -v main.go
``` ```
## Script for Linux ## Script for Linux
@ -342,9 +282,8 @@ map $http_upgrade $connection_upgrade {
} }
server { server {
listen 443 ssl; listen 443 ssl http2;
listen [::]:443 ssl; listen [::]:443 ssl http2;
http2 on;
server_name <your_server_name>; server_name <your_server_name>;

@ -1,147 +0,0 @@
package analytic
import (
"fmt"
"github.com/0xJacky/Nginx-UI/internal/analytic"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/host"
"github.com/shirou/gopsutil/v3/load"
"github.com/shirou/gopsutil/v3/net"
"github.com/spf13/cast"
"net/http"
"runtime"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
func Analytic(c *gin.Context) {
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
logger.Error(err)
return
}
defer ws.Close()
var stat Stat
for {
stat.Memory, err = analytic.GetMemoryStat()
if err != nil {
logger.Error(err)
return
}
cpuTimesBefore, _ := cpu.Times(false)
time.Sleep(1000 * time.Millisecond)
cpuTimesAfter, _ := cpu.Times(false)
threadNum := runtime.GOMAXPROCS(0)
cpuUserUsage := (cpuTimesAfter[0].User - cpuTimesBefore[0].User) / (float64(1000*threadNum) / 1000)
cpuSystemUsage := (cpuTimesAfter[0].System - cpuTimesBefore[0].System) / (float64(1000*threadNum) / 1000)
stat.CPU = CPUStat{
User: cast.ToFloat64(fmt.Sprintf("%.2f", cpuUserUsage*100)),
System: cast.ToFloat64(fmt.Sprintf("%.2f", cpuSystemUsage*100)),
Idle: cast.ToFloat64(fmt.Sprintf("%.2f", (1-cpuUserUsage-cpuSystemUsage)*100)),
Total: cast.ToFloat64(fmt.Sprintf("%.2f", (cpuUserUsage+cpuSystemUsage)*100)),
}
stat.Uptime, _ = host.Uptime()
stat.LoadAvg, _ = load.Avg()
stat.Disk, err = analytic.GetDiskStat()
if err != nil {
logger.Error(err)
return
}
network, _ := net.IOCounters(false)
if len(network) > 0 {
stat.Network = network[0]
}
// write
err = ws.WriteJSON(stat)
if helper.IsUnexpectedWebsocketError(err) {
logger.Error(err)
break
}
time.Sleep(800 * time.Microsecond)
}
}
func GetAnalyticInit(c *gin.Context) {
cpuInfo, err := cpu.Info()
if err != nil {
logger.Error(err)
}
network, err := net.IOCounters(false)
if err != nil {
logger.Error(err)
}
memory, err := analytic.GetMemoryStat()
if err != nil {
logger.Error(err)
}
diskStat, err := analytic.GetDiskStat()
if err != nil {
logger.Error(err)
}
var _net net.IOCountersStat
if len(network) > 0 {
_net = network[0]
}
hostInfo, _ := host.Info()
switch hostInfo.Platform {
case "ubuntu":
hostInfo.Platform = "Ubuntu"
case "centos":
hostInfo.Platform = "CentOS"
}
loadAvg, err := load.Avg()
if err != nil {
logger.Error(err)
}
c.JSON(http.StatusOK, InitResp{
Host: hostInfo,
CPU: CPURecords{
Info: cpuInfo,
User: analytic.CpuUserRecord,
Total: analytic.CpuTotalRecord,
},
Network: NetworkRecords{
Init: _net,
BytesRecv: analytic.NetRecvRecord,
BytesSent: analytic.NetSentRecord,
},
DiskIO: DiskIORecords{
Writes: analytic.DiskWriteRecord,
Reads: analytic.DiskReadRecord,
},
Memory: memory,
Disk: diskStat,
LoadAvg: loadAvg,
})
}

@ -1,65 +0,0 @@
package analytic
import (
"github.com/0xJacky/Nginx-UI/internal/analytic"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
"time"
)
func GetNodeStat(c *gin.Context) {
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
logger.Error(err)
return
}
defer ws.Close()
for {
// write
err = ws.WriteJSON(analytic.GetNodeStat())
if helper.IsUnexpectedWebsocketError(err) {
logger.Error(err)
break
}
time.Sleep(10 * time.Second)
}
}
func GetNodesAnalytic(c *gin.Context) {
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
logger.Error(err)
return
}
defer ws.Close()
for {
// write
err = ws.WriteJSON(analytic.NodeMap)
if helper.IsUnexpectedWebsocketError(err) {
logger.Error(err)
break
}
time.Sleep(10 * time.Second)
}
}

@ -1,15 +0,0 @@
package analytic
import (
"github.com/gin-gonic/gin"
)
func InitWebSocketRouter(r *gin.RouterGroup) {
r.GET("analytic", Analytic)
r.GET("analytic/intro", GetNodeStat)
r.GET("analytic/nodes", GetNodesAnalytic)
}
func InitRouter(r *gin.RouterGroup) {
r.GET("analytic/init", GetAnalyticInit)
}

@ -1,52 +0,0 @@
package analytic
import (
"github.com/0xJacky/Nginx-UI/internal/analytic"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/host"
"github.com/shirou/gopsutil/v3/load"
"github.com/shirou/gopsutil/v3/net"
)
type CPUStat struct {
User float64 `json:"user"`
System float64 `json:"system"`
Idle float64 `json:"idle"`
Total float64 `json:"total"`
}
type Stat struct {
Uptime uint64 `json:"uptime"`
LoadAvg *load.AvgStat `json:"loadavg"`
CPU CPUStat `json:"cpu"`
Memory analytic.MemStat `json:"memory"`
Disk analytic.DiskStat `json:"disk"`
Network net.IOCountersStat `json:"network"`
}
type CPURecords struct {
Info []cpu.InfoStat `json:"info"`
User []analytic.Usage[float64] `json:"user"`
Total []analytic.Usage[float64] `json:"total"`
}
type NetworkRecords struct {
Init net.IOCountersStat `json:"init"`
BytesRecv []analytic.Usage[uint64] `json:"bytesRecv"`
BytesSent []analytic.Usage[uint64] `json:"bytesSent"`
}
type DiskIORecords struct {
Writes []analytic.Usage[uint64] `json:"writes"`
Reads []analytic.Usage[uint64] `json:"reads"`
}
type InitResp struct {
Host *host.InfoStat `json:"host"`
CPU CPURecords `json:"cpu"`
Network NetworkRecords `json:"network"`
DiskIO DiskIORecords `json:"disk_io"`
Memory analytic.MemStat `json:"memory"`
Disk analytic.DiskStat `json:"disk"`
LoadAvg *load.AvgStat `json:"loadavg"`
}

@ -1,127 +0,0 @@
package api
import (
"errors"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/model"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"net/http"
"reflect"
"regexp"
"strings"
)
func CurrentUser(c *gin.Context) *model.User {
return c.MustGet("user").(*model.User)
}
func ErrHandler(c *gin.Context, err error) {
logger.GetLogger().Errorln(err)
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
}
type ValidError struct {
Key string
Message string
}
func BindAndValid(c *gin.Context, target interface{}) bool {
err := c.ShouldBindJSON(target)
if err != nil {
logger.Error("bind err", err)
var verrs validator.ValidationErrors
ok := errors.As(err, &verrs)
if !ok {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "Requested with wrong parameters",
"code": http.StatusNotAcceptable,
})
return false
}
t := reflect.TypeOf(target).Elem()
errorsMap := make(map[string]interface{})
for _, value := range verrs {
var path []string
namespace := strings.Split(value.StructNamespace(), ".")
// logger.Debug(t.Name(), namespace)
if t.Name() != "" && len(namespace) > 1 {
namespace = namespace[1:]
}
getJsonPath(t, namespace, &path)
insertError(errorsMap, path, value.Tag())
}
c.JSON(http.StatusNotAcceptable, gin.H{
"errors": errorsMap,
"message": "Requested with wrong parameters",
"code": http.StatusNotAcceptable,
})
return false
}
return true
}
// findField recursively finds the field in a nested struct
func getJsonPath(t reflect.Type, fields []string, path *[]string) {
field := fields[0]
// used in case of array
var index string
if field[len(field)-1] == ']' {
re := regexp.MustCompile(`(\w+)\[(\d+)\]`)
matches := re.FindStringSubmatch(field)
if len(matches) > 2 {
field = matches[1]
index = matches[2]
}
}
f, ok := t.FieldByName(field)
if !ok {
return
}
*path = append(*path, f.Tag.Get("json"))
if index != "" {
*path = append(*path, index)
}
if len(fields) > 1 {
subFields := fields[1:]
getJsonPath(f.Type, subFields, path)
}
}
// insertError inserts an error into the errors map
func insertError(errorsMap map[string]interface{}, path []string, errorTag string) {
if len(path) == 0 {
return
}
jsonTag := path[0]
if len(path) == 1 {
// Last element in the path, set the error
errorsMap[jsonTag] = errorTag
return
}
// Create a new map if necessary
if _, ok := errorsMap[jsonTag]; !ok {
errorsMap[jsonTag] = make(map[string]interface{})
}
// Recursively insert into the nested map
subMap, _ := errorsMap[jsonTag].(map[string]interface{})
insertError(subMap, path[1:], errorTag)
}

@ -1,96 +0,0 @@
package certificate
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"net/http"
)
func GetAcmeUser(c *gin.Context) {
u := query.AcmeUser
id := cast.ToInt(c.Param("id"))
user, err := u.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, user)
}
func CreateAcmeUser(c *gin.Context) {
cosy.Core[model.AcmeUser](c).SetValidRules(gin.H{
"name": "required",
"email": "required,email",
"ca_dir": "omitempty",
}).BeforeExecuteHook(func(ctx *cosy.Ctx[model.AcmeUser]) {
if ctx.Model.CADir == "" {
ctx.Model.CADir = settings.ServerSettings.GetCADir()
}
err := ctx.Model.Register()
if err != nil {
ctx.AbortWithError(err)
return
}
}).Create()
}
func ModifyAcmeUser(c *gin.Context) {
cosy.Core[model.AcmeUser](c).SetValidRules(gin.H{
"name": "omitempty",
"email": "omitempty,email",
"ca_dir": "omitempty",
}).BeforeExecuteHook(func(ctx *cosy.Ctx[model.AcmeUser]) {
if ctx.Model.CADir == "" {
ctx.Model.CADir = settings.ServerSettings.GetCADir()
}
if ctx.OriginModel.Email != ctx.Model.Email ||
ctx.OriginModel.CADir != ctx.Model.CADir {
err := ctx.Model.Register()
if err != nil {
ctx.AbortWithError(err)
return
}
}
}).Modify()
}
func GetAcmeUserList(c *gin.Context) {
cosy.Core[model.AcmeUser](c).
SetFussy("name", "email").
PagingList()
}
func DestroyAcmeUser(c *gin.Context) {
cosy.Core[model.AcmeUser](c).Destroy()
}
func RecoverAcmeUser(c *gin.Context) {
cosy.Core[model.AcmeUser](c).Recover()
}
func RegisterAcmeUser(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
u := query.AcmeUser
user, err := u.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
err = user.Register()
if err != nil {
api.ErrHandler(c, err)
return
}
_, err = u.Where(u.ID.Eq(id)).Updates(user)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, user)
}

@ -1,243 +0,0 @@
package certificate
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cert"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/internal/notification"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/spf13/cast"
"net/http"
"os"
)
type APICertificate struct {
*model.Cert
SSLCertificate string `json:"ssl_certificate,omitempty"`
SSLCertificateKey string `json:"ssl_certificate_key,omitempty"`
CertificateInfo *cert.Info `json:"certificate_info,omitempty"`
}
func Transformer(certModel *model.Cert) (certificate *APICertificate) {
var sslCertificationBytes, sslCertificationKeyBytes []byte
var certificateInfo *cert.Info
if certModel.SSLCertificatePath != "" &&
helper.IsUnderDirectory(certModel.SSLCertificatePath, nginx.GetConfPath()) {
if _, err := os.Stat(certModel.SSLCertificatePath); err == nil {
sslCertificationBytes, _ = os.ReadFile(certModel.SSLCertificatePath)
if !cert.IsCertificate(string(sslCertificationBytes)) {
sslCertificationBytes = []byte{}
}
}
certificateInfo, _ = cert.GetCertInfo(certModel.SSLCertificatePath)
}
if certModel.SSLCertificateKeyPath != "" &&
helper.IsUnderDirectory(certModel.SSLCertificateKeyPath, nginx.GetConfPath()) {
if _, err := os.Stat(certModel.SSLCertificateKeyPath); err == nil {
sslCertificationKeyBytes, _ = os.ReadFile(certModel.SSLCertificateKeyPath)
if !cert.IsPrivateKey(string(sslCertificationKeyBytes)) {
sslCertificationKeyBytes = []byte{}
}
}
}
return &APICertificate{
Cert: certModel,
SSLCertificate: string(sslCertificationBytes),
SSLCertificateKey: string(sslCertificationKeyBytes),
CertificateInfo: certificateInfo,
}
}
func GetCertList(c *gin.Context) {
cosy.Core[model.Cert](c).SetFussy("name", "domain").SetTransformer(func(m *model.Cert) any {
info, _ := cert.GetCertInfo(m.SSLCertificatePath)
return APICertificate{
Cert: m,
CertificateInfo: info,
}
}).PagingList()
}
func GetCert(c *gin.Context) {
q := query.Cert
certModel, err := q.FirstByID(cast.ToInt(c.Param("id")))
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, Transformer(certModel))
}
type certJson struct {
Name string `json:"name" binding:"required"`
SSLCertificatePath string `json:"ssl_certificate_path" binding:"required,certificate_path"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required,privatekey_path"`
SSLCertificate string `json:"ssl_certificate" binding:"omitempty,certificate"`
SSLCertificateKey string `json:"ssl_certificate_key" binding:"omitempty,privatekey"`
KeyType certcrypto.KeyType `json:"key_type" binding:"omitempty,auto_cert_key_type"`
ChallengeMethod string `json:"challenge_method"`
DnsCredentialID int `json:"dns_credential_id"`
ACMEUserID int `json:"acme_user_id"`
SyncNodeIds []int `json:"sync_node_ids"`
}
func AddCert(c *gin.Context) {
var json certJson
if !api.BindAndValid(c, &json) {
return
}
certModel := &model.Cert{
Name: json.Name,
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
KeyType: json.KeyType,
ChallengeMethod: json.ChallengeMethod,
DnsCredentialID: json.DnsCredentialID,
ACMEUserID: json.ACMEUserID,
SyncNodeIds: json.SyncNodeIds,
}
err := certModel.Insert()
if err != nil {
api.ErrHandler(c, err)
return
}
content := &cert.Content{
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
SSLCertificate: json.SSLCertificate,
SSLCertificateKey: json.SSLCertificateKey,
}
err = content.WriteFile()
if err != nil {
api.ErrHandler(c, err)
return
}
err = cert.SyncToRemoteServer(certModel)
if err != nil {
notification.Error("Sync Certificate Error", err.Error())
return
}
c.JSON(http.StatusOK, Transformer(certModel))
}
func ModifyCert(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
var json certJson
if !api.BindAndValid(c, &json) {
return
}
q := query.Cert
certModel, err := q.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
err = certModel.Updates(&model.Cert{
Name: json.Name,
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
ChallengeMethod: json.ChallengeMethod,
KeyType: json.KeyType,
DnsCredentialID: json.DnsCredentialID,
ACMEUserID: json.ACMEUserID,
SyncNodeIds: json.SyncNodeIds,
})
if err != nil {
api.ErrHandler(c, err)
return
}
content := &cert.Content{
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
SSLCertificate: json.SSLCertificate,
SSLCertificateKey: json.SSLCertificateKey,
}
err = content.WriteFile()
if err != nil {
api.ErrHandler(c, err)
return
}
err = cert.SyncToRemoteServer(certModel)
if err != nil {
notification.Error("Sync Certificate Error", err.Error())
return
}
GetCert(c)
}
func RemoveCert(c *gin.Context) {
cosy.Core[model.Cert](c).Destroy()
}
func SyncCertificate(c *gin.Context) {
var json cert.SyncCertificatePayload
if !api.BindAndValid(c, &json) {
return
}
certModel := &model.Cert{
Name: json.Name,
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
KeyType: json.KeyType,
AutoCert: model.AutoCertSync,
}
db := model.UseDB()
err := db.Where(certModel).FirstOrCreate(certModel).Error
if err != nil {
api.ErrHandler(c, err)
return
}
content := &cert.Content{
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
SSLCertificate: json.SSLCertificate,
SSLCertificateKey: json.SSLCertificateKey,
}
err = content.WriteFile()
if err != nil {
api.ErrHandler(c, err)
return
}
nginx.Reload()
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,105 +0,0 @@
package certificate
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cert/dns"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"net/http"
)
func GetDnsCredential(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
d := query.DnsCredential
dnsCredential, err := d.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
type apiDnsCredential struct {
model.Model
Name string `json:"name"`
Provider string `json:"provider"`
dns.Config
}
c.JSON(http.StatusOK, apiDnsCredential{
Model: dnsCredential.Model,
Name: dnsCredential.Name,
Provider: dnsCredential.Provider,
Config: *dnsCredential.Config,
})
}
func GetDnsCredentialList(c *gin.Context) {
cosy.Core[model.DnsCredential](c).SetFussy("provider").PagingList()
}
type DnsCredentialManageJson struct {
Name string `json:"name" binding:"required"`
Provider string `json:"provider"`
dns.Config
}
func AddDnsCredential(c *gin.Context) {
var json DnsCredentialManageJson
if !api.BindAndValid(c, &json) {
return
}
json.Config.Name = json.Provider
dnsCredential := model.DnsCredential{
Name: json.Name,
Config: &json.Config,
Provider: json.Provider,
}
d := query.DnsCredential
err := d.Create(&dnsCredential)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, dnsCredential)
}
func EditDnsCredential(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
var json DnsCredentialManageJson
if !api.BindAndValid(c, &json) {
return
}
d := query.DnsCredential
dnsCredential, err := d.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
json.Config.Name = json.Provider
_, err = d.Where(d.ID.Eq(dnsCredential.ID)).Updates(&model.DnsCredential{
Name: json.Name,
Config: &json.Config,
Provider: json.Provider,
})
if err != nil {
api.ErrHandler(c, err)
return
}
GetDnsCredential(c)
}
func DeleteDnsCredential(c *gin.Context) {
cosy.Core[model.DnsCredential](c).Destroy()
}

@ -1,27 +0,0 @@
package certificate
import (
"github.com/0xJacky/Nginx-UI/internal/cert/dns"
"github.com/gin-gonic/gin"
"net/http"
)
func GetDNSProvidersList(c *gin.Context) {
c.JSON(http.StatusOK, dns.GetProvidersList())
}
func GetDNSProvider(c *gin.Context) {
code := c.Param("code")
provider, ok := dns.GetProvider(code)
if !ok {
c.JSON(http.StatusNotFound, gin.H{
"message": "provider not found",
})
return
}
c.JSON(http.StatusOK, provider)
}

@ -1,155 +0,0 @@
package certificate
import (
"github.com/0xJacky/Nginx-UI/internal/cert"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/model"
"github.com/gin-gonic/gin"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/gorilla/websocket"
"net/http"
)
const (
Success = "success"
Info = "info"
Error = "error"
)
type IssueCertResponse struct {
Status string `json:"status"`
Message string `json:"message"`
SSLCertificate string `json:"ssl_certificate,omitempty"`
SSLCertificateKey string `json:"ssl_certificate_key,omitempty"`
KeyType certcrypto.KeyType `json:"key_type"`
}
func handleIssueCertLogChan(conn *websocket.Conn, log *cert.Logger, logChan chan string) {
defer func() {
if err := recover(); err != nil {
logger.Error(err)
}
}()
for logString := range logChan {
log.Info(logString)
err := conn.WriteJSON(IssueCertResponse{
Status: Info,
Message: logString,
})
if err != nil {
logger.Error(err)
return
}
}
}
func IssueCert(c *gin.Context) {
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
logger.Error(err)
return
}
defer func(ws *websocket.Conn) {
_ = ws.Close()
}(ws)
// read
payload := &cert.ConfigPayload{}
err = ws.ReadJSON(payload)
if err != nil {
logger.Error(err)
return
}
certModel, err := model.FirstOrCreateCert(c.Param("name"), payload.GetKeyType())
if err != nil {
logger.Error(err)
return
}
certInfo, _ := cert.GetCertInfo(certModel.SSLCertificatePath)
if certInfo != nil {
payload.Resource = certModel.Resource
payload.NotBefore = certInfo.NotBefore
}
logChan := make(chan string, 1)
errChan := make(chan error, 1)
log := &cert.Logger{}
log.SetCertModel(&certModel)
payload.CertID = certModel.ID
go cert.IssueCert(payload, logChan, errChan)
go handleIssueCertLogChan(ws, log, logChan)
// block, until errChan closes
for err = range errChan {
log.Error(err)
// Save logs to db
log.Exit()
err = ws.WriteJSON(IssueCertResponse{
Status: Error,
Message: err.Error(),
})
if err != nil {
logger.Error(err)
return
}
return
}
err = certModel.Updates(&model.Cert{
Domains: payload.ServerName,
SSLCertificatePath: payload.GetCertificatePath(),
SSLCertificateKeyPath: payload.GetCertificateKeyPath(),
AutoCert: model.AutoCertEnabled,
KeyType: payload.KeyType,
ChallengeMethod: payload.ChallengeMethod,
DnsCredentialID: payload.DNSCredentialID,
Resource: payload.Resource,
MustStaple: payload.MustStaple,
LegoDisableCNAMESupport: payload.LegoDisableCNAMESupport,
})
if err != nil {
logger.Error(err)
_ = ws.WriteJSON(IssueCertResponse{
Status: Error,
Message: err.Error(),
})
return
}
// Save logs to db
log.Exit()
err = ws.WriteJSON(IssueCertResponse{
Status: Success,
Message: "Issued certificate successfully",
SSLCertificate: payload.GetCertificatePath(),
SSLCertificateKey: payload.GetCertificateKeyPath(),
KeyType: payload.GetKeyType(),
})
if err != nil {
logger.Error(err)
return
}
}

@ -1,36 +0,0 @@
package certificate
import "github.com/gin-gonic/gin"
func InitDNSCredentialRouter(r *gin.RouterGroup) {
r.GET("dns_credentials", GetDnsCredentialList)
r.GET("dns_credential/:id", GetDnsCredential)
r.POST("dns_credential", AddDnsCredential)
r.POST("dns_credential/:id", EditDnsCredential)
r.DELETE("dns_credential/:id", DeleteDnsCredential)
}
func InitCertificateRouter(r *gin.RouterGroup) {
r.GET("certs", GetCertList)
r.GET("cert/:id", GetCert)
r.POST("cert", AddCert)
r.POST("cert/:id", ModifyCert)
r.DELETE("cert/:id", RemoveCert)
r.PUT("cert_sync", SyncCertificate)
r.GET("certificate/dns_providers", GetDNSProvidersList)
r.GET("certificate/dns_provider/:code", GetDNSProvider)
}
func InitCertificateWebSocketRouter(r *gin.RouterGroup) {
r.GET("domain/:name/cert", IssueCert)
}
func InitAcmeUserRouter(r *gin.RouterGroup) {
r.GET("acme_users", GetAcmeUserList)
r.GET("acme_user/:id", GetAcmeUser)
r.POST("acme_user", CreateAcmeUser)
r.POST("acme_user/:id", ModifyAcmeUser)
r.POST("acme_user/:id/register", RegisterAcmeUser)
r.DELETE("acme_user/:id", DestroyAcmeUser)
r.PATCH("acme_user/:id", RecoverAcmeUser)
}

@ -1,103 +0,0 @@
package cluster
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/analytic"
"github.com/0xJacky/Nginx-UI/internal/cluster"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"gorm.io/gorm"
"net/http"
)
func GetEnvironment(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
envQuery := query.Environment
env, err := envQuery.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, analytic.GetNode(env))
}
func GetEnvironmentList(c *gin.Context) {
core := cosy.Core[model.Environment](c).
SetFussy("name")
// fix for sqlite
if c.Query("enabled") != "" {
core.GormScope(func(tx *gorm.DB) *gorm.DB {
return tx.Where("enabled = ?", cast.ToInt(cast.ToBool(c.Query("enabled"))))
})
}
core.SetTransformer(func(m *model.Environment) any {
return analytic.GetNode(m)
}).PagingList()
}
func AddEnvironment(c *gin.Context) {
cosy.Core[model.Environment](c).SetValidRules(gin.H{
"name": "required",
"url": "required,url",
"token": "required",
"enabled": "omitempty,boolean",
}).ExecutedHook(func(c *cosy.Ctx[model.Environment]) {
go analytic.RestartRetrieveNodesStatus()
}).Create()
}
func EditEnvironment(c *gin.Context) {
cosy.Core[model.Environment](c).SetValidRules(gin.H{
"name": "required",
"url": "required,url",
"token": "required",
"enabled": "omitempty,boolean",
}).ExecutedHook(func(c *cosy.Ctx[model.Environment]) {
go analytic.RestartRetrieveNodesStatus()
}).Modify()
}
func DeleteEnvironment(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
envQuery := query.Environment
env, err := envQuery.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
err = envQuery.DeleteByID(env.ID)
if err != nil {
api.ErrHandler(c, err)
return
}
go analytic.RestartRetrieveNodesStatus()
c.JSON(http.StatusNoContent, nil)
}
func LoadEnvironmentFromSettings(c *gin.Context) {
err := settings.ReloadCluster()
if err != nil {
api.ErrHandler(c, err)
return
}
cluster.RegisterPredefinedNodes()
go analytic.RestartRetrieveNodesStatus()
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,46 +0,0 @@
package cluster
import (
"github.com/0xJacky/Nginx-UI/api"
analytic2 "github.com/0xJacky/Nginx-UI/internal/analytic"
"github.com/0xJacky/Nginx-UI/internal/upgrader"
"github.com/dustin/go-humanize"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"net/http"
)
func GetCurrentNode(c *gin.Context) {
if _, ok := c.Get("NodeSecret"); !ok {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "node secret not exist",
})
return
}
runtimeInfo, err := upgrader.GetRuntimeInfo()
if err != nil {
api.ErrHandler(c, err)
return
}
cpuInfo, _ := cpu.Info()
memory, _ := analytic2.GetMemoryStat()
ver, _ := upgrader.GetCurrentVersion()
diskUsage, _ := disk.Usage(".")
nodeInfo := analytic2.NodeInfo{
NodeRuntimeInfo: runtimeInfo,
CPUNum: len(cpuInfo),
MemoryTotal: memory.Total,
DiskTotal: humanize.Bytes(diskUsage.Total),
Version: ver.Version,
}
stat := analytic2.GetNodeStat()
c.JSON(http.StatusOK, analytic2.Node{
NodeInfo: nodeInfo,
NodeStat: stat,
})
}

@ -1,18 +0,0 @@
package cluster
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
// Environment
r.GET("environments", GetEnvironmentList)
r.POST("environments/load_from_settings", LoadEnvironmentFromSettings)
envGroup := r.Group("environment")
{
envGroup.GET("/:id", GetEnvironment)
envGroup.POST("", AddEnvironment)
envGroup.POST("/:id", EditEnvironment)
envGroup.DELETE("/:id", DeleteEnvironment)
}
// Node
r.GET("node", GetCurrentNode)
}

@ -1,97 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/config"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/sashabaranov/go-openai"
"net/http"
"os"
"path/filepath"
"time"
)
func AddConfig(c *gin.Context) {
var json struct {
Name string `json:"name" binding:"required"`
NewFilepath string `json:"new_filepath" binding:"required"`
Content string `json:"content"`
Overwrite bool `json:"overwrite"`
SyncNodeIds []int `json:"sync_node_ids"`
}
if !api.BindAndValid(c, &json) {
return
}
name := json.Name
content := json.Content
path := json.NewFilepath
if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
c.JSON(http.StatusForbidden, gin.H{
"message": "new filepath is not under the nginx conf path",
})
return
}
if !json.Overwrite && helper.FileExists(path) {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists",
})
return
}
// check if the dir exists, if not, use mkdirAll to create the dir
dir := filepath.Dir(path)
if !helper.FileExists(dir) {
err := os.MkdirAll(dir, 0755)
if err != nil {
api.ErrHandler(c, err)
return
}
}
err := os.WriteFile(path, []byte(content), 0644)
if err != nil {
api.ErrHandler(c, err)
return
}
output := nginx.Reload()
if nginx.GetLogLevel(output) >= nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{
"message": output,
})
return
}
q := query.Config
_, err = q.Where(q.Filepath.Eq(path)).Delete()
if err != nil {
api.ErrHandler(c, err)
return
}
err = q.Create(&model.Config{
Name: name,
Filepath: path,
SyncNodeIds: json.SyncNodeIds,
SyncOverwrite: json.Overwrite,
})
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, config.Config{
Name: name,
Content: content,
ChatGPTMessages: make([]openai.ChatCompletionMessage, 0),
FilePath: path,
ModifiedAt: time.Now(),
})
}

@ -1,13 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/gin-gonic/gin"
"net/http"
)
func GetBasePath(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"base_path": nginx.GetConfPath(),
})
}

@ -1,72 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/config"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/sashabaranov/go-openai"
"net/http"
"os"
)
type APIConfigResp struct {
config.Config
SyncNodeIds []int `json:"sync_node_ids" gorm:"serializer:json"`
SyncOverwrite bool `json:"sync_overwrite"`
}
func GetConfig(c *gin.Context) {
name := c.Param("name")
path := nginx.GetConfPath("/", name)
if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
c.JSON(http.StatusForbidden, gin.H{
"message": "path is not under the nginx conf path",
})
return
}
stat, err := os.Stat(path)
if err != nil {
api.ErrHandler(c, err)
return
}
content, err := os.ReadFile(path)
if err != nil {
api.ErrHandler(c, err)
return
}
q := query.Config
g := query.ChatGPTLog
chatgpt, err := g.Where(g.Name.Eq(path)).FirstOrCreate()
if err != nil {
api.ErrHandler(c, err)
return
}
if chatgpt.Content == nil {
chatgpt.Content = make([]openai.ChatCompletionMessage, 0)
}
cfg, err := q.Where(q.Filepath.Eq(path)).FirstOrInit()
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, APIConfigResp{
Config: config.Config{
Name: stat.Name(),
Content: string(content),
ChatGPTMessages: chatgpt.Content,
FilePath: path,
ModifiedAt: stat.ModTime(),
},
SyncNodeIds: cfg.SyncNodeIds,
SyncOverwrite: cfg.SyncOverwrite,
})
}

@ -1,75 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/config"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/gin-gonic/gin"
"net/http"
"os"
"strings"
)
func GetConfigs(c *gin.Context) {
name := c.Query("name")
orderBy := c.Query("order_by")
sort := c.DefaultQuery("sort", "desc")
dir := c.DefaultQuery("dir", "/")
configFiles, err := os.ReadDir(nginx.GetConfPath(dir))
if err != nil {
api.ErrHandler(c, err)
return
}
configs := make([]config.Config, 0)
for i := range configFiles {
file := configFiles[i]
fileInfo, _ := file.Info()
if name != "" && !strings.Contains(file.Name(), name) {
continue
}
switch mode := fileInfo.Mode(); {
case mode.IsRegular(): // regular file, not a hidden file
if "." == file.Name()[0:1] {
continue
}
case mode&os.ModeSymlink != 0: // is a symbol
var targetPath string
targetPath, err = os.Readlink(nginx.GetConfPath(dir, file.Name()))
if err != nil {
logger.Error("Read Symlink Error", targetPath, err)
continue
}
var targetInfo os.FileInfo
targetInfo, err = os.Stat(targetPath)
if err != nil {
logger.Error("Stat Error", targetPath, err)
continue
}
// hide the file if it's target file is a directory
if targetInfo.IsDir() {
continue
}
}
configs = append(configs, config.Config{
Name: file.Name(),
ModifiedAt: fileInfo.ModTime(),
Size: fileInfo.Size(),
IsDir: fileInfo.IsDir(),
})
}
configs = config.Sort(orderBy, sort, configs)
c.JSON(http.StatusOK, gin.H{
"data": configs,
})
}

@ -1,37 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/gin-gonic/gin"
"net/http"
"os"
)
func Mkdir(c *gin.Context) {
var json struct {
BasePath string `json:"base_path"`
FolderName string `json:"folder_name"`
}
if !api.BindAndValid(c, &json) {
return
}
fullPath := nginx.GetConfPath(json.BasePath, json.FolderName)
if !helper.IsUnderDirectory(fullPath, nginx.GetConfPath()) {
c.JSON(http.StatusForbidden, gin.H{
"message": "You are not allowed to create a folder " +
"outside of the nginx configuration directory",
})
return
}
err := os.Mkdir(fullPath, 0755)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,143 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/config"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/sashabaranov/go-openai"
"net/http"
"os"
"time"
)
type EditConfigJson struct {
Content string `json:"content" binding:"required"`
}
func EditConfig(c *gin.Context) {
name := c.Param("name")
var json struct {
Name string `json:"name" binding:"required"`
Filepath string `json:"filepath" binding:"required"`
NewFilepath string `json:"new_filepath" binding:"required"`
Content string `json:"content"`
SyncOverwrite bool `json:"sync_overwrite"`
SyncNodeIds []int `json:"sync_node_ids"`
}
if !api.BindAndValid(c, &json) {
return
}
path := json.Filepath
if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
c.JSON(http.StatusForbidden, gin.H{
"message": "filepath is not under the nginx conf path",
})
return
}
if !helper.IsUnderDirectory(json.NewFilepath, nginx.GetConfPath()) {
c.JSON(http.StatusForbidden, gin.H{
"message": "new filepath is not under the nginx conf path",
})
return
}
if !helper.FileExists(path) {
c.JSON(http.StatusNotFound, gin.H{
"message": "file not found",
})
return
}
content := json.Content
origContent, err := os.ReadFile(path)
if err != nil {
api.ErrHandler(c, err)
return
}
if content != "" && content != string(origContent) {
err = os.WriteFile(path, []byte(content), 0644)
if err != nil {
api.ErrHandler(c, err)
return
}
}
q := query.Config
cfg, err := q.Where(q.Filepath.Eq(json.Filepath)).FirstOrCreate()
if err != nil {
api.ErrHandler(c, err)
return
}
_, err = q.Where(q.Filepath.Eq(json.Filepath)).
Select(q.Name, q.Filepath, q.SyncNodeIds, q.SyncOverwrite).
Updates(&model.Config{
Name: json.Name,
Filepath: json.NewFilepath,
SyncNodeIds: json.SyncNodeIds,
SyncOverwrite: json.SyncOverwrite,
})
if err != nil {
api.ErrHandler(c, err)
return
}
g := query.ChatGPTLog
// handle rename
if path != json.NewFilepath {
if helper.FileExists(json.NewFilepath) {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists",
})
return
}
err := os.Rename(json.Filepath, json.NewFilepath)
if err != nil {
api.ErrHandler(c, err)
return
}
// update ChatGPT record
_, _ = g.Where(g.Name.Eq(json.NewFilepath)).Delete()
_, _ = g.Where(g.Name.Eq(path)).Update(g.Name, json.NewFilepath)
}
err = config.SyncToRemoteServer(cfg, json.NewFilepath)
if err != nil {
api.ErrHandler(c, err)
return
}
output := nginx.Reload()
if nginx.GetLogLevel(output) >= nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{
"message": output,
})
return
}
chatgpt, err := g.Where(g.Name.Eq(json.NewFilepath)).FirstOrCreate()
if err != nil {
api.ErrHandler(c, err)
return
}
if chatgpt.Content == nil {
chatgpt.Content = make([]openai.ChatCompletionMessage, 0)
}
c.JSON(http.StatusOK, config.Config{
Name: name,
Content: content,
ChatGPTMessages: chatgpt.Content,
FilePath: json.NewFilepath,
ModifiedAt: time.Now(),
})
}

@ -1,97 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/config"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"net/http"
"os"
)
func Rename(c *gin.Context) {
var json struct {
BasePath string `json:"base_path"`
OrigName string `json:"orig_name"`
NewName string `json:"new_name"`
SyncNodeIds []int `json:"sync_node_ids" gorm:"serializer:json"`
}
if !api.BindAndValid(c, &json) {
return
}
logger.Debug(json)
if json.OrigName == json.NewName {
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
return
}
origFullPath := nginx.GetConfPath(json.BasePath, json.OrigName)
newFullPath := nginx.GetConfPath(json.BasePath, json.NewName)
if !helper.IsUnderDirectory(origFullPath, nginx.GetConfPath()) ||
!helper.IsUnderDirectory(newFullPath, nginx.GetConfPath()) {
c.JSON(http.StatusForbidden, gin.H{
"message": "you are not allowed to rename a file " +
"outside of the nginx config path",
})
return
}
stat, err := os.Stat(origFullPath)
if err != nil {
api.ErrHandler(c, err)
return
}
if helper.FileExists(newFullPath) {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "target file already exists",
})
return
}
err = os.Rename(origFullPath, newFullPath)
if err != nil {
api.ErrHandler(c, err)
return
}
// update ChatGPT records
g := query.ChatGPTLog
q := query.Config
cfg, err := q.Where(q.Filepath.Eq(origFullPath)).FirstOrInit()
if err != nil {
api.ErrHandler(c, err)
return
}
if !stat.IsDir() {
_, _ = g.Where(g.Name.Eq(newFullPath)).Delete()
_, _ = g.Where(g.Name.Eq(origFullPath)).Update(g.Name, newFullPath)
// for file, the sync policy for this file is used
json.SyncNodeIds = cfg.SyncNodeIds
} else {
// is directory, update all records under the directory
_, _ = g.Where(g.Name.Like(origFullPath+"%")).Update(g.Name, g.Name.Replace(origFullPath, newFullPath))
}
_, err = q.Where(q.Filepath.Eq(origFullPath)).Update(q.Filepath, newFullPath)
if err != nil {
api.ErrHandler(c, err)
return
}
if len(json.SyncNodeIds) > 0 {
err = config.SyncRenameOnRemoteServer(origFullPath, newFullPath, json.SyncNodeIds)
if err != nil {
api.ErrHandler(c, err)
return
}
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,21 +0,0 @@
package config
import (
"github.com/0xJacky/Nginx-UI/internal/middleware"
"github.com/gin-gonic/gin"
)
func InitRouter(r *gin.RouterGroup) {
r.GET("config_base_path", GetBasePath)
r.GET("configs", GetConfigs)
r.GET("config/*name", GetConfig)
r.POST("config", AddConfig)
r.POST("config/*name", EditConfig)
o := r.Group("", middleware.RequireSecureSession())
{
o.POST("config_mkdir", Mkdir)
o.POST("config_rename", Rename)
}
}

@ -1,47 +0,0 @@
package nginx
import (
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/gin-gonic/gin"
"net/http"
"os"
)
func Reload(c *gin.Context) {
output := nginx.Reload()
c.JSON(http.StatusOK, gin.H{
"message": output,
"level": nginx.GetLogLevel(output),
})
}
func Test(c *gin.Context) {
output := nginx.TestConf()
c.JSON(http.StatusOK, gin.H{
"message": output,
"level": nginx.GetLogLevel(output),
})
}
func Restart(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
go nginx.Restart()
}
func Status(c *gin.Context) {
pidPath := nginx.GetPIDPath()
lastOutput := nginx.GetLastOutput()
running := true
if fileInfo, err := os.Stat(pidPath); err != nil || fileInfo.Size() == 0 { // fileInfo.Size() == 0 no process id
running = false
}
c.JSON(http.StatusOK, gin.H{
"running": running,
"message": lastOutput,
"level": nginx.GetLogLevel(lastOutput),
})
}

@ -1,59 +0,0 @@
package nginx
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/gin-gonic/gin"
"net/http"
)
func BuildNginxConfig(c *gin.Context) {
var ngxConf nginx.NgxConfig
if !api.BindAndValid(c, &ngxConf) {
return
}
content, err := ngxConf.BuildConfig()
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"content": content,
})
}
func TokenizeNginxConfig(c *gin.Context) {
var json struct {
Content string `json:"content" binding:"required"`
}
if !api.BindAndValid(c, &json) {
return
}
ngxConfig, err := nginx.ParseNgxConfigByContent(json.Content)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, ngxConfig)
}
func FormatNginxConfig(c *gin.Context) {
var json struct {
Content string `json:"content" binding:"required"`
}
if !api.BindAndValid(c, &json) {
return
}
content, err := nginx.FmtCode(json.Content)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"content": content,
})
}

@ -1,18 +0,0 @@
package nginx
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
r.POST("ngx/build_config", BuildNginxConfig)
r.POST("ngx/tokenize_config", TokenizeNginxConfig)
r.POST("ngx/format_code", FormatNginxConfig)
r.POST("nginx/reload", Reload)
r.POST("nginx/restart", Restart)
r.POST("nginx/test", Test)
r.GET("nginx/status", Status)
r.POST("nginx_log", GetNginxLogPage)
}
func InitNginxLogRouter(r *gin.RouterGroup) {
r.GET("nginx_log", Log)
}

@ -1,56 +0,0 @@
package notification
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"net/http"
)
func Get(c *gin.Context) {
n := query.Notification
id := cast.ToInt(c.Param("id"))
data, err := n.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, data)
}
func GetList(c *gin.Context) {
cosy.Core[model.Notification](c).PagingList()
}
func Destroy(c *gin.Context) {
cosy.Core[model.Notification](c).Destroy()
}
func DestroyAll(c *gin.Context) {
db := model.UseDB()
// remove all records
err := db.Exec("DELETE FROM notifications").Error
if err != nil {
api.ErrHandler(c, err)
return
}
// reset auto increment
err = db.Exec("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'notifications';").Error
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,10 +0,0 @@
package notification
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
r.GET("notifications", GetList)
r.GET("notification/:id", Get)
r.DELETE("notification/:id", Destroy)
r.DELETE("notifications", DestroyAll)
}

@ -1,9 +0,0 @@
package openai
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
// ChatGPT
r.POST("chatgpt", MakeChatCompletionRequest)
r.POST("chatgpt_record", StoreChatGPTRecord)
}

@ -1,44 +0,0 @@
package openai
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/sashabaranov/go-openai"
"net/http"
)
func StoreChatGPTRecord(c *gin.Context) {
var json struct {
FileName string `json:"file_name"`
Messages []openai.ChatCompletionMessage `json:"messages"`
}
if !api.BindAndValid(c, &json) {
return
}
name := json.FileName
g := query.ChatGPTLog
_, err := g.Where(g.Name.Eq(name)).FirstOrCreate()
if err != nil {
api.ErrHandler(c, err)
return
}
_, err = g.Where(g.Name.Eq(name)).Updates(&model.ChatGPTLog{
Name: name,
Content: json.Messages,
})
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,45 +0,0 @@
package settings
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func GetBanLoginIP(c *gin.Context) {
b := query.BanIP
// clear expired banned IPs
_, _ = b.Where(b.ExpiredAt.Lte(time.Now().Unix())).Delete()
banIps, err := b.Where(
b.ExpiredAt.Gte(time.Now().Unix()),
b.Attempts.Gte(settings.AuthSettings.MaxAttempts)).Find()
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, banIps)
}
func RemoveBannedIP(c *gin.Context) {
var json struct {
IP string `json:"ip"`
}
if !api.BindAndValid(c, &json) {
return
}
b := query.BanIP
_, err := b.Where(b.IP.Eq(json.IP)).Delete()
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusNoContent, nil)
}

@ -1,15 +0,0 @@
package settings
import (
"github.com/0xJacky/Nginx-UI/internal/middleware"
"github.com/gin-gonic/gin"
)
func InitRouter(r *gin.RouterGroup) {
r.GET("settings/server/name", GetServerName)
r.GET("settings", GetSettings)
r.POST("settings", middleware.RequireSecureSession(), SaveSettings)
r.GET("settings/auth/banned_ips", GetBanLoginIP)
r.DELETE("settings/auth/banned_ip", RemoveBannedIP)
}

@ -1,58 +0,0 @@
package settings
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cron"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"net/http"
)
func GetServerName(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"name": settings.ServerSettings.Name,
})
}
func GetSettings(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"server": settings.ServerSettings,
"nginx": settings.NginxSettings,
"openai": settings.OpenAISettings,
"logrotate": settings.LogrotateSettings,
"auth": settings.AuthSettings,
})
}
func SaveSettings(c *gin.Context) {
var json struct {
Server settings.Server `json:"server"`
Nginx settings.Nginx `json:"nginx"`
Openai settings.OpenAI `json:"openai"`
Logrotate settings.Logrotate `json:"logrotate"`
Auth settings.Auth `json:"auth"`
}
if !api.BindAndValid(c, &json) {
return
}
if settings.LogrotateSettings.Enabled != json.Logrotate.Enabled ||
settings.LogrotateSettings.Interval != json.Logrotate.Interval {
go cron.RestartLogrotate()
}
settings.ProtectedFill(&settings.ServerSettings, &json.Server)
settings.ProtectedFill(&settings.NginxSettings, &json.Nginx)
settings.ProtectedFill(&settings.OpenAISettings, &json.Openai)
settings.ProtectedFill(&settings.LogrotateSettings, &json.Logrotate)
settings.ProtectedFill(&settings.AuthSettings, &json.Auth)
err := settings.Save()
if err != nil {
api.ErrHandler(c, err)
return
}
GetSettings(c)
}

@ -1,42 +0,0 @@
package sites
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"net/http"
)
func DomainEditByAdvancedMode(c *gin.Context) {
var json struct {
Advanced bool `json:"advanced"`
}
if !api.BindAndValid(c, &json) {
return
}
name := c.Param("name")
path := nginx.GetConfPath("sites-available", name)
s := query.Site
_, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
if err != nil {
api.ErrHandler(c, err)
return
}
_, err = s.Where(s.Path.Eq(path)).Update(s.Advanced, json.Advanced)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,67 +0,0 @@
package sites
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/model"
"github.com/gin-gonic/gin"
"github.com/go-acme/lego/v4/certcrypto"
"net/http"
)
func AddDomainToAutoCert(c *gin.Context) {
name := c.Param("name")
var json struct {
DnsCredentialID int `json:"dns_credential_id"`
ChallengeMethod string `json:"challenge_method"`
Domains []string `json:"domains"`
KeyType certcrypto.KeyType `json:"key_type"`
}
if !api.BindAndValid(c, &json) {
return
}
certModel, err := model.FirstOrCreateCert(name, helper.GetKeyType(json.KeyType))
if err != nil {
api.ErrHandler(c, err)
return
}
err = certModel.Updates(&model.Cert{
Name: name,
Domains: json.Domains,
AutoCert: model.AutoCertEnabled,
DnsCredentialID: json.DnsCredentialID,
ChallengeMethod: json.ChallengeMethod,
})
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, certModel)
}
func RemoveDomainFromAutoCert(c *gin.Context) {
name := c.Param("name")
certModel, err := model.FirstCert(name)
if err != nil {
api.ErrHandler(c, err)
return
}
err = certModel.Updates(&model.Cert{
AutoCert: model.AutoCertDisabled,
})
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, nil)
}

@ -1,44 +0,0 @@
package sites
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/gin-gonic/gin"
"net/http"
)
func DuplicateSite(c *gin.Context) {
// Source name
name := c.Param("name")
// Destination name
var json struct {
Name string `json:"name" binding:"required"`
}
if !api.BindAndValid(c, &json) {
return
}
src := nginx.GetConfPath("sites-available", name)
dst := nginx.GetConfPath("sites-available", json.Name)
if helper.FileExists(dst) {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists",
})
return
}
_, err := helper.CopyFile(src, dst)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"dst": dst,
})
}

@ -1,16 +0,0 @@
package sites
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
r.GET("domains", GetDomains)
r.GET("domain/:name", GetDomain)
r.POST("domain/:name", SaveDomain)
r.POST("domain/:name/enable", EnableDomain)
r.POST("domain/:name/disable", DisableDomain)
r.POST("domain/:name/advance", DomainEditByAdvancedMode)
r.DELETE("domain/:name", DeleteDomain)
r.POST("domain/:name/duplicate", DuplicateSite)
r.POST("auto_cert/:name", AddDomainToAutoCert)
r.DELETE("auto_cert/:name", RemoveDomainFromAutoCert)
}

@ -1,21 +0,0 @@
package sites
import (
"github.com/0xJacky/Nginx-UI/internal/cert"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/sashabaranov/go-openai"
"time"
)
type Site struct {
ModifiedAt time.Time `json:"modified_at"`
Advanced bool `json:"advanced"`
Enabled bool `json:"enabled"`
Name string `json:"name"`
Config string `json:"config"`
AutoCert bool `json:"auto_cert"`
ChatGPTMessages []openai.ChatCompletionMessage `json:"chatgpt_messages,omitempty"`
Tokenized *nginx.NgxConfig `json:"tokenized,omitempty"`
CertInfo map[int][]*cert.Info `json:"cert_info,omitempty"`
Filepath string `json:"filepath"`
}

@ -1,42 +0,0 @@
package streams
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"net/http"
)
func AdvancedEdit(c *gin.Context) {
var json struct {
Advanced bool `json:"advanced"`
}
if !api.BindAndValid(c, &json) {
return
}
name := c.Param("name")
path := nginx.GetConfPath("streams-available", name)
s := query.Site
_, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
if err != nil {
api.ErrHandler(c, err)
return
}
_, err = s.Where(s.Path.Eq(path)).Update(s.Advanced, json.Advanced)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,44 +0,0 @@
package streams
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/gin-gonic/gin"
"net/http"
)
func Duplicate(c *gin.Context) {
// Source name
name := c.Param("name")
// Destination name
var json struct {
Name string `json:"name" binding:"required"`
}
if !api.BindAndValid(c, &json) {
return
}
src := nginx.GetConfPath("streams-available", name)
dst := nginx.GetConfPath("streams-available", json.Name)
if helper.FileExists(dst) {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists",
})
return
}
_, err := helper.CopyFile(src, dst)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"dst": dst,
})
}

@ -1,14 +0,0 @@
package streams
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
r.GET("streams", GetStreams)
r.GET("stream/:name", GetStream)
r.POST("stream/:name", SaveStream)
r.POST("stream/:name/enable", EnableStream)
r.POST("stream/:name/disable", DisableStream)
r.POST("stream/:name/advance", AdvancedEdit)
r.DELETE("stream/:name", DeleteStream)
r.POST("stream/:name/duplicate", Duplicate)
}

@ -1,359 +0,0 @@
package streams
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/config"
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/nginx"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/sashabaranov/go-openai"
"net/http"
"os"
"strings"
"time"
)
type Stream struct {
ModifiedAt time.Time `json:"modified_at"`
Advanced bool `json:"advanced"`
Enabled bool `json:"enabled"`
Name string `json:"name"`
Config string `json:"config"`
ChatGPTMessages []openai.ChatCompletionMessage `json:"chatgpt_messages,omitempty"`
Tokenized *nginx.NgxConfig `json:"tokenized,omitempty"`
Filepath string `json:"filepath"`
}
func GetStreams(c *gin.Context) {
name := c.Query("name")
orderBy := c.Query("order_by")
sort := c.DefaultQuery("sort", "desc")
configFiles, err := os.ReadDir(nginx.GetConfPath("streams-available"))
if err != nil {
api.ErrHandler(c, err)
return
}
enabledConfig, err := os.ReadDir(nginx.GetConfPath("streams-enabled"))
if err != nil {
api.ErrHandler(c, err)
return
}
enabledConfigMap := make(map[string]bool)
for i := range enabledConfig {
enabledConfigMap[enabledConfig[i].Name()] = true
}
var configs []config.Config
for i := range configFiles {
file := configFiles[i]
fileInfo, _ := file.Info()
if !file.IsDir() {
if name != "" && !strings.Contains(file.Name(), name) {
continue
}
configs = append(configs, config.Config{
Name: file.Name(),
ModifiedAt: fileInfo.ModTime(),
Size: fileInfo.Size(),
IsDir: fileInfo.IsDir(),
Enabled: enabledConfigMap[file.Name()],
})
}
}
configs = config.Sort(orderBy, sort, configs)
c.JSON(http.StatusOK, gin.H{
"data": configs,
})
}
func GetStream(c *gin.Context) {
rewriteName, ok := c.Get("rewriteConfigFileName")
name := c.Param("name")
// for modify filename
if ok {
name = rewriteName.(string)
}
path := nginx.GetConfPath("streams-available", name)
file, err := os.Stat(path)
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{
"message": "file not found",
})
return
}
enabled := true
if _, err := os.Stat(nginx.GetConfPath("streams-enabled", name)); os.IsNotExist(err) {
enabled = false
}
g := query.ChatGPTLog
chatgpt, err := g.Where(g.Name.Eq(path)).FirstOrCreate()
if err != nil {
api.ErrHandler(c, err)
return
}
if chatgpt.Content == nil {
chatgpt.Content = make([]openai.ChatCompletionMessage, 0)
}
s := query.Stream
stream, err := s.Where(s.Path.Eq(path)).FirstOrInit()
if err != nil {
api.ErrHandler(c, err)
return
}
if stream.Advanced {
origContent, err := os.ReadFile(path)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, Stream{
ModifiedAt: file.ModTime(),
Advanced: stream.Advanced,
Enabled: enabled,
Name: name,
Config: string(origContent),
ChatGPTMessages: chatgpt.Content,
Filepath: path,
})
return
}
nginxConfig, err := nginx.ParseNgxConfig(path)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, Stream{
ModifiedAt: file.ModTime(),
Advanced: stream.Advanced,
Enabled: enabled,
Name: name,
Config: nginxConfig.FmtCode(),
Tokenized: nginxConfig,
ChatGPTMessages: chatgpt.Content,
Filepath: path,
})
}
func SaveStream(c *gin.Context) {
name := c.Param("name")
if name == "" {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "param name is empty",
})
return
}
var json struct {
Name string `json:"name" binding:"required"`
Content string `json:"content" binding:"required"`
Overwrite bool `json:"overwrite"`
}
if !api.BindAndValid(c, &json) {
return
}
path := nginx.GetConfPath("streams-available", name)
if !json.Overwrite && helper.FileExists(path) {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists",
})
return
}
err := os.WriteFile(path, []byte(json.Content), 0644)
if err != nil {
api.ErrHandler(c, err)
return
}
enabledConfigFilePath := nginx.GetConfPath("streams-enabled", name)
// rename the config file if needed
if name != json.Name {
newPath := nginx.GetConfPath("streams-available", json.Name)
s := query.Stream
_, err = s.Where(s.Path.Eq(path)).Update(s.Path, newPath)
// check if dst file exists, do not rename
if helper.FileExists(newPath) {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "File exists",
})
return
}
// recreate a soft link
if helper.FileExists(enabledConfigFilePath) {
_ = os.Remove(enabledConfigFilePath)
enabledConfigFilePath = nginx.GetConfPath("streams-enabled", json.Name)
err = os.Symlink(newPath, enabledConfigFilePath)
if err != nil {
api.ErrHandler(c, err)
return
}
}
err = os.Rename(path, newPath)
if err != nil {
api.ErrHandler(c, err)
return
}
name = json.Name
c.Set("rewriteConfigFileName", name)
}
enabledConfigFilePath = nginx.GetConfPath("streams-enabled", name)
if helper.FileExists(enabledConfigFilePath) {
// Test nginx configuration
output := nginx.TestConf()
if nginx.GetLogLevel(output) > nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{
"message": output,
})
return
}
output = nginx.Reload()
if nginx.GetLogLevel(output) > nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{
"message": output,
})
return
}
}
GetStream(c)
}
func EnableStream(c *gin.Context) {
configFilePath := nginx.GetConfPath("streams-available", c.Param("name"))
enabledConfigFilePath := nginx.GetConfPath("streams-enabled", c.Param("name"))
_, err := os.Stat(configFilePath)
if err != nil {
api.ErrHandler(c, err)
return
}
if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) {
err = os.Symlink(configFilePath, enabledConfigFilePath)
if err != nil {
api.ErrHandler(c, err)
return
}
}
// Test nginx config, if not pass, then disable the stream.
output := nginx.TestConf()
if nginx.GetLogLevel(output) > nginx.Warn {
_ = os.Remove(enabledConfigFilePath)
c.JSON(http.StatusInternalServerError, gin.H{
"message": output,
})
return
}
output = nginx.Reload()
if nginx.GetLogLevel(output) > nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{
"message": output,
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}
func DisableStream(c *gin.Context) {
enabledConfigFilePath := nginx.GetConfPath("streams-enabled", c.Param("name"))
_, err := os.Stat(enabledConfigFilePath)
if err != nil {
api.ErrHandler(c, err)
return
}
err = os.Remove(enabledConfigFilePath)
if err != nil {
api.ErrHandler(c, err)
return
}
output := nginx.Reload()
if nginx.GetLogLevel(output) > nginx.Warn {
c.JSON(http.StatusInternalServerError, gin.H{
"message": output,
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}
func DeleteStream(c *gin.Context) {
var err error
name := c.Param("name")
availablePath := nginx.GetConfPath("streams-available", name)
enabledPath := nginx.GetConfPath("streams-enabled", name)
if _, err = os.Stat(availablePath); os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{
"message": "stream not found",
})
return
}
if _, err = os.Stat(enabledPath); err == nil {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "stream is enabled",
})
return
}
if err = os.Remove(availablePath); err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,78 +0,0 @@
package system
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/kernal"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"net/http"
)
func installLockStatus() bool {
return settings.ServerSettings.SkipInstallation || "" != settings.ServerSettings.JwtSecret
}
func InstallLockCheck(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"lock": installLockStatus(),
})
}
type InstallJson struct {
Email string `json:"email" binding:"required,email"`
Username string `json:"username" binding:"required,max=255"`
Password string `json:"password" binding:"required,max=255"`
Database string `json:"database"`
}
func InstallNginxUI(c *gin.Context) {
// Visit this api after installed is forbidden
if installLockStatus() {
c.JSON(http.StatusForbidden, gin.H{
"error": "installed",
})
return
}
var json InstallJson
ok := api.BindAndValid(c, &json)
if !ok {
return
}
settings.ServerSettings.JwtSecret = uuid.New().String()
settings.ServerSettings.NodeSecret = uuid.New().String()
settings.ServerSettings.Email = json.Email
if "" != json.Database {
settings.ServerSettings.Database = json.Database
}
err := settings.Save()
if err != nil {
api.ErrHandler(c, err)
return
}
// Init model
kernal.InitDatabase()
pwd, _ := bcrypt.GenerateFromPassword([]byte(json.Password), bcrypt.DefaultCost)
u := query.User
err = u.Create(&model.User{
Name: json.Username,
Password: string(pwd),
})
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,20 +0,0 @@
package system
import (
"github.com/gin-gonic/gin"
)
func InitPublicRouter(r *gin.RouterGroup) {
r.GET("install", InstallLockCheck)
r.POST("install", InstallNginxUI)
r.GET("translation/:code", GetTranslation)
}
func InitPrivateRouter(r *gin.RouterGroup) {
r.GET("upgrade/release", GetRelease)
r.GET("upgrade/current", GetCurrentVersion)
}
func InitWebSocketRouter(r *gin.RouterGroup) {
r.GET("upgrade/perform", PerformCoreUpgrade)
}

@ -1,13 +0,0 @@
package system
import (
"github.com/0xJacky/Nginx-UI/internal/translation"
"github.com/gin-gonic/gin"
"net/http"
)
func GetTranslation(c *gin.Context) {
code := c.Param("code")
c.JSON(http.StatusOK, translation.GetTranslation(code))
}

@ -1,156 +0,0 @@
package system
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/upgrader"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
"os"
)
func GetRelease(c *gin.Context) {
data, err := upgrader.GetRelease(c.Query("channel"))
if err != nil {
api.ErrHandler(c, err)
return
}
runtimeInfo, err := upgrader.GetRuntimeInfo()
if err != nil {
api.ErrHandler(c, err)
return
}
type resp struct {
upgrader.TRelease
upgrader.RuntimeInfo
}
c.JSON(http.StatusOK, resp{
data, runtimeInfo,
})
}
func GetCurrentVersion(c *gin.Context) {
curVer, err := upgrader.GetCurrentVersion()
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, curVer)
}
const (
UpgradeStatusInfo = "info"
UpgradeStatusError = "error"
UpgradeStatusProgress = "progress"
)
type CoreUpgradeResp struct {
Status string `json:"status"`
Progress float64 `json:"progress"`
Message string `json:"message"`
}
func PerformCoreUpgrade(c *gin.Context) {
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
logger.Error(err)
return
}
defer ws.Close()
var control struct {
DryRun bool `json:"dry_run"`
Channel string `json:"channel"`
}
err = ws.ReadJSON(&control)
if err != nil {
logger.Error(err)
return
}
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusInfo,
Message: "Initialing core upgrader",
})
u, err := upgrader.NewUpgrader(control.Channel)
if err != nil {
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusError,
Message: "Initial core upgrader error",
})
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusError,
Message: err.Error(),
})
logger.Error(err)
return
}
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusInfo,
Message: "Downloading latest release",
})
progressChan := make(chan float64)
go func() {
for progress := range progressChan {
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusProgress,
Progress: progress,
})
}
}()
tarName, err := u.DownloadLatestRelease(progressChan)
if err != nil {
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusError,
Message: "Download latest release error",
})
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusError,
Message: err.Error(),
})
logger.Error(err)
return
}
defer func() {
_ = os.Remove(tarName)
_ = os.Remove(tarName + ".digest")
}()
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusInfo,
Message: "Performing core upgrade",
})
// dry run
if control.DryRun || settings.ServerSettings.Demo {
return
}
// bye, will restart nginx-ui in performCoreUpgrade
err = u.PerformCoreUpgrade(tarName)
if err != nil {
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusError,
Message: "Perform core upgrade error",
})
_ = ws.WriteJSON(CoreUpgradeResp{
Status: UpgradeStatusError,
Message: err.Error(),
})
logger.Error(err)
return
}
}

@ -1,11 +0,0 @@
package template
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
r.GET("template", GetTemplate)
r.GET("template/configs", GetTemplateConfList)
r.GET("template/blocks", GetTemplateBlockList)
r.GET("template/block/:name", GetTemplateBlock)
r.POST("template/block/:name", GetTemplateBlock)
}

@ -1,7 +0,0 @@
package terminal
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
r.GET("pty", Pty)
}

@ -1,7 +0,0 @@
package upstream
import "github.com/gin-gonic/gin"
func InitRouter(r *gin.RouterGroup) {
r.GET("/availability_test", AvailabilityTest)
}

@ -1,46 +0,0 @@
package upstream
import (
"github.com/0xJacky/Nginx-UI/internal/helper"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/upstream"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
"time"
)
func AvailabilityTest(c *gin.Context) {
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
logger.Error(err)
return
}
defer ws.Close()
var body []string
err = ws.ReadJSON(&body)
if err != nil {
logger.Error(err)
return
}
for {
err = ws.WriteJSON(upstream.AvailabilityTest(body))
if helper.IsUnexpectedWebsocketError(err) {
logger.Error(err)
break
}
time.Sleep(10 * time.Second)
}
}

@ -1,156 +0,0 @@
package user
import (
"encoding/base64"
"fmt"
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cache"
"github.com/0xJacky/Nginx-UI/internal/passkey"
"github.com/0xJacky/Nginx-UI/internal/user"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/google/uuid"
"net/http"
"strings"
"time"
)
type Status2FA struct {
Enabled bool `json:"enabled"`
OTPStatus bool `json:"otp_status"`
PasskeyStatus bool `json:"passkey_status"`
}
func get2FAStatus(c *gin.Context) (status Status2FA) {
// when accessing the node from the main cluster, there is no user in the context
u, ok := c.Get("user")
if ok {
userPtr := u.(*model.User)
status.OTPStatus = userPtr.EnabledOTP()
status.PasskeyStatus = userPtr.EnabledPasskey() && passkey.Enabled()
status.Enabled = status.OTPStatus || status.PasskeyStatus
}
return
}
func Get2FAStatus(c *gin.Context) {
c.JSON(http.StatusOK, get2FAStatus(c))
}
func SecureSessionStatus(c *gin.Context) {
status2FA := get2FAStatus(c)
if !status2FA.Enabled {
c.JSON(http.StatusOK, gin.H{
"status": false,
})
return
}
ssid := c.GetHeader("X-Secure-Session-ID")
if ssid == "" {
ssid = c.Query("X-Secure-Session-ID")
}
if ssid == "" {
c.JSON(http.StatusOK, gin.H{
"status": false,
})
return
}
u := api.CurrentUser(c)
c.JSON(http.StatusOK, gin.H{
"status": user.VerifySecureSessionID(ssid, u.ID),
})
}
func Start2FASecureSessionByOTP(c *gin.Context) {
var json struct {
OTP string `json:"otp"`
RecoveryCode string `json:"recovery_code"`
}
if !api.BindAndValid(c, &json) {
return
}
u := api.CurrentUser(c)
if !u.EnabledOTP() {
c.JSON(http.StatusBadRequest, gin.H{
"message": "User has not configured OTP as 2FA",
})
return
}
if json.OTP == "" && json.RecoveryCode == "" {
c.JSON(http.StatusBadRequest, LoginResponse{
Message: "The user has enabled OTP as 2FA",
})
return
}
if err := user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
c.JSON(http.StatusBadRequest, LoginResponse{
Message: "Invalid OTP or recovery code",
})
return
}
sessionId := user.SetSecureSessionID(u.ID)
c.JSON(http.StatusOK, gin.H{
"session_id": sessionId,
})
}
func BeginStart2FASecureSessionByPasskey(c *gin.Context) {
if !passkey.Enabled() {
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
return
}
webauthnInstance := passkey.GetInstance()
u := api.CurrentUser(c)
options, sessionData, err := webauthnInstance.BeginLogin(u)
if err != nil {
api.ErrHandler(c, err)
return
}
passkeySessionID := uuid.NewString()
cache.Set(passkeySessionID, sessionData, passkeyTimeout)
c.JSON(http.StatusOK, gin.H{
"session_id": passkeySessionID,
"options": options,
})
}
func FinishStart2FASecureSessionByPasskey(c *gin.Context) {
if !passkey.Enabled() {
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
return
}
passkeySessionID := c.GetHeader("X-Passkey-Session-ID")
sessionDataBytes, ok := cache.Get(passkeySessionID)
if !ok {
api.ErrHandler(c, fmt.Errorf("session not found"))
return
}
sessionData := sessionDataBytes.(*webauthn.SessionData)
webauthnInstance := passkey.GetInstance()
u := api.CurrentUser(c)
credential, err := webauthnInstance.FinishLogin(u, *sessionData, c.Request)
if err != nil {
api.ErrHandler(c, err)
return
}
rawID := strings.TrimRight(base64.StdEncoding.EncodeToString(credential.ID), "=")
p := query.Passkey
_, _ = p.Where(p.RawID.Eq(rawID)).Updates(&model.Passkey{
LastUsedAt: time.Now().Unix(),
})
sessionId := user.SetSecureSessionID(u.ID)
c.JSON(http.StatusOK, gin.H{
"session_id": sessionId,
})
}

@ -1,142 +0,0 @@
package user
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/user"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"math/rand/v2"
"net/http"
"sync"
"time"
)
var mutex = &sync.Mutex{}
type LoginUser struct {
Name string `json:"name" binding:"required,max=255"`
Password string `json:"password" binding:"required,max=255"`
OTP string `json:"otp"`
RecoveryCode string `json:"recovery_code"`
}
const (
ErrPasswordIncorrect = 4031
ErrMaxAttempts = 4291
ErrUserBanned = 4033
Enabled2FA = 199
Error2FACode = 4034
LoginSuccess = 200
)
type LoginResponse struct {
Message string `json:"message"`
Error string `json:"error,omitempty"`
Code int `json:"code"`
Token string `json:"token,omitempty"`
SecureSessionID string `json:"secure_session_id,omitempty"`
}
func Login(c *gin.Context) {
// make sure that only one request is processed at a time
mutex.Lock()
defer mutex.Unlock()
// check if the ip is banned
clientIP := c.ClientIP()
b := query.BanIP
banIP, _ := b.Where(b.IP.Eq(clientIP),
b.ExpiredAt.Gte(time.Now().Unix()),
b.Attempts.Gte(settings.AuthSettings.MaxAttempts),
).Count()
if banIP > 0 {
c.JSON(http.StatusTooManyRequests, LoginResponse{
Message: "Max attempts",
Code: ErrMaxAttempts,
})
return
}
var json LoginUser
ok := api.BindAndValid(c, &json)
if !ok {
return
}
u, err := user.Login(json.Name, json.Password)
if err != nil {
random := time.Duration(rand.Int() % 10)
time.Sleep(random * time.Second)
switch {
case errors.Is(err, user.ErrPasswordIncorrect):
c.JSON(http.StatusForbidden, LoginResponse{
Message: "Password incorrect",
Code: ErrPasswordIncorrect,
})
case errors.Is(err, user.ErrUserBanned):
c.JSON(http.StatusForbidden, LoginResponse{
Message: "The user is banned",
Code: ErrUserBanned,
})
default:
api.ErrHandler(c, err)
}
user.BanIP(clientIP)
return
}
// Check if the user enables 2FA
var secureSessionID string
if u.EnabledOTP() {
if json.OTP == "" && json.RecoveryCode == "" {
c.JSON(http.StatusOK, LoginResponse{
Message: "The user has enabled 2FA",
Code: Enabled2FA,
})
user.BanIP(clientIP)
return
}
if err = user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
c.JSON(http.StatusForbidden, LoginResponse{
Message: "Invalid 2FA or recovery code",
Code: Error2FACode,
})
user.BanIP(clientIP)
return
}
secureSessionID = user.SetSecureSessionID(u.ID)
}
// login success, clear banned record
_, _ = b.Where(b.IP.Eq(clientIP)).Delete()
logger.Info("[User Login]", u.Name)
token, err := user.GenerateJWT(u)
if err != nil {
c.JSON(http.StatusInternalServerError, LoginResponse{
Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, LoginResponse{
Code: LoginSuccess,
Message: "ok",
Token: token,
SecureSessionID: secureSessionID,
})
}
func Logout(c *gin.Context) {
token := c.GetHeader("Authorization")
if token != "" {
user.DeleteToken(token)
}
c.JSON(http.StatusNoContent, nil)
}

@ -1,98 +0,0 @@
package user
import (
"fmt"
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/user"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"gorm.io/gorm"
"net/http"
"net/url"
)
type CasdoorLoginUser struct {
Code string `json:"code" binding:"required,max=255"`
State string `json:"state" binding:"required,max=255"`
}
func CasdoorCallback(c *gin.Context) {
var loginUser CasdoorLoginUser
ok := api.BindAndValid(c, &loginUser)
if !ok {
return
}
endpoint := settings.CasdoorSettings.Endpoint
clientId := settings.CasdoorSettings.ClientId
clientSecret := settings.CasdoorSettings.ClientSecret
certificate := settings.CasdoorSettings.Certificate
organization := settings.CasdoorSettings.Organization
application := settings.CasdoorSettings.Application
if endpoint == "" || clientId == "" || clientSecret == "" || certificate == "" || organization == "" || application == "" {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Casdoor is not configured",
})
return
}
casdoorsdk.InitConfig(endpoint, clientId, clientSecret, certificate, organization, application)
token, err := casdoorsdk.GetOAuthToken(loginUser.Code, loginUser.State)
if err != nil {
api.ErrHandler(c, err)
return
}
claims, err := casdoorsdk.ParseJwtToken(token.AccessToken)
if err != nil {
api.ErrHandler(c, err)
return
}
u, err := user.GetUser(claims.Name)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusForbidden, gin.H{
"message": "User not exist",
})
} else {
api.ErrHandler(c, err)
}
return
}
userToken, err := user.GenerateJWT(u)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, LoginResponse{
Message: "ok",
Token: userToken,
})
}
func GetCasdoorUri(c *gin.Context) {
endpoint := settings.CasdoorSettings.Endpoint
clientId := settings.CasdoorSettings.ClientId
redirectUri := settings.CasdoorSettings.RedirectUri
state := settings.CasdoorSettings.Application
if endpoint == "" || clientId == "" || redirectUri == "" || state == "" {
c.JSON(http.StatusOK, gin.H{
"uri": "",
})
return
}
encodedRedirectUri := url.QueryEscape(redirectUri)
c.JSON(http.StatusOK, gin.H{
"uri": fmt.Sprintf("%s/login/oauth/authorize?client_id=%s&response_type=code&redirect_uri=%s&state=%s&scope=read", endpoint, clientId, encodedRedirectUri, state),
})
}

@ -1,147 +0,0 @@
package user
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"fmt"
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/crypto"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"image/jpeg"
"net/http"
"strings"
)
func GenerateTOTP(c *gin.Context) {
u := api.CurrentUser(c)
issuer := fmt.Sprintf("Nginx UI %s", settings.ServerSettings.Name)
issuer = strings.TrimSpace(issuer)
otpOpts := totp.GenerateOpts{
Issuer: issuer,
AccountName: u.Name,
Period: 30, // seconds
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA1,
}
otpKey, err := totp.Generate(otpOpts)
if err != nil {
api.ErrHandler(c, err)
return
}
qrCode, err := otpKey.Image(512, 512)
if err != nil {
api.ErrHandler(c, err)
return
}
// Encode the image to a buffer
var buf []byte
buffer := bytes.NewBuffer(buf)
err = jpeg.Encode(buffer, qrCode, nil)
if err != nil {
fmt.Println("Error encoding image:", err)
return
}
// Convert the buffer to a base64 string
base64Str := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(buffer.Bytes())
c.JSON(http.StatusOK, gin.H{
"secret": otpKey.Secret(),
"qr_code": base64Str,
})
}
func EnrollTOTP(c *gin.Context) {
cUser := api.CurrentUser(c)
if cUser.EnabledOTP() {
c.JSON(http.StatusBadRequest, gin.H{
"message": "User already enrolled",
})
return
}
if settings.ServerSettings.Demo {
c.JSON(http.StatusBadRequest, gin.H{
"message": "This feature is disabled in demo mode",
})
return
}
var json struct {
Secret string `json:"secret" binding:"required"`
Passcode string `json:"passcode" binding:"required"`
}
if !api.BindAndValid(c, &json) {
return
}
if ok := totp.Validate(json.Passcode, json.Secret); !ok {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "Invalid passcode",
})
return
}
ciphertext, err := crypto.AesEncrypt([]byte(json.Secret))
if err != nil {
api.ErrHandler(c, err)
return
}
u := query.User
_, err = u.Where(u.ID.Eq(cUser.ID)).Update(u.OTPSecret, ciphertext)
if err != nil {
api.ErrHandler(c, err)
return
}
recoveryCode := sha1.Sum(ciphertext)
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"recovery_code": hex.EncodeToString(recoveryCode[:]),
})
}
func ResetOTP(c *gin.Context) {
var json struct {
RecoveryCode string `json:"recovery_code"`
}
if !api.BindAndValid(c, &json) {
return
}
recoverCode, err := hex.DecodeString(json.RecoveryCode)
if err != nil {
api.ErrHandler(c, err)
return
}
cUser := api.CurrentUser(c)
k := sha1.Sum(cUser.OTPSecret)
if !bytes.Equal(k[:], recoverCode) {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid recovery code",
})
return
}
u := query.User
_, err = u.Where(u.ID.Eq(cUser.ID)).UpdateSimple(u.OTPSecret.Null())
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}

@ -1,195 +0,0 @@
package user
import (
"encoding/base64"
"fmt"
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cache"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/internal/logger"
"github.com/0xJacky/Nginx-UI/internal/passkey"
"github.com/0xJacky/Nginx-UI/internal/user"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/gin-gonic/gin"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/google/uuid"
"github.com/spf13/cast"
"gorm.io/gorm"
"net/http"
"strings"
"time"
)
const passkeyTimeout = 30 * time.Second
func buildCachePasskeyRegKey(id int) string {
return fmt.Sprintf("passkey-reg-%d", id)
}
func GetPasskeyConfigStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": passkey.Enabled(),
})
}
func BeginPasskeyRegistration(c *gin.Context) {
u := api.CurrentUser(c)
webauthnInstance := passkey.GetInstance()
options, sessionData, err := webauthnInstance.BeginRegistration(u)
if err != nil {
api.ErrHandler(c, err)
return
}
cache.Set(buildCachePasskeyRegKey(u.ID), sessionData, passkeyTimeout)
c.JSON(http.StatusOK, options)
}
func FinishPasskeyRegistration(c *gin.Context) {
cUser := api.CurrentUser(c)
webauthnInstance := passkey.GetInstance()
sessionDataBytes, ok := cache.Get(buildCachePasskeyRegKey(cUser.ID))
if !ok {
api.ErrHandler(c, fmt.Errorf("session not found"))
return
}
sessionData := sessionDataBytes.(*webauthn.SessionData)
credential, err := webauthnInstance.FinishRegistration(cUser, *sessionData, c.Request)
if err != nil {
api.ErrHandler(c, err)
return
}
cache.Del(buildCachePasskeyRegKey(cUser.ID))
rawId := strings.TrimRight(base64.StdEncoding.EncodeToString(credential.ID), "=")
passkeyName := c.Query("name")
p := query.Passkey
err = p.Create(&model.Passkey{
UserID: cUser.ID,
Name: passkeyName,
RawID: rawId,
Credential: credential,
LastUsedAt: time.Now().Unix(),
})
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}
func BeginPasskeyLogin(c *gin.Context) {
if !passkey.Enabled() {
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
return
}
webauthnInstance := passkey.GetInstance()
options, sessionData, err := webauthnInstance.BeginDiscoverableLogin()
if err != nil {
api.ErrHandler(c, err)
return
}
sessionID := uuid.NewString()
cache.Set(sessionID, sessionData, passkeyTimeout)
c.JSON(http.StatusOK, gin.H{
"session_id": sessionID,
"options": options,
})
}
func FinishPasskeyLogin(c *gin.Context) {
if !passkey.Enabled() {
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
return
}
sessionId := c.GetHeader("X-Passkey-Session-ID")
sessionDataBytes, ok := cache.Get(sessionId)
if !ok {
api.ErrHandler(c, fmt.Errorf("session not found"))
return
}
webauthnInstance := passkey.GetInstance()
sessionData := sessionDataBytes.(*webauthn.SessionData)
var outUser *model.User
_, err := webauthnInstance.FinishDiscoverableLogin(
func(rawID, userHandle []byte) (user webauthn.User, err error) {
encodeRawID := strings.TrimRight(base64.StdEncoding.EncodeToString(rawID), "=")
u := query.User
logger.Debug("[WebAuthn] Discoverable Login", cast.ToInt(string(userHandle)))
p := query.Passkey
_, _ = p.Where(p.RawID.Eq(encodeRawID)).Updates(&model.Passkey{
LastUsedAt: time.Now().Unix(),
})
outUser, err = u.FirstByID(cast.ToInt(string(userHandle)))
return outUser, err
}, *sessionData, c.Request)
if err != nil {
api.ErrHandler(c, err)
return
}
b := query.BanIP
clientIP := c.ClientIP()
// login success, clear banned record
_, _ = b.Where(b.IP.Eq(clientIP)).Delete()
logger.Info("[User Login]", outUser.Name)
token, err := user.GenerateJWT(outUser)
if err != nil {
c.JSON(http.StatusInternalServerError, LoginResponse{
Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, LoginResponse{
Code: LoginSuccess,
Message: "ok",
Token: token,
// SecureSessionID: secureSessionID,
})
}
func GetPasskeyList(c *gin.Context) {
u := api.CurrentUser(c)
p := query.Passkey
passkeys, err := p.Where(p.UserID.Eq(u.ID)).Find()
if err != nil {
api.ErrHandler(c, err)
return
}
if len(passkeys) == 0 {
passkeys = make([]*model.Passkey, 0)
}
c.JSON(http.StatusOK, passkeys)
}
func UpdatePasskey(c *gin.Context) {
u := api.CurrentUser(c)
cosy.Core[model.Passkey](c).
SetValidRules(gin.H{
"name": "required",
}).GormScope(func(tx *gorm.DB) *gorm.DB {
return tx.Where("user_id", u.ID)
}).Modify()
}
func DeletePasskey(c *gin.Context) {
u := api.CurrentUser(c)
cosy.Core[model.Passkey](c).
GormScope(func(tx *gorm.DB) *gorm.DB {
return tx.Where("user_id", u.ID)
}).PermanentlyDelete()
}

@ -1,46 +0,0 @@
package user
import (
"github.com/gin-gonic/gin"
)
func InitAuthRouter(r *gin.RouterGroup) {
r.POST("/login", Login)
r.DELETE("/logout", Logout)
r.GET("/begin_passkey_login", BeginPasskeyLogin)
r.POST("/finish_passkey_login", FinishPasskeyLogin)
r.GET("/casdoor_uri", GetCasdoorUri)
r.POST("/casdoor_callback", CasdoorCallback)
r.GET("/passkeys/config", GetPasskeyConfigStatus)
}
func InitManageUserRouter(r *gin.RouterGroup) {
r.GET("users", GetUsers)
r.GET("user/:id", GetUser)
r.POST("user", AddUser)
r.POST("user/:id", EditUser)
r.DELETE("user/:id", DeleteUser)
r.PATCH("user/:id", RecoverUser)
}
func InitUserRouter(r *gin.RouterGroup) {
r.GET("/2fa_status", Get2FAStatus)
r.GET("/2fa_secure_session/status", SecureSessionStatus)
r.POST("/2fa_secure_session/otp", Start2FASecureSessionByOTP)
r.GET("/2fa_secure_session/passkey", BeginStart2FASecureSessionByPasskey)
r.POST("/2fa_secure_session/passkey", FinishStart2FASecureSessionByPasskey)
r.GET("/otp_secret", GenerateTOTP)
r.POST("/otp_enroll", EnrollTOTP)
r.POST("/otp_reset", ResetOTP)
r.GET("/begin_passkey_register", BeginPasskeyRegistration)
r.POST("/finish_passkey_register", FinishPasskeyRegistration)
r.GET("/passkeys", GetPasskeyList)
r.POST("/passkeys/:id", UpdatePasskey)
r.DELETE("/passkeys/:id", DeletePasskey)
}

@ -1,132 +0,0 @@
package user
import (
"github.com/0xJacky/Nginx-UI/api"
"github.com/0xJacky/Nginx-UI/internal/cosy"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"golang.org/x/crypto/bcrypt"
"net/http"
)
func GetUsers(c *gin.Context) {
cosy.Core[model.User](c).SetFussy("name").PagingList()
}
func GetUser(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
u := query.User
user, err := u.FirstByID(id)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, user)
}
type UserJson struct {
Name string `json:"name" binding:"required,max=255"`
Password string `json:"password" binding:"max=255"`
}
func AddUser(c *gin.Context) {
var json UserJson
ok := api.BindAndValid(c, &json)
if !ok {
return
}
u := query.User
pwd, err := bcrypt.GenerateFromPassword([]byte(json.Password), bcrypt.DefaultCost)
if err != nil {
api.ErrHandler(c, err)
return
}
json.Password = string(pwd)
user := model.User{
Name: json.Name,
Password: json.Password,
}
err = u.Create(&user)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, user)
}
func EditUser(c *gin.Context) {
userId := cast.ToInt(c.Param("id"))
if settings.ServerSettings.Demo && userId == 1 {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "Changing user password is forbidden in demo mode",
})
return
}
var json UserJson
ok := api.BindAndValid(c, &json)
if !ok {
return
}
u := query.User
user, err := u.FirstByID(userId)
if err != nil {
api.ErrHandler(c, err)
return
}
edit := &model.User{
Name: json.Name,
}
// encrypt password
if json.Password != "" {
var pwd []byte
pwd, err = bcrypt.GenerateFromPassword([]byte(json.Password), bcrypt.DefaultCost)
if err != nil {
api.ErrHandler(c, err)
return
}
edit.Password = string(pwd)
}
_, err = u.Where(u.ID.Eq(userId)).Updates(&edit)
if err != nil {
api.ErrHandler(c, err)
return
}
c.JSON(http.StatusOK, user)
}
func DeleteUser(c *gin.Context) {
id := cast.ToInt(c.Param("id"))
if cast.ToInt(id) == 1 {
c.JSON(http.StatusNotAcceptable, gin.H{
"message": "Prohibit deleting the default user",
})
return
}
cosy.Core[model.User](c).Destroy()
}
func RecoverUser(c *gin.Context) {
cosy.Core[model.User](c).Recover()
}

@ -1,67 +1,29 @@
; suppress inspection "DuplicateKeyInSection" for whole file
[server] [server]
HttpPort = 9000 HttpPort = 9000
RunMode = debug RunMode = debug
JwtSecret = JwtSecret =
Email = Email =
HTTPChallengePort = 9180 HTTPChallengePort = 9180
StartCmd = bash StartCmd = login
Database = database Database = database
CADir = CADir =
GithubProxy = Demo =
NodeSecret = GithubProxy =
Demo = false NginxConfigDir =
PageSize = 10
HttpHost = 0.0.0.0 [nginx_log]
CertRenewalInterval = 7
RecursiveNameservers =
SkipInstallation = false
Name =
InsecureSkipVerify = false
[nginx]
AccessLogPath = /var/log/nginx/access.log AccessLogPath = /var/log/nginx/access.log
ErrorLogPath = /var/log/nginx/error.log ErrorLogPath = /var/log/nginx/error.log
ConfigDir =
PIDPath =
TestConfigCmd =
ReloadCmd =
RestartCmd =
[openai] [openai]
Model = Model =
BaseUrl = BaseUrl =
Proxy = Proxy =
Token = Token =
[casdoor] [git]
Endpoint = Url =
ClientId = AuthMethod =
ClientSecret = Username =
Certificate = Password =
Organization = PrivateKeyFile =
Application =
RedirectUri =
[logrotate]
Enabled = false
CMD = logrotate /etc/logrotate.d/nginx
Interval = 1440
[cluster]
Node = http://10.0.0.1:9000?name=node1&node_secret=my-node-secret&enabled=true
Node = http://10.0.0.2:9000?name=node2&node_secret=my-node-secret&enabled=true
Node = http://10.0.0.3?name=node3&node_secret=my-node-secret&enabled=true
[auth]
IPWhiteList =
BanThresholdMinutes = 10
MaxAttempts = 10
[crypto]
Secret = secret2
[webauthn]
RPDisplayName =
RPID =
RPOrigins =

@ -1 +0,0 @@
VITE_PROXY_TARGET=http://127.0.0.1:9001

@ -1,257 +0,0 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'@antfu/eslint-config-vue',
'plugin:vue/vue3-recommended',
'plugin:import/recommended',
'plugin:import/typescript',
'plugin:sonarjs/recommended',
'plugin:@typescript-eslint/recommended',
// 'plugin:unicorn/recommended',
],
parser: 'vue-eslint-parser',
parserOptions: {
ecmaVersion: 13,
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
plugins: [
'vue',
'@typescript-eslint',
'regex',
],
ignorePatterns: ['src/@iconify/*.js', 'node_modules', 'dist', '*.d.ts'],
rules: {
'vue/no-v-html': 'off',
'vue/block-tag-newline': 'off',
// eslint-disable-next-line n/prefer-global/process
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
// eslint-disable-next-line n/prefer-global/process
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
// indentation (Already present in TypeScript)
'comma-spacing': ['error', {
before: false,
after: true,
}],
'key-spacing': ['error', {afterColon: true}],
'vue/first-attribute-linebreak': ['error', {
singleline: 'beside',
multiline: 'below',
}],
'antfu/top-level-function': 'off',
// Enforce trailing comma (Already present in TypeScript)
'comma-dangle': ['error', 'always-multiline'],
// Disable max-len
'max-len': 'off',
// we don't want it
'semi': ['error', 'never'],
// add parens ony when required in arrow function
'arrow-parens': ['error', 'as-needed'],
// add new line above comment
'newline-before-return': 'error',
// add new line above comment
'lines-around-comment': [
'error',
{
beforeBlockComment: true,
beforeLineComment: true,
allowBlockStart: true,
allowClassStart: true,
allowObjectStart: true,
allowArrayStart: true,
},
],
// Ignore _ as unused variable
'@typescript-eslint/no-unused-vars': ['error', {argsIgnorePattern: '^_+$'}],
'array-element-newline': ['error', 'consistent'],
'array-bracket-newline': ['error', 'consistent'],
'vue/multi-word-component-names': 'off',
'padding-line-between-statements': [
'error',
{
blankLine: 'always',
prev: 'expression',
next: 'const',
},
{
blankLine: 'always',
prev: 'const',
next: 'expression',
},
{
blankLine: 'always',
prev: 'multiline-const',
next: '*',
},
{
blankLine: 'always',
prev: '*',
next: 'multiline-const',
},
],
// Plugin: eslint-plugin-import
'import/prefer-default-export': 'off',
'import/newline-after-import': ['error', {count: 1}],
'no-restricted-imports': ['error', 'vuetify/components'],
// For omitting extension for ts files
'import/extensions': [
'error',
'ignorePackages',
{
mjs: 'never',
js: 'never',
jsx: 'never',
ts: 'never',
tsx: 'never',
},
],
// ignore virtual files
'import/no-unresolved': [2, {
ignore: [
'~pages$',
'virtual:generated-layouts',
// Ignore vite's ?raw imports
'.*\?raw',
],
}],
// Thanks: https://stackoverflow.com/a/63961972/10796681
'no-shadow': 'off',
'@typescript-eslint/no-shadow': ['error'],
'@typescript-eslint/consistent-type-imports': 'error',
// Plugin: eslint-plugin-promise
'promise/always-return': 'off',
'promise/catch-or-return': 'off',
// ESLint plugin vue
'vue/component-api-style': 'error',
'vue/component-name-in-template-casing': ['error', 'PascalCase', {registeredComponentsOnly: false}],
'vue/custom-event-name-casing': ['error', 'camelCase', {
ignores: [
'/^(click):[a-z]+((\d)|([A-Z0-9][a-z0-9]+))*([A-Z])?/',
],
}],
'vue/define-macros-order': 'error',
'vue/html-comment-content-newline': 'error',
'vue/html-comment-content-spacing': 'error',
'vue/html-comment-indent': 'error',
'vue/match-component-file-name': 'error',
'vue/no-child-content': 'error',
'vue/require-default-prop': 'off',
// NOTE this rule only supported in SFC, Users of the unplugin-vue-define-options should disable that rule: https://github.com/vuejs/eslint-plugin-vue/issues/1886
// 'vue/no-duplicate-attr-inheritance': 'error',
'vue/no-multiple-objects-in-class': 'error',
'vue/no-reserved-component-names': 'error',
'vue/no-template-target-blank': 'error',
'vue/no-useless-mustaches': 'error',
'vue/no-useless-v-bind': 'error',
'vue/padding-line-between-blocks': 'error',
'vue/prefer-separate-static-class': 'error',
'vue/prefer-true-attribute-shorthand': 'error',
'vue/v-on-function-call': 'error',
'vue/valid-v-slot': ['error', {
allowModifiers: true,
}],
// -- Extension Rules
'vue/no-irregular-whitespace': 'error',
// -- Sonarlint
'sonarjs/no-duplicate-string': 'off',
'sonarjs/no-nested-template-literals': 'off',
// -- Unicorn
// 'unicorn/filename-case': 'off',
// 'unicorn/prevent-abbreviations': ['error', {
// replacements: {
// props: false,
// },
// }],
// https://github.com/gmullerb/eslint-plugin-regex
'regex/invalid': [
'error',
[
{
regex: '@/assets/images',
replacement: '@images',
message: 'Use \'@images\' path alias for image imports',
},
{
regex: '@/styles',
replacement: '@styles',
message: 'Use \'@styles\' path alias for importing styles from \'src/styles\'',
},
// {
// id: 'Disallow icon of icon library',
// regex: 'tabler-\\w',
// message: 'Only \'mdi\' icons are allowed',
// },
{
regex: '@core/\\w',
message: 'You can\'t use @core when you are in @layouts module',
files: {
inspect: '@layouts/.*',
},
},
{
regex: 'useLayouts\\(',
message: '`useLayouts` composable is only allowed in @layouts & @core directory. Please use `useThemeConfig` composable instead.',
files: {
inspect: '^(?!.*(@core|@layouts)).*',
},
},
],
// Ignore files
'\.eslintrc\.js',
],
},
settings: {
'import/resolver': {
node: {
extensions: ['.ts', '.js', '.tsx', '.jsx', '.mjs', '.png', '.jpg'],
},
typescript: {},
alias: {
map: [
['@', './src'],
],
},
},
},
overrides: [
{
files: ['*.json'],
rules: {
'no-invalid-meta': 'off',
},
},
],
}

@ -1,7 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# GitHub Copilot persisted chat sessions
/copilot/chatSessions

@ -1,5 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
<excludeFolder url="file://$MODULE_DIR$/dist" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="ERROR" enabled_by_default="true" editorAttributes="ERRORS_ATTRIBUTES" />
</profile>
</component>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<includedPredefinedLibrary name="Node.js Core" />
</component>
</project>

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EslintConfiguration">
<custom-configuration-file used="false" path="$PROJECT_DIR$/.eslintrc.cjs" />
<option name="fix-on-save" value="true" />
</component>
</project>

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/frontend.iml" filepath="$PROJECT_DIR$/.idea/frontend.iml" />
</modules>
</component>
</project>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectTasksOptions" suppressed-tasks="Less" />
</project>

@ -1,5 +0,0 @@
{
"recommendations": [
"Vue.volar"
]
}

@ -1,8 +0,0 @@
package app
import (
"embed"
)
//go:embed i18n.json dist/* dist/*/* src/language/* src/language/*/*
var DistFS embed.FS

@ -1,176 +0,0 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
const $gettext: typeof import('@/gettext')['$gettext']
const $ngettext: typeof import('@/gettext')['$ngettext']
const $npgettext: typeof import('@/gettext')['$npgettext']
const $pgettext: typeof import('@/gettext')['$pgettext']
const EffectScope: typeof import('vue')['EffectScope']
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const createPinia: typeof import('pinia')['createPinia']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const defineStore: typeof import('pinia')['defineStore']
const effectScope: typeof import('vue')['effectScope']
const getActivePinia: typeof import('pinia')['getActivePinia']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const mapActions: typeof import('pinia')['mapActions']
const mapGetters: typeof import('pinia')['mapGetters']
const mapState: typeof import('pinia')['mapState']
const mapStores: typeof import('pinia')['mapStores']
const mapWritableState: typeof import('pinia')['mapWritableState']
const markRaw: typeof import('vue')['markRaw']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeRouteLeave: typeof import('vue-router')['onBeforeRouteLeave']
const onBeforeRouteUpdate: typeof import('vue-router')['onBeforeRouteUpdate']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onMounted: typeof import('vue')['onMounted']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
const provide: typeof import('vue')['provide']
const reactive: typeof import('vue')['reactive']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const setActivePinia: typeof import('pinia')['setActivePinia']
const setMapStoreSuffix: typeof import('pinia')['setMapStoreSuffix']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const storeToRefs: typeof import('pinia')['storeToRefs']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useId: typeof import('vue')['useId']
const useLink: typeof import('vue-router')['useLink']
const useModel: typeof import('vue')['useModel']
const useRoute: typeof import('vue-router')['useRoute']
const useRouter: typeof import('vue-router')['useRouter']
const useSlots: typeof import('vue')['useSlots']
const useTemplateRef: typeof import('vue')['useTemplateRef']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
}
// for type re-export
declare global {
// @ts-ignore
export type { Component, ComponentPublicInstance, ComputedRef, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, VNode, WritableComputedRef } from 'vue'
import('vue')
}
// for vue template auto import
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface GlobalComponents {}
interface ComponentCustomProperties {
readonly $gettext: UnwrapRef<typeof import('@/gettext')['$gettext']>
readonly $ngettext: UnwrapRef<typeof import('@/gettext')['$ngettext']>
readonly $npgettext: UnwrapRef<typeof import('@/gettext')['$npgettext']>
readonly $pgettext: UnwrapRef<typeof import('@/gettext')['$pgettext']>
readonly EffectScope: UnwrapRef<typeof import('vue')['EffectScope']>
readonly acceptHMRUpdate: UnwrapRef<typeof import('pinia')['acceptHMRUpdate']>
readonly computed: UnwrapRef<typeof import('vue')['computed']>
readonly createApp: UnwrapRef<typeof import('vue')['createApp']>
readonly createPinia: UnwrapRef<typeof import('pinia')['createPinia']>
readonly customRef: UnwrapRef<typeof import('vue')['customRef']>
readonly defineAsyncComponent: UnwrapRef<typeof import('vue')['defineAsyncComponent']>
readonly defineComponent: UnwrapRef<typeof import('vue')['defineComponent']>
readonly defineStore: UnwrapRef<typeof import('pinia')['defineStore']>
readonly effectScope: UnwrapRef<typeof import('vue')['effectScope']>
readonly getActivePinia: UnwrapRef<typeof import('pinia')['getActivePinia']>
readonly getCurrentInstance: UnwrapRef<typeof import('vue')['getCurrentInstance']>
readonly getCurrentScope: UnwrapRef<typeof import('vue')['getCurrentScope']>
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
readonly isReadonly: UnwrapRef<typeof import('vue')['isReadonly']>
readonly isRef: UnwrapRef<typeof import('vue')['isRef']>
readonly mapActions: UnwrapRef<typeof import('pinia')['mapActions']>
readonly mapGetters: UnwrapRef<typeof import('pinia')['mapGetters']>
readonly mapState: UnwrapRef<typeof import('pinia')['mapState']>
readonly mapStores: UnwrapRef<typeof import('pinia')['mapStores']>
readonly mapWritableState: UnwrapRef<typeof import('pinia')['mapWritableState']>
readonly markRaw: UnwrapRef<typeof import('vue')['markRaw']>
readonly nextTick: UnwrapRef<typeof import('vue')['nextTick']>
readonly onActivated: UnwrapRef<typeof import('vue')['onActivated']>
readonly onBeforeMount: UnwrapRef<typeof import('vue')['onBeforeMount']>
readonly onBeforeRouteLeave: UnwrapRef<typeof import('vue-router')['onBeforeRouteLeave']>
readonly onBeforeRouteUpdate: UnwrapRef<typeof import('vue-router')['onBeforeRouteUpdate']>
readonly onBeforeUnmount: UnwrapRef<typeof import('vue')['onBeforeUnmount']>
readonly onBeforeUpdate: UnwrapRef<typeof import('vue')['onBeforeUpdate']>
readonly onDeactivated: UnwrapRef<typeof import('vue')['onDeactivated']>
readonly onErrorCaptured: UnwrapRef<typeof import('vue')['onErrorCaptured']>
readonly onMounted: UnwrapRef<typeof import('vue')['onMounted']>
readonly onRenderTracked: UnwrapRef<typeof import('vue')['onRenderTracked']>
readonly onRenderTriggered: UnwrapRef<typeof import('vue')['onRenderTriggered']>
readonly onScopeDispose: UnwrapRef<typeof import('vue')['onScopeDispose']>
readonly onServerPrefetch: UnwrapRef<typeof import('vue')['onServerPrefetch']>
readonly onUnmounted: UnwrapRef<typeof import('vue')['onUnmounted']>
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly onWatcherCleanup: UnwrapRef<typeof import('vue')['onWatcherCleanup']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
readonly readonly: UnwrapRef<typeof import('vue')['readonly']>
readonly ref: UnwrapRef<typeof import('vue')['ref']>
readonly resolveComponent: UnwrapRef<typeof import('vue')['resolveComponent']>
readonly setActivePinia: UnwrapRef<typeof import('pinia')['setActivePinia']>
readonly setMapStoreSuffix: UnwrapRef<typeof import('pinia')['setMapStoreSuffix']>
readonly shallowReactive: UnwrapRef<typeof import('vue')['shallowReactive']>
readonly shallowReadonly: UnwrapRef<typeof import('vue')['shallowReadonly']>
readonly shallowRef: UnwrapRef<typeof import('vue')['shallowRef']>
readonly storeToRefs: UnwrapRef<typeof import('pinia')['storeToRefs']>
readonly toRaw: UnwrapRef<typeof import('vue')['toRaw']>
readonly toRef: UnwrapRef<typeof import('vue')['toRef']>
readonly toRefs: UnwrapRef<typeof import('vue')['toRefs']>
readonly toValue: UnwrapRef<typeof import('vue')['toValue']>
readonly triggerRef: UnwrapRef<typeof import('vue')['triggerRef']>
readonly unref: UnwrapRef<typeof import('vue')['unref']>
readonly useAttrs: UnwrapRef<typeof import('vue')['useAttrs']>
readonly useCssModule: UnwrapRef<typeof import('vue')['useCssModule']>
readonly useCssVars: UnwrapRef<typeof import('vue')['useCssVars']>
readonly useId: UnwrapRef<typeof import('vue')['useId']>
readonly useLink: UnwrapRef<typeof import('vue-router')['useLink']>
readonly useModel: UnwrapRef<typeof import('vue')['useModel']>
readonly useRoute: UnwrapRef<typeof import('vue-router')['useRoute']>
readonly useRouter: UnwrapRef<typeof import('vue-router')['useRouter']>
readonly useSlots: UnwrapRef<typeof import('vue')['useSlots']>
readonly useTemplateRef: UnwrapRef<typeof import('vue')['useTemplateRef']>
readonly watch: UnwrapRef<typeof import('vue')['watch']>
readonly watchEffect: UnwrapRef<typeof import('vue')['watchEffect']>
readonly watchPostEffect: UnwrapRef<typeof import('vue')['watchPostEffect']>
readonly watchSyncEffect: UnwrapRef<typeof import('vue')['watchSyncEffect']>
}
}

5
app/env.d.ts vendored

@ -1,5 +0,0 @@
declare module '*.svg' {
import React from 'react'
const content: React.FC<React.SVGProps<SVGElement>>
export default content
}

@ -1,11 +0,0 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const i18n = require('./i18n.json')
module.exports = {
input: {
include: ['**/*.js', '**/*.ts', '**/*.vue', '**/*.jsx', '**/*.tsx'],
},
output: {
locales: Object.keys(i18n),
},
}

@ -1,10 +0,0 @@
{
"en": "En",
"zh_CN": "简",
"zh_TW": "繁",
"fr_FR": "Fr",
"es": "Es",
"ru_RU": "Ru",
"vi_VN": "Vi",
"ko_KR": "한글"
}

@ -1,26 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<link href="/favicon.ico" rel="icon">
<meta content="width=device-width,initial-scale=1.0,user-scalable=0" name="viewport">
<style>
body {
height: auto !important;
min-height: 100%;
}
body.dark {
background-color: #141414;
color: #fff;
}
#app {
height: 100%;
}
</style>
<title>Nginx UI</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

@ -1,81 +0,0 @@
{
"name": "nginx-ui-app-next",
"version": "2.0.0-beta.35",
"type": "module",
"scripts": {
"dev": "vite --host",
"typecheck": "vue-tsc --noEmit",
"lint": "eslint . -c .eslintrc.cjs --fix --ext .ts,.vue,.tsx,.d.ts",
"build": "vite build",
"preview": "vite preview",
"gettext:extract": "vue-gettext-extract"
},
"dependencies": {
"@0xjacky/vue-github-button": "^3.1.1",
"@ant-design/icons-vue": "^7.0.1",
"@formkit/auto-animate": "^0.8.2",
"@simplewebauthn/browser": "^10.0.0",
"@vue/reactivity": "^3.5.6",
"@vue/shared": "^3.5.6",
"@vueuse/components": "^11.1.0",
"@vueuse/core": "^11.1.0",
"@vueuse/integrations": "^11.1.0",
"@xterm/addon-attach": "^0.11.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
"ant-design-vue": "^4.2.4",
"apexcharts": "^3.53.0",
"axios": "^1.7.7",
"dayjs": "^1.11.13",
"highlight.js": "^11.10.0",
"lodash": "^4.17.21",
"marked": "^10.0.0",
"nprogress": "^0.2.0",
"pinia": "^2.2.2",
"pinia-plugin-persistedstate": "^3.2.3",
"reconnecting-websocket": "^4.4.0",
"sortablejs": "^1.15.3",
"universal-cookie": "^7.2.0",
"vite-plugin-build-id": "0.3.6",
"vue": "^3.5.6",
"vue-router": "^4.4.5",
"vue3-ace-editor": "2.2.4",
"vue3-apexcharts": "1.5.3",
"vue3-gettext": "3.0.0-beta.6",
"vue3-otp-input": "^0.5.21",
"vuedraggable": "^4.1.0"
},
"devDependencies": {
"@antfu/eslint-config-vue": "^0.43.1",
"@simplewebauthn/types": "^10.0.0",
"@types/lodash": "^4.17.7",
"@types/nprogress": "^0.2.3",
"@types/sortablejs": "^1.15.8",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"@vitejs/plugin-vue": "^5.1.3",
"@vitejs/plugin-vue-jsx": "^4.0.1",
"@vue/compiler-sfc": "^3.5.6",
"@vue/tsconfig": "^0.5.1",
"ace-builds": "^1.36.2",
"autoprefixer": "^10.4.20",
"eslint": "^8.57.1",
"eslint-import-resolver-alias": "^1.1.2",
"eslint-import-resolver-typescript": "^3.6.3",
"eslint-plugin-import": "^2.30.0",
"eslint-plugin-regex": "^1.10.0",
"eslint-plugin-sonarjs": "^0.23.0",
"eslint-plugin-vue": "^9.28.0",
"less": "^4.2.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.11",
"typescript": "5.3.3",
"unplugin-auto-import": "^0.18.3",
"unplugin-vue-components": "^0.27.4",
"unplugin-vue-define-options": "^1.5.1",
"vite": "^5.4.6",
"vite-svg-loader": "^5.1.0",
"vue-tsc": "^2.1.6"
},
"packageManager": "pnpm@9.10.0"
}

File diff suppressed because it is too large Load Diff

@ -1,6 +0,0 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

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

Loading…
Cancel
Save