Compare commits

..
39 Commits
Author SHA1 Message Date
Kevin Yue 2bce296f05 chore: cut 2.3.13 2026-04-19 11:03:27 +08:00
Kevin Yue 0e32dab997 fix: update 2.3.x package and release flow 2026-04-19 10:58:39 +08:00
Kevin Yue 6db0ed726a ci: rename publish to publish-ppa 2026-04-19 09:43:54 +08:00
Kevin Yue 2a089f69d1 ci: align release workflow matrix with build 2026-04-19 09:24:55 +08:00
Kevin Yue ef4770c0dd Release 2.3.12 2026-04-19 09:00:50 +08:00
Kevin Yue 21822074a8 fix: support custom VPN ports on 2.3.x 2026-04-19 08:37:05 +08:00
Kevin Yue e0db4631ca chore: pin vendored openssl in lockfile 2026-04-19 00:46:43 +08:00
Kevin Yue e733b38ab7 refactor: backport xmltree parser migration to 2.3.x 2026-04-19 00:40:00 +08:00
Kevin Yue c206e72885 docs: note epel and restore rpm appindicator deps 2026-04-19 00:24:59 +08:00
Kevin Yue c1f00aca82 chore: refresh lockfile deps for Rust 1.71 2026-04-19 00:13:18 +08:00
Kevin Yue d28c567e95 chore: add ayatana appindicator rpm runtime dep 2026-04-19 00:00:27 +08:00
Kevin Yue e305af607b chore: add ayatana appindicator rpm build dep 2026-04-18 23:53:31 +08:00
Kevin Yue af903f5d5b ci: run build-gp on arm64 2026-04-18 23:28:54 +08:00
Kevin Yue 745e72892d ci: always include arm64 in build matrix 2026-04-18 23:25:01 +08:00
Kevin Yue ce7df6ea5c ci: add 2.3.x branch to workflow triggers 2026-04-18 23:18:09 +08:00
Kevin Yue a269a60e93 Merge pull request #593 from yuezk/codex/backport-openconnect-2.3 2026-04-18 11:16:11 -04:00
Kevin Yue 3bb27f0193 ci: use GitHub hosted arm action runner 2026-04-18 23:05:38 +08:00
Kevin Yue 3028224bd2 backport browser flag default value support 2026-04-18 23:01:26 +08:00
Kevin Yue 2576b08a89 backport remote browser and arm64 runner updates 2026-04-18 22:54:25 +08:00
Kevin Yue 19106150dd fix: bump wry to 0.24.12 2026-04-18 22:26:37 +08:00
Kevin Yue 11c4a16f73 fix: fall back to direct gmp linking 2026-04-18 22:05:59 +08:00
Kevin Yue 90d3f409d6 fix: force utf-8 locale for debmake 2026-04-18 21:55:36 +08:00
Kevin Yue 56835a5c4d ci: add 2.3.x pull request builds 2026-04-18 21:42:12 +08:00
Kevin Yue 46564ed65d ci: only run 2.3.x builds for pull requests 2026-04-18 21:40:52 +08:00
Kevin Yue 06a25354a7 Revert "ci: use tauri2 builders for 2.3.x pushes"
This reverts commit 7e4f65b1c8.
2026-04-18 21:39:14 +08:00
Kevin Yue 7e4f65b1c8 ci: use tauri2 builders for 2.3.x pushes 2026-04-18 21:37:29 +08:00
Kevin Yue fd4702c2f4 ci: use artifact actions v4 2026-04-18 21:28:38 +08:00
Kevin Yue 8785f7308a ci: use artifact actions v4 2026-04-18 21:28:22 +08:00
Kevin Yue e18d6d3ed0 ci: trigger 2.3.x pull request builds 2026-04-18 21:26:49 +08:00
Kevin Yue f754a7f3c7 Backport vendored openconnect and HIP flow 2026-04-18 20:21:10 +08:00
Kevin Yue 51c55376e8 ci: use gh to download release asset 2025-01-21 22:48:40 +08:00
Kevin Yue 26d5d5bcf0 Release 2.3.11 2025-01-21 21:37:56 +08:00
Kevin Yue b99053718a ci: upload offline tarball 2025-01-21 21:11:03 +08:00
Kevin Yue 6e603c84b3 chore: pin rust version 1.71.1 2025-01-21 20:18:06 +08:00
Kevin Yue eeb60125e6 ci: update publish PPA action 2025-01-21 00:54:43 +08:00
Kevin Yue 875c463bc2 ci: update publish PPA action 2025-01-21 00:46:03 +08:00
Kevin Yue 8cc73df3d6 Release 2.3.10 2025-01-21 00:06:02 +08:00
Kevin Yue fd3ff7b0de Do not use default value for os version 2025-01-21 00:05:46 +08:00
Kevin Yue 72a83f12d0 fix: disconnect VPN when sleep 2025-01-20 20:17:18 +08:00
173 changed files with 7826 additions and 21467 deletions

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
BasedOnStyle: LLVM
IndentWidth: 8
TabWidth: 8
UseTab: Always
ColumnLimit: 80
BreakBeforeBraces: Linux
+20 -38
View File
@@ -1,4 +1,4 @@
FROM ubuntu:22.04
FROM ubuntu:18.04
ARG USERNAME=vscode
ARG USER_UID=1000
@@ -7,63 +7,45 @@ ARG USER_GID=$USER_UID
ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:$PATH \
RUST_VERSION=1.89.0 \
DEBIAN_FRONTEND=noninteractive
RUST_VERSION=1.75.0
# Install all system dependencies in a single layer and clean up apt cache
RUN set -eux; \
apt-get update; \
apt-get install -y --no-install-recommends \
# Common utilities
dh-autoreconf \
sudo \
ca-certificates \
curl \
gnupg \
git \
less \
wget \
file \
software-properties-common \
# libopenconnect-dev to install the related dependencies for building openconnect from source
# Otherwise, we have to install them manually one by one
libopenconnect-dev \
# Tauri dependencies
libwebkit2gtk-4.1-dev \
build-essential \
libxdo-dev \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev; \
# Clean up apt cache to reduce image size
apt-get clean; \
rm -rf /var/lib/apt/lists/*
# Create a non-root user
RUN set -eux; \
libwebkit2gtk-4.0-dev build-essential wget libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev; \
# Install openconnect
add-apt-repository ppa:yuezk/globalprotect-openconnect; \
apt-get update; \
apt-get install -y openconnect libopenconnect-dev; \
# Create a non-root user
groupadd --gid $USER_GID $USERNAME; \
useradd --uid $USER_UID --gid $USER_GID -m $USERNAME; \
echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME; \
chmod 0440 /etc/sudoers.d/$USERNAME
# Install Rust
RUN set -eux; \
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION --profile minimal; \
chmod 0440 /etc/sudoers.d/$USERNAME; \
# Install Node.js
mkdir -p /etc/apt/keyrings; \
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg; \
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_16.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list; \
apt-get update; \
apt-get install -y nodejs; \
corepack enable; \
# Install diff-so-fancy
npm install -g diff-so-fancy; \
# Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION; \
chown -R $USERNAME:$USERNAME $RUSTUP_HOME $CARGO_HOME; \
rustup --version; \
cargo --version; \
rustc --version
# Install Node.js and global npm packages
RUN set -eux; \
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -; \
apt-get install -y --no-install-recommends nodejs; \
corepack enable; \
npm install -g diff-so-fancy; \
# Clean up apt cache
apt-get clean; \
rm -rf /var/lib/apt/lists/*
USER $USERNAME
# Install Oh My Zsh
-6
View File
@@ -1,6 +0,0 @@
.build
.git
.vendor
apps/gpgui-helper/node_modules
target
vendor.tar.xz
-4
View File
@@ -8,9 +8,5 @@ end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[{*.c,*.h}]
indent_style = tab
indent_size = 8
[{Makefile,Makefile.in}]
indent_style = tab
+70 -483
View File
@@ -1,25 +1,5 @@
name: Build
on:
workflow_dispatch:
inputs:
gp_branch:
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
required: true
default: dev
gpgui_branch:
description: 'gpgui branch to use for the snapshot release'
required: true
default: dev
build_bsd:
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
required: true
default: false
type: boolean
build_bsd_arm64:
description: 'Build optional FreeBSD/OpenBSD arm64 packages for the snapshot release. Slow and disabled by default'
required: true
default: false
type: boolean
push:
paths-ignore:
- LICENSE
@@ -28,35 +8,59 @@ on:
- .devcontainer
branches:
- main
- dev
- 2.3.x
- hotfix/*
- feature/*
- release/*
tags:
- v*.*.*
pull_request:
paths-ignore:
- LICENSE
- "*.md"
- .vscode
- .devcontainer
branches:
- 2.3.x
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
GP_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.ref }}
GPGUI_REF: ${{ github.event_name == 'pull_request' && github.base_ref || github.ref_name }}
jobs:
# Always include arm64
setup-matrix:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- name: Set up matrix
id: set-matrix
run: |
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "ubuntu-24.04-arm", "arch": "ubuntu-24.04-arm"}]' >> $GITHUB_OUTPUT
tarball:
runs-on: ubuntu-latest
needs: [setup-matrix]
steps:
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v2
with:
version: 9
version: 8
- name: Prepare workspace
run: rm -rf source && mkdir -p source/artifacts
run: rm -rf source && mkdir source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
uses: actions/checkout@v3
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
ref: ${{ env.GP_REF }}
path: source/gp
submodules: recursive
- name: Create tarball
run: |
cd source/gp
@@ -65,44 +69,29 @@ jobs:
touch SNAPSHOT
fi
make tarball
mv -v .build/tarball/*.tar.gz ../artifacts/
- name: Generate RPM spec file
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
cd source/gp
make init-rpm \
REVISION='1%{?dist}' \
RPM_SOURCE=https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${RELEASE_TAG}/%{name}-%{version}.tar.gz
mv -v .build/rpm/*.spec ../artifacts/
- name: Upload tarball
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-source
if-no-files-found: error
path: |
source/artifacts/*
source/gp/.build/tarball/*.tar.gz
tarball-offline:
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
if: ${{ startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
needs:
- tarball
steps:
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v2
with:
version: 9
version: 8
- name: Prepare workspace
run: rm -rf source-offline && mkdir source-offline
- name: Download tarball
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
name: artifact-source
path: source-offline
@@ -123,7 +112,7 @@ jobs:
mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
path: source-offline/*.offline.tar.gz
name: artifact-source-offline
@@ -131,16 +120,12 @@ jobs:
build-gp:
needs:
- setup-matrix
- tarball
strategy:
fail-fast: false
matrix:
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
package: [deb, rpm, pkg, apk, binary, ubuntu-rolling]
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
package: [deb, rpm, pkg, binary]
runs-on: ${{ matrix.os.runner }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
steps:
@@ -149,134 +134,61 @@ jobs:
rm -rf build-gp-${{ matrix.package }}
mkdir -p build-gp-${{ matrix.package }}
- name: Download tarball
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
name: artifact-source
path: build-gp-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: |
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
docker run --rm \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2
-v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \
yuezk/gpdev:${{ matrix.package }}-builder
- name: Install ${{ matrix.package }} package in Docker
run: |
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
docker run --rm \
-e GPGUI_INSTALLED=0 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
-v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \
yuezk/gpdev:${{ matrix.package }}-builder \
bash install.sh
# Don't upload package for ubuntu-rolling because it's duplicate of deb package
- name: Upload ${{ matrix.package }} package
if: ${{ matrix.package != 'ubuntu-rolling' }}
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
build-gp-${{ matrix.package }}/artifacts/*
build-docker-image:
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: .
file: packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
build-gpgui:
needs:
- setup-matrix
strategy:
fail-fast: false
matrix:
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
libc:
- name: glibc
builder: gpgui-builder-tauri2
artifact_suffix: ""
- name: musl
builder: gpgui-alpine-builder-tauri2
artifact_suffix: "-musl"
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.libc.name }}, ${{ matrix.os.arch }})
name: build-gpgui (${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v2
with:
version: 9
version: 8
- name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
uses: actions/checkout@v3
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
ref: ${{ env.GP_REF }}
path: gpgui-source/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
- name: Checkout gpgui@${{ env.GPGUI_REF }}
uses: actions/checkout@v3
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
ref: ${{ env.GPGUI_REF }}
path: gpgui-source/gpgui
- name: Tarball
run: |
@@ -286,376 +198,51 @@ jobs:
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build gpgui in Docker
run: |
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
docker run --rm -e LIBXML2_STATIC=1 -v $(pwd)/gpgui-source:/gpgui yuezk/gpdev:gpgui-builder
- name: Install gpgui in Docker
run: |
cd gpgui-source
tar -xJf *.bin.tar.xz
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
docker run --rm -v $(pwd):/gpgui yuezk/gpdev:gpgui-builder \
bash -c "cd /gpgui/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-gpgui${{ matrix.libc.artifact_suffix }}-${{ matrix.os.arch }}
name: artifact-gpgui-${{ matrix.os.arch }}
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256
setup-bsd-matrix:
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.matrix.outputs.enabled }}
matrix: ${{ steps.matrix.outputs.matrix }}
steps:
- name: Build matrix
id: matrix
env:
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
BUILD_BSD: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd }}
BUILD_BSD_ARM64: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd_arm64 }}
run: |
python3 - <<'PY'
import json
import os
build_bsd = os.environ["IS_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
build_bsd_arm64 = os.environ["BUILD_BSD_ARM64"] == "true"
include = []
def add(os_name, arch):
include.append({
"os": os_name,
"arch": arch,
"workspace": f"{os_name}-{arch}-source",
"artifact": f"artifact-bsd-{os_name}-{arch}",
"package_target": f"package-{os_name}",
"artifact_dir": os_name,
})
if build_bsd:
add("freebsd", "x86_64")
add("openbsd", "x86_64")
if build_bsd_arm64:
add("freebsd", "arm64")
add("openbsd", "arm64")
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
output.write(f"enabled={str(bool(include)).lower()}\n")
output.write(f"matrix={json.dumps({'include': include}, separators=(',', ':'))}\n")
PY
build-gpgui-frontend:
needs: setup-bsd-matrix
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-frontend && mkdir gpgui-frontend
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gpgui-frontend/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: gpgui-frontend/gpgui
- name: Build gpgui frontend
run: |
cd gpgui-frontend/gpgui/app
pnpm install --frozen-lockfile
pnpm build
- name: Upload gpgui frontend
uses: actions/upload-artifact@v7
with:
name: bsd-gpgui-frontend
if-no-files-found: error
path: gpgui-frontend/gpgui/app/dist/**
build-bsd:
needs:
- setup-bsd-matrix
- build-gpgui-frontend
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
runs-on: ubuntu-latest
name: build-${{ matrix.os }} (${{ matrix.arch }})
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-bsd-matrix.outputs.matrix) }}
steps:
- name: Prepare workspace
run: rm -rf "${{ matrix.workspace }}" && mkdir "${{ matrix.workspace }}"
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: ${{ matrix.workspace }}/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: ${{ matrix.workspace }}/gpgui
- name: Download gpgui frontend
uses: actions/download-artifact@v8
with:
name: bsd-gpgui-frontend
path: ${{ matrix.workspace }}/gpgui/app/dist
- name: Build on FreeBSD
if: ${{ matrix.os == 'freebsd' }}
uses: vmactions/freebsd-vm@v1
with:
release: "14.3"
arch: ${{ matrix.arch }}
usesh: true
prepare: |
pkg install -y \
git \
rust \
libiconv \
gettext-tools \
autoconf \
automake \
libtool \
patch \
gmake \
pkgconf \
libxml2 \
gnutls \
p11-kit \
nettle \
gmp \
gnome-keyring \
libayatana-appindicator \
polkit \
webkit2-gtk_41
run: |
set -eu
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/app/src-tauri
cargo build --release --workspace
cd ../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Build on OpenBSD
if: ${{ matrix.os == 'openbsd' }}
uses: vmactions/openbsd-vm@v1
with:
release: "7.9"
arch: ${{ matrix.arch }}
usesh: true
prepare: |
pkg_add -z \
git \
rust \
libiconv \
gettext-tools \
autoconf-2.72 \
automake-1.17 \
libtool \
patch \
gmake \
pkgconf \
libxml \
gnutls \
p11-kit \
nettle \
gmp \
gnome-keyring \
polkit \
webkitgtk41
ln -sf /usr/local/bin/autoreconf-2.72 /usr/local/bin/autoreconf
ln -sf /usr/local/bin/autoconf-2.72 /usr/local/bin/autoconf
ln -sf /usr/local/bin/autoheader-2.72 /usr/local/bin/autoheader
ln -sf /usr/local/bin/autom4te-2.72 /usr/local/bin/autom4te
ln -sf /usr/local/bin/aclocal-1.17 /usr/local/bin/aclocal
ln -sf /usr/local/bin/automake-1.17 /usr/local/bin/automake
run: |
set -eu
export AUTOCONF_VERSION=2.72
export AUTOMAKE_VERSION=1.17
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/app/src-tauri
cargo build --release --workspace
cd ../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Upload BSD package
uses: actions/upload-artifact@v7
with:
name: ${{ matrix.artifact }}
if-no-files-found: error
path: |
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
gh-release:
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }}
if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
needs:
- tarball
- tarball-offline
- build-gp
- build-docker-image
- build-gpgui
- setup-bsd-matrix
- build-gpgui-frontend
- build-bsd
steps:
- name: Check required jobs
env:
NEEDS_JSON: ${{ toJson(needs) }}
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
run: |
python3 - <<'PY'
import json
import os
import sys
needs = json.loads(os.environ["NEEDS_JSON"])
bsd_matrix_enabled = os.environ["BSD_MATRIX_ENABLED"] == "true"
failed = []
for name, data in needs.items():
result = data["result"]
if result in {"failure", "cancelled"}:
failed.append(f"{name}: {result}")
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
continue
elif result == "skipped":
failed.append(f"{name}: {result}")
if failed:
print("Required jobs did not complete successfully:")
for item in failed:
print(f" - {item}")
sys.exit(1)
PY
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
uses: actions/checkout@v3
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
ref: ${{ github.ref }}
path: gh-release/gp
submodules: recursive
- name: Download all artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
path: gh-release/gp/.build/artifacts
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-amd64/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-ubuntu-24.04-arm/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Generate release asset checksums
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-assets.sh "$RELEASE_TAG" > .build/release-assets.txt
if [ ! -s .build/release-assets.txt ]; then
echo "No release assets found"
exit 1
fi
while IFS= read -r file; do
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
printf '%s %s\n' "$digest" "$(basename "$file")"
done < .build/release-assets.txt > .build/release-assets.sha256
- name: Attest release assets
uses: actions/attest-build-provenance@v4
with:
subject-checksums: gh-release/gp/.build/release-assets.sha256
- name: Create GH release
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }}
run: |
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
publish-docker-image:
needs:
- build-docker-image
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
docker buildx imagetools create -t "$IMAGE:$RELEASE_TAG" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$RELEASE_TAG"
-142
View File
@@ -1,142 +0,0 @@
name: Publish AUR git package
on:
workflow_dispatch:
inputs:
build-package:
type: boolean
description: "Build the package before publishing"
required: true
default: true
publish:
type: boolean
description: "Push PKGBUILD, .SRCINFO, and gp.install to AUR"
required: true
default: true
push:
branches:
- main
paths:
- packaging/aur/globalprotect-openconnect-git/**
- .github/workflows/publish-aur-git.yaml
permissions:
contents: read
jobs:
aur:
runs-on: ubuntu-latest
container: archlinux:base-devel
defaults:
run:
shell: bash
env:
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
steps:
- name: Install checkout tools
run: pacman -Syu --noconfirm --needed git openssh
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install build tools
run: |
pacman -Syu --noconfirm --needed \
appmenu-gtk-module \
cargo \
curl \
desktop-file-utils \
file \
git \
libappindicator-gtk3 \
libsecret \
libxml2 \
namcap \
openconnect \
openssl \
pkgconf \
librsvg \
shared-mime-info \
vpnc \
wget \
webkit2gtk-4.1
- name: Save committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: cp "$AUR_PACKAGE_DIR/.SRCINFO" /tmp/committed.SRCINFO
- name: Prepare build user
run: |
useradd -m builder
chown -R builder:builder "$GITHUB_WORKSPACE"
- name: Refresh VCS package version
if: ${{ github.event_name == 'workflow_dispatch' }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --nobuild --noconfirm --cleanbuild
- name: Regenerate .SRCINFO
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --printsrcinfo > .SRCINFO
- name: Check committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: |
cmp -s /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO" || {
diff -u /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO"
echo ".SRCINFO is out of date. Regenerate it with makepkg --printsrcinfo." >&2
exit 1
}
- name: Run namcap
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- namcap PKGBUILD
- name: Build package
if: ${{ github.event_name == 'workflow_dispatch' && inputs['build-package'] }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --noconfirm --clean --cleanbuild
- name: Configure SSH
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
env:
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
run: |
if [[ -z "$AUR_SSH_PRIVATE_KEY" ]]; then
echo "AUR_SSH_PRIVATE_KEY is required to publish to AUR" >&2
exit 1
fi
install -d -m 700 ~/.ssh
printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > ~/.ssh/aur
chmod 600 ~/.ssh/aur
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
- name: Publish to AUR
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
env:
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
run: |
workdir="$(mktemp -d)"
git clone "$AUR_REPO" "$workdir/aur"
cp "$AUR_PACKAGE_DIR"/PKGBUILD "$workdir/aur/PKGBUILD"
cp "$AUR_PACKAGE_DIR"/.SRCINFO "$workdir/aur/.SRCINFO"
cp "$AUR_PACKAGE_DIR"/gp.install "$workdir/aur/gp.install"
cd "$workdir/aur"
if git diff --quiet; then
echo "AUR package is already up to date"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add PKGBUILD .SRCINFO gp.install
git commit -m "Update globalprotect-openconnect-git"
git push origin master
+46 -103
View File
@@ -8,111 +8,65 @@ on:
required: true
revision:
description: 'Package revision'
required: false
default: "1"
series:
description: 'Space-separated Ubuntu series. Leave empty to publish all supported series.'
type: "string"
required: false
default: ""
rust:
description: 'Rust version to use'
type: "string"
required: true
default: "1.89"
default: "1"
ppa:
description: 'Publish to PPA'
type: boolean
required: true
default: true
obs:
description: 'Publish to OBS'
type: boolean
required: true
default: true
aur:
description: 'Publish to AUR'
type: boolean
required: true
default: true
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Check tag exists
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
uses: mukunku/[email protected]
id: check-tag
with:
tag: ${{ inputs.tag }}
- name: Exit if tag does not exist
run: |
if ! gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null 2>&1; then
echo "Tag $TAG does not exist"
if [[ "${{ steps.check-tag.outputs.exists }}" == "false" ]]; then
echo "Tag ${{ inputs.tag }} does not exist"
exit 1
fi
resolve-series:
needs: check
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.resolve.outputs.matrix }}
steps:
- name: Resolve Ubuntu series
id: resolve
env:
INPUT_SERIES: ${{ inputs.series }}
run: |
sudo apt-get update
sudo apt-get install -y distro-info distro-info-data
if [[ "$INPUT_SERIES" == *","* ]]; then
echo "Use space-separated series, for example: jammy noble" >&2
exit 1
fi
series=()
if [[ -z "${INPUT_SERIES// }" ]]; then
while IFS= read -r item; do
[[ -n "$item" ]] && series+=("$item")
done < <(ubuntu-distro-info --supported)
else
read -r -a series <<< "$INPUT_SERIES"
fi
if [[ "${#series[@]}" -eq 0 ]]; then
echo "No Ubuntu series resolved" >&2
exit 1
fi
for item in "${series[@]}"; do
ubuntu-distro-info --series "$item" >/dev/null
done
matrix="$(printf '%s\n' "${series[@]}" | jq -R . | jq -s -c '{series: .}')"
echo "Resolved matrix: $matrix"
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
publish-ppa:
needs: [check, resolve-series]
name: publish-ppa (${{ matrix.series }})
needs: check
if: ${{ inputs.ppa }}
runs-on: ubuntu-latest
container:
image: ubuntu:${{ matrix.series }}
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.resolve-series.outputs.matrix) }}
steps:
- name: Install container tools
run: |
apt-get update
apt-get install -y ca-certificates curl gpg sudo
mkdir -p /etc/apt/keyrings
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
| gpg --dearmor -o /etc/apt/keyrings/githubcli-archive-keyring.gpg
chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list
apt-get update
apt-get install -y gh
- uses: pnpm/action-setup@v2
with:
version: 8
- name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} offline source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*.offline.tar.gz' \
--dir publish-ppa
uses: robinraju/[email protected]
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.offline.tar.gz
tarBall: false
zipBall: false
out-file-path: publish-ppa
- name: Patch the source code
run: |
cd publish-ppa
# Rename the source tarball without the offline suffix
mv -v *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
mv *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
# Extract the source tarball
tar -xzf *.tar.gz
@@ -120,32 +74,21 @@ jobs:
# Prepare the debian directory with custom files
cd globalprotect-openconnect-*/
# Prepare the debian directory with custom files
mkdir -p .build/debian
cp -v packaging/deb/control.in .build/debian/control
cp -v packaging/deb/rules.in .build/debian/rules
cp -v packaging/deb/compat .build/debian/compat
cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@BUILD_GUI_HELPER@/1/g" .build/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/1/g" .build/debian/rules
# Update the control file with the correct Rust version
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/rules
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
sed 's/@RUST@/rust-all(>=1.71)/g' packaging/deb/control.in > .build/debian/control
sed 's/@OFFLINE@/1/g' packaging/deb/rules.in > .build/debian/rules
cp packaging/deb/postrm .build/debian/postrm
- name: Publish to PPA
uses: yuezk/publish-ppa-package@gp
uses: yuezk/publish-ppa-package@gp_2.3.x
with:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: ${{ vars.DEB_EMAIL }}
deb_fullname: ${{ vars.DEB_FULLNAME }}
extra_ppa: "yuezk/globalprotect-openconnect"
series: ${{ matrix.series }}
deb_email: "[email protected]"
deb_fullname: "Kevin Yue"
extra_ppa: "yuezk/globalprotect-openconnect liushuyu-011/rust-bpo-1.75"
series: "bionic focal"
revision: ${{ inputs.revision }}
+20 -179
View File
@@ -30,21 +30,11 @@ on:
description: 'Build PKG package'
required: true
default: true
release-apk:
type: boolean
description: 'Build APK package'
required: true
default: true
release-binary:
type: boolean
description: 'Build binary package'
required: true
default: true
release-docker:
type: boolean
description: 'Publish Docker image'
required: true
default: true
gh-release:
type: boolean
description: 'Update GitHub release'
@@ -83,13 +73,16 @@ jobs:
const inputs = ${{ toJson(inputs) }}
const { arch } = inputs
const osMap = {
"all": ["ubuntu-latest", "ubuntu-24.04-arm"],
"x86_64": ["ubuntu-latest"],
"arm64": ["ubuntu-24.04-arm"]
"all": [
{ runner: "ubuntu-latest", arch: "amd64" },
{ runner: "ubuntu-24.04-arm", arch: "ubuntu-24.04-arm" },
],
"x86_64": [{ runner: "ubuntu-latest", arch: "amd64" }],
"arm64": [{ runner: "ubuntu-24.04-arm", arch: "ubuntu-24.04-arm" }],
}
const package = Object.entries(inputs)
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value)
.filter(([key, value]) => key.startsWith('release-') && value)
.map(([key, value]) => key.replace('release-', ''))
return JSON.stringify({
@@ -102,7 +95,8 @@ jobs:
- setup-matrix
strategy:
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }}
runs-on: ${{ matrix.os }}
runs-on: ${{ matrix.os.runner }}
name: build (${{ matrix.package }}, ${{ matrix.os.arch }})
steps:
- name: Prepare workspace
run: rm -rf build-${{ matrix.package }} && mkdir -p build-${{ matrix.package }}
@@ -119,194 +113,40 @@ jobs:
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: |
docker run --pull=always --rm \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
-e COREPACK_INTEGRITY_KEYS=0 \
docker run --rm \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
-e INCLUDE_GUI=1 \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2
yuezk/gpdev:${{ matrix.package }}-builder
- name: Install ${{ matrix.package }} package in Docker
run: |
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
docker run --rm \
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
yuezk/gpdev:${{ matrix.package }}-builder \
bash install.sh
- name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-${{ matrix.os }}-${{ matrix.package }}
name: artifact-${{ matrix.os.arch }}-${{ matrix.package }}
if-no-files-found: error
path: |
build-${{ matrix.package }}/artifacts/*
build-docker-image:
needs:
- check
if: ${{ inputs.release-docker }}
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Prepare workspace
run: rm -rf docker-image && mkdir -p docker-image/source
- name: Download ${{ inputs.tag }} source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir docker-image
tar -xzf docker-image/*.tar.gz -C docker-image/source --strip-components=1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: docker-image/source
file: docker-image/source/packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
publish-docker-image:
needs:
- build-docker-image
if: ${{ inputs.release-docker }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
TAG: ${{ inputs.tag }}
run: |
VERSION="${TAG#v}"
tags=(-t "$IMAGE:$TAG")
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
tags+=(-t "$IMAGE:$VERSION" -t "$IMAGE:latest")
fi
docker buildx imagetools create "${tags[@]}" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$TAG"
gh-release:
needs:
- build
runs-on: ubuntu-latest
if: ${{ inputs.gh-release }}
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
steps:
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
path: gh-release/gp
submodules: recursive
- name: Download artifact
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
path: gh-release
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/artifact-ubuntu-latest-apk/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Generate release asset checksums
id: release-assets
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-assets.sh all "$GITHUB_WORKSPACE/gh-release" > .build/release-assets.txt
if [ ! -s .build/release-assets.txt ]; then
echo "No release assets found"
exit 1
fi
while IFS= read -r file; do
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
printf '%s %s\n' "$digest" "$(basename "$file")"
done < .build/release-assets.txt > .build/release-assets.sha256
{
echo 'files<<EOF'
cat .build/release-assets.txt
echo EOF
} >> "$GITHUB_OUTPUT"
- name: Attest release assets
uses: actions/attest-build-provenance@v4
with:
subject-checksums: gh-release/gp/.build/release-assets.sha256
- name: Update release
uses: softprops/action-gh-release@v1
with:
@@ -314,4 +154,5 @@ jobs:
prerelease: ${{ contains(github.ref, 'snapshot') }}
fail_on_unmatched_files: true
tag_name: ${{ inputs.tag }}
files: ${{ steps.release-assets.outputs.files }}
files: |
gh-release/artifact-*/*
@@ -1,69 +0,0 @@
name: Update flake hashes
on:
workflow_dispatch:
inputs:
version:
description: "Release version. Defaults to Cargo.toml workspace version."
required: false
release:
types:
- published
permissions:
contents: write
pull-requests: write
jobs:
update-flake-hashes:
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Update flake hashes
env:
RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }}
run: |
if [[ -n "$RELEASE_VERSION" ]]; then
scripts/update-flake-hashes.sh "$RELEASE_VERSION"
else
scripts/update-flake-hashes.sh
fi
- name: Open pull request
env:
GH_TOKEN: ${{ github.token }}
RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }}
run: |
if git diff --quiet -- flake.nix; then
echo "flake.nix hashes are already up to date"
exit 0
fi
version="${RELEASE_VERSION:-$(grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')}"
version="${version#v}"
branch="chore/update-flake-hashes-v${version}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -c "$branch"
git add flake.nix
git commit -m "chore: update flake hashes for v${version}"
git push --force-with-lease origin "$branch"
if gh pr view "$branch" --json number > /tmp/flake-pr.json 2> /dev/null; then
pr_number="$(jq -r '.number' /tmp/flake-pr.json)"
gh pr edit "$pr_number" \
--title "chore: update flake hashes for v${version}" \
--body "Updates the Nix flake fetchzip hashes for v${version} release assets."
else
gh pr create \
--title "chore: update flake hashes for v${version}" \
--body "Updates the Nix flake fetchzip hashes for v${version} release assets." \
--base main \
--head "$branch"
fi
-7
View File
@@ -8,10 +8,3 @@
.cargo
.build
SNAPSHOT
SOURCE_COMMIT
# Tauri generated files
gen
# Nix files
result
-14
View File
@@ -1,14 +0,0 @@
{
"configurations": [
{
"name": "Mac",
"includePath": ["crates/openconnect/deps/openconnect"],
"macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"],
"intelliSenseMode": "macos-clang-x64",
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++17"
}
],
"version": 4
}
-11
View File
@@ -23,12 +23,8 @@
"gpgui",
"gpservice",
"hidpi",
"Ivars",
"jnlp",
"LOGNAME",
"NSHTTPURL",
"NSURL",
"objc",
"oneshot",
"openconnect",
"pkcs",
@@ -59,16 +55,9 @@
"Vite",
"vpnc",
"vpninfo",
"webbrowser",
"wmctrl",
"XAUTHORITY",
"yuezk"
],
"rust-analyzer.cargo.features": "all",
"files.associations": {
"unistd.h": "c",
"utsname.h": "c",
"vpn.h": "c",
"openconnect.h": "c"
},
}
Generated
+1875 -2263
View File
File diff suppressed because it is too large. Load diff
+18 -23
View File
@@ -10,60 +10,55 @@ members = [
]
[workspace.package]
rust-version = "1.89"
version = "2.6.0"
rust-version = "1.71.1"
version = "2.3.13"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024"
edition = "2021"
license = "GPL-3.0"
[workspace.dependencies]
anyhow = "1.0"
askama = "0.16"
base64 = "0.22"
chrono = "0.4"
clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3"
clap = { version = "~4.4.2", features = ["derive"] }
ctrlc = "3.4"
directories = "6.0"
dns-lookup = "3"
directories = "5.0"
dns-lookup = "2.0.4"
env_logger = "0.11"
is_executable = "1.0"
log = "0.4"
regex = "1"
reqwest = { version = "0.13", features = ["native-tls", "json", "form", "query"] }
reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] }
openssl = "0.10"
pem = "3"
xmltree = { version = "0.12", features = ["attribute-order"] }
xmltree = "0.11"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Use 0.36 as newer versions requires Rust 1.88+
sysinfo = "0.36"
sysinfo = "0.30"
tempfile = "3.8"
tokio = { version = "1" }
tokio-util = "0.7"
url = "2.4"
urlencoding = "2.1.3"
axum = "0.8"
axum = "0.7"
futures = "0.3"
futures-util = "0.3"
tokio-tungstenite = "0.26.1"
uzers = "0.12"
whoami = "2"
whoami = "1"
thiserror = "2"
redact-engine = "0.1"
compile-time = "0.2"
serde_urlencoded = "0.7"
md5 = "0.8"
md5 = "0.7"
sha256 = "1"
which = "8"
uuid = "1"
netdev = "0.40"
humantime = "2"
which = "7"
# Tauri dependencies
tauri = { version = "2" }
specta = "=2.0.0-rc.20"
proptest = "1"
tauri = { version = "1" }
specta = "=2.0.0-rc.1"
specta-macros = "=2.0.0-rc.1"
rspc = { version = "1.0.0-rc.5", features = ["tauri"] }
[profile.release]
opt-level = 'z' # Optimize for size
+43 -204
View File
@@ -1,50 +1,21 @@
SHELL := /bin/sh
.SHELLFLAGS := -ec
.SHELLFLAGS += -e
OFFLINE ?= 0
BUILD_FE ?= 1
INCLUDE_GUI ?= 0
CARGO ?= cargo
DISABLE_RUST_TOOLCHAIN ?= 0
RUST_VERSION ?= 1.89
IGNORE_RUST_VERSION ?= 0
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
SOURCE_COMMIT_VALUE := $(shell \
if [ -n "$$SOURCE_GIT_COMMIT" ]; then \
printf '%s' "$$SOURCE_GIT_COMMIT" | cut -c1-9; \
elif [ -n "$$GITHUB_SHA" ]; then \
printf '%s' "$$GITHUB_SHA" | cut -c1-9; \
elif [ -f SOURCE_COMMIT ]; then \
head -n1 SOURCE_COMMIT | tr -d '[:space:]' | cut -c1-9; \
else \
git rev-parse --short=9 HEAD 2>/dev/null || printf unknown; \
fi)
GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true)
VERSION = $(shell $(CARGO) metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz
PPA_REVISION ?= 1
PKG_NAME = globalprotect-openconnect
PKG = $(PKG_NAME)-$(VERSION)
SERIES ?= $(shell lsb_release -cs)
PUBLISH ?= 0
# Indicates whether to build the GUI components
BUILD_GUI_HELPER ?= 1
# Indicates whether to build embedded webview auth support into gpauth
BUILD_WEBVIEW_AUTH ?= 1
PREFIX ?= /usr/local
BSD_FLAVOR ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
GPGUI_BINARY ?= ../gpgui/target/release/gpgui
export DEBEMAIL = [email protected]
export DEBFULLNAME = Kevin Yue
export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false")
export OFFLINE_BUILD = $(shell test -f OFFLINE_BUILD && echo "1" || echo "0")
# If OFFLINE is not set, use OFFLINE_BUILD
ifndef OFFLINE
OFFLINE = $(OFFLINE_BUILD)
endif
ifeq ($(SNAPSHOT), true)
RELEASE_TAG = snapshot
@@ -58,10 +29,6 @@ ifeq ($(OFFLINE), 1)
CARGO_BUILD_ARGS += --frozen
endif
ifeq ($(IGNORE_RUST_VERSION), 1)
CARGO_BUILD_ARGS += --ignore-rust-version
endif
default: build
version:
@@ -72,20 +39,24 @@ clean-tarball:
rm -rf .vendor
rm -rf vendor.tar.xz
rm -rf .cargo
rm -f SOURCE_COMMIT
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball
if [ $(BUILD_FE) -eq 1 ]; then \
echo "Building frontend..."; \
cd apps/gpgui-helper && pnpm install && pnpm build; \
fi
# Remove node_modules to reduce the tarball size
rm -rf apps/gpgui-helper/node_modules
mkdir -p .cargo
mkdir -p .build/tarball
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
# If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build
if [ $(OFFLINE) -eq 1 ]; then \
$(CARGO) vendor .vendor > .cargo/config.toml; \
tar -cJf vendor.tar.xz .vendor; \
touch OFFLINE_BUILD; \
fi
@echo "Creating tarball..."
@@ -97,38 +68,36 @@ download-gui:
if [ $(INCLUDE_GUI) -eq 1 ]; then \
echo "Downloading GlobalProtect GUI..."; \
mkdir -p .build/gpgui; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m).bin.tar.xz; \
tar -xJf .build/gpgui/*.tar.xz -C .build/gpgui; \
else \
echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \
fi
build: download-gui build-rs
build: download-gui build-fe build-rs
# Install and build the frontend
# If OFFLINE is set to 1, skip it
build-fe:
if [ $(OFFLINE) -eq 1 ] || [ $(BUILD_FE) -eq 0 ]; then \
echo "Skipping frontend build (OFFLINE=1 or BUILD_FE=0)"; \
else \
cd apps/gpgui-helper && pnpm install && pnpm build; \
fi
if [ ! -d apps/gpgui-helper/dist ]; then \
echo "Error: frontend build failed"; \
exit 1; \
fi
build-rs:
if [ $(OFFLINE) -eq 1 ]; then \
tar -xJf vendor.tar.xz; \
fi
# Remove the rust-toolchain.toml if DISABLE_RUST_TOOLCHAIN is set to 1
if [ $(DISABLE_RUST_TOOLCHAIN) -eq 1 ]; then \
rm -vf rust-toolchain.toml; \
fi
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice
# Build gpauth with or without embedded webview auth support
if [ $(BUILD_WEBVIEW_AUTH) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth; \
else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth --no-default-features; \
fi
# Only build the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper; \
fi
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper --features "tauri/custom-protocol"
clean:
$(CARGO) clean
@@ -142,11 +111,7 @@ install:
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
# Install the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper; \
fi
install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper
if [ -f .build/gpgui/gpgui_*/gpgui ]; then \
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
@@ -166,98 +131,6 @@ install:
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
install -Dm644 packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
install-bsd:
@echo "Installing $(PKG_NAME) for BSD under $(PREFIX)..."
install -d $(DESTDIR)$(PREFIX)/bin
install -m 755 target/release/gpclient $(DESTDIR)$(PREFIX)/bin/gpclient
install -m 755 target/release/gpauth $(DESTDIR)$(PREFIX)/bin/gpauth
install -m 755 target/release/gpservice $(DESTDIR)$(PREFIX)/bin/gpservice
if [ "$(BUILD_GUI_HELPER)" = "1" ]; then \
install -m 755 target/release/gpgui-helper $(DESTDIR)$(PREFIX)/bin/gpgui-helper; \
fi
if [ -x "$(GPGUI_BINARY)" ]; then \
install -m 755 "$(GPGUI_BINARY)" $(DESTDIR)$(PREFIX)/bin/gpgui; \
fi
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script
install -m 755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)$(PREFIX)/libexec/gpclient/hipreport.sh
install -d $(DESTDIR)$(PREFIX)/share/applications
install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps/gpgui.svg
install -m 644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps/gpgui.png
install -d $(DESTDIR)$(PREFIX)/share/polkit-1/actions
install -m 644 packaging/bsd/com.yuezk.gpgui.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy
clean-bsd-package:
rm -rf .build/$(BSD_FLAVOR)
bsd-gpgui-tarball:
test -x "$(GPGUI_BINARY)"
rm -rf .build/$(BSD_FLAVOR)/gpgui
mkdir -p .build/$(BSD_FLAVOR)/artifacts .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)
cp "$(GPGUI_BINARY)" .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)/
tar -cf - -C .build/$(BSD_FLAVOR)/gpgui gpgui_$(VERSION) | xz -c > .build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz
file=.build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz; \
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$$file" | cut -d ' ' -f 1; \
elif command -v sha256 >/dev/null 2>&1; then sha256 -q "$$file"; \
else cksum -a sha256 "$$file" | awk '{print $$1}'; fi > "$$file.sha256"
package-freebsd: BSD_FLAVOR=freebsd
package-freebsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/freebsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
find .build/freebsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/freebsd/pkgroot$(PREFIX)/||' | sort > .build/freebsd/PLIST
freebsd_major=$$(freebsd-version -u | sed 's/\..*//'); \
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
sed \
-e 's/@PKG_NAME@/$(PKG_NAME)/g' \
-e 's/@VERSION@/$(VERSION)/g' \
-e "s/@ABI@/FreeBSD:$$freebsd_major:$$freebsd_arch/g" \
-e "s/@ARCH@/freebsd:$$freebsd_major:$$freebsd_arch/g" \
-e 's|@PREFIX@|$(PREFIX)|g' \
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/+MANIFEST
pkg create -r .build/freebsd/pkgroot -M .build/freebsd/+MANIFEST -p .build/freebsd/PLIST -o .build/freebsd/artifacts
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
mv .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION).pkg .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION)-freebsd-$$freebsd_arch.pkg
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=freebsd GPGUI_BINARY="$(GPGUI_BINARY)"
package-openbsd: BSD_FLAVOR=openbsd
package-openbsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/openbsd/pkgroot .build/openbsd/artifacts
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/openbsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
find .build/openbsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/openbsd/pkgroot$(PREFIX)/||' | sort > .build/openbsd/PLIST
comment=$$(cat .build/openbsd/+COMMENT); \
openbsd_arch=$$(uname -m | sed 's/x86_64/amd64/'); \
gnome_keyring_pkg=$$(pkg_info -e 'gnome-keyring-*' | sed 's/^inst://' | head -n 1); \
polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | sed 's/^inst://' | head -n 1); \
pkg_create \
-B .build/openbsd/pkgroot \
-D COMMENT="$$comment" \
-d .build/openbsd/+DESC \
-f .build/openbsd/PLIST \
-p $(PREFIX) \
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
-P sysutils/polkit:polkit-*:$$polkit_pkg \
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_pkg \
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
uninstall:
@echo "Uninstalling $(PKG_NAME)..."
@@ -289,40 +162,23 @@ init-debian: clean-debian tarball
cp .build/tarball/${PKG}.tar.gz .build/deb
tar -xzf .build/deb/${PKG}.tar.gz -C .build/deb
cd .build/deb/${PKG} && debmake
cd .build/deb/${PKG} && LC_ALL=C.UTF-8 LANG=C.UTF-8 PYTHONUTF8=1 debmake
cp -f packaging/deb/control.in .build/deb/$(PKG)/debian/control
cp -f packaging/deb/rules.in .build/deb/$(PKG)/debian/rules
cp -f packaging/deb/postrm .build/deb/$(PKG)/debian/postrm
cp -f packaging/deb/compat .build/deb/$(PKG)/debian/compat
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/control
# Remove the GUI dependencies if BUILD_GUI_HELPER is set to 0
if [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \
sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \
fi
# Remove the WebKitGTK build dependency only if neither gpauth webview auth nor gpgui-helper needs it
if [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
fi
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/$(BUILD_WEBVIEW_AUTH)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/deb/$(PKG)/debian/rules
rm -f .build/deb/$(PKG)/debian/changelog
deb: init-debian
# Remove the rust build depdency from the control file
sed -i "s/@RUST@//g" .build/deb/$(PKG)/debian/control
cd .build/deb/$(PKG) && dch --create --distribution unstable --package $(PKG_NAME) --newversion $(VERSION)-$(REVISION) "Bugfix and improvements."
# Install build dependencies
cd .build/deb/$(PKG) && sudo mk-build-deps --install --remove debian/control || echo "mk-build-deps failed, continuing"
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b -d
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b
check-ppa:
if [ $(OFFLINE) -eq 0 ]; then \
@@ -331,6 +187,8 @@ check-ppa:
# Usage: make ppa SERIES=focal OFFLINE=1 PUBLISH=1
ppa: check-ppa init-debian
sed -i "s/@RUST@/rust-all(>=1.70)/g" .build/deb/$(PKG)/debian/control
$(eval SERIES_VER = $(shell distro-info --series $(SERIES) -r | cut -d' ' -f1))
@echo "Building for $(SERIES) $(SERIES_VER)"
@@ -357,7 +215,7 @@ init-rpm: clean-rpm
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@REVISION@/$(REVISION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s|@SOURCE@|$(RPM_SOURCE)|g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@DATE@/$(shell LC_ALL=en.US date "+%a %b %d %Y")/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.changes
@@ -390,30 +248,11 @@ init-pkgbuild: clean-pkgbuild tarball
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/pkgbuild/PKGBUILD
sed -i "s/@VERSION@/$(VERSION)/g" .build/pkgbuild/PKGBUILD
sed -i "s/@REVISION@/$(REVISION)/g" .build/pkgbuild/PKGBUILD
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/pkgbuild/PKGBUILD
pkgbuild: init-pkgbuild
cd .build/pkgbuild && makepkg -s --noconfirm
clean-apk:
rm -rf .build/apk
init-apk: clean-apk tarball
mkdir -p .build/apk
cp .build/tarball/${PKG}.tar.gz .build/apk
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/apk/APKBUILD
sed -i "s/@VERSION@/$(VERSION)/g" .build/apk/APKBUILD
sed -i "s/@REVISION@/$(REVISION)/g" .build/apk/APKBUILD
checksum=$$(sha512sum .build/apk/${PKG}.tar.gz | cut -d' ' -f1); \
sed -i "s/@SHA512@/$$checksum/g" .build/apk/APKBUILD
apk: init-apk
cd .build/apk && abuild -r -P "$(CURDIR)/.build/apk/packages"
find .build/apk/packages -type f -name "$(PKG_NAME)-*.apk" -exec cp {} .build/apk \;
clean-binary:
rm -rf .build/binary
@@ -425,7 +264,7 @@ binary: clean-binary tarball
mkdir -p .build/binary/$(PKG_NAME)_$(VERSION)/artifacts
make -C .build/binary/${PKG} build INCLUDE_GUI=$(INCLUDE_GUI)
make -C .build/binary/${PKG} build OFFLINE=$(OFFLINE) BUILD_FE=0 INCLUDE_GUI=$(INCLUDE_GUI)
make -C .build/binary/${PKG} install DESTDIR=$(PWD)/.build/binary/$(PKG_NAME)_$(VERSION)/artifacts
cp packaging/binary/Makefile.in .build/binary/$(PKG_NAME)_$(VERSION)/Makefile
+112 -353
View File
@@ -1,54 +1,32 @@
# GlobalProtect-openconnect
A modern GlobalProtect VPN client for Linux, built on OpenConnect with full support for SSO authentication. This project provides both command-line and graphical interfaces for seamless VPN connectivity.
A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method. Inspired by [gp-saml-gui](https://github.com/dlenski/gp-saml-gui).
<p align="center">
<img width="300" src="https://github.com/user-attachments/assets/2fb6116c-dc57-43f2-af75-9c3d97ab7122">
<img width="300" src="https://github.com/yuezk/GlobalProtect-openconnect/assets/3297602/9242df9c-217d-42ab-8c21-8f9f69cd4eb5">
</p>
> **Inspired by** [gp-saml-gui](https://github.com/dlenski/gp-saml-gui)
## Table of Contents
- [Features](#features)
- [Usage](#usage)
- [Command-Line Interface](#command-line-interface)
- [Graphical User Interface](#graphical-user-interface)
- [Installation](#installation)
- [Debian / Ubuntu](#debian--ubuntu)
- [Arch Linux / Manjaro](#arch-linux--manjaro)
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
- [Other RPM-based Distributions](#other-rpm-based-distributions)
- [Alpine Linux](#alpine-linux)
- [Gentoo](#gentoo)
- [NixOS](#nixos)
- [Official Docker Image](#official-docker-image)
- [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions)
- [License](#license)
## Features
- **Cross-Platform Linux Support** – Optimized for various Linux distributions
- **Dual Interface** – Available as both CLI and GUI applications
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication
- **Browser Integration** – Authenticate using your default browser or any specified browser
- **Multi-Portal Support** – Connect to multiple portals and gateways
- **Direct Gateway Connection** – Bypass portal selection when needed
- **Auto-Connect** – Automatically connect on system startup
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME)
- [x] Better Linux support
- [x] Support both CLI and GUI
- [x] Support both SSO and non-SSO authentication
- [x] Support the FIDO2 authentication (e.g., YubiKey)
- [x] Support authentication using default browser
- [x] Support client certificate authentication
- [x] Support multiple portals
- [x] Support gateway selection
- [x] Support connect gateway directly
- [x] Support auto-connect on startup
- [x] Support system tray icon
## Usage
### Command-Line Interface
### CLI
The CLI version is fully open source and feature-rich, providing nearly identical functionality to the GUI version.
The CLI version is always free and open source in this repo. It has almost the same features as the GUI version.
#### Basic Commands
```bash
```
Usage: gpclient [OPTIONS] <COMMAND>
Commands:
@@ -58,55 +36,44 @@ Commands:
help Print this message or the help of the given subcommand(s)
Options:
--fix-openssl Get around the OpenSSL 'unsafe legacy renegotiation' error
--ignore-tls-errors Ignore TLS errors
--fix-openssl Get around the OpenSSL `unsafe legacy renegotiation` error
--ignore-tls-errors Ignore the TLS errors
-h, --help Print help
-V, --version Print version
See 'gpclient help <command>' for more information on a specific command.
```
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
#### External Browser Authentication
For browser-based authentication with the CLI:
**Method 1:** Using sudo with environment preservation:
```bash
sudo -E gpclient connect --browser <portal>
```
**Method 2:** Using authentication piping:
```bash
gpauth <portal> --browser 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
```
**Browser Options:**
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
- Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
### Graphical User Interface
The GUI application provides an intuitive interface for managing VPN connections. Launch it from your application menu or via the terminal:
To use the external browser for authentication with the CLI version, you need to use the following command:
```bash
gpclient launch-gui
sudo -E gpclient connect --browser default <portal>
```
Or you can try the following command if the above command does not work:
```bash
gpauth <portal> --browser default 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
```
You can specify the browser with the `--browser <browser>` option, e.g., `--browser firefox`, `--browser chrome`, etc.
### GUI
The GUI version is also available after you installed it. You can launch it from the application menu or run `gpclient launch-gui` in the terminal.
> [!Note]
>
> The GUI version is partially open source. The background service ([gpservice](./apps/gpservice/)) is open source, while the GUI wrapper is proprietary.
> The GUI version is partially open source. Its background service is open sourced in this repo as [gpservice](./apps/gpservice/). The GUI part is a wrapper of the background service, which is not open sourced.
## Installation
> [!Note]
>
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
### Debian/Ubuntu based distributions
### Debian / Ubuntu
#### Install from PPA (Ubuntu 18.04 and later, except 24.04)
#### Option 1: Install from PPA (Recommended)
```bash
```
sudo apt-get install gir1.2-gtk-3.0 gir1.2-webkit2-4.0
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
sudo apt-get update
sudo apt-get install globalprotect-openconnect
@@ -114,14 +81,24 @@ sudo apt-get install globalprotect-openconnect
> [!Note]
>
> **For Linux Mint users:** If you encounter a GPG key error, import the key manually:
> ```bash
> sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761
> ```
> For Linux Mint, you might need to import the GPG key with: `sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761` if you encountered an error `gpg: keyserver receive failed: General error`.
#### Option 2: Install from DEB Package
#### **Ubuntu 24.04 and later**
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
The `libwebkit2gtk-4.0-37` package was [removed](https://bugs.launchpad.net/ubuntu/+source/webkit2gtk/+bug/2061914) from its repo. You can use the [`deb-install.sh`](./scripts/deb-install.sh) script to install the package:
```bash
curl -o- https://raw.githubusercontent.com/yuezk/GlobalProtect-openconnect/main/scripts/deb-install.sh \
| bash -s -- 2.3.9
```
#### **Ubuntu 18.04**
The latest package is not available in the PPA either, but you still needs to add the `ppa:yuezk/globalprotect-openconnect` repo beforehand to use the required `openconnect` package. Then you can follow the [Install from deb package](#install-from-deb-package) section to install the latest package.
#### Install from deb package
Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `apt`:
```bash
sudo apt install --fix-broken globalprotect-openconnect_*.deb
@@ -129,335 +106,117 @@ sudo apt install --fix-broken globalprotect-openconnect_*.deb
### Arch Linux / Manjaro
#### Option 1: Install from AUR
#### Install from AUR
Package: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
You can install it using an AUR helper like [`yay`](https://github.com/Jguer/yay):
Install from AUR: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
```bash
yay -S globalprotect-openconnect-git
```
#### Option 2: Install from the Official Extra Repository
#### Install from package
The package is also available in the official Arch Linux Extra repository.
Package: [globalprotect-openconnect](https://archlinux.org/packages/extra/x86_64/globalprotect-openconnect/)
> [!Note]
>
> Since the official package does not include the system tray support dependency, you need to install `libappindicator` manually:
```bash
sudo pacman -S libappindicator globalprotect-openconnect
```
#### Option 3: Install from Package
Download the latest package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
Download the latest package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `pacman`:
```bash
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
```
### Fedora 38+ / Rawhide
### Fedora 38 and later / Fedora Rawhide
#### Install from COPR
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for RPM-based distributions:
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for various RPM-based distributions. You can install it with the following commands:
```bash
sudo dnf copr enable yuezk/globalprotect-openconnect
sudo dnf install globalprotect-openconnect
```
### openSUSE Leap 15.6+ / Tumbleweed
### openSUSE Leap 15.6 / openSUSE Tumbleweed
#### Install from OBS (openSUSE Build Service)
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [installation instructions](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
The package is also available on [OBS](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect) for various RPM-based distributions. You can follow the instructions [on this page](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) to install it.
### Other RPM-based Distributions
### Other RPM-based distributions
#### Install from RPM Package
#### Install from RPM package
Download the latest RPM package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
Download the latest RPM package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
On RHEL / Rocky Linux / AlmaLinux / CentOS, enable EPEL first:
```bash
sudo dnf install epel-release
```
```bash
sudo rpm -i globalprotect-openconnect-*.rpm
```
### Alpine Linux
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
```
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
### Gentoo
Available via the `guru` and `lamdness` overlays:
It is available via `guru` and `lamdness` overlays.
```bash
sudo eselect repository enable guru
sudo emerge --sync guru
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
sudo emerge -r guru sync
sudo emerge -av net-vpn/globalprotect-openconnect
```
### NixOS
### Other distributions
This repository includes a flake for NixOS integration.
- Install `openconnect >= 8.20`, `webkit2gtk`, `libsecret`, `libayatana-appindicator` or `libappindicator-gtk3`.
- Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
- Extract the tarball with `tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz`.
- Run `sudo make install` to install the client.
#### Installation Steps
## Build from source
1. Add the flake to your `flake.nix`:
You can also build the client from source, steps are as follows:
```nix
{
inputs = {
# ... other inputs
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
};
### Prerequisites
outputs = { nixpkgs, ... }@inputs: {
nixosConfigurations.<your-host> = nixpkgs.lib.nixosSystem {
specialArgs = { inherit inputs; };
modules = [
./configuration.nix
];
};
};
}
```
- [Install Rust 1.75 or later](https://www.rust-lang.org/tools/install)
- Install Tauri dependencies: https://tauri.app/v1/guides/getting-started/prerequisites/#setting-up-linux
- Install `perl` and `jq`
- Install `openconnect >= 8.20` and `libopenconnect-dev` (or `openconnect-devel` on RPM-based distributions)
- Install `pkexec`, `gnome-keyring` (or `pam_kwallet` on KDE)
- Install `nodejs` and `pnpm` (optional only if you downloaded the source tarball from the release page and run with the `BUILD_FE=0` flag, see below)
2. Add the package to your `configuration.nix`:
### Build
```nix
{ pkgs, inputs, ... }:
1. Download the source code tarball from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Choose `globalprotect-openconnect-${version}.tar.gz`.
2. Extract the tarball with `tar -xzf globalprotect-openconnect-${version}.tar.gz`.
3. Enter the source directory and run `make build BUILD_FE=0` to build the client.
3. Run `sudo make install` to install the client. (Note, `DESTDIR` is not supported)
{
# ... other configurations
environment.systemPackages = with pkgs; [
# ... other packages
inputs.globalprotect-openconnect.packages.${pkgs.stdenv.hostPlatform.system}.default
];
}
```
## FAQ
3. Apply the changes:
1. How to deal with error `Secure Storage not ready`
```bash
sudo nixos-rebuild switch
```
Try upgrade the client to `2.2.0` or later, which will use a file-based storage as a fallback.
### Official Docker Image
You need to install the `gnome-keyring` package, and restart the system (See [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
The official Docker image provides the CLI tools on Alpine Linux:
2. How to deal with error `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`
```bash
docker pull yuezk/globalprotect-openconnect:<version>
```
If you encounter this error when using the CLI version, try to run the command with `sudo -E` (See [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
## About Trial
Run it with access to the TUN device:
The CLI version is always free, while the GUI version is paid. There are two trial modes for the GUI version:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
1. 10-day trial: You can use the GUI stable release for 10 days after the installation.
2. 14-day trial: Each beta release has a fresh trial period (at most 14 days) after released.
For browser authentication in a headless environment, use remote browser authentication:
## License
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
```bash
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
Alternatively, pipe `gpauth` remote-browser output into `gpclient`:
```bash
docker run --rm -it --entrypoint gpauth yuezk/globalprotect-openconnect:<version> \
<portal> --browser remote 2>/dev/null \
| docker run --rm -i --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
### Other Distributions
#### Manual Installation
1. **Install dependencies:**
- `webkit2gtk`
- `libsecret`
- `libayatana-appindicator` or `libappindicator-gtk3`
2. **Download and extract:**
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
```bash
tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz
```
3. **Install:**
```bash
sudo make install
```
## Building from Source
You can build the application from source using either a DevContainer (recommended) or a local development environment.
### Method 1: Using DevContainer (Recommended)
This project includes a DevContainer configuration that provides a consistent, reproducible build environment with all dependencies pre-installed.
#### Prerequisites
- [Docker](https://docs.docker.com/get-docker/)
- [Visual Studio Code](https://code.visualstudio.com/) (optional, for IDE support)
- [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (if using VS Code)
#### Build Steps
1. **Clone the repository:**
```bash
git clone https://github.com/yuezk/GlobalProtect-openconnect.git
cd GlobalProtect-openconnect
git submodule update --init --recursive
```
2. **Build the DevContainer image:**
```bash
docker build -t gpoc-devcontainer .devcontainer/
```
3. **Build the project:**
To build everything including the GUI helper run this command:
```bash
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
```
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
5. **Locate build artifacts:**
The compiled binaries will be available in `target/release/`:
- `gpclient` – CLI client
- `gpservice` – Background service
- `gpauth` – Authentication helper
- `gpgui-helper` – GUI helper
#### Alternative: Using VS Code
1. Open the project in VS Code
2. When prompted, click "Reopen in Container" (or run **Dev Containers: Reopen in Container**)
3. Once the container is ready, open a terminal and run:
```bash
make build
```
### Method 2: Local Development Build
#### Prerequisites
- [Rust 1.89 or later](https://www.rust-lang.org/tools/install)
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
- `nodejs` and `pnpm` (optional)
#### Build Steps
1. **Download source code:**
Download `globalprotect-openconnect-${version}.tar.gz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
2. **Extract and build:**
```bash
tar -xzf globalprotect-openconnect-${version}.tar.gz
cd globalprotect-openconnect-${version}
make build
```
3. **Install:**
```bash
sudo make install
```
> **Note:** `DESTDIR` is not currently supported.
### Testing Your Build
Verify the CLI client is working correctly:
```bash
./target/release/gpclient --help
```
### Build Options
- `BUILD_GUI_HELPER=0` – Build CLI components only (excludes GUI)
- `OFFLINE=1` – Build in offline mode using vendored dependencies
## Frequently Asked Questions
### Q: How do I resolve the "Secure Storage not ready" error?
**Solution 1:** Update to version 2.2.0 or later, which includes a file-based storage fallback.
**Solution 2:** Install the `gnome-keyring` package and restart your system.
See related issues: [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
### Q: How do I fix the "cannot open display" error when using CLI?
If you encounter `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`, try running the command with `sudo -E`:
```bash
sudo -E gpclient connect <portal>
```
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
## Licensing
### Trial and Pricing
The **CLI version** is completely free and open source.
The **GUI version** is a paid application with a **7-day trial period** after installation.
### Open Source Licenses
This project consists of multiple components, each with its own license:
| Component | Type | License |
|-----------|------|---------|
| [gpapi](./crates/gpapi) | Crate | [MIT](./crates/gpapi/LICENSE) |
| [openconnect](./crates/openconnect) | Crate | [GPL-3.0](./crates/openconnect/LICENSE) |
| [common](./crates/common) | Crate | [GPL-3.0](./crates/common/LICENSE) |
| [auth](./crates/auth) | Crate | [GPL-3.0](./crates/auth/LICENSE) |
| [gpservice](./apps/gpservice) | Application | [GPL-3.0](./apps/gpservice/LICENSE) |
| [gpclient](./apps/gpclient) | Application | [GPL-3.0](./apps/gpclient/LICENSE) |
| [gpauth](./apps/gpauth) | Application | [GPL-3.0](./apps/gpauth/LICENSE) |
| [gpgui-helper](./apps/gpgui-helper) | Application | [GPL-3.0](./apps/gpgui-helper/LICENSE) |
- crate [gpapi](./crates/gpapi): [MIT](./crates/gpapi/LICENSE)
- crate [openconnect](./crates/openconnect): [GPL-3.0](./crates/openconnect/LICENSE)
- crate [common](./crates/common): [GPL-3.0](./crates/common/LICENSE)
- app [gpservice](./apps/gpservice): [GPL-3.0](./apps/gpservice/LICENSE)
- app [gpclient](./apps/gpclient): [GPL-3.0](./apps/gpclient/LICENSE)
- app [gpauth](./apps/gpauth): [GPL-3.0](./apps/gpauth/LICENSE)
- app [gpgui-helper](./apps/gpgui-helper): [GPL-3.0](./apps/gpgui-helper/LICENSE)
+12 -19
View File
@@ -1,36 +1,29 @@
[package]
name = "gpauth"
rust-version.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
license.workspace = true
[build-dependencies]
tauri-build = { version = "2", features = [], optional = true }
tauri-build = { version = "1.5", features = [] }
[dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
auth = { path = "../../crates/auth", features = ["browser-auth"] }
# Shared dependencies
gpapi = { path = "../../crates/gpapi", features = [
"tauri",
"clap",
"browser-auth",
] }
anyhow.workspace = true
clap.workspace = true
env_logger.workspace = true
log.workspace = true
regex.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio.workspace = true
tokio-util.workspace = true
tempfile.workspace = true
html-escape = "0.2.13"
webkit2gtk = "0.18.2"
tauri = { workspace = true, features = ["http-all"] }
compile-time.workspace = true
# Pin to specific version due to MSRV
home = "=0.5.11"
# webview auth dependencies
tauri = { workspace = true, optional = true }
[features]
default = ["webview-auth"]
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
-60
View File
@@ -1,63 +1,3 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPAUTH_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPAUTH_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
#[cfg(feature = "webview-auth")]
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPAUTH_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+523
View File
@@ -0,0 +1,523 @@
use std::{
rc::Rc,
sync::Arc,
time::{Duration, Instant},
};
use anyhow::bail;
use gpapi::{
auth::SamlAuthData,
error::AuthDataParseError,
gp_params::GpParams,
portal::{prelogin, Prelogin},
utils::{redact::redact_uri, window::WindowExt},
};
use log::{info, warn};
use regex::Regex;
use tauri::{AppHandle, Window, WindowEvent, WindowUrl};
use tokio::sync::{mpsc, oneshot, RwLock};
use tokio_util::sync::CancellationToken;
use webkit2gtk::{
gio::Cancellable,
glib::{GString, TimeSpan},
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponse, URIResponseExt, WebContextExt, WebResource, WebResourceExt,
WebView, WebViewExt, WebsiteDataManagerExtManual, WebsiteDataTypes,
};
enum AuthDataError {
/// Failed to load page due to TLS error
TlsError,
/// 1. Found auth data in headers/body but it's invalid
/// 2. Loaded an empty page, failed to load page. etc.
Invalid,
/// No auth data found in headers/body
NotFound,
}
type AuthResult = Result<SamlAuthData, AuthDataError>;
pub(crate) struct AuthWindow<'a> {
app_handle: AppHandle,
server: &'a str,
saml_request: &'a str,
user_agent: &'a str,
gp_params: Option<GpParams>,
clean: bool,
}
impl<'a> AuthWindow<'a> {
pub fn new(app_handle: AppHandle) -> Self {
Self {
app_handle,
server: "",
saml_request: "",
user_agent: "",
gp_params: None,
clean: false,
}
}
pub fn server(mut self, server: &'a str) -> Self {
self.server = server;
self
}
pub fn saml_request(mut self, saml_request: &'a str) -> Self {
self.saml_request = saml_request;
self
}
pub fn user_agent(mut self, user_agent: &'a str) -> Self {
self.user_agent = user_agent;
self
}
pub fn gp_params(mut self, gp_params: GpParams) -> Self {
self.gp_params.replace(gp_params);
self
}
pub fn clean(mut self, clean: bool) -> Self {
self.clean = clean;
self
}
pub async fn open(&self) -> anyhow::Result<SamlAuthData> {
info!("Open auth window, user_agent: {}", self.user_agent);
let window = Window::builder(&self.app_handle, "auth_window", WindowUrl::default())
.title("GlobalProtect Login")
// .user_agent(self.user_agent)
.focused(true)
.visible(false)
.center()
.build()?;
let window = Arc::new(window);
let cancel_token = CancellationToken::new();
let cancel_token_clone = cancel_token.clone();
window.on_window_event(move |event| {
if let WindowEvent::CloseRequested { .. } = event {
cancel_token_clone.cancel();
}
});
let window_clone = Arc::clone(&window);
let timeout_secs = 15;
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(timeout_secs)).await;
let visible = window_clone.is_visible().unwrap_or(false);
if !visible {
info!("Try to raise auth window after {} seconds", timeout_secs);
raise_window(&window_clone);
}
});
tokio::select! {
_ = cancel_token.cancelled() => {
bail!("Auth cancelled");
}
saml_result = self.auth_loop(&window) => {
window.close()?;
saml_result
}
}
}
async fn auth_loop(&self, window: &Arc<Window>) -> anyhow::Result<SamlAuthData> {
let saml_request = self.saml_request.to_string();
let (auth_result_tx, mut auth_result_rx) = mpsc::unbounded_channel::<AuthResult>();
let raise_window_cancel_token: Arc<RwLock<Option<CancellationToken>>> = Default::default();
let gp_params = self.gp_params.as_ref().unwrap();
let tls_err_policy = if gp_params.ignore_tls_errors() {
TLSErrorsPolicy::Ignore
} else {
TLSErrorsPolicy::Fail
};
if self.clean {
clear_webview_cookies(window).await?;
}
let raise_window_cancel_token_clone = Arc::clone(&raise_window_cancel_token);
window.with_webview(move |wv| {
let wv = wv.inner();
if let Some(context) = wv.context() {
context.set_tls_errors_policy(tls_err_policy);
}
if let Some(settings) = wv.settings() {
let ua = settings.user_agent().unwrap_or("".into());
info!("Auth window user agent: {}", ua);
}
// Load the initial SAML request
load_saml_request(&wv, &saml_request);
let auth_result_tx_clone = auth_result_tx.clone();
wv.connect_load_changed(move |wv, event| {
if event == LoadEvent::Started {
let Ok(mut cancel_token) = raise_window_cancel_token_clone.try_write() else {
return;
};
// Cancel the raise window task
if let Some(cancel_token) = cancel_token.take() {
cancel_token.cancel();
}
return;
}
if event != LoadEvent::Finished {
return;
}
if let Some(main_resource) = wv.main_resource() {
let uri = main_resource.uri().unwrap_or("".into());
if uri.is_empty() {
warn!("Loaded an empty uri");
send_auth_result(&auth_result_tx_clone, Err(AuthDataError::Invalid));
return;
}
info!("Loaded uri: {}", redact_uri(&uri));
if uri.starts_with("globalprotectcallback:") {
return;
}
read_auth_data(&main_resource, auth_result_tx_clone.clone());
}
});
let auth_result_tx_clone = auth_result_tx.clone();
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
let redacted_uri = redact_uri(uri);
warn!(
"Failed to load uri: {} with error: {}, cert: {}",
redacted_uri, err, cert
);
send_auth_result(&auth_result_tx_clone, Err(AuthDataError::TlsError));
true
});
wv.connect_load_failed(move |_wv, _event, uri, err| {
let redacted_uri = redact_uri(uri);
if !uri.starts_with("globalprotectcallback:") {
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
}
// NOTE: Don't send error here, since load_changed event will be triggered after this
// send_auth_result(&auth_result_tx, Err(AuthDataError::Invalid));
// true to stop other handlers from being invoked for the event. false to propagate the event further.
true
});
})?;
let portal = self.server.to_string();
loop {
if let Some(auth_result) = auth_result_rx.recv().await {
match auth_result {
Ok(auth_data) => return Ok(auth_data),
Err(AuthDataError::TlsError) => bail!("TLS error: certificate verify failed"),
Err(AuthDataError::NotFound) => {
info!("No auth data found, it may not be the /SAML20/SP/ACS endpoint");
// The user may need to interact with the auth window, raise it in 3 seconds
if !window.is_visible().unwrap_or(false) {
let window = Arc::clone(window);
let cancel_token = CancellationToken::new();
raise_window_cancel_token.write().await.replace(cancel_token.clone());
tokio::spawn(async move {
let delay_secs = 1;
info!("Raise window in {} second(s)", delay_secs);
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(delay_secs)) => {
raise_window(&window);
}
_ = cancel_token.cancelled() => {
info!("Raise window cancelled");
}
}
});
}
}
Err(AuthDataError::Invalid) => {
info!("Got invalid auth data, retrying...");
window.with_webview(|wv| {
let wv = wv.inner();
wv.run_javascript(r#"
var loading = document.createElement("div");
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
document.body.appendChild(loading);
"#,
Cancellable::NONE,
|_| info!("Injected loading element successfully"),
);
})?;
let saml_request = portal_prelogin(&portal, gp_params).await?;
window.with_webview(move |wv| {
let wv = wv.inner();
load_saml_request(&wv, &saml_request);
})?;
}
}
}
}
}
}
fn raise_window(window: &Arc<Window>) {
let visible = window.is_visible().unwrap_or(false);
if !visible {
if let Err(err) = window.raise() {
warn!("Failed to raise window: {}", err);
}
}
}
pub async fn portal_prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<String> {
match prelogin(portal, gp_params).await? {
Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
}
}
fn send_auth_result(auth_result_tx: &mpsc::UnboundedSender<AuthResult>, auth_result: AuthResult) {
if let Err(err) = auth_result_tx.send(auth_result) {
warn!("Failed to send auth event: {}", err);
}
}
fn load_saml_request(wv: &Rc<WebView>, saml_request: &str) {
if saml_request.starts_with("http") {
info!("Load the SAML request as URI...");
wv.load_uri(saml_request);
} else {
info!("Load the SAML request as HTML...");
wv.load_html(saml_request, None);
}
}
fn read_auth_data_from_headers(response: &URIResponse) -> AuthResult {
response.http_headers().map_or_else(
|| {
info!("No headers found in response");
Err(AuthDataError::NotFound)
},
|mut headers| match headers.get("saml-auth-status") {
Some(status) if status == "1" => {
let username = headers.get("saml-username").map(GString::into);
let prelogin_cookie = headers.get("prelogin-cookie").map(GString::into);
let portal_userauthcookie = headers.get("portal-userauthcookie").map(GString::into);
if SamlAuthData::check(&username, &prelogin_cookie, &portal_userauthcookie) {
return Ok(SamlAuthData::new(
username.unwrap(),
prelogin_cookie,
portal_userauthcookie,
));
}
info!("Found invalid auth data in headers");
Err(AuthDataError::Invalid)
}
Some(status) => {
info!("Found invalid SAML status: {} in headers", status);
Err(AuthDataError::Invalid)
}
None => {
info!("No saml-auth-status header found");
Err(AuthDataError::NotFound)
}
},
)
}
fn read_auth_data_from_body<F>(main_resource: &WebResource, callback: F)
where
F: FnOnce(Result<SamlAuthData, AuthDataParseError>) + Send + 'static,
{
main_resource.data(Cancellable::NONE, |data| match data {
Ok(data) => {
let html = String::from_utf8_lossy(&data);
callback(read_auth_data_from_html(&html));
}
Err(err) => {
info!("Failed to read response body: {}", err);
callback(Err(AuthDataParseError::Invalid))
}
});
}
fn read_auth_data_from_html(html: &str) -> Result<SamlAuthData, AuthDataParseError> {
if html.contains("Temporarily Unavailable") {
info!("Found 'Temporarily Unavailable' in HTML, auth failed");
return Err(AuthDataParseError::Invalid);
}
SamlAuthData::from_html(html).or_else(|err| {
if let Some(gpcallback) = extract_gpcallback(html) {
info!("Found gpcallback from html...");
SamlAuthData::from_gpcallback(&gpcallback)
} else {
Err(err)
}
})
}
fn extract_gpcallback(html: &str) -> Option<String> {
let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap();
re.captures(html)
.and_then(|captures| captures.get(0))
.map(|m| html_escape::decode_html_entities(m.as_str()).to_string())
}
fn read_auth_data(main_resource: &WebResource, auth_result_tx: mpsc::UnboundedSender<AuthResult>) {
let Some(response) = main_resource.response() else {
info!("No response found in main resource");
send_auth_result(&auth_result_tx, Err(AuthDataError::Invalid));
return;
};
info!("Trying to read auth data from response headers...");
match read_auth_data_from_headers(&response) {
Ok(auth_data) => {
info!("Got auth data from headers");
send_auth_result(&auth_result_tx, Ok(auth_data));
}
Err(AuthDataError::Invalid) => {
info!("Found invalid auth data in headers, trying to read from body...");
read_auth_data_from_body(main_resource, move |auth_result| {
// Since we have already found invalid auth data in headers, which means this could be the `/SAML20/SP/ACS` endpoint
// any error result from body should be considered as invalid, and trigger a retry
let auth_result = auth_result.map_err(|err| {
info!("Failed to read auth data from body: {}", err);
AuthDataError::Invalid
});
send_auth_result(&auth_result_tx, auth_result);
});
}
Err(AuthDataError::NotFound) => {
info!("No auth data found in headers, trying to read from body...");
let is_acs_endpoint = main_resource.uri().map_or(false, |uri| uri.contains("/SAML20/SP/ACS"));
read_auth_data_from_body(main_resource, move |auth_result| {
// If the endpoint is `/SAML20/SP/ACS` and no auth data found in body, it should be considered as invalid
let auth_result = auth_result.map_err(|err| {
info!("Failed to read auth data from body: {}", err);
if !is_acs_endpoint && matches!(err, AuthDataParseError::NotFound) {
AuthDataError::NotFound
} else {
AuthDataError::Invalid
}
});
send_auth_result(&auth_result_tx, auth_result)
});
}
Err(AuthDataError::TlsError) => {
// NOTE: This is unreachable
info!("TLS error found in headers, trying to read from body...");
send_auth_result(&auth_result_tx, Err(AuthDataError::TlsError));
}
}
}
pub(crate) async fn clear_webview_cookies(window: &Window) -> anyhow::Result<()> {
let (tx, rx) = oneshot::channel::<Result<(), String>>();
window.with_webview(|wv| {
let send_result = move |result: Result<(), String>| {
if let Err(err) = tx.send(result) {
info!("Failed to send result: {:?}", err);
}
};
let wv = wv.inner();
let context = match wv.context() {
Some(context) => context,
None => {
send_result(Err("No webview context found".into()));
return;
}
};
let data_manager = match context.website_data_manager() {
Some(manager) => manager,
None => {
send_result(Err("No data manager found".into()));
return;
}
};
let now = Instant::now();
data_manager.clear(
WebsiteDataTypes::COOKIES,
TimeSpan(0),
Cancellable::NONE,
move |result| match result {
Err(err) => {
send_result(Err(err.to_string()));
}
Ok(_) => {
info!("Cookies cleared in {} ms", now.elapsed().as_millis());
send_result(Ok(()));
}
},
);
})?;
rx.await?.map_err(|err| anyhow::anyhow!(err))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extract_gpcallback_some() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:PGh0bWw+PCEtLSA8c")
);
}
#[test]
fn extract_gpcallback_cas() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:cas-as=1&amp;[email protected]&amp;token=very_long_string">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:cas-as=1&[email protected]&token=very_long_string")
);
}
#[test]
fn extract_gpcallback_none() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(extract_gpcallback(html), None);
}
}
+173 -170
View File
@@ -1,26 +1,25 @@
use auth::{BrowserAuthenticator, auth_prelogin};
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
use clap::Parser;
use gpapi::{
auth::{SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
clap::args::Os,
gp_params::{ClientOs, GpParams},
process::browser_authenticator::BrowserAuthenticator,
utils::{normalize_server, openssl},
GP_USER_AGENT,
};
use log::info;
use log::{info, LevelFilter};
use serde_json::json;
use tauri::{App, AppHandle, RunEvent};
use tempfile::NamedTempFile;
use tokio::{io::AsyncReadExt, net::TcpListener};
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPAUTH_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
use crate::auth_window::{portal_prelogin, AuthWindow};
#[derive(Parser)]
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
#[derive(Parser, Clone)]
#[command(
version = VERSION,
author,
@@ -48,14 +47,17 @@ struct Cli {
#[arg(long, help = "The SAML authentication request")]
saml_request: Option<String>,
#[arg(long, value_enum, default_value_t = Os::default())]
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
os: Os,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long)]
os_version: Option<String>,
#[arg(long, help = "Override the GlobalProtect client version reported to the server")]
client_version: Option<String>,
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
fix_openssl: bool,
@@ -63,44 +65,94 @@ struct Cli {
#[arg(long, help = "Ignore TLS errors")]
ignore_tls_errors: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Clean the cache of the embedded browser")]
clean: bool,
#[arg(long, help = "Use the default browser for authentication")]
default_browser: bool,
#[arg(
long,
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable",
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers",
default_missing_value = "default",
num_args=0..=1
)]
browser: Option<String>,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Clean the cache of the embedded browser")]
pub clean: bool,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Args for Cli {
fn fix_openssl(&self) -> bool {
self.fix_openssl
}
fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
}
impl Cli {
async fn run(&mut self) -> anyhow::Result<()> {
if self.ignore_tls_errors {
info!("TLS errors will be ignored");
}
let mut openssl_conf = self.prepare_env()?;
self.server = normalize_server(&self.server)?;
let gp_params = self.build_gp_params();
// Get the initial SAML request
let saml_request = match self.saml_request {
Some(ref saml_request) => saml_request.clone(),
None => portal_prelogin(&self.server, &gp_params).await?,
};
let browser_auth = if let Some(browser) = &self.browser {
Some(BrowserAuthenticator::new_with_browser(&saml_request, browser))
} else if self.default_browser {
Some(BrowserAuthenticator::new(&saml_request))
} else {
None
};
if let Some(browser_auth) = browser_auth {
if let Some(auth_data) = browser_auth.authenticate()? {
info!("Authentication completed");
println!("{}", json!(SamlAuthResult::Success(auth_data)));
return Ok(());
}
info!("Please continue the authentication process in the default browser");
let auth_result = match wait_auth_data().await {
Ok(auth_data) => SamlAuthResult::Success(auth_data),
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
info!("Authentication completed");
println!("{}", json!(auth_result));
return Ok(());
}
self.saml_request.replace(saml_request);
let app = create_app(self.clone())?;
app.run(move |_app_handle, event| {
if let RunEvent::Exit = event {
if let Some(file) = openssl_conf.take() {
if let Err(err) = file.close() {
info!("Error closing OpenSSL config file: {}", err);
}
}
}
});
Ok(())
}
fn prepare_env(&self) -> anyhow::Result<Option<NamedTempFile>> {
#[cfg(feature = "webview-auth")]
gpapi::utils::env_utils::patch_gui_runtime_env(self.hidpi);
std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
if self.hidpi {
info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5");
std::env::set_var("GDK_SCALE", "2");
std::env::set_var("GDK_DPI_SCALE", "0.5");
}
if self.fix_openssl {
info!("Fixing OpenSSL environment");
@@ -112,151 +164,102 @@ impl Cli {
Ok(None)
}
async fn run(&self) -> anyhow::Result<()> {
if self.ignore_tls_errors {
info!("TLS errors will be ignored");
}
let openssl_conf = self.prepare_env()?;
let server = normalize_server(&self.server)?;
let gp_params = self.build_gp_params();
info!(
"gpauth auth host-id: {}",
gp_params.os_profile().host_identity().host_id()
);
let auth_request = match self.saml_request.as_deref() {
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&server, &gp_params, self.external_browser_requested()).await?,
};
#[cfg(feature = "webview-auth")]
let browser = self
.browser
.as_deref()
.or_else(|| self.default_browser.then(|| "default"));
#[cfg(not(feature = "webview-auth"))]
let browser = self.browser.as_deref().or(Some("default"));
if let Some(browser) = browser {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
let authenticator = BrowserAuthenticator::new(&auth_request, browser);
let auth_result = authenticator.authenticate().await;
print_auth_result(auth_result, Some(&auth_host_id));
// explicitly drop openssl_conf to avoid the unused variable warning
drop(openssl_conf);
return Ok(());
}
#[cfg(feature = "webview-auth")]
crate::webview_auth::authenticate(server, gp_params, auth_request, self.clean, openssl_conf).await?;
Ok(())
}
fn build_gp_params(&self) -> GpParams {
GpParams::builder(self.build_os_profile())
let gp_params = GpParams::builder()
.user_agent(&self.user_agent)
.client_os(ClientOs::from(&self.os))
.os_version(self.os_version.clone())
.ignore_tls_errors(self.ignore_tls_errors)
.is_gateway(self.gateway)
.build()
.build();
gp_params
}
fn build_os_profile(&self) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(self.os));
if let Some(host_id) = self.host_id.as_deref() {
builder = builder.host_id_override(host_id);
}
if let Some(client_version) = self.client_version.as_deref() {
builder = builder.client_version(client_version);
}
builder.build()
}
async fn saml_auth(&self, app_handle: AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_window = AuthWindow::new(app_handle)
.server(&self.server)
.user_agent(&self.user_agent)
.gp_params(self.build_gp_params())
.saml_request(self.saml_request.as_ref().unwrap())
.clean(self.clean);
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.default_browser || self.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
true
}
auth_window.open().await
}
}
fn init_logger(cli: &Cli) {
env_logger::builder()
.filter_level(cli.verbose.log_level_filter())
.init();
fn create_app(cli: Cli) -> anyhow::Result<App> {
let app = tauri::Builder::default()
.setup(|app| {
let app_handle = app.handle();
tauri::async_runtime::spawn(async move {
let auth_result = match cli.saml_auth(app_handle.clone()).await {
Ok(auth_data) => SamlAuthResult::Success(auth_data),
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
println!("{}", json!(auth_result));
});
Ok(())
})
.build(tauri::generate_context!())?;
Ok(app)
}
fn init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
}
pub async fn run() {
let cli = Cli::parse();
let mut cli = Cli::parse();
init_logger(&cli);
init_logger();
info!("gpauth started: {}", VERSION);
if let Err(err) = cli.run().await {
handle_error(err, &cli);
eprintln!("\nError: {}", err);
if err.to_string().contains("unsafe legacy renegotiation") && !cli.fix_openssl {
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
// Print the command
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
}
std::process::exit(1);
}
}
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) {
let auth_result = match auth_result {
Ok(auth_data) => {
let auth_data = match host_id {
Some(host_id) => auth_data.with_host_id(host_id),
None => auth_data,
};
SamlAuthResult::Success(auth_data)
}
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
// Start a local server to receive the browser authentication data
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
let port_file = temp_dir().join("gpcallback.port");
println!("{}", json!(auth_result));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn os_defaults_to_runtime_os() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
assert_eq!(cli.os, Os::default());
}
#[test]
fn host_id_arg_sets_profile_host_id_seed() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.host_identity().host_id(), "host-seed");
}
#[test]
fn browser_arg_requests_external_browser() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "firefox"]).expect("gpauth args should parse");
assert!(cli.external_browser_requested());
}
#[test]
fn client_version_arg_sets_profile_client_version() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
// Write the port to a file
fs::write(&port_file, port.to_string())?;
fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?;
// Remove the previous log file
let callback_log = temp_dir().join("gpcallback.log");
let _ = fs::remove_file(&callback_log);
info!("Listening authentication data on port {}", port);
info!(
"If it hangs, please check the logs at `{}` for more information",
callback_log.display()
);
let (mut socket, _) = listener.accept().await?;
info!("Received the browser authentication data from the socket");
let mut data = String::new();
socket.read_to_string(&mut data).await?;
// Remove the port file
fs::remove_file(&port_file)?;
let auth_data = SamlAuthData::from_gpcallback(&data)?;
Ok(auth_data)
}
+1 -3
View File
@@ -1,10 +1,8 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod auth_window;
mod cli;
#[cfg(feature = "webview-auth")]
mod webview_auth;
#[tokio::main]
async fn main() {
cli::run().await;
-49
View File
@@ -1,49 +0,0 @@
use auth::WebviewAuthenticator;
use gpapi::gp_params::GpParams;
use log::info;
use tauri::RunEvent;
use tempfile::NamedTempFile;
use crate::cli::print_auth_result;
pub async fn authenticate(
server: String,
gp_params: GpParams,
auth_request: String,
clean: bool,
mut openssl_conf: Option<NamedTempFile>,
) -> anyhow::Result<()> {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
tauri::Builder::default()
.setup(move |app| {
let app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
.with_auth_request(&auth_request)
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
.with_clean(clean);
let auth_result = authenticator.authenticate(&app_handle).await;
print_auth_result(auth_result, Some(&auth_host_id));
// Ensure the app exits after the authentication process
app_handle.exit(0);
});
Ok(())
})
.build(tauri::generate_context!())?
.run(move |_app_handle, event| {
if let RunEvent::Exit = event {
if let Some(file) = openssl_conf.take() {
if let Err(err) = file.close() {
info!("Error closing OpenSSL config file: {}", err);
}
}
}
});
Ok(())
}
+39 -8
View File
@@ -1,16 +1,47 @@
{
"$schema": "https://cdn.jsdelivr.net/gh/tauri-apps/tauri@tauri-v2.1.1/crates/tauri-cli/config.schema.json",
"$schema": "https://cdn.jsdelivr.net/gh/tauri-apps/tauri@tauri-v1.5.0/tooling/cli/schema.json",
"build": {
"frontendDist": ["index.html"],
"distDir": [
"index.html"
],
"devPath": [
"index.html"
],
"beforeDevCommand": "",
"beforeBuildCommand": ""
"beforeBuildCommand": "",
"withGlobalTauri": false
},
"identifier": "com.yuezk.gpauth",
"productName": "gpauth",
"app": {
"withGlobalTauri": false,
"package": {
"productName": "gpauth",
"version": "0.0.0"
},
"tauri": {
"allowlist": {
"all": false,
"http": {
"all": true,
"request": true,
"scope": [
"http://*",
"https://*"
]
}
},
"bundle": {
"active": true,
"targets": "deb",
"identifier": "com.yuezk.gpauth",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
]
},
"security": {
"csp": null
}
},
"windows": []
}
}
+5 -14
View File
@@ -1,6 +1,5 @@
[package]
name = "gpclient"
rust-version.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
@@ -10,28 +9,20 @@ license.workspace = true
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
openconnect = { path = "../../crates/openconnect" }
anyhow.workspace = true
askama.workspace = true
chrono.workspace = true
askama = "0.12"
chrono = "0.4"
clap.workspace = true
env_logger.workspace = true
inquire = "0.9"
inquire = "0.6.2"
log.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_urlencoded.workspace = true
whoami.workspace = true
tempfile.workspace = true
reqwest.workspace = true
directories.workspace = true
directories = "5.0"
compile-time.workspace = true
netdev.workspace = true
xmltree.workspace = true
uuid = { workspace = true, features = ["v5"] }
[features]
default = ["webview-auth"]
webview-auth = ["gpapi/webview-auth"]
xmltree = "0.11"
-56
View File
@@ -1,56 +0,0 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
let commit = env_commit("GPCLIENT_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(&source_commit))
.or_else(|| git_commit(&repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string());
println!("cargo:rustc-env=GPCLIENT_GIT_COMMIT={commit}");
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=12", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+32 -68
View File
@@ -1,37 +1,22 @@
use std::{env::temp_dir, fs::File, str::FromStr};
use std::{env::temp_dir, fs::File};
use anyhow::bail;
use clap::{Parser, Subcommand};
use gpapi::{
clap::{Args, InfoLevelVerbosity, handle_error},
utils::openssl,
};
use log::info;
use sysinfo::{Pid, System};
use gpapi::utils::openssl;
use log::{info, LevelFilter};
use tempfile::NamedTempFile;
use tokio::fs;
use crate::{
GP_CLIENT_LOCK_FILE,
connect::{ConnectArgs, ConnectHandler},
disconnect::{DisconnectArgs, DisconnectHandler},
hip::{HipArgs, HipHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
};
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPCLIENT_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
pub(crate) struct SharedArgs<'a> {
pub(crate) struct SharedArgs {
pub(crate) fix_openssl: bool,
pub(crate) ignore_tls_errors: bool,
pub(crate) verbose: &'a InfoLevelVerbosity,
}
#[derive(Subcommand)]
@@ -75,41 +60,9 @@ struct Cli {
fix_openssl: bool,
#[arg(long, help = "Ignore the TLS errors")]
ignore_tls_errors: bool,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Args for Cli {
fn fix_openssl(&self) -> bool {
self.fix_openssl
}
fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
}
impl Cli {
async fn is_running(&self) -> bool {
let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE).await else {
return false;
};
let Ok(pid) = Pid::from_str(c.trim()) else {
return false;
};
let s = System::new_all();
let Some(p) = s.process(pid) else {
return false;
};
p.exe()
.map(|exe| exe.to_string_lossy().contains("gpclient"))
.unwrap_or(false)
}
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
if self.fix_openssl {
let file = openssl::fix_openssl_env()?;
@@ -120,18 +73,12 @@ impl Cli {
}
async fn run(&self) -> anyhow::Result<()> {
// check if an instance is running
if !matches!(self.command, CliCommand::Disconnect(_)) && self.is_running().await {
bail!("Another instance of the client is already running");
}
// The temp file will be dropped automatically when the file handle is dropped
// So, declare it here to ensure it's not dropped
let _file = self.fix_openssl()?;
let shared_args = SharedArgs {
fix_openssl: self.fix_openssl,
ignore_tls_errors: self.ignore_tls_errors,
verbose: &self.verbose,
};
if self.ignore_tls_errors {
@@ -147,18 +94,18 @@ impl Cli {
}
}
fn init_logger(cli: &Cli) {
fn init_logger(command: &CliCommand) {
let mut builder = env_logger::builder();
builder.filter_level(cli.verbose.log_level_filter());
builder.filter_level(LevelFilter::Info);
// Output the log messages to a file if the command is the auth callback
if let CliCommand::LaunchGui(args) = &cli.command {
if let CliCommand::LaunchGui(args) = command {
let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty()
&& let Ok(log_file) = File::create(temp_dir().join("gpcallback.log"))
{
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
if !auth_data.is_empty() {
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
}
}
@@ -168,12 +115,29 @@ fn init_logger(cli: &Cli) {
pub(crate) async fn run() {
let cli = Cli::parse();
init_logger(&cli);
init_logger(&cli.command);
info!("gpclient started: {}", VERSION);
if let Err(err) = cli.run().await {
handle_error(err, &cli);
eprintln!("\nError: {}", err);
let err = err.to_string();
if err.contains("unsafe legacy renegotiation") && !cli.fix_openssl {
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
// Print the command
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
}
if err.contains("certificate verify failed") && !cli.ignore_tls_errors {
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
// Print the command
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
}
std::process::exit(1);
}
}
+436
View File
@@ -0,0 +1,436 @@
use std::{cell::RefCell, fs, sync::Arc};
use anyhow::bail;
use clap::Args;
use common::vpn_utils::find_csd_wrapper;
use gpapi::{
auth::SamlAuthResult,
clap::args::Os,
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{gateway_login, GatewayLogin},
gp_params::{ClientOs, GpParams},
portal::{prelogin, retrieve_config, Prelogin},
process::{
auth_launcher::SamlAuthLauncher,
users::{get_non_root_user, get_user_by_name},
},
utils::{request::RequestIdentityError, shutdown_signal},
GP_USER_AGENT,
};
use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::info;
use openconnect::Vpn;
use crate::{cli::SharedArgs, GP_CLIENT_LOCK_FILE};
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
gateway: Option<String>,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
passwd_on_stdin: bool,
#[arg(long, help = "Read the cookie from standard input")]
cookie_on_stdin: bool,
#[arg(long, short, help = "The VPNC script to use")]
script: Option<String>,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
as_gateway: bool,
#[arg(
long,
help = "Use the default CSD wrapper to generate the HIP report and send it to the server"
)]
hip: bool,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>,
#[arg(long, help = "Same as the '--csd-user' option in the openconnect command")]
csd_user: Option<String>,
#[arg(long, help = "Same as the '--csd-wrapper' option in the openconnect command")]
csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
disable_ipv6: bool,
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
os: Os,
#[arg(long, help = "If not specified, it will be computed based on the --os option")]
os_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")]
no_dtls: bool,
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
clean: bool,
#[arg(long, help = "Use the default browser to authenticate")]
default_browser: bool,
#[arg(
long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers",
default_missing_value = "default",
num_args=0..=1
)]
browser: Option<String>,
}
impl ConnectArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else {
Os::Linux
}
}
fn os_version(&self) -> String {
if let Some(os_version) = self.os_version.as_deref() {
return os_version.to_string();
}
match self.os {
Os::Linux => format!("Linux {}", whoami::distro()),
Os::Windows => String::from("Microsoft Windows 11 Pro , 64-bit"),
Os::Mac => String::from("Apple Mac OS X 13.4.0"),
}
}
}
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs,
latest_key_password: RefCell<Option<String>>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
Self {
args,
shared_args,
latest_key_password: Default::default(),
}
}
fn build_gp_params(&self) -> GpParams {
GpParams::builder()
.user_agent(&self.args.user_agent)
.client_os(ClientOs::from(&self.args.os))
.os_version(self.args.os_version())
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.build()
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
let Err(err) = self.handle_impl().await else {
return Ok(());
};
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
eprintln!("ERROR: No private key found in the certificate file");
eprintln!("ERROR: Please provide the private key file using the `-k` option");
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
// Decrypt the private key error, ask for the key password
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
if as_gateway {
info!("Treating the server as a gateway");
return self.connect_gateway_with_prelogin(server).await;
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
info!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server).await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = prelogin(portal, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, portal).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
portal_config.sort_gateways(prelogin.region());
let gateways = portal_config.gateways();
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into();
let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(cookie) => cookie,
Err(err) => {
info!("Gateway login failed: {}", err);
return self.connect_gateway_with_prelogin(gateway).await;
}
};
self.connect_gateway(gateway, &cookie).await
}
async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
self.connect_gateway(gateway, &cookie).await
}
async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
let mut gp_params = gp_params.clone();
loop {
match gateway_login(gateway, cred, &gp_params).await? {
GatewayLogin::Cookie(cookie) => return Ok(cookie),
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
gp_params.set_otp(&otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
async fn connect_gateway(&self, gateway: &str, cookie: &str) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0);
let csd_uid = get_csd_uid(&self.args.csd_user)?;
let csd_wrapper = if self.args.csd_wrapper.is_some() {
self.args.csd_wrapper.clone()
} else if self.args.hip {
find_csd_wrapper()
} else {
None
};
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_string();
let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.user_agent(self.args.user_agent.clone())
.os(Some(os))
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.build()?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
// Listen for the interrupt signal in the background
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
vpn_clone.disconnect();
});
vpn.connect(write_pid_file);
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
fs::remove_file(GP_CLIENT_LOCK_FILE)?;
}
Ok(())
}
async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
if self.args.cookie_on_stdin {
return read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
let browser = if prelogin.support_default_browser() {
self.args.browser.as_deref()
} else {
None
};
let cred = SamlAuthLauncher::new(&self.args.server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.user_agent(&self.args.user_agent)
.os(self.args.os.as_str())
.os_version(Some(&self.args.os_version()))
.hidpi(self.args.hidpi)
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.clean(self.args.clean)
.default_browser(use_default_browser)
.browser(browser)
.launch()
.await?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
let password = if self.args.passwd_on_stdin {
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
input.trim_end().to_owned()
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into())
}
}
}
}
fn read_cookie_from_stdin() -> anyhow::Result<Credential> {
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
let Ok(auth_result) = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()) else {
bail!("Failed to parse auth data")
};
Credential::try_from(auth_result)
}
fn write_pid_file() {
let pid = std::process::id();
fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()).unwrap();
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
}
fn get_csd_uid(csd_user: &Option<String>) -> anyhow::Result<u32> {
if let Some(csd_user) = csd_user {
get_user_by_name(csd_user).map(|user| user.uid())
} else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
-381
View File
@@ -1,381 +0,0 @@
use clap::Args;
use gpapi::{
clap::args::Os,
cookie_store,
gp_params::CscMode,
os_profile::{ClientOs, OsProfile},
};
use log::warn;
use std::path::PathBuf;
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
pub(super) server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
pub(super) gateway: Option<String>,
#[arg(
long,
conflicts_with = "gateway",
help = "Automatically try gateways in priority order until gateway auth/config succeeds, without prompting"
)]
pub(super) auto_gateway: bool,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
pub(super) user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
pub(super) passwd_on_stdin: bool,
#[arg(long, help = "Read the gpauth authentication result from standard input")]
pub(super) cookie_on_stdin: bool,
#[arg(
long,
help = "Read and write the portal cookie cache, optionally specify the cache file path",
default_missing_value = "",
num_args=0..=1
)]
pub(super) cookie_cache: Option<String>,
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
pub(super) script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
pub(super) interface: Option<String>,
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
pub(super) script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
pub(super) as_gateway: bool,
#[arg(
long,
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
default_missing_value = "",
num_args=0..=1
)]
pub(super) hip: Option<String>,
#[arg(long, help = "The user used to run the HIP script")]
pub(super) hip_user: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
pub(super) certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
pub(super) sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
pub(super) key_password: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_user: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
pub(super) reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
pub(super) mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
pub(super) disable_ipv6: bool,
#[arg(long = "user-agent", hide = true)]
pub(super) deprecated_user_agent: Option<String>,
#[arg(long = "os-version", hide = true)]
pub(super) deprecated_os_version: Option<String>,
#[arg(long, help = "Override the client version reported to the server, e.g., '6.2.4-49'")]
pub(super) client_version: Option<String>,
#[arg(long, value_enum, default_value_t = Os::default())]
pub(super) os: Os,
#[arg(long, value_enum, default_value_t = CscMode::Auto, help = "CSC support mode: auto, yes, or no")]
pub(super) csc: CscMode,
#[arg(long, help = "Disable DTLS and ESP")]
pub(super) no_dtls: bool,
#[arg(
long = "local-hostname",
help = "Same as the '--local-hostname' option in the openconnect command"
)]
pub(super) local_hostname: Option<String>,
#[arg(
long = "force-dpd",
help = "Same as the '--force-dpd' option in the openconnect command"
)]
pub(super) dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
pub(super) no_xmlpost: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
pub(super) hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
pub(super) clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
pub(super) default_browser: bool,
#[arg(
long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`.\nOr the path to the browser executable.\nUse 'remote' for headless servers.",
default_missing_value = "default",
num_args=0..=1
)]
pub(super) browser: Option<String>,
}
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
build_os_profile_with_host_id(args, None)
}
pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option<&str>) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(args.os));
if let Some(client_version) = args.client_version.as_deref() {
builder = builder.client_version(client_version.to_string());
}
if let Some(local_hostname) = args.local_hostname.as_deref() {
builder = builder.computer_name_override(local_hostname.to_string());
}
if let Some(host_id) = host_id {
builder = builder.host_id_override(host_id);
}
builder.build()
}
pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option<PathBuf> {
args.cookie_cache.as_deref().map(|path| {
let custom = (!path.is_empty()).then_some(path);
cookie_store::cookie_path(custom)
})
}
pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
if args.csd_user.is_some() {
warn!("Deprecated option --csd-user will be removed; use --hip-user instead");
}
if args.csd_wrapper.is_some() {
warn!("Deprecated option --csd-wrapper will be removed; use --hip instead");
}
if args.deprecated_user_agent.is_some() {
warn!("Deprecated option --user-agent is ignored; user agent is derived from --os");
}
if args.deprecated_os_version.is_some() {
warn!("Deprecated option --os-version is ignored; OS version is derived from --os");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(clap::Parser)]
struct ConnectArgsTestCli {
#[command(flatten)]
args: ConnectArgs,
}
#[test]
fn parses_csc_mode_values() {
use clap::ValueEnum;
assert_eq!(CscMode::from_str("auto", false), Ok(CscMode::Auto));
assert_eq!(CscMode::from_str("yes", false), Ok(CscMode::Yes));
assert_eq!(CscMode::from_str("no", false), Ok(CscMode::No));
assert!(CscMode::from_str("maybe", false).is_err());
}
#[test]
fn auto_gateway_flag_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--auto-gateway"])
.expect("--auto-gateway alone should parse");
assert!(cli.args.auto_gateway);
assert!(cli.args.gateway.is_none());
}
#[test]
fn auto_gateway_help_describes_auth_config_retry() {
use clap::CommandFactory;
let help = ConnectArgsTestCli::command().render_long_help().to_string();
assert!(help.contains("--auto-gateway"));
assert!(help.contains("Automatically try gateways in priority order until gateway auth/config succeeds"));
}
#[test]
fn gateway_flag_alone_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1"])
.expect("--gateway alone should parse");
assert!(!cli.args.auto_gateway);
assert_eq!(cli.args.gateway.as_deref(), Some("gw1"));
}
#[test]
fn os_defaults_to_runtime_os() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert_eq!(cli.args.os, Os::default());
}
#[test]
fn deprecated_profile_override_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
assert_eq!(cli.args.deprecated_user_agent.as_deref(), Some("legacy-agent"));
assert_eq!(cli.args.deprecated_os_version.as_deref(), Some("legacy-os"));
assert_eq!(cli.args.client_version.as_deref(), Some("legacy-client"));
}
#[test]
fn deprecated_profile_override_flags_do_not_affect_os_profile() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--os",
"Linux",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
let profile = build_os_profile(&cli.args);
assert_ne!(profile.user_agent(), "legacy-agent");
assert_ne!(profile.os_version(), "legacy-os");
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
#[test]
fn stdin_host_id_sets_profile_runtime_identity_seed() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--os", "Linux"])
.expect("connect args should parse");
let profile = build_os_profile_with_host_id(&cli.args, Some("auth-host-id"));
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
}
#[test]
fn cookie_cache_is_disabled_by_default() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert!(cli.args.cookie_cache.is_none());
assert!(cookie_cache_path(&cli.args).is_none());
}
#[test]
fn cookie_cache_accepts_default_path_without_value() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache"])
.expect("--cookie-cache without value should parse");
assert_eq!(cli.args.cookie_cache.as_deref(), Some(""));
assert!(cookie_cache_path(&cli.args).is_some());
}
#[test]
fn cookie_cache_accepts_custom_path() {
use clap::Parser;
let cli =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache", "/tmp/gp-cookie.json"])
.expect("--cookie-cache with value should parse");
assert_eq!(
cookie_cache_path(&cli.args).as_deref(),
Some(std::path::Path::new("/tmp/gp-cookie.json"))
);
}
#[test]
fn deprecated_hip_alias_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--csd-user",
"legacy-user",
"--csd-wrapper",
"/tmp/legacy-hip.sh",
])
.expect("deprecated HIP alias flags should remain parse-compatible");
assert_eq!(cli.args.csd_user.as_deref(), Some("legacy-user"));
assert_eq!(cli.args.csd_wrapper.as_deref(), Some("/tmp/legacy-hip.sh"));
}
#[test]
fn auto_gateway_and_gateway_are_mutually_exclusive() {
use clap::Parser;
use clap::error::ErrorKind;
let result =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1", "--auto-gateway"]);
let err = match result {
Ok(_) => panic!("--gateway and --auto-gateway must conflict"),
Err(err) => err,
};
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
}
-267
View File
@@ -1,267 +0,0 @@
use anyhow::{Context, bail};
use gpapi::{
auth::SamlAuthResult,
clap::ToVerboseArg,
credential::{Credential, PasswordCredential},
portal::{Prelogin, StandardPrelogin},
process::auth_launcher::SamlAuthLauncher,
};
use inquire::{Password, PasswordDisplayMode, Text};
use log::info;
use super::ConnectHandler;
#[derive(Default)]
pub(super) struct CleanAuthState {
requested: bool,
}
impl CleanAuthState {
pub(super) fn new(requested: bool) -> Self {
Self { requested }
}
fn consume_for_webview(&mut self, webview_auth: bool) -> bool {
if !webview_auth || !self.requested {
return false;
}
self.requested = false;
true
}
}
impl ConnectHandler<'_> {
pub(super) fn prepare_cookie_from_stdin(&self) -> anyhow::Result<()> {
if !self.args.cookie_on_stdin || self.cookie_from_stdin.borrow().is_some() {
return Ok(());
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Ok(())
}
pub(super) async fn obtain_credential(
&self,
prelogin: &Prelogin,
server: &str,
portal_default_browser_enabled: bool,
) -> anyhow::Result<Credential> {
if should_read_stdin_credential(self.args.cookie_on_stdin, self.args.as_gateway, prelogin.is_gateway()) {
return self.read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let external_browser_supported = default_browser_auth_allowed(
prelogin.support_default_browser(),
is_gateway,
portal_default_browser_enabled,
);
let browser = if external_browser_supported {
self.args.browser.as_deref()
} else if !cfg!(feature = "webview-auth") {
bail!(
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
);
} else {
None
};
let verbose = self.shared_args.verbose.to_verbose_arg();
let os_profile = self.os_profile.borrow().clone();
let auth_launcher = SamlAuthLauncher::new(server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.os_profile(&os_profile)
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.browser(browser)
.verbose(verbose);
#[cfg(feature = "webview-auth")]
let use_default_browser = external_browser_supported && self.args.default_browser;
#[cfg(feature = "webview-auth")]
let browser_kind = if browser.is_some() || use_default_browser {
"external"
} else {
"embedded"
};
#[cfg(not(feature = "webview-auth"))]
let browser_kind = "external";
let clean_auth = self
.clean_auth_state
.borrow_mut()
.consume_for_webview(browser_kind == "embedded");
info!(
"SAML auth launch: gateway={}, clean={}, browser={}",
is_gateway, clean_auth, browser_kind
);
#[cfg(feature = "webview-auth")]
let auth_launcher = auth_launcher
.hidpi(self.args.hidpi)
.clean(clean_auth)
.default_browser(use_default_browser);
let cred = auth_launcher.launch().await?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
let password = self.obtain_password(prelogin)?;
let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into())
}
}
}
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> {
if let Some(cookie) = self.cookie_from_stdin.borrow().as_ref() {
info!("Reusing the cookie read from standard input");
return Credential::try_from(serde_json::from_str::<SamlAuthResult>(cookie)?);
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Credential::try_from(auth_result)
}
fn read_auth_result_from_stdin(&self) -> anyhow::Result<SamlAuthResult> {
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
self.cookie_from_stdin.replace(Some(cookie.trim_end().to_owned()));
let auth_result = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()).context("Failed to parse auth data")?;
Ok(auth_result)
}
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
let password = if self.args.passwd_on_stdin {
if let Some(password) = self.password_from_stdin.borrow().as_ref() {
info!("Reusing the password read from standard input");
return Ok(password.clone());
}
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let password = input.trim_end().to_owned();
self.password_from_stdin.replace(Some(password.clone()));
password
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
Ok(password)
}
}
fn should_read_stdin_credential(cookie_on_stdin: bool, as_gateway: bool, prelogin_is_gateway: bool) -> bool {
cookie_on_stdin && (!prelogin_is_gateway || as_gateway)
}
fn default_browser_auth_allowed(
saml_support_default_browser: bool,
is_gateway: bool,
portal_default_browser_enabled: bool,
) -> bool {
saml_support_default_browser && (!is_gateway || portal_default_browser_enabled)
}
fn log_stdin_host_id(host_id: Option<&str>) {
match host_id {
Some(host_id) => info!("stdin auth result host-id: {}", host_id),
None => info!("stdin auth result host-id: <none>"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_auth_state_is_consumed_once_for_webview() {
let mut state = CleanAuthState::new(true);
assert!(state.consume_for_webview(true));
assert!(!state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_is_not_consumed_by_external_browser() {
let mut state = CleanAuthState::new(true);
assert!(!state.consume_for_webview(false));
assert!(state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_remains_false_when_not_requested() {
let mut state = CleanAuthState::new(false);
assert!(!state.consume_for_webview(true));
assert!(!state.consume_for_webview(false));
}
#[test]
fn stdin_credential_is_allowed_for_portal_auth() {
assert!(should_read_stdin_credential(true, false, false));
}
#[test]
fn stdin_credential_is_allowed_for_direct_gateway_auth() {
assert!(should_read_stdin_credential(true, true, true));
}
#[test]
fn stdin_credential_is_not_reused_for_gateway_fallback_auth() {
assert!(!should_read_stdin_credential(true, false, true));
}
#[test]
fn stdin_credential_is_not_used_when_flag_is_disabled() {
assert!(!should_read_stdin_credential(false, false, false));
assert!(!should_read_stdin_credential(false, true, true));
}
#[test]
fn portal_saml_can_use_default_browser_when_supported() {
assert!(default_browser_auth_allowed(true, false, false));
}
#[test]
fn gateway_saml_requires_portal_default_browser_policy() {
assert!(!default_browser_auth_allowed(true, true, false));
assert!(default_browser_auth_allowed(true, true, true));
}
#[test]
fn default_browser_auth_requires_saml_support() {
assert!(!default_browser_auth_allowed(false, false, true));
assert!(!default_browser_auth_allowed(false, true, true));
}
}
-505
View File
@@ -1,505 +0,0 @@
use std::{
fs,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
};
use gpapi::{
cookie_store,
credential::{AuthCookieCredential, Credential},
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
gp_params::GpParams,
os_profile::OsProfile,
portal::prelogin,
process::users::{get_non_root_user, get_user_by_name},
utils::shutdown_signal,
};
use inquire::Text;
use log::{info, warn};
use openconnect::{Vpn, VpnBuilder};
use tokio::{runtime::Handle, task::JoinHandle};
use crate::{
GP_CLIENT_LOCK_FILE,
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
};
use super::{ConnectHandler, args::cookie_cache_path};
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GatewayConnectFailureStage {
BeforeTunnel,
AfterTunnel,
}
#[derive(Debug)]
pub(super) struct GatewayConnectError {
stage: GatewayConnectFailureStage,
error: anyhow::Error,
}
impl GatewayConnectError {
fn before_tunnel(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::BeforeTunnel,
error,
}
}
fn after_tunnel(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::AfterTunnel,
error,
}
}
pub(super) fn is_before_tunnel(&self) -> bool {
self.stage == GatewayConnectFailureStage::BeforeTunnel
}
pub(super) fn as_error(&self) -> &anyhow::Error {
&self.error
}
pub(super) fn into_error(self) -> anyhow::Error {
self.error
}
}
impl ConnectHandler<'_> {
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<()> {
let path = cookie_cache_path(self.args)?;
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
let stored = cookie_store::load(&path, server, &host_id)?;
if !stored.auth_cookie.can_authenticate_gateway() {
warn!(
"Cached portal cookie for {} is not usable for gateway authentication. Clearing cache.",
stored.server
);
cookie_store::clear(&path);
return None;
}
info!(
"Using cached portal cookie for {} (saved_at={}, gateway={})",
stored.server, stored.saved_at, stored.last_gateway
);
let cred: Credential = (&stored.auth_cookie).into();
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params, None).await {
Ok(session) => session,
Err(err) => {
warn!(
"Cached portal cookie rejected by gateway {}: {}. Clearing cache and falling back to portal auth.",
stored.last_gateway, err
);
cookie_store::clear(&path);
return None;
}
};
match self
.connect_gateway(
server,
&stored.last_gateway,
&login_session.cookie,
false,
login_session.extension_auth,
)
.await
{
Ok(()) => Some(()),
Err(err) => {
warn!("Gateway connect failed after cached-cookie login: {}", err.as_error());
None
}
}
}
pub(super) async fn connect_gateway_with_prelogin(
&self,
portal: &str,
gateway: &str,
allow_extend_session: bool,
gateway_context: Option<GatewayLoginContext>,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let prelogin = prelogin(gateway, &gp_params, self.prelogin_options(false)).await?;
let cred = self.obtain_credential(&prelogin, gateway, false).await?;
let login_session = self
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
.await?;
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await
.map_err(GatewayConnectError::into_error)
}
/// Connect to a gateway using the official client's auth flow:
///
/// 1. Call gateway prelogin and retain the response (SAML data is held as a fallback).
/// 2. If the portal provided auth cookies, attempt gateway login using them.
/// 3. If that login succeeds, proceed directly to the VPN connection.
/// 4. If no portal auth cookies exist or portal-cookie login fails, use the retained gateway prelogin response to authenticate
/// against the gateway (SAML or username/password) and obtain a gateway-issued
/// credential.
/// 5. Retry gateway login with the gateway credential (now carrying the gateway's
/// `prelogin-cookie`) and connect on success.
pub(super) async fn connect_gateway_with_fallback(
&self,
portal: &str,
gateway: &str,
portal_cred: &AuthCookieCredential,
allow_extend_session: bool,
portal_default_browser_enabled: bool,
gateway_context: GatewayLoginContext,
) -> Result<(), GatewayConnectError> {
info!("Connecting to gateway with portal-cookie first, gateway prelogin fallback...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let gateway_prelogin = prelogin(
gateway,
&gp_params,
self.prelogin_options(portal_default_browser_enabled),
)
.await
.map_err(GatewayConnectError::before_tunnel)?;
if portal_cred.can_authenticate_gateway() {
let portal_cred_for_login: Credential = portal_cred.into();
match self
.login_gateway(gateway, &portal_cred_for_login, &gp_params, Some(&gateway_context))
.await
{
Ok(login_session) => {
info!("Gateway login with portal auth cookies succeeded");
self.save_cookie_cache(portal, gateway, portal_cred);
return self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await;
}
Err(err) => {
info!("Gateway login with portal auth cookies failed: {}", err);
info!("Falling back to gateway prelogin authentication...");
}
}
} else {
info!("Portal config did not provide gateway auth cookies; using gateway prelogin flow");
}
let gateway_cred = match self
.obtain_credential(&gateway_prelogin, gateway, portal_default_browser_enabled)
.await
{
Ok(cred) => cred,
Err(err) => {
self.print_direct_gateway_recommendation(gateway);
return Err(GatewayConnectError::before_tunnel(err));
}
};
let login_session = match self
.login_gateway(gateway, &gateway_cred, &gp_params, Some(&gateway_context))
.await
{
Ok(login_session) => login_session,
Err(err) => {
self.print_direct_gateway_recommendation(gateway);
return Err(GatewayConnectError::before_tunnel(err));
}
};
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await
}
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
let Some(path) = cookie_cache_path(self.args) else {
return;
};
if !auth_cookie.can_authenticate_gateway() {
return;
}
let stored = cookie_store::StoredCookie::new(
portal.to_string(),
auth_cookie.username().to_string(),
self.os_profile.borrow().host_identity().host_id().to_string(),
gateway.to_string(),
auth_cookie.clone(),
);
match cookie_store::save(&path, &stored) {
Ok(()) => info!("Saved portal cookie cache to {}", path.display()),
Err(err) => warn!("Failed to save portal cookie cache to {}: {}", path.display(), err),
}
}
fn print_direct_gateway_recommendation(&self, gateway: &str) {
if !self.args.cookie_on_stdin {
return;
}
eprintln!("\nNOTE: Gateway authentication failed after portal login.");
eprintln!("NOTE: If this server also accepts direct gateway login, try:");
eprintln!("NOTE: {}", direct_gateway_command(gateway));
}
async fn login_gateway(
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
gateway_context: Option<&GatewayLoginContext>,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone();
loop {
let login = match gateway_context {
Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?,
None => gateway_login(gateway, cred, &gp_params).await?,
};
match login {
GatewayLogin::Cookie(cookie) => {
return Ok(GatewayLoginSession {
cookie,
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
});
}
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
gp_params.set_otp(&otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
async fn connect_gateway(
&self,
portal: &str,
gateway: &str,
cookie: &str,
allow_extend_session: bool,
extension_auth: SessionExtensionAuth,
) -> Result<(), GatewayConnectError> {
let mtu = self.args.mtu.unwrap_or(0);
let (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user();
let csd_uid = get_uid(&hip_user).map_err(GatewayConnectError::before_tunnel)?;
let os_profile = self.os_profile.borrow().clone();
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
os_profile: os_profile.clone(),
certificate: self.args.certificate.clone(),
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn_builder = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.interface(self.args.interface.clone())
.script_tun(self.args.script_tun)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.hip(hip)
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
.no_xmlpost(self.args.no_xmlpost);
let vpn = apply_os_profile(vpn_builder, &os_profile)
.build()
.map_err(|err| GatewayConnectError::before_tunnel(err.into()))?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
let tunnel_established = Arc::new(AtomicBool::new(false));
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
vpn_clone.disconnect();
});
let connect_result = vpn.connect(move |vpn_session_info| {
tunnel_established_on_connect.store(true, Ordering::SeqCst);
write_pid_file();
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
info!("VPN session info: {}", session_info.log_summary());
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
session_task_on_connect.lock().unwrap().replace(task);
});
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
fs::remove_file(GP_CLIENT_LOCK_FILE).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
}
classify_openconnect_result(connect_result, tunnel_established)
}
fn determine_hip_script(&self) -> (bool, Option<String>) {
if let Some(hip) = &self.args.hip {
return if hip.is_empty() {
(true, None)
} else {
(true, Some(hip.clone()))
};
}
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
}
fn determine_hip_user(&self) -> Option<String> {
if let Some(hip_user) = &self.args.hip_user {
return Some(hip_user.clone());
}
self.args.csd_user.clone()
}
}
fn classify_openconnect_result(exit_code: i32, tunnel_established: bool) -> Result<(), GatewayConnectError> {
if exit_code == 0 {
return Ok(());
}
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
if tunnel_established {
Err(GatewayConnectError::after_tunnel(error))
} else {
Err(GatewayConnectError::before_tunnel(error))
}
}
fn direct_gateway_command(gateway: &str) -> String {
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
}
fn write_pid_file() {
let pid = std::process::id();
if let Err(err) = fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()) {
warn!("Failed to write PID file: {}", err);
} else {
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
}
}
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
if let Some(user) = user {
get_user_by_name(user).map(|user| user.uid())
} else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
builder
.os(Some(profile.client_os().to_openconnect_os().to_string()))
.os_version(Some(profile.os_version().to_string()))
.client_version(Some(profile.client_version().to_string()))
.host_id(Some(profile.host_identity().host_id().to_string()))
.user_agent(Some(profile.user_agent().to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn openconnect_success_is_not_a_gateway_failure() {
assert!(classify_openconnect_result(0, false).is_ok());
assert!(classify_openconnect_result(0, true).is_ok());
}
#[test]
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
let err = classify_openconnect_result(1, false).expect_err("nonzero exit should fail");
assert!(err.is_before_tunnel());
}
#[test]
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
let err = classify_openconnect_result(1, true).expect_err("nonzero exit should fail");
assert!(!err.is_before_tunnel());
}
#[test]
fn direct_gateway_recommendation_uses_gateway_server() {
assert_eq!(
direct_gateway_command("gateway.example.test"),
"gpauth --gateway gateway.example.test | sudo gpclient connect gateway.example.test --as-gateway --cookie-on-stdin"
);
}
}
-281
View File
@@ -1,281 +0,0 @@
mod args;
mod credential;
mod gateway;
use std::cell::RefCell;
use anyhow::bail;
use gpapi::{
error::PortalError,
gateway::{GatewayLoginContext, GatewaySelection},
gp_params::GpParams,
os_profile::OsProfile,
portal::{PreloginOptions, prelogin, retrieve_config},
utils::request::RequestIdentityError,
};
use inquire::{Password, PasswordDisplayMode, Select};
use log::{info, warn};
use crate::cli::SharedArgs;
pub(crate) use args::ConnectArgs;
use args::{build_os_profile, build_os_profile_with_host_id, warn_deprecated_connect_args};
use credential::CleanAuthState;
use gateway::GatewayConnectError;
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs<'a>,
os_profile: RefCell<OsProfile>,
latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>,
clean_auth_state: RefCell<CleanAuthState>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
warn_deprecated_connect_args(args);
#[cfg(feature = "webview-auth")]
let clean_auth = args.clean;
#[cfg(not(feature = "webview-auth"))]
let clean_auth = false;
Self {
args,
shared_args,
os_profile: RefCell::new(build_os_profile(args)),
latest_key_password: Default::default(),
password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(),
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
}
}
fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder(self.os_profile.borrow().clone());
builder
.csc_mode(self.args.csc)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone());
builder.build()
}
pub(super) fn prelogin_options(&self, portal_default_browser_enabled: bool) -> PreloginOptions {
PreloginOptions::default()
.external_browser_requested(self.external_browser_requested())
.portal_default_browser_enabled(portal_default_browser_enabled)
}
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.args.default_browser || self.args.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
self.args.browser.is_some()
}
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
#[cfg(feature = "webview-auth")]
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
let Err(err) = self.handle_impl().await else {
return Ok(());
};
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
eprintln!("ERROR: No private key found in the certificate file");
eprintln!("ERROR: Please provide the private key file using the `-k` option");
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
self.prepare_cookie_from_stdin()?;
if as_gateway {
info!("Treating the server as a gateway");
return self.connect_gateway_with_prelogin(server, server, false, None).await;
}
if !self.args.cookie_on_stdin {
if let Some(()) = self.try_cached_cookie(server).await {
return Ok(());
}
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server, server, false, None).await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = prelogin(portal, &gp_params, self.prelogin_options(false)).await?;
let cred = self.obtain_credential(&prelogin, portal, false).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
portal_config.sort_gateways(prelogin.region());
let auth_cookie = match cred.password() {
Some(password) => portal_config.auth_cookie().clone().with_password(password),
None => portal_config.auth_cookie().clone(),
};
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
let portal_default_browser_enabled = portal_config.default_browser().unwrap_or(false);
if self.args.auto_gateway {
let gateways = portal_config.gateways();
if gateways.is_empty() {
bail!("No gateways available in portal config for auto-gateway selection");
}
info!(
"Auto-gateway mode: trying {} gateway(s) in priority order",
gateways.len()
);
let mut last_err: Option<anyhow::Error> = None;
for gateway in &gateways {
info!("Auto-gateway: attempting gateway {}", gateway);
let gateway_context =
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(portal_config.connect_method());
match self
.connect_gateway_with_fallback(
portal,
gateway.server(),
&auth_cookie,
allow_extend_session,
portal_default_browser_enabled,
gateway_context,
)
.await
{
Ok(()) => return Ok(()),
Err(err) => {
if !err.is_before_tunnel() {
return Err(err.into_error());
}
warn!(
"Auto-gateway: gateway {} failed before tunnel setup: {}",
gateway,
err.as_error()
);
last_err = Some(err.into_error());
}
}
}
let detail = last_err
.map(|e| e.to_string())
.unwrap_or_else(|| "unknown error".to_string());
bail!(
"Auto-gateway: all {} gateway(s) failed to connect; last error: {}",
gateways.len(),
detail
);
}
let gateway_selection = if self.args.gateway.is_some() {
GatewaySelection::Manual
} else {
GatewaySelection::Auto
};
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
let gateways = portal_config.gateways();
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
let gateway = selected_gateway.server();
let gateway_context =
GatewayLoginContext::new(selected_gateway, gateway_selection).with_connect_method(portal_config.connect_method());
self
.connect_gateway_with_fallback(
portal,
gateway,
&auth_cookie,
allow_extend_session,
portal_default_browser_enabled,
gateway_context,
)
.await
.map_err(GatewayConnectError::into_error)
}
fn apply_stdin_host_id(&self, host_id: Option<&str>) {
let Some(host_id) = host_id else {
return;
};
self
.os_profile
.replace(build_os_profile_with_host_id(self.args, Some(host_id)));
info!(
"connect profile host-id: {}",
self.os_profile.borrow().host_identity().host_id()
);
}
}
+113 -435
View File
@@ -1,13 +1,8 @@
use askama::Template;
use clap::Args;
use gpapi::{
clap::args::Os,
os_profile::{ClientOs, OsProfile, OsProfileBuilder},
};
use gpapi::{clap::args::Os, utils::host_utils};
use log::debug;
use serde::Deserialize;
use std::collections::HashMap;
use std::process::Command;
use std::{collections::HashMap, env};
use xmltree::Element;
#[derive(Template)]
@@ -19,47 +14,22 @@ struct HipReportTemplate<'a> {
month: String,
year: String,
user_name: &'a str,
host_info: HostInfo,
host_info: HostInfo<'a>,
md5: &'a str,
}
#[derive(Debug, Clone, Deserialize)]
struct DefenderInfo {
#[serde(rename = "appVersion")]
app_version: String,
#[serde(rename = "engineVersion")]
engine_version: String,
#[serde(rename = "definitionsVersion")]
definitions_version: String,
#[serde(rename = "realTimeProtectionEnabled")]
real_time_protection_enabled: RealTimeProtection,
}
#[derive(Debug, Clone, Deserialize)]
struct RealTimeProtection {
value: bool,
}
/// Host information for HIP reporting
struct HostInfo {
/// Common for all OSes, e.g., "Apple", "Microsoft", "Linux"
os_vendor: String,
/// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc.
os_version: String,
/// Per-OS machine identifier (UUID for Linux/Windows, MAC for macOS)
struct HostInfo<'a> {
os_vendor: &'a str,
os_version: &'a str,
host_id: String,
/// Common for all OSes
host_name: String,
/// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130"
software_version: String,
software_version: &'a str,
domain: String,
network_interfaces: Vec<NetworkInterface>,
defender: Option<DefenderInfo>,
}
impl HostInfo {
/// Get the first available IPv4 address from network interfaces
pub fn default_ipv4(&self) -> &str {
impl<'a> HostInfo<'a> {
fn default_ipv4(&self) -> &str {
self
.network_interfaces
.first()
@@ -67,8 +37,7 @@ impl HostInfo {
.unwrap_or_default()
}
/// Get the first available IPv6 address from network interfaces
pub fn default_ipv6(&self) -> &str {
fn default_ipv6(&self) -> &str {
self
.network_interfaces
.first()
@@ -77,7 +46,6 @@ impl HostInfo {
}
}
/// Network interface information
#[derive(Clone)]
struct NetworkInterface {
name: String,
@@ -88,30 +56,21 @@ struct NetworkInterface {
}
impl NetworkInterface {
/// Create a new network interface with basic information
fn new(name: String, description: String) -> Self {
fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
Self {
name,
description,
name: name.into(),
description: description.into(),
mac_address: None,
ipv4: None,
ipv6: None,
}
}
/// Set MAC address
fn with_mac(mut self, mac: Option<String>) -> Self {
self.mac_address = mac;
self
}
/// Set IPv4 address
fn with_ipv4(mut self, ipv4: Option<String>) -> Self {
self.ipv4 = ipv4;
self
}
/// Set IPv6 address
fn with_ipv6(mut self, ipv6: Option<String>) -> Self {
self.ipv6 = ipv6;
self
@@ -120,18 +79,18 @@ impl NetworkInterface {
#[derive(Args)]
pub(crate) struct HipArgs {
#[arg(long, help = "The GP client version, e.g., 6.2.4-49")]
client_version: String,
#[arg(
long,
help = "The GP client version, defaults to APP_VERSION or the packaged version"
)]
client_version: Option<String>,
#[arg(long, value_enum, help = "The client OS")]
#[arg(long, value_enum, default_value_t = HipArgs::default_os(), help = "The client OS")]
client_os: Os,
#[arg(long, hide = true)]
#[arg(long, help = "The OS version string, defaults to a computed value for the target OS")]
os_version: Option<String>,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long, help = "The authentication cookie")]
cookie: String,
@@ -145,15 +104,41 @@ pub(crate) struct HipArgs {
md5: String,
}
impl HipArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else if cfg!(target_os = "windows") {
Os::Windows
} else {
Os::Linux
}
}
fn client_version(&self) -> String {
self
.client_version
.clone()
.or_else(|| env::var("APP_VERSION").ok())
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string())
}
fn os_version(&self) -> String {
self.os_version.clone().unwrap_or_else(|| match self.client_os {
Os::Linux => host_utils::get_linux_os_string().to_string(),
Os::Windows => host_utils::get_windows_os_string().to_string(),
Os::Mac => host_utils::get_macos_os_string().to_string(),
})
}
}
pub(crate) struct HipHandler<'a> {
args: &'a HipArgs,
profile: OsProfile,
}
impl<'a> HipHandler<'a> {
pub(crate) fn new(args: &'a HipArgs) -> Self {
let profile = build_os_profile(args);
Self { args, profile }
Self { args }
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
@@ -167,18 +152,18 @@ impl<'a> HipHandler<'a> {
}
fn parse_cookie(&self) -> HashMap<String, String> {
// Parse URL-encoded cookie string using serde_urlencoded
serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default()
}
/// Generate the complete HIP report XML
fn generate_hip_report(&self, cookie_params: &HashMap<String, String>) -> anyhow::Result<String> {
let (generate_time, day, month, year) = get_current_time_components();
let user_name = cookie_params.get("user").map(|s| s.as_str()).unwrap_or("");
let host_info = self.collect_host_info(cookie_params);
let client_version = self.args.client_version();
let os_version = self.args.os_version();
let user_name = cookie_params.get("user").map(|value| value.as_str()).unwrap_or("");
let host_info = self.collect_host_info(cookie_params, &os_version);
let template = HipReportTemplate {
client_version: &self.args.client_version,
client_version: &client_version,
generate_time,
day,
month,
@@ -188,215 +173,73 @@ impl<'a> HipHandler<'a> {
md5: &self.args.md5,
};
let report = template.render()?;
format_xml(&report)
format_xml(&template.render()?)
}
/// Collect host information using the configured OsProfile.
fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo {
HostInfoCollector::new(&self.profile, self.args, cookie_params).collect()
}
}
fn collect_host_info<'b>(&'b self, cookie_params: &'b HashMap<String, String>, os_version: &'b str) -> HostInfo<'b> {
let domain = cookie_params.get("domain").cloned().unwrap_or_default();
let ipv4 = self
.args
.client_ip
.clone()
.or_else(|| cookie_params.get("preferred-ip").cloned());
let ipv6 = self
.args
.client_ipv6
.clone()
.or_else(|| cookie_params.get("preferred-ipv6").cloned());
/// Construct an `OsProfile` from CLI args, falling back to per-OS defaults
/// for any value not supplied on the command line.
fn build_os_profile(args: &HipArgs) -> OsProfile {
let client_os = ClientOs::from(args.client_os);
let mut builder = OsProfileBuilder::new(client_os).client_version(args.client_version.clone());
if let Some(host_id) = args.host_id.as_deref() {
debug!("HIP host-id override supplied: {}", host_id);
builder = builder.host_id_override(host_id);
}
let profile = builder.build();
debug!(
"HIP OS profile host-id: runtime={}, projected={}, client_os={}",
profile.host_identity().host_id(),
profile.host_id(),
client_os.as_str()
);
profile
}
match self.args.client_os {
Os::Linux => HostInfo {
os_vendor: "Linux",
os_version,
host_id: host_utils::derive_uuid(&["linux"]),
host_name: whoami::devicename(),
software_version: "",
domain,
network_interfaces: vec![NetworkInterface::new("enp1s0f0", "enp1s0f0")
.with_ipv4(ipv4)
.with_ipv6(ipv6)],
},
Os::Mac => HostInfo {
os_vendor: "Apple",
os_version,
host_id: host_utils::get_machine_id().to_string(),
host_name: whoami::devicename(),
software_version: host_utils::get_macos_version(),
domain,
network_interfaces: vec![NetworkInterface::new("en0", "en0").with_ipv4(ipv4).with_ipv6(ipv6)],
},
Os::Windows => {
let iface = NetworkInterface::new(
format!("{{{}}}", host_utils::derive_uuid(&["pangp"]).to_uppercase()),
"PANGP Virtual Ethernet Adapter Secure",
)
.with_ipv4(ipv4)
.with_ipv6(ipv6);
// ============================================================================
// Host Information Collector
// ============================================================================
let loopback = NetworkInterface {
name: iface.name.clone(),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
};
/// Helper struct for collecting host information.
///
/// Identity values (vendor, host_id, computer name, software version) come
/// from the configured `OsProfile`, while runtime state (network interfaces,
/// IP addresses) is enumerated here from the underlying machine.
struct HostInfoCollector<'p, 'a> {
profile: &'p OsProfile,
args: &'a HipArgs,
cookie_params: &'a HashMap<String, String>,
}
impl<'p, 'a> HostInfoCollector<'p, 'a> {
fn new(profile: &'p OsProfile, args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self {
Self {
profile,
args,
cookie_params,
}
}
/// Domain belongs to the runtime user/session, not the simulated OS, so
/// it is sourced from the auth cookie when available.
fn get_domain(&self) -> String {
self
.cookie_params
.get("domain")
.map(|s| s.to_string())
.unwrap_or_default()
}
/// Collect network interface information with fallback
fn collect_network_interface(&self) -> NetworkInterface {
match netdev::get_default_interface() {
Ok(iface) => NetworkInterface::new(
iface.name.clone(),
iface.description.unwrap_or_else(|| iface.name.clone()),
)
.with_mac(iface.mac_addr.map(|mac| mac.address()))
.with_ipv4(iface.ipv4.first().map(|ip| ip.addr().to_string()))
.with_ipv6(iface.ipv6.first().map(|ip| ip.addr().to_string())),
Err(_) => NetworkInterface::new("unknown".to_string(), "unknown".to_string())
.with_ipv4(self.args.client_ip.clone())
.with_ipv6(self.args.client_ipv6.clone()),
}
}
/// Single entry point for collecting host info — dispatches per-OS
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
fn collect(&self) -> HostInfo {
let runtime_iface = self.collect_network_interface();
let primary = self.adapt_primary_interface(&runtime_iface);
let mut interfaces = vec![primary.clone()];
interfaces.extend(self.extra_interfaces(&primary));
HostInfo {
os_vendor: self.profile.os_vendor().to_string(),
os_version: self.profile.os_version().to_string(),
host_id: self.profile.host_id().to_string(),
host_name: self.profile.computer().to_string(),
software_version: self.profile.software_version().to_string(),
domain: self.domain_for_profile(),
network_interfaces: interfaces,
defender: self.defender_for_profile(),
}
}
/// Build the primary network interface with OS-appropriate naming and
/// MAC formatting. When emulating a different OS, the runtime interface
/// name/description are replaced with the canonical placeholder for the
/// target OS.
fn adapt_primary_interface(&self, runtime: &NetworkInterface) -> NetworkInterface {
let (name, description) = if self.profile.is_native() {
(runtime.name.clone(), runtime.description.clone())
} else {
placeholder_interface_for(self.profile, runtime)
};
NetworkInterface {
name,
description,
mac_address: format_mac_for(self.profile, runtime.mac_address.clone()),
ipv4: runtime.ipv4.clone(),
ipv6: runtime.ipv6.clone(),
}
}
/// Additional interfaces appended after the primary. Only Windows
/// emits the software loopback interface in HIP reports.
fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec<NetworkInterface> {
match self.profile.client_os() {
ClientOs::Windows => vec![NetworkInterface {
name: derive_windows_network_name(self.profile.host_id(), primary),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
}],
ClientOs::Linux | ClientOs::Mac => vec![],
}
}
/// Linux HIP reports omit the domain field; macOS/Windows include it
/// from the auth cookie.
fn domain_for_profile(&self) -> String {
match self.profile.client_os() {
ClientOs::Linux => String::new(),
ClientOs::Mac | ClientOs::Windows => self.get_domain(),
}
}
fn defender_for_profile(&self) -> Option<DefenderInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_microsoft_defender_blocking(),
ClientOs::Mac | ClientOs::Windows => None,
HostInfo {
os_vendor: "Microsoft",
os_version,
host_id: host_utils::get_machine_id().to_string(),
host_name: whoami::devicename(),
software_version: host_utils::get_windows_version(),
domain,
network_interfaces: vec![iface, loopback],
}
}
}
}
}
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
let output = Command::new("mdatp")
.arg("health")
.arg("--output")
.arg("json")
.output()
.ok()?;
if !output.status.success() {
debug!("mdatp health command failed");
return None;
}
let json = String::from_utf8(output.stdout).ok()?;
let defender = parse_defender_info(&json)?;
debug!("Detected Microsoft Defender: {:?}", defender);
Some(defender)
}
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
serde_json::from_str(json).ok()
}
// ============================================================================
// Per-OS interface helpers (selected via OsProfile, not cfg)
// ============================================================================
/// Canonical interface name/description for the target OS when the runtime
/// is a different OS (i.e. emulation).
fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> (String, String) {
match profile.client_os() {
ClientOs::Linux => ("enp1s0f0".to_string(), "enp1s0f0".to_string()),
ClientOs::Mac => ("en0".to_string(), "en0".to_string()),
ClientOs::Windows => (
derive_windows_network_name(profile.host_id(), runtime),
"PANGP Virtual Ethernet Adapter Secure".to_string(),
),
}
}
/// MAC address formatting per target OS. Windows uses hyphen separators;
/// Linux and macOS preserve the colon-separated form returned by the
/// platform.
fn format_mac_for(profile: &OsProfile, mac: Option<String>) -> Option<String> {
match profile.client_os() {
ClientOs::Windows => mac.map(|m| m.replace(':', "-")),
ClientOs::Linux | ClientOs::Mac => mac,
}
}
// ============================================================================
// Utility Functions
// ============================================================================
/// Get current time components for HIP report
fn get_current_time_components() -> (String, String, String, String) {
let now = chrono::Local::now();
(
@@ -407,174 +250,9 @@ fn get_current_time_components() -> (String, String, String, String) {
)
}
/// Format XML string with proper indentation
fn format_xml(xml_str: &str) -> anyhow::Result<String> {
let xml = Element::parse(xml_str.as_bytes())?;
let config = xmltree::EmitterConfig::new().perform_indent(true);
let mut xml_buf = Vec::new();
xml.write_with_config(&mut xml_buf, config)?;
xml.write_with_config(&mut xml_buf, xmltree::EmitterConfig::new().perform_indent(true))?;
Ok(String::from_utf8(xml_buf)?)
}
fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> String {
let seed = format!(
"{}-{}-{}",
host_id,
iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"),
iface.name
);
format!(
"{{{}}}",
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_DNS, seed.as_bytes())
.to_string()
.to_uppercase()
)
}
#[cfg(test)]
mod tests {
use super::*;
use gpapi::os_profile::runtime_client_os;
fn make_hip_args(client_os: Os) -> HipArgs {
HipArgs {
client_version: "6.2.4-49".to_string(),
client_os,
os_version: Some("test-os-version".to_string()),
host_id: None,
cookie: String::new(),
client_ip: None,
client_ipv6: None,
md5: "deadbeef".to_string(),
}
}
fn make_profile(client_os: ClientOs) -> OsProfile {
OsProfileBuilder::new(client_os).build()
}
#[test]
fn host_info_os_vendor_is_linux_for_linux_profile() {
let args = make_hip_args(Os::Linux);
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Linux");
}
#[test]
fn host_info_os_vendor_is_apple_for_mac_profile() {
let args = make_hip_args(Os::Mac);
let profile = make_profile(ClientOs::Mac);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Apple");
}
#[test]
fn host_info_os_vendor_is_microsoft_for_windows_profile() {
let args = make_hip_args(Os::Windows);
let profile = make_profile(ClientOs::Windows);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Microsoft");
}
#[test]
fn host_info_host_id_comes_from_os_profile() {
let args = make_hip_args(Os::Linux);
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.host_id, profile.host_id());
}
#[test]
fn host_info_host_id_independent_of_runtime_for_each_os() {
// host_id should reflect the OsProfile's machine identity for every
// simulated OS, regardless of the runtime platform.
for (client_os, os_arg) in [
(ClientOs::Linux, Os::Linux),
(ClientOs::Mac, Os::Mac),
(ClientOs::Windows, Os::Windows),
] {
let args = make_hip_args(os_arg);
let profile = make_profile(client_os);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.host_id, profile.host_id());
}
}
#[test]
fn hip_os_version_argument_is_ignored() {
let args = make_hip_args(Os::Linux);
let profile = build_os_profile(&args);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_version, profile.os_version());
assert_ne!(info.os_version, "test-os-version");
}
#[test]
fn host_id_argument_sets_profile_runtime_identity() {
let mut args = make_hip_args(Os::default());
args.host_id = Some("auth-host-id".to_string());
let profile = build_os_profile(&args);
assert_eq!(profile.client_os(), runtime_client_os());
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
}
#[test]
fn host_info_uses_host_id_argument_for_native_profile() {
let mut args = make_hip_args(Os::default());
args.host_id = Some("auth-host-id".to_string());
let profile = build_os_profile(&args);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
assert_eq!(info.host_id, profile.host_id());
}
#[test]
fn parses_microsoft_defender_health_json() {
let defender = parse_defender_info(
r#"{
"appVersion": "101.25042.0000",
"engineVersion": "1.1.25040.2",
"definitionsVersion": "1.429.201.0",
"realTimeProtectionEnabled": { "value": true }
}"#,
)
.expect("defender health json should parse");
assert_eq!(defender.app_version, "101.25042.0000");
assert_eq!(defender.engine_version, "1.1.25040.2");
assert_eq!(defender.definitions_version, "1.429.201.0");
assert!(defender.real_time_protection_enabled.value);
}
#[test]
fn rejects_invalid_microsoft_defender_health_json() {
assert!(parse_defender_info("{}").is_none());
}
}
+30 -6
View File
@@ -1,11 +1,10 @@
use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf};
use clap::Args;
use common::constants::GP_CALLBACK_PORT_FILENAME;
use directories::ProjectDirs;
use gpapi::{
process::service_launcher::ServiceLauncher,
utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
utils::{endpoint::http_endpoint, env_file, shutdown_signal},
};
use log::info;
use tokio::io::AsyncWriteExt;
@@ -32,7 +31,7 @@ impl<'a> LaunchGuiHandler<'a> {
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
// `launch-gui`cannot be run as root
let user = whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))?;
let user = whoami::username();
if user == "root" {
anyhow::bail!("`launch-gui` cannot be run as root");
}
@@ -63,7 +62,7 @@ impl<'a> LaunchGuiHandler<'a> {
extra_envs.insert("GP_LOG_FILE".into(), log_file_path.clone());
// Persist the environment variables to a file
let env_file = env_utils::persist_env_vars(Some(extra_envs))?;
let env_file = env_file::persist_env_vars(Some(extra_envs))?;
let env_file = env_file.into_temp_path();
let env_file_path = env_file.to_string_lossy().to_string();
@@ -81,17 +80,42 @@ impl<'a> LaunchGuiHandler<'a> {
}
async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> {
if let Err(err) = feed_auth_data_cli(auth_data).await {
let (res_gui, res_cli) = tokio::join!(feed_auth_data_gui(auth_data), feed_auth_data_cli(auth_data));
if let Err(err) = res_gui {
info!("Failed to feed auth data to the GUI: {}", err);
}
if let Err(err) = res_cli {
info!("Failed to feed auth data to the CLI: {}", err);
}
// Cleanup the temporary file
let html_file = temp_dir().join("gpauth.html");
if let Err(err) = std::fs::remove_file(&html_file) {
info!("Failed to remove {}: {}", html_file.display(), err);
}
Ok(())
}
async fn feed_auth_data_gui(auth_data: &str) -> anyhow::Result<()> {
info!("Feeding auth data to the GUI");
let service_endpoint = http_endpoint().await?;
reqwest::Client::default()
.post(format!("{}/auth-data", service_endpoint))
.body(auth_data.to_string())
.send()
.await?
.error_for_status()?;
Ok(())
}
async fn feed_auth_data_cli(auth_data: &str) -> anyhow::Result<()> {
info!("Feeding auth data to the CLI");
let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME);
let port_file = temp_dir().join("gpcallback.port");
let port = tokio::fs::read_to_string(port_file).await?;
let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port.trim())).await?;
-1
View File
@@ -3,7 +3,6 @@ mod connect;
mod disconnect;
mod hip;
mod launch_gui;
mod session;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
-245
View File
@@ -1,245 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use gpapi::{
gateway::{SessionContext, SessionExtensionAuth, extend_session},
os_profile::OsProfile,
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{info, warn};
use openconnect::VpnSessionInfo;
use tokio::{runtime::Handle, task::JoinHandle};
#[derive(Debug, PartialEq, Eq)]
struct SessionWarningSchedule {
delay: Duration,
message: String,
should_auto_extend: bool,
}
pub(crate) struct SessionContextInput {
pub(crate) portal: String,
pub(crate) gateway: String,
pub(crate) cookie: String,
pub(crate) os_profile: OsProfile,
pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
pub(crate) disable_ipv6: bool,
pub(crate) extension_auth: Option<SessionExtensionAuth>,
}
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
let session_args = SessionRequestArgs::new(input.cookie)
.with_user_agent(input.os_profile.user_agent().to_string())
.with_certificate(input.certificate)
.with_sslkey(input.sslkey)
.with_key_password(input.key_password)
.with_disable_ipv6(input.disable_ipv6);
let ctx = SessionContext::new(input.gateway, input.portal, session_args);
match input.extension_auth {
Some(extension_auth) => ctx.with_extension_auth(extension_auth),
None => ctx,
}
}
pub(crate) fn session_info_from_vpn(vpn_session_info: VpnSessionInfo, allow_extend_session: bool) -> SessionInfo {
SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
)
}
pub(crate) fn spawn_session_runtime_with_info(
handle: &Handle,
session_ctx: SessionContext,
session_info: SessionInfo,
) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx, session_info))
}
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo) {
loop {
let Some(schedule) = build_session_warning_schedule(&session_info) else {
info!("No session warning schedule provided by the gateway");
return;
};
tokio::time::sleep(schedule.delay).await;
eprintln!("\nWARNING: {}", schedule.message);
if !schedule.should_auto_extend {
info!("Session extension is not allowed by the gateway");
return;
}
info!("Attempting to extend the session");
match extend_session(&session_ctx).await {
Ok(()) => {
let Some(next_session_info) = session_info.rescheduled_after_extension() else {
info!("Session extended, but no lifetime is available to schedule another warning");
return;
};
eprintln!("Session extended.");
session_info = next_session_info;
}
Err(err) => {
warn!("Failed to extend session: {}", err);
eprintln!("WARNING: Failed to extend session: {}", err);
return;
}
}
}
}
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
let warning = session_info.lifetime_warning.as_ref()?;
let warning_secs = if let Some(user_expires) = session_info.user_expires {
let now = unix_timestamp();
user_expires.saturating_sub(warning.prior_secs).saturating_sub(now)
} else if let Some(lifetime_secs) = session_info.lifetime_secs {
lifetime_secs.saturating_sub(warning.prior_secs)
} else {
return None;
};
Some(SessionWarningSchedule {
delay: Duration::from_secs(warning_secs as u64),
message: warning.message.clone(),
should_auto_extend: session_info.allow_extend_session,
})
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
SessionInfo {
user_expires,
lifetime_warning: Some(SessionWarning {
prior_secs: 1800,
message: "Session expires soon".to_string(),
}),
allow_extend_session,
..Default::default()
}
}
#[test]
fn builds_warning_schedule_for_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert_eq!(schedule.message, "Session expires soon");
assert!(schedule.delay <= Duration::from_secs(30));
assert!(schedule.should_auto_extend);
}
#[test]
fn builds_warning_schedule_without_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), false);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert!(!schedule.should_auto_extend);
}
#[test]
fn schedules_next_warning_after_extension_from_lifetime() {
let mut session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
session_info.lifetime_secs = Some(7200);
let next_session_info = session_info.rescheduled_after_extension().unwrap();
let schedule = build_session_warning_schedule(&next_session_info).unwrap();
assert!(schedule.delay <= Duration::from_secs(5400));
}
#[test]
fn builds_session_context_from_os_profile() {
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Mac)
.client_version("6.3.1-12".to_string())
.build();
let expected_user_agent = profile.user_agent().to_string();
let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(),
os_profile: profile,
certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
disable_ipv6: true,
extension_auth: None,
});
assert_eq!(ctx.portal(), "portal.example.com");
assert_eq!(ctx.server(), "vpn.example.com");
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
assert_eq!(
ctx.session_args().user_agent().as_deref(),
Some(expected_user_agent.as_str())
);
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
assert!(ctx.session_args().disable_ipv6());
}
#[test]
fn maps_openconnect_session_metadata_to_runtime_session_info() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_gateway_session_info_does_not_allow_extension_without_portal_policy() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(!info.allow_extend_session);
}
}
+5 -20
View File
@@ -136,7 +136,7 @@
</list>
<missing-patches/>
</entry>
{% elif host_info.os_vendor == "Apple" -%}
{% else if host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
<entry>
@@ -216,22 +216,9 @@
<missing-patches>
</missing-patches>
</entry>
{% elif host_info.os_vendor == "Linux" -%}
{% else if host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
{% if let Some(defender) = &host_info.defender -%}
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Defender ATP" version="{{ defender.app_version }}" defver="{{ defender.definitions_version }}" prodType="3" engver="{{ defender.engine_version }}" osType="1" vendor="Microsoft Corporation" dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>{% if defender.real_time_protection_enabled.value %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
{% else -%}
<list/>
{% endif -%}
</entry>
<entry name="disk-backup">
<list/>
@@ -274,17 +261,15 @@
<list>
<entry>
<ProductInfo>
<Prod name="Dandified Yum" version="4.2.23" vendor="Red Hat, Inc.">
<Prod name="Apt" version="2.0.11" vendor="Canonical Ltd.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
<missing-patches>
</missing-patches>
</entry>
{% endif -%}
<entry name="data-loss-prevention">
<list/>
</entry>
</categories>
</hip-report>
File renamed without changes.

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

+1
View File
@@ -0,0 +1 @@
html,body,#root{height:100%;margin:0;padding:0;-webkit-user-select:none;user-select:none;cursor:default}
-1
View File
@@ -1 +0,0 @@
html,body,#root{-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0}
-168
View File
@@ -1,168 +0,0 @@
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,re());else{var t=n(l);t!==null&&oe(x,t.startTime-e)}}var S=!1,C=-1,w=5,ee=-1;function te(){return g?!0:!(e.unstable_now()-ee<w)}function ne(){if(g=!1,S){var t=e.unstable_now();ee=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&oe(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?re():S=!1}}}var re;if(typeof y==`function`)re=function(){y(ne)};else if(typeof MessageChannel<`u`){var ie=new MessageChannel,ae=ie.port2;ie.port1.onmessage=ne,re=function(){ae.postMessage(null)}}else re=function(){_(ne,0)};function oe(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,oe(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,re()))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),u=o(((e,t)=>{t.exports=l()})),d=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`)Line truncated
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
`+be+e+xe}var Ce=!1;function we(e,t){if(!e||Ce)return``;Ce=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,`props`,{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,`name`,{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
`),l=s.split(`
`);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Ce=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Se(n):``}function Te(e,t){switch(e.tag){case 26:case 27:case 5:return Se(e.type);case 16:return Se(`Lazy`);case 13:return e.child!==t&&t!==null?Se(`Suspense Fallback`):Se(`Suspense`);case 19:return Se(`SuspenseList`);case 0:case 15:return we(e.type,!1);case 11:return we(e.type.render,!1);case 1:return we(e.type,!0);case 31:return Se(`Activity`);default:return``}}function Ee(e){try{var t=``,n=null;do t+=Te(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
Error generating stack: `+e.message+`
`+e.stack}}var De=Object.prototype.hasOwnProperty,Oe=t.unstable_scheduleCallback,ke=t.unstable_cancelCallback,Ae=t.unstable_shouldYield,je=t.unstable_requestPaint,Me=t.unstable_now,Ne=t.unstable_getCurrentPriorityLevel,Pe=t.unstable_ImmediatePriority,Fe=t.unstable_UserBlockingPriority,Ie=t.unstable_NormalPriority,Le=t.unstable_LowPriority,Re=t.unstable_IdlePriority,ze=t.log,Be=t.unstable_setDisableYieldValue,Ve=null,He=null;function Ue(e){if(typeof ze==`function`&&Be(e),He&&typeof He.setStrictMode==`function`)try{He.setStrictMode(Ve,e)}catch{}}var We=Math.clz32?Math.clz32:qe,Ge=Math.log,Ke=Math.LN2;function qe(e){return e>>>=0,e===0?32:31-(Ge(e)/Ke|0)|0}var Je=256,Ye=262144,Xe=4194304;function Ze(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Qe(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Ze(n))):i=Ze(o):i=Ze(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ze(n))):i=Ze(o)):i=Ze(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function $e(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function et(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function tt(){var e=Xe;return Xe<<=1,!(Xe&62914560)&&(Xe=4194304),e}function nt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function rt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function it(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-We(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&at(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function at(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-We(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function ot(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-We(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function st(e,t){var n=t&-t;return n=n&42?1:ct(n),(n&(e.suspendedLanes|t))===0?n:0}function ct(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function lt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function ut(){var e=O.p;return e===0?(e=window.event,e===void 0?32:mp(e.type)):e}function dt(e,t){var n=O.p;try{return O.p=e,t()}finally{O.p=n}}var ft=Math.random().toString(36).slice(2),pt=`__reactFiber$`+ft,mt=`__reactProps$`+ft,ht=`__reactContainer$`+ft,gt=`__reactEvents$`+ft,_t=`__reactListeners$`+ft,vt=`__reactHandles$`+ft,yt=`__reactResources$`+ft,bt=`__reactMarker$`+ft;function xt(e){delete e[pt],delete e[mt],delete e[gt],delete e[_t],delete e[vt]}function St(e){var t=e[pt];if(t)return t;for(var n=e.parentNode;n;){if(t=n[ht]||n[pt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=df(e);e!==null;){if(n=e[pt])return n;e=df(e)}return t}e=n,n=e.parentNode}return null}function Ct(e){if(e=e[pt]||e[ht]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function wt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(i(33))}function Tt(e){var t=e[yt];return t||=e[yt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function Et(e){e[bt]=!0}var Dt=new Set,Ot={};function kt(e,t){At(e,t),At(e+`Capture`,t)}function At(e,t){for(Ot[e]=t,e=0;e<t.length;e++)Dt.add(t[e])}var jt=RegExp(`^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001Line truncated
`).replace(Ad,``)}function Md(e,t){return t=jd(t),jd(e)===t}function $(e,t,n,r,a,o){switch(n){case`children`:typeof r==`string`?t===`body`||t===`textarea`&&r===``||Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&t!==`body`&&Zt(e,``+r);break;case`className`:Ft(e,`class`,r);break;case`tabIndex`:Ft(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:Ft(e,n,r);break;case`style`:en(e,r,o);break;case`data`:if(t!==`object`){Ft(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)){e.removeAttribute(n);break}if(r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=an(``+r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}else typeof o==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,a.name,a,null),$(e,t,`formEncType`,a.formEncType,a,null),$(e,t,`formMethod`,a.formMethod,a,null),$(e,t,`formTarget`,a.formTarget,a,null)):($(e,t,`encType`,a.encType,a,null),$(e,t,`method`,a.method,a,null),$(e,t,`target`,a.target,a,null)));if(r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=an(``+r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=on);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=an(``+r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``+r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),Pt(e,`popover`,r);break;case`xlinkActuate`:It(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:It(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:It(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:It(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:Pt(e,`is`,r);break;case`innerText`:case`textContent`:break;default:(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)&&(n=nn.get(n)||n,Pt(e,n,r))}}function Nd(e,t,n,r,a,o){switch(n){case`style`:en(e,r,o);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`children`:typeof r==`string`?Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&Zt(e,``+r);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;case`onClick`:r!=null&&(e.onclick=on);break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`innerHTML`:case`re Line truncated
const theme = ${JSON.stringify(t,null,2)};
theme.breakpoints = createBreakpoints(theme.breakpoints || {});
theme.transitions = createTransitions(theme.transitions || {});
export default theme;`}function xa(e){return typeof e==`number`?`${(e*100).toFixed(0)}%`:`calc((${e}) * 100%)`}var Sa=e=>{if(!Number.isNaN(+e))return+e;let t=e.match(/\d*\.?\d+/g);if(!t)return 0;let n=0;for(let e=0;e<t.length;e+=1)n+=+t[e];return n};function Ca(e){Object.assign(e,{alpha(t,n){let r=this||e;return r.colorSpace?`oklch(from ${t} l c h / ${typeof n==`string`?`calc(${n})`:n})`:r.vars?`rgba(${t.replace(/var\(--([^,\s)]+)(?:,[^)]+)?\)+/g,`var(--$1Channel)`)} / ${typeof n==`string`?`calc(${n})`:n})`:bi(t,Sa(n))},lighten(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #fff ${xa(n)})`:Ci(t,n)},darken(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #000 ${xa(n)})`:Si(t,n)}})}function wa(e={},...t){let{breakpoints:n,mixins:r={},spacing:i,palette:a={},transitions:o={},typography:s={},shape:c,colorSpace:l,...u}=e;if(e.vars&&e.generateThemeVars===void 0)throw Error(ee(20));let d=na({...a,colorSpace:l}),f=Nr(e),p=vn(f,{mixins:ia(f.breakpoints,r),palette:d,shadows:fa.slice(),typography:ca(d,s),transitions:_a(o),zIndex:{...va}});return p=vn(p,u),p=t.reduce((e,t)=>vn(e,t),p),p.unstable_sxConfig={...Dr,...u?.unstable_sxConfig},p.unstable_sx=function(e){return jr({sx:e,theme:this})},p.toRuntimeSource=ba,Ca(p),p}function Ta(e){let t;return t=e<1?5.11916*e**2:4.5*Math.log(e+1)+2,Math.round(t*10)/1e3}var Ea=[...Array(25)].map((e,t)=>{if(t===0)return`none`;let n=Ta(t);return`linear-gradient(rgba(255 255 255 / ${n}), rgba(255 255 255 / ${n}))`});function Da(e){return{inputPlaceholder:e===`dark`?.5:.42,inputUnderline:e===`dark`?.7:.42,switchTrackDisabled:e===`dark`?.2:.12,switchTrack:e===`dark`?.3:.38}}function Oa(e){return e===`dark`?Ea:[]}function ka(e){let{palette:t={mode:`light`},opacity:n,overlays:r,colorSpace:i,...a}=e,o=na({...t,colorSpace:i});return{palette:o,opacity:{...Da(o.mode),...n},overlays:r||Oa(o.mode),...a}}function Aa(e){return!!e[0].match(/(cssVarPrefix|colorSchemeSelector|modularCssLayers|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!e[0].match(/sxConfig$/)||e[0]===`palette`&&!!e[1]?.match(/(mode|contrastThreshold|tonalOffset)/)}var ja=e=>[...[...Array(25)].map((t,n)=>`--${e?`${e}-`:``}overlays-${n}`),`--${e?`${e}-`:``}palette-AppBar-darkBg`,`--${e?`${e}-`:``}palette-AppBar-darkColor`],Ma=e=>(t,n)=>{let r=e.rootSelector||`:root`,i=e.colorSchemeSelector,a=i;if(i===`class`&&(a=`.%s`),i===`data`&&(a=`[data-%s]`),i?.startsWith(`data-`)&&!i.includes(`%s`)&&(a=`[${i}="%s"]`),e.defaultColorScheme===t){if(t===`dark`){let i={};return ja(e.cssVarPrefix).forEach(e=>{i[e]=n[e],delete n[e]}),a===`media`?{[r]:n,"@media (prefers-color-scheme: dark)":{[r]:i}}:a?{[a.replace(`%s`,t)]:i,[`${r}, ${a.replace(`%s`,t)}`]:n}:{[r]:{...n,...i}}}if(a&&a!==`media`)return`${r}, ${a.replace(`%s`,String(t))}`}else if(t){if(a===`media`)return{[`@media (prefers-color-scheme: ${String(t)})`]:{[r]:n}};if(a)return a.replace(`%s`,String(t))}return r};function Na(e,t){t.forEach(t=>{e[t]||(e[t]={})})}function B(e,t,n){!e[t]&&n&&(e[t]=n)}function Pa(e){return typeof e!=`string`||!e.startsWith(`hsl`)?e:_i(e)}function Fa(e,t){`${t}Channel`in e||(e[`${t}Channel`]=hi(Pa(e[t]),`MUI: Can't create \`palette.${t}Channel\` because \`palette.${t}\` is not one of these formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().
To suppress this warning, you need to explicitly provide the \`palette.${t}Channel\` as a string (in rgb format, for example "12 12 12") or undefined if you want to remove the channel token.`))}function Ia(e){return typeof e==`number`?`${e}px`:typeof e==`string`||typeof e==`function`||Array.isArray(e)?e:`8px`}var La=e=>{try{return e()}catch{}},Ra=(e=`mui`)=>R(e);function za(e,t,n,r,i){if(!n)return;n=n===!0?{}:n;let a=i===`dark`?`dark`:`light`;if(!r){t[i]=ka({...n,palette:{mode:a,...n?.palette},colorSpace:e});return}let{palette:o,...s}=wa({...r,palette:{mode:a,...n?.palette},colorSpace:e});return t[i]={...n,palette:o,opacity:{...Da(a),...n?.opacity},overlays:n?.overlays||Oa(a)},s}function Ba(e={},...t){let{colorSchemes:n={light:!0},defaultColorScheme:r,disableCssColorScheme:i=!1,cssVarPrefix:a=`mui`,nativeColor:o=!1,shouldSkipGeneratingVar:s=Aa,colorSchemeSelector:c=n.light&&n.dark?`media`:void 0,rootSelector:l=`:root`,...u}=e,d=Object.keys(n)[0],f=r||(n.light&&d!==`light`?`light`:d),p=Ra(a),{[f]:m,light:h,dark:g,..._}=n,v={..._},y=m;if((f===`dark`&&!(`dark`in n)||f===`light`&&!(`light`in n))&&(y=!0),!y)throw Error(ee(21,f));let b;o&&(b=`oklch`);let x=za(b,v,y,u,f);h&&!v.light&&za(b,v,h,void 0,`light`),g&&!v.dark&&za(b,v,g,void 0,`dark`);let S={defaultColorScheme:f,...x,cssVarPrefix:a,colorSchemeSelector:c,rootSelector:l,getCssVar:p,colorSchemes:v,font:{...ra(x.typography),...x.font},spacing:Ia(u.spacing)};Object.keys(S.colorSchemes).forEach(e=>{let t=S.colorSchemes[e].palette,n=e=>{let n=e.split(`-`),r=n[1],i=n[2];return p(e,t[r][i])};t.mode===`light`&&(B(t.common,`background`,`#fff`),B(t.common,`onBackground`,`#000`)),t.mode===`dark`&&(B(t.common,`background`,`#000`),B(t.common,`onBackground`,`#fff`));function r(e,t,n){if(b){let r;return e===xi&&(r=`transparent ${((1-n)*100).toFixed(0)}%`),e===F&&(r=`#000 ${(n*100).toFixed(0)}%`),e===I&&(r=`#fff ${(n*100).toFixed(0)}%`),`color-mix(in ${b}, ${t}, ${r})`}return e(t,n)}if(Na(t,[`Alert`,`AppBar`,`Avatar`,`Button`,`Chip`,`FilledInput`,`LinearProgress`,`Skeleton`,`Slider`,`SnackbarContent`,`SpeedDialAction`,`StepConnector`,`StepContent`,`Switch`,`TableCell`,`Tooltip`]),t.mode===`light`){B(t.Alert,`errorColor`,r(F,t.error.light,.6)),B(t.Alert,`infoColor`,r(F,t.info.light,.6)),B(t.Alert,`successColor`,r(F,t.success.light,.6)),B(t.Alert,`warningColor`,r(F,t.warning.light,.6)),B(t.Alert,`errorFilledBg`,n(`palette-error-main`)),B(t.Alert,`infoFilledBg`,n(`palette-info-main`)),B(t.Alert,`successFilledBg`,n(`palette-success-main`)),B(t.Alert,`warningFilledBg`,n(`palette-warning-main`)),B(t.Alert,`errorFilledColor`,La(()=>t.getContrastText(t.error.main))),B(t.Alert,`infoFilledColor`,La(()=>t.getContrastText(t.info.main))),B(t.Alert,`successFilledColor`,La(()=>t.getContrastText(t.success.main))),B(t.Alert,`warningFilledColor`,La(()=>t.getContrastText(t.warning.main))),B(t.Alert,`errorStandardBg`,r(I,t.error.light,.9)),B(t.Alert,`infoStandardBg`,r(I,t.info.light,.9)),B(t.Alert,`successStandardBg`,r(I,t.success.light,.9)),B(t.Alert,`warningStandardBg`,r(I,t.warning.light,.9)),B(t.Alert,`errorIconColor`,n(`palette-error-main`)),B(t.Alert,`infoIconColor`,n(`palette-info-main`)),B(t.Alert,`successIconColor`,n(`palette-success-main`)),B(t.Alert,`warningIconColor`,n(`palette-warning-main`)),B(t.AppBar,`defaultBg`,n(`palette-grey-100`)),B(t.Avatar,`defaultBg`,n(`palette-grey-400`)),B(t.Button,`inheritContainedBg`,n(`palette-grey-300`)),B(t.Button,`inheritContainedHoverBg`,n(`palette-grey-A100`)),B(t.Chip,`defaultBorder`,n(`palette-grey-400`)),B(t.Chip,`defaultAvatarColor`,n(`palette-grey-700`)),B(t.Chip,`defaultIconColor`,n(`palette-grey-700`)),B(t.FilledInput,`bg`,`rgba(0, 0, 0, 0.06)`),B(t.FilledInput,`hoverBg`,`rgba(0, 0, 0, 0.09)`),B(t.FilledInput,`disabledBg`,`rgba(0, 0, 0, 0.12)`),B(t.LinearProgress,`primaryBg`,r(I,t.primary.main,.62)),B(t.LinearProgress,`secondaryBg`,r(I,t.secondary.main,.62)),B(t.LinearProgress,`errorBg`,r(I,t.error.main,.62)),B(t.LinearProgress,`infoBg`,r(I,t.info.main,.62)),B(t.LinearProgress,`successBg`,r(I,t.success.main,.62)),B(t.LinearProgress,`warningBg`,r(I,t.warning.main,.62)),B(t.Skeleton,`bg`,b?r(xi,t.text.primary,.11):`rgba(${n(`palette-text-primaryChannel`)} / 0.11)`),B(t.Slider,`primaryTrack`,r(I,t.primary.main,.62)),B(t.Slider,`secondaryTrack`,r(I,t.secondary.main,.62)),B(t.Slider,`errorTrack`,r(I,t.error.main,.62)),B(t.Slider,`infoTrack`,r(I,t.info.main,.62)),B(t.Slider,`successTrack`,r(I,t.success.main,.62)),B(t.Slider,`warningTrack`,r(I,t.warning.main,.62));let e=b?r(F,t.background.default,.6825):Ti(t.background.default,.8);B(t.SnackbarContent,`bg`,e),B(t.SnackbarContent,`color`,La(()=>b?Ki.text.primary:t.getContrastText(e))),B(t.SpeedDialAction,`fabHoverBg`,Ti(t.background.paper,.15)),B(t.StepConnector,`border`,n(`palette-grey-400`)),B(t.StepContent,`border`,n(`palette-grey-400`)),B(t.Switch,`defaultColor`,n(`palette-common-white`)),B(t.Switch,`defaultDisabledColor`,n(`palette-grey-100`)),B(t.Switch,`primaryDisabledColor`,r(I,t.primarLine truncated
0% {
transform: scale(0);
opacity: 0.1;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`,ko=Jt`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`,Ao=Jt`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`,jo=Ka(`span`,{name:`MuiTouchRipple`,slot:`Root`})({overflow:`hidden`,pointerEvents:`none`,position:`absolute`,zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:`inherit`}),Mo=Ka(To,{name:`MuiTouchRipple`,slot:`Ripple`})`
opacity: 0;
position: absolute;
&.${Eo.rippleVisible} {
opacity: 0.3;
transform: scale(1);
animation-name: ${Oo};
animation-duration: ${Do}ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
}
&.${Eo.ripplePulsate} {
animation-duration: ${({theme:e})=>e.transitions.duration.shorter}ms;
}
& .${Eo.child} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${Eo.childLeaving} {
opacity: 0;
animation-name: ${ko};
animation-duration: ${Do}ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
}
& .${Eo.childPulsate} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${Ao};
animation-duration: 2500ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`,No=M.forwardRef(function(e,t){let{center:n=!1,classes:r={},className:i,...a}=Za({props:e,name:`MuiTouchRipple`}),[o,s]=M.useState([]),c=M.useRef(0),l=M.useRef(null);M.useEffect(()=>{l.current&&=(l.current(),null)},[o]);let u=M.useRef(!1),d=bo(),f=M.useRef(null),p=M.useRef(null),m=M.useCallback(e=>{let{pulsate:t,rippleX:n,rippleY:i,rippleSize:a,cb:o}=e;s(e=>[...e,(0,N.jsx)(Mo,{classes:{ripple:Gr(r.ripple,Eo.ripple),rippleVisible:Gr(r.rippleVisible,Eo.rippleVisible),ripplePulsate:Gr(r.ripplePulsate,Eo.ripplePulsate),child:Gr(r.child,Eo.child),childLeaving:Gr(r.childLeaving,Eo.childLeaving),childPulsate:Gr(r.childPulsate,Eo.childPulsate)},timeout:Do,pulsate:t,rippleX:n,rippleY:i,rippleSize:a},c.current)]),c.current+=1,l.current=o},[r]),h=M.useCallback((e={},t={},r=()=>{})=>{let{pulsate:i=!1,center:a=n||t.pulsate,fakeElement:o=!1}=t;if(e?.type===`mousedown`&&u.current){u.current=!1;return}e?.type===`touchstart`&&(u.current=!0);let s=o?null:p.current,c=s?s.getBoundingClientRect():{width:0,height:0,left:0,top:0},l,h,g;if(a||e===void 0||e.clientX===0&&e.clientY===0||!e.clientX&&!e.touches)l=Math.round(c.width/2),h=Math.round(c.height/2);else{let{clientX:t,clientY:n}=e.touches&&e.touches.length>0?e.touches[0]:e;l=Math.round(t-c.left),h=Math.round(n-c.top)}if(a)g=Math.sqrt((2*c.width**2+c.height**2)/3),g%2==0&&(g+=1);else{let e=Math.max(Math.abs((s?s.clientWidth:0)-l),l)*2+2,t=Math.max(Math.abs((s?s.clientHeight:0)-h),h)*2+2;g=Math.sqrt(e**2+t**2)}e?.touches?f.current===null&&(f.current=()=>{m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},d.start(80,()=>{f.current&&=(f.current(),null)})):m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},[n,m,d]),g=M.useCallback(()=>{h({},{pulsate:!0})},[h]),_=M.useCallback((e,t)=>{if(d.clear(),e?.type===`touchend`&&f.current){f.current(),f.current=null,d.start(0,()=>{_(e,t)});return}f.current=null,s(e=>e.length>0?e.slice(1):e),l.current=t},[d]);return M.useImperativeHandle(t,()=>({pulsate:g,start:h,stop:_}),[g,h,_]),(0,N.jsx)(jo,{className:Gr(Eo.root,r.root,i),ref:p,...a,children:(0,N.jsx)(mo,{component:null,exit:!0,children:o})})});function Po(e){return Jr(`MuiButtonBase`,e)}var Fo=Yr(`MuiButtonBase`,[`root`,`disabled`,`focusVisible`]),Io=e=>{let{disabled:t,focusVisible:n,focusVisibleClassName:r,classes:i}=e,a=Hi({root:[`root`,t&&`disabled`,n&&`focusVisible`]},Po,i);return n&&r&&(a.root+=` ${r}`),a},Lo=Ka(`button`,{name:`MuiButtonBase`,slot:`Root`})({display:`inline-flex`,alignItems:`center`,justifyContent:`center`,position:`relative`,boxSizing:`border-box`,WebkitTapHighlightColor:`transparent`,backgroundColor:`transparent`,outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:`pointer`,userSelect:`none`,verticalAlign:`middle`,MozAppearance:`none`,WebkitAppearance:`none`,textDecoration:`none`,color:`inherit`,"&::-moz-focus-inner":{borderStyle:`none`},[`&.${Fo.disabled}`]:{pointerEvents:`none`,cursor:`default`},"@media print":{colorAdjust:`exact`}}),Ro=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiButtonBase`}),{action:r,centerRipple:i=!1,children:a,className:o,component:s=`button`,disabled:c=!1,disableRipple:l=!1,disableTouchRipple:u=!1,focusRipple:d=!1,focusVisibleClassName:f,LinkComponent:p=`a`,onBlur:m,onClick:h,onContextMenu:g,onDragLeave:_,onFocus:v,onFocusVisible:y,onKeyDown:b,onKeyUp:x,onMouseDown:S,onMouseLeave:C,onMouseUp:w,onTouchEnd:ee,onTouchMove:te,onTouchStart:ne,tabIndex:re=0,TouchRippleProps:ie,touchRippleRef:ae,type:oe,...T}=n,se=M.useRef(null),E=Co(),ce=no(E.ref,ae),[D,O]=M.useState(!1);c&&D&&O(!1),M.useImperativeHandle(r,()=>({focusVisible:()=>{O(!0),se.current.focus()}}),[]);let le=E.shouldMount&&!l&&!c;M.useEffect(()=>{D&&d&&!l&&E.pulsate()},[l,d,D,E]);let ue=zo(E,`start`,S,u),de=zo(E,`stop`,g,u),fe=zo(E,`stop`,_,u),pe=zo(E,`stop`,w,u),k=zo(E,`stop`,e=>{D&&e.preventDefault(),C&&C(e)},u),me=zo(E,`start`,ne,u),he=zo(E,`stop`,ee,u),ge=zo(E,`stop`,te,u),A=zo(E,`stop`,e=>{xo(e.target)||O(!1),m&&m(e)},!1),_e=eo(e=>{se.current||=e.currentTarget,xo(e.target)&&(O(!0),y&&y(e)),v&&v(e)}),j=()=>{let e=se.current;return s&&s!==`button`&&!(e.tagName===`A`&&e.href)},ve=eo(e=>{d&&!e.repeat&&D&&e.key===` `&&E.stop(e,()=>{E.start(e)}),e.target===e.currentTarget&&j()&&e.key===` `&&e.preventDefault(),b&&b(e),e.target===e.currentTarget&&j()&&e.key===`Enter`&&!c&&(e.preventDefault(),h&&h(e))}),ye=eo(e=>{d&&e.key===` `&&D&&!e.defaultPrevented&&E.stop(e,()=>{E.pulsate(e)}),x&&x(e),h&&e.target===e.currentTarget&&j()&&e.key===` `&&!e.defaultPrevented&&h(e)}),be=s;be===`button`&&(T.href||T.to)&&(be=p);let xe={};if(be===`button`){let e=!!T.formAction;xe.type=oe===void 0&&!e?`button`:oe,xe.disabled=c}else !T.href&&!T.to&&(xe.role=`button`),c&&(xe[`aria-disabled`]=c);let Se=no(t,se),Ce={...n,centerRipple:i,component:s,disabled:c,disableRipple:l,disableTouchRipple:u,focusRipple:d,tabIndex:re,focusVisible:D},we=Io(Ce);return(0,N.jsxs)(Lo,{as:be,className:Gr(we.root,o),ownerState:Ce,onBlur:A,onClick:h,onContextMenu:de,onFocus:_e,onKeyDown:ve,onKeyUp:ye,onMouseDown:ue Line truncated
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
`,Ko=Jt`
0% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 100px, 200px;
stroke-dashoffset: -15px;
}
100% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: -126px;
}
`,qo=typeof Go==`string`?null:qt`
animation: ${Go} 1.4s linear infinite;
`,Jo=typeof Ko==`string`?null:qt`
animation: ${Ko} 1.4s ease-in-out infinite;
`,Yo=e=>{let{classes:t,variant:n,color:r,disableShrink:i}=e;return Hi({root:[`root`,n,`color${V(r)}`],svg:[`svg`],track:[`track`],circle:[`circle`,`circle${V(n)}`,i&&`circleDisableShrink`]},Uo,t)},Xo=Ka(`span`,{name:`MuiCircularProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.variant],t[`color${V(n.color)}`]]}})(Xa(({theme:e})=>({display:`inline-block`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`transform`)}},{props:{variant:`indeterminate`},style:qo||{animation:`${Go} 1.4s linear infinite`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}}))]}))),Zo=Ka(`svg`,{name:`MuiCircularProgress`,slot:`Svg`})({display:`block`}),Qo=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Circle`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.circle,t[`circle${V(n.variant)}`],n.disableShrink&&t.circleDisableShrink]}})(Xa(({theme:e})=>({stroke:`currentColor`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`stroke-dashoffset`)}},{props:{variant:`indeterminate`},style:{strokeDasharray:`80px, 200px`,strokeDashoffset:0}},{props:({ownerState:e})=>e.variant===`indeterminate`&&!e.disableShrink,style:Jo||{animation:`${Ko} 1.4s ease-in-out infinite`}}]}))),$o=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Track`})(Xa(({theme:e})=>({stroke:`currentColor`,opacity:(e.vars||e).palette.action.activatedOpacity}))),es=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiCircularProgress`}),{className:r,color:i=`primary`,disableShrink:a=!1,enableTrackSlot:o=!1,size:s=40,style:c,thickness:l=3.6,value:u=0,variant:d=`indeterminate`,...f}=n,p={...n,color:i,disableShrink:a,size:s,thickness:l,value:u,variant:d,enableTrackSlot:o},m=Yo(p),h={},g={},_={};if(d===`determinate`){let e=2*Math.PI*((Wo-l)/2);h.strokeDasharray=e.toFixed(3),_[`aria-valuenow`]=Math.round(u),h.strokeDashoffset=`${((100-u)/100*e).toFixed(3)}px`,g.transform=`rotate(-90deg)`}return(0,N.jsx)(Xo,{className:Gr(m.root,r),style:{width:s,height:s,...g,...c},ownerState:p,ref:t,role:`progressbar`,..._,...f,children:(0,N.jsxs)(Zo,{className:m.svg,ownerState:p,viewBox:`${Wo/2} ${Wo/2} ${Wo} ${Wo}`,children:[o?(0,N.jsx)($o,{className:m.track,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l,"aria-hidden":`true`}):null,(0,N.jsx)(Qo,{className:m.circle,style:h,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l})]})})});function ts(e){return Jr(`MuiTypography`,e)}Yr(`MuiTypography`,[`root`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`subtitle1`,`subtitle2`,`body1`,`body2`,`inherit`,`button`,`caption`,`overline`,`alignLeft`,`alignRight`,`alignCenter`,`alignJustify`,`noWrap`,`gutterBottom`,`paragraph`]);var ns={primary:!0,secondary:!0,error:!0,info:!0,success:!0,warning:!0,textPrimary:!0,textSecondary:!0,textDisabled:!0},rs=Ya(),is=e=>{let{align:t,gutterBottom:n,noWrap:r,paragraph:i,variant:a,classes:o}=e;return Hi({root:[`root`,a,e.align!==`inherit`&&`align${V(t)}`,n&&`gutterBottom`,r&&`noWrap`,i&&`paragraph`]},ts,o)},as=Ka(`span`,{name:`MuiTypography`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,n.variant&&t[n.variant],n.align!==`inherit`&&t[`align${V(n.align)}`],n.noWrap&&t.noWrap,n.gutterBottom&&t.gutterBottom,n.paragraph&&t.paragraph]}})(Xa(({theme:e})=>({margin:0,variants:[{props:{variant:`inherit`},style:{font:`inherit`,lineHeight:`inherit`,letterSpacing:`inherit`}},...Object.entries(e.typography).filter(([e,t])=>e!==`inherit`&&t&&typeof t==`object`).map(([e,t])=>({props:{variant:e},style:t})),...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}})),...Object.entries(e.palette?.text||{}).filter(([,e])=>typeof e==`string`).map(([t])=>({props:{color:`text${V(t)}`},style:{color:(e.vars||e).palette.text[t]}})),{props:({ownerState:e})=>e.align!==`inherit`,style:{textAlign:`var(--Typography-textAlign)`}},{props:({ownerState:e})=>e.noWrap,style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`}},{props:({ownerState:e})=>e.gutterBottom,style:{marginBottom:`0.35em`}},{props:({ownerState:e})=>e.paragraph,style:{marginBottom:16}}]}))),os={h1:`h1`,h2:`h2`,h3:`h3`,h4:`h4`,h5:`h5`,h6:`h6`,subtitle1:`h6`,subtitle2:`h6`,body1:`p`,body2:`p`,inherit:`p`},ss=M.forwardRef(function(e,t){let{color:n,...r}=Za({props:e,name:`MuiTypography`}),i=!ns[n],a=rs({...r,...i&&{color:n}}),{align:o=`inherit`,className:s,component:c,gutterBottom:l=!1,noWrap:u=!1,paragraph:d=!1,variant:f=`body1`,variantMapping:p=os,...m}=a,h={...a,align:o,color:n,className:s,component:c,gutterBottom:l,noWrap:u,paragraph:d,variant:f,variantMapping:p};return(0,N.jsx)(as,{as:c||(d?`p`:p[f]||os[f])||`span`,ref:t,className:Gr(is(h).root,s),...m,ownerState:h,style:{...o!==`inherit`&&{"--Typography-textAlign":o},...m.style}})}),cs=Yr(`MuiBox`,[`root`]),ls=Kr({themeId:te,defaultTheme:Ha(),defaultClassName:cs.root,generateClassName:Ur.generate});function us(e){return Line truncated
0% {
left: -35%;
right: 100%;
}
60% {
left: 100%;
right: -90%;
}
100% {
left: 100%;
right: -90%;
}
`,Ns=typeof Ms==`string`?null:qt`
animation: ${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
`,Ps=Jt`
0% {
left: -200%;
right: 100%;
}
60% {
left: 107%;
right: -8%;
}
100% {
left: 107%;
right: -8%;
}
`,Fs=typeof Ps==`string`?null:qt`
animation: ${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
`,Is=Jt`
0% {
opacity: 1;
background-position: 0 -23px;
}
60% {
opacity: 0;
background-position: 0 -23px;
}
100% {
opacity: 1;
background-position: -200px -23px;
}
`,Ls=typeof Is==`string`?null:qt`
animation: ${Is} 3s infinite linear;
`,Rs=e=>{let{classes:t,variant:n,color:r}=e;return Hi({root:[`root`,`color${V(r)}`,n],dashed:[`dashed`,`dashedColor${V(r)}`],bar1:[`bar`,`bar1`,`barColor${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar1Indeterminate`,n===`determinate`&&`bar1Determinate`,n===`buffer`&&`bar1Buffer`],bar2:[`bar`,`bar2`,n!==`buffer`&&`barColor${V(r)}`,n===`buffer`&&`color${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar2Indeterminate`,n===`buffer`&&`bar2Buffer`]},As,t)},zs=(e,t)=>e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode===`light`?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.5),Bs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[`color${V(n.color)}`],t[n.variant]]}})(Xa(({theme:e})=>({position:`relative`,overflow:`hidden`,display:`block`,height:4,zIndex:0,"@media print":{colorAdjust:`exact`},variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:zs(e,t)}})),{props:({ownerState:e})=>e.color===`inherit`&&e.variant!==`buffer`,style:{"&::before":{content:`""`,position:`absolute`,left:0,top:0,right:0,bottom:0,backgroundColor:`currentColor`,opacity:.3}}},{props:{variant:`buffer`},style:{backgroundColor:`transparent`}},{props:{variant:`query`},style:{transform:`rotate(180deg)`}}]}))),Vs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Dashed`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.dashed,t[`dashedColor${V(n.color)}`]]}})(Xa(({theme:e})=>({position:`absolute`,marginTop:0,height:`100%`,width:`100%`,backgroundSize:`10px 10px`,backgroundPosition:`0 -23px`,variants:[{props:{color:`inherit`},style:{opacity:.3,backgroundImage:`radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>{let n=zs(e,t);return{props:{color:t},style:{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`}}})]})),Ls||{animation:`${Is} 3s infinite linear`}),Hs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar1`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar1,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar1Indeterminate,n.variant===`determinate`&&t.bar1Determinate,n.variant===`buffer`&&t.bar1Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[{props:{color:`inherit`},style:{backgroundColor:`currentColor`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:(e.vars||e).palette[t].main}})),{props:{variant:`determinate`},style:{transition:`transform .${js}s linear`}},{props:{variant:`buffer`},style:{zIndex:1,transition:`transform .${js}s linear`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Ns||{animation:`${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}}]}))),Us=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar2`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar2,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar2Indeterminate,n.variant===`buffer`&&t.bar2Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{"--LinearProgressBar2-barColor":(e.vars||e).palette[t].main}})),{props:({ownerState:e})=>e.variant!==`buffer`&&e.color!==`inherit`,style:{backgroundColor:`var(--LinearProgressBar2-barColor, currentColor)`}},{props:({ownerState:e})=>e.variant!==`buffer`&&e.color===`inherit`,style:{backgroundColor:`currentColor`}},{props:{color:`inherit`},style:{opacity:.3}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t,variant:`buffer`},style:{backgroundColor:zs(e,t),transition:`transform .${js}s linear`}})),{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Fs||{animation:`${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}}]}))),Ws=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiLinearProgress`}),{className:r,color:i=`primary`,value:a,valueBuffer:o,variant:s=`indeterminate`,...c}=n,l={...n,color:i,variant:s},u=Rs(l),d=Di(),f={},p={bar1:{},bar2:{}};if((s===`determinate`||s===`buffer`)&&a!==void 0){f[`aria-valuenow`]=Math.round(a),f[`aria-valuemin`]=0,f[`aria-valuemax`]=100;let e=a-100;d&&(e=-e),p.bar1.transform=`translateX(${e}%)`}if(s===`buffer`&&o!==void 0){let e=(o||0)-100;d&&(e=-e),p.bar2.transform=`translateX(${e}%)`}return(0,N.jsxs)(Bs,{className:Gr(u.root,r),ownerState:l,role:`progressbar`,...f,ref:t,...c,children:[s===`buffer`?(0,N.jsx)(Vs,{className:u.dashed,ownerState:l}):null,(0,N.jsx)(Hs,{className:u.bar1,ownerState:l,s Line truncated
+188
View File
@@ -0,0 +1,188 @@
function dh(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const o in r)if(o!=="default"&&!(o in e)){const i=Object.getOwnPropertyDescriptor(r,o);i&&Object.defineProperty(e,o,i.get?i:{enumerable:!0,get:()=>r[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();function ph(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function sn(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var jf={exports:{}},Bi={},Ff={exports:{}},D={};/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var yo=Symbol.for("react.element"),mh=Symbol.for("react.portal"),hh=Symbol.for("react.fragment"),yh=Symbol.for("react.strict_mode"),gh=Symbol.for("react.profiler"),vh=Symbol.for("react.provider"),wh=Symbol.for("react.context"),xh=Symbol.for("react.forward_ref"),Sh=Symbol.for("react.suspense"),kh=Symbol.for("react.memo"),_h=Symbol.for("react.lazy"),Uu=Symbol.iterator;function Ch(e){return e===null||typeof e!="object"?null:(e=Uu&&e[Uu]||e["@@iterator"],typeof e=="function"?e:null)}var Wf={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Bf=Object.assign,Uf={};function fr(e,t,n){this.props=e,this.context=t,this.refs=Uf,this.updater=n||Wf}fr.prototype.isReactComponent={};fr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};fr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Vf(){}Vf.prototype=fr.prototype;function _s(e,t,n){this.props=e,this.context=t,this.refs=Uf,this.updater=n||Wf}var Cs=_s.prototype=new Vf;Cs.constructor=_s;Bf(Cs,fr.prototype);Cs.isPureReactComponent=!0;var Vu=Array.isArray,Hf=Object.prototype.hasOwnProperty,Es={current:null},Kf={key:!0,ref:!0,__self:!0,__source:!0};function Qf(e,t,n){var r,o={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)Hf.call(t,r)&&!Kf.hasOwnProperty(r)&&(o[r]=t[r]);var a=arguments.length-2;if(a===1)o.children=n;else if(1<a){for(var s=Array(a),u=0;u<a;u++)s[u]=arguments[u+2];o.children=s}if(e&&e.defaultProps)for(r in a=e.defaultProps,a)o[r]===void 0&&(o[r]=a[r]);return{$$typeof:yo,type:e,key:i,ref:l,props:o,_owner:Es.current}}function Eh(e,t){return{$$typeof:yo,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Ps(e){return typeof e=="object"&&e!==null&&e.$$typeof===yo}function Ph(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var Hu=/\/+/g;function Wl(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Ph(""+e.key):t.toString(36)}function qo(e,t,n,r,o){var i=typeof e;(i==="undefined"||i==="boolean")&&(e=null);var l=!1;if(e===null)l=!0;else switch(i){case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case yo:case mh:l=!0}}if(l)return l=e,o=o(l),e=r===""?"."+Wl(l,0):r,Vu(o)?(n="",e!=null&&(n=e.replace(Hu,"$&/")+"/"),qo(o,t,n,"",function(u){return u})):o!=null&&(Ps(o)&&(o=Eh(o,n+(!o.key||l&&l.key===o.key?"":(""+o.key).replace(Hu,"$&/")+"/")+e)),t.push(o)),1;if(l=0,r=r===""?".":r+":",Vu(e))for(var a=0;a<e.length;a++){i=e[a];var s=r+Wl(i,a);l+=qo(i,t,n,s,o)}else if(s=Ch(e),typeof s=="function")for(e=s.call(e),a=0;!(i=e.next()).done;)i=i.value,s=r+Wl(i,a++),l+=qo(i,t,n,s,o);else if(i==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return l}function Ro(e,t,n){if(e==null)return e;var r=[],o=0;return qo(e,r,"","",function(i){return t.call(n,i,o++)}),r}function $h(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var be={current:null},Zo={transition:null},Th={ReactCurrentDispatcher:be,ReactCurrentBatchConfig:Zo,ReactCurrentOwner:Es};function Gf(){throw Error("act(...) is not supported in production builds of React.")}D.Children={map:Ro,forEach:function(e,t,n){Ro(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return Ro(e,function(){t++}),t},toArray:function(e){return Ro(e,function(t){return t})||[]},only:function(e){if(!Ps(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};D.Component=fr;D.Fragment=hh;D.Profiler=gh;D.PureComponent=_s;D.StrictMode=yh;D.Suspense=Sh;D.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Th;D.act=Gf;D.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=Bf({},e.props),o=e.key,i=e.ref,l=e._owner;if(t!=null){if(t.ref!==void 0&&(i=t.ref,l=Es.current),t.key!==void 0&&(o=""+t.key),e.type&&e.type.defaultProps)var a=e.type.defaultProps;for(s in t)Hf.call(t,s)&&!Kf.hasOwnProperty(s)&&(r[s]=t[s]===void 0&&a!==void 0?a[s]:t[s])}var s=arguments.length-2;if(s===1)r.children=n;else if(1<s){a=Array(s);for(var u=0;u<s;u++)a[u]=arguments[u+2];r.children=a}return{$$typeof:yo,type:e.type,key:o,ref:i,props:r,_owner:l}};D.createContext=function(e){return e={$$typeof:wh,_currentValue:e,_currentValue2:e,_threadCount:0,ProviderLine truncated
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Rh=C,Oh=Symbol.for("react.element"),Mh=Symbol.for("react.fragment"),bh=Object.prototype.hasOwnProperty,zh=Rh.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Nh={key:!0,ref:!0,__self:!0,__source:!0};function Yf(e,t,n){var r,o={},i=null,l=null;n!==void 0&&(i=""+n),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(l=t.ref);for(r in t)bh.call(t,r)&&!Nh.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:Oh,type:e,key:i,ref:l,props:o,_owner:zh.current}}Bi.Fragment=Mh;Bi.jsx=Yf;Bi.jsxs=Yf;jf.exports=Bi;var b=jf.exports,Xf={exports:{}},Ge={},qf={exports:{}},Zf={};/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/(function(e){function t(E,z){var N=E.length;E.push(z);e:for(;0<N;){var Z=N-1>>>1,ue=E[Z];if(0<o(ue,z))E[Z]=z,E[N]=ue,N=Z;else break e}}function n(E){return E.length===0?null:E[0]}function r(E){if(E.length===0)return null;var z=E[0],N=E.pop();if(N!==z){E[0]=N;e:for(var Z=0,ue=E.length,Tn=ue>>>1;Z<Tn;){var Te=2*(Z+1)-1,Bt=E[Te],ct=Te+1,Rn=E[ct];if(0>o(Bt,N))ct<ue&&0>o(Rn,Bt)?(E[Z]=Rn,E[ct]=N,Z=ct):(E[Z]=Bt,E[Te]=N,Z=Te);else if(ct<ue&&0>o(Rn,N))E[Z]=Rn,E[ct]=N,Z=ct;else break e}}return z}function o(E,z){var N=E.sortIndex-z.sortIndex;return N!==0?N:E.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,a=l.now();e.unstable_now=function(){return l.now()-a}}var s=[],u=[],p=1,m=null,d=3,v=!1,g=!1,y=!1,$=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,c=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function h(E){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=E)r(u),z.sortIndex=z.expirationTime,t(s,z);else break;z=n(u)}}function w(E){if(y=!1,h(E),!g)if(n(s)!==null)g=!0,$e(x);else{var z=n(u);z!==null&&Tt(w,z.startTime-E)}}function x(E,z){g=!1,y&&(y=!1,f(P),P=-1),v=!0;var N=d;try{for(h(z),m=n(s);m!==null&&(!(m.expirationTime>z)||E&&!W());){var Z=m.callback;if(typeof Z=="function"){m.callback=null,d=m.priorityLevel;var ue=Z(m.expirationTime<=z);z=e.unstable_now(),typeof ue=="function"?m.callback=ue:m===n(s)&&r(s),h(z)}else r(s);m=n(s)}if(m!==null)var Tn=!0;else{var Te=n(u);Te!==null&&Tt(w,Te.startTime-z),Tn=!1}return Tn}finally{m=null,d=N,v=!1}}var k=!1,S=null,P=-1,I=5,O=-1;function W(){return!(e.unstable_now()-O<I)}function H(){if(S!==null){var E=e.unstable_now();O=E;var z=!0;try{z=S(!0,E)}finally{z?se():(k=!1,S=null)}}else k=!1}var se;if(typeof c=="function")se=function(){c(H)};else if(typeof MessageChannel<"u"){var Se=new MessageChannel,ut=Se.port2;Se.port1.onmessage=H,se=function(){ut.postMessage(null)}}else se=function(){$(H,0)};function $e(E){S=E,k||(k=!0,se())}function Tt(E,z){P=$(function(){E(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(E){E.callback=null},e.unstable_continueExecution=function(){g||v||(g=!0,$e(x))},e.unstable_forceFrameRate=function(E){0>E||125<E?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):I=0<E?Math.floor(1e3/E):5},e.unstable_getCurrentPriorityLevel=function(){return d},e.unstable_getFirstCallbackNode=function(){return n(s)},e.unstable_next=function(E){switch(d){case 1:case 2:case 3:var z=3;break;default:z=d}var N=d;d=z;try{return E()}finally{d=N}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(E,z){switch(E){case 1:case 2:case 3:case 4:case 5:break;default:E=3}var N=d;d=E;try{return z()}finally{d=N}},e.unstable_scheduleCallback=function(E,z,N){var Z=e.unstable_now();switch(typeof N=="object"&&N!==null?(N=N.delay,N=typeof N=="number"&&0<N?Z+N:Z):N=Z,E){case 1:var ue=-1;break;case 2:ue=250;break;case 5:ue=1073741823;break;case 4:ue=1e4;break;default:ue=5e3}return ue=N+ue,E={id:p++,callback:z,priorityLevel:E,startTime:N,expirationTime:ue,sortIndex:-1},N>Z?(E.sortIndex=N,t(u,E),n(s)===null&&E===n(u)&&(y?(f(P),P=-1):y=!0,Tt(w,N-Z))):(E.sortIndex=ue,t(s,E),g||v||(g=!0,$e(x))),E},e.unstable_shouldYield=W,e.unstable_wrapCallback=function(E){var z=d;return function(){var N=d;d=z;try{return E.apply(this,arguments)}finally{d=N}}}})(Zf);qf.exports=Zf;var Lh=qf.exports;/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Ih=C,Qe=Lh;function _(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Jf=new Set,Hr={};function En(e,t){rr(e,t),rr(e+"Capture",t)}function rr(e,t){for(Hr[e]=t,e=0;e<t.length;e++)Jf.add(t[e])}var It=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),va=Object.prototype.hasOwnProperty,Dh=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Qu={},Gu={};function Ah(e){return va.call(Gu,e)?!0:va.call(Qu,e)?!1:Dh.test(e)?Gu[e]=!0:(Qu[e]=!0,!1)}function jh(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Fh(e,t,n,r){if(t===null||typeof t>"u"||jh(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ze(e,t,n,r,o,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var xe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){xe[e]=new ze(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];xe[t]=new ze(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){xe[e]=new ze(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){xe[e]=new ze(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){xe[e]=new ze(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){xe[e]=new ze(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){xe[e]=new ze(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){xe[e]=new ze(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){xe[e]=new ze(e,5,!1,e.toLowerCase(),null,!1,!1)});var $s=/[\-:]([a-z])/g;function Ts(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace($s,Ts);xe[t]=new ze(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace($s,Ts);xe[t]=new ze(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace($s,Ts);xe[t]=new ze(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){xe[e]=new ze(e,1,!1,e.toLowerCase(),null,!1,!1)});xe.xlinkHref=new ze("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){xe[e]=new ze(e,1,!1,e.toLowerCase(),null,!0,!0)});function Rs(e,t,n,r){var o=xe.hasOwnProperty(t)?xe[t]:null;(o!==null?o.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!==" Line truncated
`+Bl+e}var Ul=!1;function Vl(e,t){if(!e||Ul)return"";Ul=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(u){var r=u}Reflect.construct(e,[],t)}else{try{t.call()}catch(u){r=u}e.call(t.prototype)}else{try{throw Error()}catch(u){r=u}e()}}catch(u){if(u&&r&&typeof u.stack=="string"){for(var o=u.stack.split(`
`),i=r.stack.split(`
`),l=o.length-1,a=i.length-1;1<=l&&0<=a&&o[l]!==i[a];)a--;for(;1<=l&&0<=a;l--,a--)if(o[l]!==i[a]){if(l!==1||a!==1)do if(l--,a--,0>a||o[l]!==i[a]){var s=`
`+o[l].replace(" at new "," at ");return e.displayName&&s.includes("<anonymous>")&&(s=s.replace("<anonymous>",e.displayName)),s}while(1<=l&&0<=a);break}}}finally{Ul=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Mr(e):""}function Wh(e){switch(e.tag){case 5:return Mr(e.type);case 16:return Mr("Lazy");case 13:return Mr("Suspense");case 19:return Mr("SuspenseList");case 0:case 2:case 15:return e=Vl(e.type,!1),e;case 11:return e=Vl(e.type.render,!1),e;case 1:return e=Vl(e.type,!0),e;default:return""}}function ka(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case An:return"Fragment";case Dn:return"Portal";case wa:return"Profiler";case Os:return"StrictMode";case xa:return"Suspense";case Sa:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case td:return(e.displayName||"Context")+".Consumer";case ed:return(e._context.displayName||"Context")+".Provider";case Ms:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case bs:return t=e.displayName||null,t!==null?t:ka(e.type)||"Memo";case Vt:t=e._payload,e=e._init;try{return ka(e(t))}catch{}}return null}function Bh(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ka(t);case 8:return t===Os?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ln(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function rd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Uh(e){var t=rd(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Mo(e){e._valueTracker||(e._valueTracker=Uh(e))}function od(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=rd(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function mi(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function _a(e,t){var n=t.checked;return te({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Xu(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ln(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function id(e,t){t=t.checked,t!=null&&Rs(e,"checked",t,!1)}function Ca(e,t){id(e,t);var n=ln(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ea(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ea(e,t.type,ln(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function qu(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ea(e,t,n){(t!=="number"||mi(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var br=Array.isArray;function Yn(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o<n.length;o++)t["$"+n[o]]=!0;for(n=0;n<e.length;n++)o=t.hasOwnProperty("$"+e[n].value),e[n].selected!==o&&(e[n].selected=o),o&&r&&(e[n].defaultSelected=!0)}else{for(n=""+ln(n),t=null,o=0;o<e.length;o++){if(e[o].value===n){e[o].selected=!0,r&&(e[o].defaultSelected=!0);return}t!==null||e[o].disabled||(t=e[o])}t!==null&&(t.selected=!0)}}function Pa(e,t){if(t.dan Line truncated
`).replace(J0,"")}function jo(e,t,n){if(t=xc(t),xc(e)!==t&&n)throw Error(_(425))}function ki(){}var ja=null,Fa=null;function Wa(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Ba=typeof setTimeout=="function"?setTimeout:void 0,ey=typeof clearTimeout=="function"?clearTimeout:void 0,Sc=typeof Promise=="function"?Promise:void 0,ty=typeof queueMicrotask=="function"?queueMicrotask:typeof Sc<"u"?function(e){return Sc.resolve(null).then(e).catch(ny)}:Ba;function ny(e){setTimeout(function(){throw e})}function ra(e,t){var n=t,r=0;do{var o=n.nextSibling;if(e.removeChild(n),o&&o.nodeType===8)if(n=o.data,n==="/$"){if(r===0){e.removeChild(o),Xr(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=o}while(n);Xr(t)}function en(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function kc(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var pr=Math.random().toString(36).slice(2),_t="__reactFiber$"+pr,to="__reactProps$"+pr,Dt="__reactContainer$"+pr,Ua="__reactEvents$"+pr,ry="__reactListeners$"+pr,oy="__reactHandles$"+pr;function mn(e){var t=e[_t];if(t)return t;for(var n=e.parentNode;n;){if(t=n[Dt]||n[_t]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=kc(e);e!==null;){if(n=e[_t])return n;e=kc(e)}return t}e=n,n=e.parentNode}return null}function wo(e){return e=e[_t]||e[Dt],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Bn(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(_(33))}function Qi(e){return e[to]||null}var Va=[],Un=-1;function cn(e){return{current:e}}function Y(e){0>Un||(e.current=Va[Un],Va[Un]=null,Un--)}function K(e,t){Un++,Va[Un]=e.current,e.current=t}var an={},Pe=cn(an),Ie=cn(!1),xn=an;function or(e,t){var n=e.type.contextTypes;if(!n)return an;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function De(e){return e=e.childContextTypes,e!=null}function _i(){Y(Ie),Y(Pe)}function _c(e,t,n){if(Pe.current!==an)throw Error(_(168));K(Pe,t),K(Ie,n)}function Qd(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(_(108,Bh(e)||"Unknown",o));return te({},n,r)}function Ci(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||an,xn=Pe.current,K(Pe,e),K(Ie,Ie.current),!0}function Cc(e,t,n){var r=e.stateNode;if(!r)throw Error(_(169));n?(e=Qd(e,t,xn),r.__reactInternalMemoizedMergedChildContext=e,Y(Ie),Y(Pe),K(Pe,e)):Y(Ie),K(Ie,n)}var Mt=null,Gi=!1,oa=!1;function Gd(e){Mt===null?Mt=[e]:Mt.push(e)}function iy(e){Gi=!0,Gd(e)}function fn(){if(!oa&&Mt!==null){oa=!0;var e=0,t=B;try{var n=Mt;for(B=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}Mt=null,Gi=!1}catch(o){throw Mt!==null&&(Mt=Mt.slice(e+1)),wd(Ns,fn),o}finally{B=t,oa=!1}}return null}var Vn=[],Hn=0,Ei=null,Pi=0,Je=[],et=0,Sn=null,bt=1,zt="";function dn(e,t){Vn[Hn++]=Pi,Vn[Hn++]=Ei,Ei=e,Pi=t}function Yd(e,t,n){Je[et++]=bt,Je[et++]=zt,Je[et++]=Sn,Sn=e;var r=bt;e=zt;var o=32-ht(r)-1;r&=~(1<<o),n+=1;var i=32-ht(t)+o;if(30<i){var l=o-o%5;i=(r&(1<<l)-1).toString(32),r>>=l,o-=l,bt=1<<32-ht(t)+o|n<<o|r,zt=i+e}else bt=1<<i|n<<o|r,zt=e}function Us(e){e.return!==null&&(dn(e,1),Yd(e,1,0))}function Vs(e){for(;e===Ei;)Ei=Vn[--Hn],Vn[Hn]=null,Pi=Vn[--Hn],Vn[Hn]=null;for(;e===Sn;)Sn=Je[--et],Je[et]=null,zt=Je[--et],Je[et]=null,bt=Je[--et],Je[et]=null}var He=null,Ve=null,q=!1,mt=null;function Xd(e,t){var n=nt(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function Ec(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,He=e,Ve=en(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,He=e,Ve=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=Sn!==null?{id:bt,overflow:zt}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=nt(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,He=e,Ve=null,!0):!1;default:return!1}}function Ha(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Ka(e){if(q){var t=Ve;if(t){var n=t;if(!Ec(e,t)){if(Ha(e))throw Error(_(418));t=en(n.nextSibling);var r=He;t&&Ec(e,t)?Xd(r,n):(e.flags=e.flags&-4097|2,q=!1,He=e)}}else{if(Ha(e))throw Error(_(418));e.flags=e.flags&-4097|2,q=!1,He=e}}}function Pc(e){for(e=e.return;e!==null&&e. Line truncated
Error generating stack: `+i.message+`
`+i.stack}return{value:e,source:t,stack:o,digest:null}}function ua(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Xa(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var my=typeof WeakMap=="function"?WeakMap:Map;function _p(e,t,n){n=Lt(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Ni||(Ni=!0,ls=r),Xa(e,t)},n}function Cp(e,t,n){n=Lt(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var o=t.value;n.payload=function(){return r(o)},n.callback=function(){Xa(e,t)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(n.callback=function(){Xa(e,t),typeof r!="function"&&(nn===null?nn=new Set([this]):nn.add(this));var l=t.stack;this.componentDidCatch(t.value,{componentStack:l!==null?l:""})}),n}function Nc(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new my;var o=new Set;r.set(t,o)}else o=r.get(t),o===void 0&&(o=new Set,r.set(t,o));o.has(n)||(o.add(n),e=Ty.bind(null,e,t,n),t.then(e,e))}function Lc(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Ic(e,t,n,r,o){return e.mode&1?(e.flags|=65536,e.lanes=o,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Lt(-1,1),t.tag=2,tn(n,t,1))),n.lanes|=1),e)}var hy=Wt.ReactCurrentOwner,Le=!1;function Re(e,t,n,r){t.child=e===null?Jd(t,null,n,r):lr(t,e.child,n,r)}function Dc(e,t,n,r,o){n=n.render;var i=t.ref;return Jn(t,o),r=tu(e,t,n,r,i,o),n=nu(),e!==null&&!Le?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~o,jt(e,t,o)):(q&&n&&Us(t),t.flags|=1,Re(e,t,r,o),t.child)}function Ac(e,t,n,r,o){if(e===null){var i=n.type;return typeof i=="function"&&!du(i)&&i.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=i,Ep(e,t,i,r,o)):(e=si(n.type,null,r,t,t.mode,o),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,!(e.lanes&o)){var l=i.memoizedProps;if(n=n.compare,n=n!==null?n:Zr,n(l,r)&&e.ref===t.ref)return jt(e,t,o)}return t.flags|=1,e=on(i,r),e.ref=t.ref,e.return=t,t.child=e}function Ep(e,t,n,r,o){if(e!==null){var i=e.memoizedProps;if(Zr(i,r)&&e.ref===t.ref)if(Le=!1,t.pendingProps=r=i,(e.lanes&o)!==0)e.flags&131072&&(Le=!0);else return t.lanes=e.lanes,jt(e,t,o)}return qa(e,t,n,r,o)}function Pp(e,t,n){var r=t.pendingProps,o=r.children,i=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},K(Gn,Be),Be|=n;else{if(!(n&1073741824))return e=i!==null?i.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,K(Gn,Be),Be|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:n,K(Gn,Be),Be|=r}else i!==null?(r=i.baseLanes|n,t.memoizedState=null):r=n,K(Gn,Be),Be|=r;return Re(e,t,o,n),t.child}function $p(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function qa(e,t,n,r,o){var i=De(n)?xn:Pe.current;return i=or(t,i),Jn(t,o),n=tu(e,t,n,r,i,o),r=nu(),e!==null&&!Le?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~o,jt(e,t,o)):(q&&r&&Us(t),t.flags|=1,Re(e,t,n,o),t.child)}function jc(e,t,n,r,o){if(De(n)){var i=!0;Ci(t)}else i=!1;if(Jn(t,o),t.stateNode===null)ii(e,t),kp(t,n,r),Ya(t,n,r,o),r=!0;else if(e===null){var l=t.stateNode,a=t.memoizedProps;l.props=a;var s=l.context,u=n.contextType;typeof u=="object"&&u!==null?u=ot(u):(u=De(n)?xn:Pe.current,u=or(t,u));var p=n.getDerivedStateFromProps,m=typeof p=="function"||typeof l.getSnapshotBeforeUpdate=="function";m||typeof l.UNSAFE_componentWillReceiveProps!="function"&&typeof l.componentWillReceiveProps!="function"||(a!==r||s!==u)&&zc(t,l,r,u),Ht=!1;var d=t.memoizedState;l.state=d,Ri(t,r,l,o),s=t.memoizedState,a!==r||d!==s||Ie.current||Ht?(typeof p=="function"&&(Ga(t,n,p,r),s=t.memoizedState),(a=Ht||bc(t,n,a,r,d,s,u))?(m||typeof l.UNSAFE_componentWillMount!="function"&&typeof l.componentWillMount!="function"||(typeof l.componentWillMount=="function"&&l.componentWillMount(),typeof l.UNSAFE_componentWillMount=="function"&&l.UNSAFE_componentWillMount()),typeof l.componentDidMount=="function"&&(t.flags|=4194308)):(typeof l.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=s),l.props=r,l.state=s,l.context=u,r=a):(typeof l.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{l=t.stateNode,tp(e,t),a=t.memoizedProps,u=t.type===t.elementType?a:dt(t.type,a),l.props=u,m=t.pendingProps,d=l.context,s=n.contextType,typeof s=="object"&&s!==null?s=ot(s):(s=De(n)?xn:Pe.current,s=or(t,s));var v=n.getDerivedStateFromProps;(p=typeof v=="function"||typeof l.getSnapshotBeforeUpdate=="function")||typeof l.UNSAFE_componentWillReceiveProps!="function"&&typeof l.componentWillReceiveProps!="function"||(a!==m||d!==s)&&zc(t,l,r,s),Ht=!1,d=t.memoizedState,l.state=d,Ri(t,r,l,o);var g=t.memoizedState;a Line truncated
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ye=typeof Symbol=="function"&&Symbol.for,Su=ye?Symbol.for("react.element"):60103,ku=ye?Symbol.for("react.portal"):60106,al=ye?Symbol.for("react.fragment"):60107,sl=ye?Symbol.for("react.strict_mode"):60108,ul=ye?Symbol.for("react.profiler"):60114,cl=ye?Symbol.for("react.provider"):60109,fl=ye?Symbol.for("react.context"):60110,_u=ye?Symbol.for("react.async_mode"):60111,dl=ye?Symbol.for("react.concurrent_mode"):60111,pl=ye?Symbol.for("react.forward_ref"):60112,ml=ye?Symbol.for("react.suspense"):60113,$g=ye?Symbol.for("react.suspense_list"):60120,hl=ye?Symbol.for("react.memo"):60115,yl=ye?Symbol.for("react.lazy"):60116,Tg=ye?Symbol.for("react.block"):60121,Rg=ye?Symbol.for("react.fundamental"):60117,Og=ye?Symbol.for("react.responder"):60118,Mg=ye?Symbol.for("react.scope"):60119;function Xe(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Su:switch(e=e.type,e){case _u:case dl:case al:case ul:case sl:case ml:return e;default:switch(e=e&&e.$$typeof,e){case fl:case pl:case yl:case hl:case cl:return e;default:return t}}case ku:return t}}}function sm(e){return Xe(e)===dl}U.AsyncMode=_u;U.ConcurrentMode=dl;U.ContextConsumer=fl;U.ContextProvider=cl;U.Element=Su;U.ForwardRef=pl;U.Fragment=al;U.Lazy=yl;U.Memo=hl;U.Portal=ku;U.Profiler=ul;U.StrictMode=sl;U.Suspense=ml;U.isAsyncMode=function(e){return sm(e)||Xe(e)===_u};U.isConcurrentMode=sm;U.isContextConsumer=function(e){return Xe(e)===fl};U.isContextProvider=function(e){return Xe(e)===cl};U.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Su};U.isForwardRef=function(e){return Xe(e)===pl};U.isFragment=function(e){return Xe(e)===al};U.isLazy=function(e){return Xe(e)===yl};U.isMemo=function(e){return Xe(e)===hl};U.isPortal=function(e){return Xe(e)===ku};U.isProfiler=function(e){return Xe(e)===ul};U.isStrictMode=function(e){return Xe(e)===sl};U.isSuspense=function(e){return Xe(e)===ml};U.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===al||e===dl||e===ul||e===sl||e===ml||e===$g||typeof e=="object"&&e!==null&&(e.$$typeof===yl||e.$$typeof===hl||e.$$typeof===cl||e.$$typeof===fl||e.$$typeof===pl||e.$$typeof===Rg||e.$$typeof===Og||e.$$typeof===Mg||e.$$typeof===Tg)};U.typeOf=Xe;am.exports=U;var bg=am.exports,um=bg,zg={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Ng={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},cm={};cm[um.ForwardRef]=zg;cm[um.Memo]=Ng;var Lg=!0;function Ig(e,t,n){var r="";return n.split(" ").forEach(function(o){e[o]!==void 0?t.push(e[o]+";"):r+=o+" "}),r}var fm=function(t,n,r){var o=t.key+"-"+n.name;(r===!1||Lg===!1)&&t.registered[o]===void 0&&(t.registered[o]=n.styles)},dm=function(t,n,r){fm(t,n,r);var o=t.key+"-"+n.name;if(t.inserted[n.name]===void 0){var i=n;do t.insert(n===i?"."+o:"",i,t.sheet,!0),i=i.next;while(i!==void 0)}};function Dg(e){for(var t=0,n,r=0,o=e.length;o>=4;++r,o-=4)n=e.charCodeAt(r)&255|(e.charCodeAt(++r)&255)<<8|(e.charCodeAt(++r)&255)<<16|(e.charCodeAt(++r)&255)<<24,n=(n&65535)*1540483477+((n>>>16)*59797<<16),n^=n>>>24,t=(n&65535)*1540483477+((n>>>16)*59797<<16)^(t&65535)*1540483477+((t>>>16)*59797<<16);switch(o){case 3:t^=(e.charCodeAt(r+2)&255)<<16;case 2:t^=(e.charCodeAt(r+1)&255)<<8;case 1:t^=e.charCodeAt(r)&255,t=(t&65535)*1540483477+((t>>>16)*59797<<16)}return t^=t>>>13,t=(t&65535)*1540483477+((t>>>16)*59797<<16),((t^t>>>15)>>>0).toString(36)}var Ag={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},jg=!1,Fg=/[A-Z]|^ms/g,Wg=/_EMO_([^_]+?)_([^]*?)_EMO_/g,pm=function(t){return t.charCodeAt(1)===45},nf=function(t){return t!=null&&typeof t!="boolean"},pa=Zp(function(e){return pm(e)?e:e.replace(Fg,"-$&").toLowerCase()}),rf=function(t,n){switch(t){case"animation":case"animationName":if(typeof n=="string")return n.replace(Wg,function(r,o,i){return kt={name:o,styles:i,next:kt},o})}return Ag[t]!==1&&!pm(t)&&typeof n=="number"&&n!==0?n+"px":n},Bg="Component selectors can only be used in conjunction with @emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware compiler transform.";function po(e,t,n){if(n==null)return"";var r=n;if(r.__emotion_styles!==void 0)return r;switch(typeof n){case"boolean":return"";case"object":{var o=n;if(o.anim===1)return kt={name:o.name,styles:o.styles,next:kt},o.name;var i=n;if(i.styles!==void 0){var l=i.next;if(l!==void 0)for(;l!==void 0;)kt={name:l.name,styles:l.styles,nextLine truncated
* @mui/styled-engine v5.16.6
*
* @license MIT
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/function vm(e,t){return ds(e,t)}const n1=(e,t)=>{Array.isArray(e.__emotion_styles)&&(e.__emotion_styles=t(e.__emotion_styles))},r1=Object.freeze(Object.defineProperty({__proto__:null,GlobalStyles:gm,StyledEngineProvider:e1,ThemeContext:gl,css:ko,default:vm,internal_processStyles:n1,keyframes:$n},Symbol.toStringTag,{value:"Module"}));function Gt(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function wm(e){if(!Gt(e))return e;const t={};return Object.keys(e).forEach(n=>{t[n]=wm(e[n])}),t}function $t(e,t,n={clone:!0}){const r=n.clone?R({},e):e;return Gt(e)&&Gt(t)&&Object.keys(t).forEach(o=>{Gt(t[o])&&Object.prototype.hasOwnProperty.call(e,o)&&Gt(e[o])?r[o]=$t(e[o],t[o],n):n.clone?r[o]=Gt(t[o])?wm(t[o]):t[o]:r[o]=t[o]}),r}const o1=Object.freeze(Object.defineProperty({__proto__:null,default:$t,isPlainObject:Gt},Symbol.toStringTag,{value:"Module"})),i1=["values","unit","step"],l1=e=>{const t=Object.keys(e).map(n=>({key:n,val:e[n]}))||[];return t.sort((n,r)=>n.val-r.val),t.reduce((n,r)=>R({},n,{[r.key]:r.val}),{})};function xm(e){const{values:t={xs:0,sm:600,md:900,lg:1200,xl:1536},unit:n="px",step:r=5}=e,o=Fe(e,i1),i=l1(t),l=Object.keys(i);function a(d){return`@media (min-width:${typeof t[d]=="number"?t[d]:d}${n})`}function s(d){return`@media (max-width:${(typeof t[d]=="number"?t[d]:d)-r/100}${n})`}function u(d,v){const g=l.indexOf(v);return`@media (min-width:${typeof t[d]=="number"?t[d]:d}${n}) and (max-width:${(g!==-1&&typeof t[l[g]]=="number"?t[l[g]]:v)-r/100}${n})`}function p(d){return l.indexOf(d)+1<l.length?u(d,l[l.indexOf(d)+1]):a(d)}function m(d){const v=l.indexOf(d);return v===0?a(l[1]):v===l.length-1?s(l[v]):u(d,l[l.indexOf(d)+1]).replace("@media","@media not all and")}return R({keys:l,values:i,up:a,down:s,between:u,only:p,not:m,unit:n},o)}const a1={borderRadius:4},s1=a1;function Vr(e,t){return t?$t(e,t,{clone:!1}):e}const Eu={xs:0,sm:600,md:900,lg:1200,xl:1536},uf={keys:["xs","sm","md","lg","xl"],up:e=>`@media (min-width:${Eu[e]}px)`};function Ft(e,t,n){const r=e.theme||{};if(Array.isArray(t)){const i=r.breakpoints||uf;return t.reduce((l,a,s)=>(l[i.up(i.keys[s])]=n(t[s]),l),{})}if(typeof t=="object"){const i=r.breakpoints||uf;return Object.keys(t).reduce((l,a)=>{if(Object.keys(i.values||Eu).indexOf(a)!==-1){const s=i.up(a);l[s]=n(t[a],a)}else{const s=a;l[s]=t[s]}return l},{})}return n(t)}function u1(e={}){var t;return((t=e.keys)==null?void 0:t.reduce((r,o)=>{const i=e.up(o);return r[i]={},r},{}))||{}}function c1(e,t){return e.reduce((n,r)=>{const o=n[r];return(!o||Object.keys(o).length===0)&&delete n[r],n},t)}function G(e){if(typeof e!="string")throw new Error(uo(7));return e.charAt(0).toUpperCase()+e.slice(1)}const f1=Object.freeze(Object.defineProperty({__proto__:null,default:G},Symbol.toStringTag,{value:"Module"}));function vl(e,t,n=!0){if(!t||typeof t!="string")return null;if(e&&e.vars&&n){const r=`vars.${t}`.split(".").reduce((o,i)=>o&&o[i]?o[i]:null,e);if(r!=null)return r}return t.split(".").reduce((r,o)=>r&&r[o]!=null?r[o]:null,e)}function ji(e,t,n,r=n){let o;return typeof e=="function"?o=e(n):Array.isArray(e)?o=e[n]||r:o=vl(e,n)||r,t&&(o=t(o,r,e)),o}function le(e){const{prop:t,cssProperty:n=e.prop,themeKey:r,transform:o}=e,i=l=>{if(l[t]==null)return null;const a=l[t],s=l.theme,u=vl(s,r)||{};return Ft(l,a,m=>{let d=ji(u,o,m);return m===d&&typeof m=="string"&&(d=ji(u,o,`${t}${m==="default"?"":G(m)}`,m)),n===!1?d:{[n]:d}})};return i.propTypes={},i.filterProps=[t],i}function d1(e){const t={};return n=>(t[n]===void 0&&(t[n]=e(n)),t[n])}const p1={m:"margin",p:"padding"},m1={t:"Top",r:"Right",b:"Bottom",l:"Left",x:["Left","Right"],y:["Top","Bottom"]},cf={marginX:"mx",marginY:"my",paddingX:"px",paddingY:"py"},h1=d1(e=>{if(e.length>2)if(cf[e])e=cf[e];else return[e];const[t,n]=e.split(""),r=p1[t],o=m1[n]||"";return Array.isArray(o)?o.map(i=>r+i):[r+o]}),Pu=["m","mt","mr","mb","ml","mx","my","margin","marginTop","marginRight","marginBottom","marginLeft","marginX","marginY","marginInline","marginInlineStart","marginInlineEnd","marginBlock","marginBlockStart","marginBlockEnd"],$u=["p","pt","pr","pb","pl","px","py","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","paddingX","paddingY","paddingInline","paddingInlineStart","paddingInlineEnd","paddingBlock","paddingBlockStart","paddingBlockEnd"];[...Pu,...$u];function _o(e,t,n,r){var o;const i=(o=vl(e,t,!1))!=null?o:n;return typeof i=="number"?l=>typeof l=="string"?l:i*l:Array.isArray(i)?l=>typeof l=="string"?l:i[l]:typeof i=="function"?i:()=>{}}function Sm(e){return _o(e,"spacing",8)}function Co(e,t){if(typeof t=="string"||t==null)return t;const n=Math.abs(t),r=e(n);return t>=0?r:typeof r=="number"?-r:`-${r}`}function y1(e,t){return n=>e.reduce((r,o)=>(r[o]=Co(t,n),r),{})}function g1(e,t,n,r){if(t.indexOf(n)===-1)return null;const o=h1(n),i=y1(o,r),l=e[n];return Ft(e,l,i)}function km(e,Line truncated
* @license React
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Mu=Symbol.for("react.element"),bu=Symbol.for("react.portal"),El=Symbol.for("react.fragment"),Pl=Symbol.for("react.strict_mode"),$l=Symbol.for("react.profiler"),Tl=Symbol.for("react.provider"),Rl=Symbol.for("react.context"),dv=Symbol.for("react.server_context"),Ol=Symbol.for("react.forward_ref"),Ml=Symbol.for("react.suspense"),bl=Symbol.for("react.suspense_list"),zl=Symbol.for("react.memo"),Nl=Symbol.for("react.lazy"),pv=Symbol.for("react.offscreen"),Om;Om=Symbol.for("react.module.reference");function st(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Mu:switch(e=e.type,e){case El:case $l:case Pl:case Ml:case bl:return e;default:switch(e=e&&e.$$typeof,e){case dv:case Rl:case Ol:case Nl:case zl:case Tl:return e;default:return t}}case bu:return t}}}V.ContextConsumer=Rl;V.ContextProvider=Tl;V.Element=Mu;V.ForwardRef=Ol;V.Fragment=El;V.Lazy=Nl;V.Memo=zl;V.Portal=bu;V.Profiler=$l;V.StrictMode=Pl;V.Suspense=Ml;V.SuspenseList=bl;V.isAsyncMode=function(){return!1};V.isConcurrentMode=function(){return!1};V.isContextConsumer=function(e){return st(e)===Rl};V.isContextProvider=function(e){return st(e)===Tl};V.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Mu};V.isForwardRef=function(e){return st(e)===Ol};V.isFragment=function(e){return st(e)===El};V.isLazy=function(e){return st(e)===Nl};V.isMemo=function(e){return st(e)===zl};V.isPortal=function(e){return st(e)===bu};V.isProfiler=function(e){return st(e)===$l};V.isStrictMode=function(e){return st(e)===Pl};V.isSuspense=function(e){return st(e)===Ml};V.isSuspenseList=function(e){return st(e)===bl};V.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===El||e===$l||e===Pl||e===Ml||e===bl||e===pv||typeof e=="object"&&e!==null&&(e.$$typeof===Nl||e.$$typeof===zl||e.$$typeof===Tl||e.$$typeof===Rl||e.$$typeof===Ol||e.$$typeof===Om||e.getModuleId!==void 0)};V.typeOf=st;Rm.exports=V;var df=Rm.exports;const mv=/^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s/]*)\s*/;function Mm(e){const t=`${e}`.match(mv);return t&&t[1]||""}function bm(e,t=""){return e.displayName||e.name||Mm(e)||t}function pf(e,t,n){const r=bm(t);return e.displayName||(r!==""?`${n}(${r})`:n)}function hv(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="function")return bm(e,"Component");if(typeof e=="object")switch(e.$$typeof){case df.ForwardRef:return pf(e,e.render,"ForwardRef");case df.Memo:return pf(e,e.type,"memo");default:return}}}const yv=Object.freeze(Object.defineProperty({__proto__:null,default:hv,getFunctionName:Mm},Symbol.toStringTag,{value:"Module"}));function Fi(e,t){const n=R({},t);return Object.keys(e).forEach(r=>{if(r.toString().match(/^(components|slots)$/))n[r]=R({},e[r],n[r]);else if(r.toString().match(/^(componentsProps|slotProps)$/)){const o=e[r]||{},i=t[r];n[r]={},!i||!Object.keys(i)?n[r]=o:!o||!Object.keys(o)?n[r]=i:(n[r]=R({},i),Object.keys(o).forEach(l=>{n[r][l]=Fi(o[l],i[l])}))}else n[r]===void 0&&(n[r]=e[r])}),n}const gv=typeof window<"u"?C.useLayoutEffect:C.useEffect,vv=gv;function wv(e,t=Number.MIN_SAFE_INTEGER,n=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,n))}const xv=Object.freeze(Object.defineProperty({__proto__:null,default:wv},Symbol.toStringTag,{value:"Module"}));function Sv(e,t){typeof e=="function"?e(t):e&&(e.current=t)}function Qo(e){const t=C.useRef(e);return vv(()=>{t.current=e}),C.useRef((...n)=>(0,t.current)(...n)).current}function mf(...e){return C.useMemo(()=>e.every(t=>t==null)?null:t=>{e.forEach(n=>{Sv(n,t)})},e)}const hf={};function kv(e,t){const n=C.useRef(hf);return n.current===hf&&(n.current=e(t)),n}const _v=[];function Cv(e){C.useEffect(e,_v)}class Ll{constructor(){this.currentId=null,this.clear=()=>{this.currentId!==null&&(clearTimeout(this.currentId),this.currentId=null)},this.disposeEffect=()=>this.clear}static create(){return new Ll}start(t,n){this.clear(),this.currentId=setTimeout(()=>{this.currentId=null,n()},t)}}function Ev(){const e=kv(Ll.create).current;return Cv(e.disposeEffect),e}let Il=!0,ms=!1;const Pv=new Ll,$v={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function Tv(e){const{type:t,tagName:n}=e;return!!(n==="INPUT"&&$v[t]&&!e.readOnly||n==="TEXTAREA"&&!e.readOnly||e.isContentEditable)}function Rv(e){e.metaKey||e.altKey||e.ctrlKey||(Il=!0)}function ma(){Il=!1}function Ov(){this.visibilityState==="hidden"&&ms&&(Il=!0)}function Mv(e){e.addEventListener("keydown",Rv,!0),e.addEventListener("mousedown",ma,!0),e.addEventListener("pointerdown",ma,!0),e.addEventListener("touchstart",ma,!0),e.addEventListener("visibilitychange",Ov,!0)}function bv(e){const{target:t}=e;try{return t.matches(":focus-visible")}catch{}return Il||Tv(t)}function zv(){const e=C.useCallback(o=>{o!=null&&Mv(o.ownerDocument)},[]),t=C.useRef(!1);function n(){return t.current?(ms=!0,Pv.start(100,()=>{ms=!1}),t.current=!1,!0):!1}function r(o){return bv(o)?(t.current=!0,!0):!1}return{isFocusVisibleRef:t,onFocusLine truncated
0% {
transform: scale(0);
opacity: 0.1;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`)),sx=$n($f||($f=Al`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`)),ux=$n(Tf||(Tf=Al`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`)),cx=vt("span",{name:"MuiTouchRipple",slot:"Root"})({overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:"inherit"}),fx=vt(rx,{name:"MuiTouchRipple",slot:"Ripple"})(Rf||(Rf=Al`
opacity: 0;
position: absolute;
&.${0} {
opacity: 0.3;
transform: scale(1);
animation-name: ${0};
animation-duration: ${0}ms;
animation-timing-function: ${0};
}
&.${0} {
animation-duration: ${0}ms;
}
& .${0} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${0} {
opacity: 0;
animation-name: ${0};
animation-duration: ${0}ms;
animation-timing-function: ${0};
}
& .${0} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${0};
animation-duration: 2500ms;
animation-timing-function: ${0};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`),Ze.rippleVisible,ax,gs,({theme:e})=>e.transitions.easing.easeInOut,Ze.ripplePulsate,({theme:e})=>e.transitions.duration.shorter,Ze.child,Ze.childLeaving,sx,gs,({theme:e})=>e.transitions.easing.easeInOut,Ze.childPulsate,ux,({theme:e})=>e.transitions.easing.easeInOut),dx=C.forwardRef(function(t,n){const r=vr({props:t,name:"MuiTouchRipple"}),{center:o=!1,classes:i={},className:l}=r,a=Fe(r,ix),[s,u]=C.useState([]),p=C.useRef(0),m=C.useRef(null);C.useEffect(()=>{m.current&&(m.current(),m.current=null)},[s]);const d=C.useRef(!1),v=Ev(),g=C.useRef(null),y=C.useRef(null),$=C.useCallback(w=>{const{pulsate:x,rippleX:k,rippleY:S,rippleSize:P,cb:I}=w;u(O=>[...O,b.jsx(fx,{classes:{ripple:Oe(i.ripple,Ze.ripple),rippleVisible:Oe(i.rippleVisible,Ze.rippleVisible),ripplePulsate:Oe(i.ripplePulsate,Ze.ripplePulsate),child:Oe(i.child,Ze.child),childLeaving:Oe(i.childLeaving,Ze.childLeaving),childPulsate:Oe(i.childPulsate,Ze.childPulsate)},timeout:gs,pulsate:x,rippleX:k,rippleY:S,rippleSize:P},p.current)]),p.current+=1,m.current=I},[i]),f=C.useCallback((w={},x={},k=()=>{})=>{const{pulsate:S=!1,center:P=o||x.pulsate,fakeElement:I=!1}=x;if((w==null?void 0:w.type)==="mousedown"&&d.current){d.current=!1;return}(w==null?void 0:w.type)==="touchstart"&&(d.current=!0);const O=I?null:y.current,W=O?O.getBoundingClientRect():{width:0,height:0,left:0,top:0};let H,se,Se;if(P||w===void 0||w.clientX===0&&w.clientY===0||!w.clientX&&!w.touches)H=Math.round(W.width/2),se=Math.round(W.height/2);else{const{clientX:ut,clientY:$e}=w.touches&&w.touches.length>0?w.touches[0]:w;H=Math.round(ut-W.left),se=Math.round($e-W.top)}if(P)Se=Math.sqrt((2*W.width**2+W.height**2)/3),Se%2===0&&(Se+=1);else{const ut=Math.max(Math.abs((O?O.clientWidth:0)-H),H)*2+2,$e=Math.max(Math.abs((O?O.clientHeight:0)-se),se)*2+2;Se=Math.sqrt(ut**2+$e**2)}w!=null&&w.touches?g.current===null&&(g.current=()=>{$({pulsate:S,rippleX:H,rippleY:se,rippleSize:Se,cb:k})},v.start(lx,()=>{g.current&&(g.current(),g.current=null)})):$({pulsate:S,rippleX:H,rippleY:se,rippleSize:Se,cb:k})},[o,$,v]),c=C.useCallback(()=>{f({},{pulsate:!0})},[f]),h=C.useCallback((w,x)=>{if(v.clear(),(w==null?void 0:w.type)==="touchend"&&g.current){g.current(),g.current=null,v.start(0,()=>{h(w,x)});return}g.current=null,u(k=>k.length>0?k.slice(1):k),m.current=x},[v]);return C.useImperativeHandle(n,()=>({pulsate:c,start:f,stop:h}),[c,f,h]),b.jsx(cx,R({className:Oe(Ze.root,i.root,l),ref:y},a,{children:b.jsx(nx,{component:null,exit:!0,children:s})}))}),px=dx;function mx(e){return Po("MuiButtonBase",e)}const hx=hr("MuiButtonBase",["root","disabled","focusVisible"]),yx=hx,gx=["action","centerRipple","children","className","component","disabled","disableRipple","disableTouchRipple","focusRipple","focusVisibleClassName","LinkComponent","onBlur","onClick","onContextMenu","onDragLeave","onFocus","onFocusVisible","onKeyDown","onKeyUp","onMouseDown","onMouseLeave","onMouseUp","onTouchEnd","onTouchMove","onTouchStart","tabIndex","TouchRippleProps","touchRippleRef","type"],vx=e=>{const{disabled:t,focusVisible:n,focusVisibleClassName:r,classes:o}=e,l=Dl({root:["root",t&&"disabled",n&&"focusVisible"]},mx,o);return n&&r&&(l.root+=` ${r}`),l},wx=vt("button",{name:"MuiButtonBase",slot:"Root",overridesResolver:(e,t)=>t.root})({display:"inline-flex",alignItems:"center",justifyContent:"center",position:"relative",boxSizing:"border-box",WebkitTapHighlightColor:"transparent",backgroundColor:"transparent",outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:"pointer",userSelect:"none",verticalAlign:"middle",MozAppearance:"none",WebkitAppearance:"none",textDecoration:"none",color:"inherit","&::-moz-focus-inner":{borderStyle:"none"},[`&.${yx.disabled}`]:{pointerEvents:"none",cursor:"default"},"@media print":{colorAdjust:"exact"}}),xx=C.forwardRef(function(t,n){const r=vr({props:t,name:"MuiButtonBase"}),{action:o,centerRipple:i=!1,children:l,className:a,component:s="button",disabled:u=!1,disableRipple:p=!1,disableTouchRipple:m=!1,focusRipple:d=!1,LinkComponent:v="a",onBlur:g,onClick:y,onContextMenu:$,onDragLeave:f,onFocus:c,onFocusVisible:h,onKeyDown:w,onKeyUp:x,onMouseDown:k,onMouseLeave:S,onMouseUp:P,onTouchEnd:I,onTouchMove:O,onTouchStart:W,tabIndex:H=0,TouchRippleProps:se,touchRippleRef:Se,type:ut}=r,$e=Fe(r,gx),Tt=C.useRef(null),E=C.useRef(null),z=mf(E,Se),{isFocusVisibleRef:N,onFocus:Z,onBlur:ue,ref:Tn}=zv(),[Te,Bt]=C.useState(!1);u&&Te&&Bt(!1),C.useImperativeHandle(o,()=>({focusVisible:()=>{Bt(!0),Tt.current.focus()}}),[]);const[ct,Rn]=C.useState(!1);C.useEffect(()=>{Rn(!0)},[]);const Xm=ct&&!p&&!u;C.useEffect(()=>{Te&&d&&!p&&ct&&E.current.pulsate()},[p,d,Te,ct]);function Rt(L,Wu,fh=m){return Qo(Bu=>(Wu&&Wu(Bu),!fh&&E.current&&E.current[L](Bu),!0))}const qm=Rt("start",k),Zm=Rt("stop",$),Jm=Rt("stop",f),eh=Rt("stop",P),th=Rt("stop",L=>{Te&&L.preventDefault(),S&&S(L)}),nh=Rt("start",W),rh=Rt("stop",I),oh=Rt("stop",O),ih=Rt("stop",L=>{ue(L),N.current===!1&&Bt(!1),g&&g(L)},!1),lh=Qo(L=>{Tt.current||(Tt.current=L.currentTarget) Line truncated
0% {
left: -35%;
right: 100%;
}
60% {
left: 100%;
right: -90%;
}
100% {
left: 100%;
right: -90%;
}
`)),eS=$n(bf||(bf=wr`
0% {
left: -200%;
right: 100%;
}
60% {
left: 107%;
right: -8%;
}
100% {
left: 107%;
right: -8%;
}
`)),tS=$n(zf||(zf=wr`
0% {
opacity: 1;
background-position: 0 -23px;
}
60% {
opacity: 0;
background-position: 0 -23px;
}
100% {
opacity: 1;
background-position: -200px -23px;
}
`)),nS=e=>{const{classes:t,variant:n,color:r}=e,o={root:["root",`color${G(r)}`,n],dashed:["dashed",`dashedColor${G(r)}`],bar1:["bar",`barColor${G(r)}`,(n==="indeterminate"||n==="query")&&"bar1Indeterminate",n==="determinate"&&"bar1Determinate",n==="buffer"&&"bar1Buffer"],bar2:["bar",n!=="buffer"&&`barColor${G(r)}`,n==="buffer"&&`color${G(r)}`,(n==="indeterminate"||n==="query")&&"bar2Indeterminate",n==="buffer"&&"bar2Buffer"]};return Dl(o,qx,t)},ju=(e,t)=>t==="inherit"?"currentColor":e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode==="light"?Dm(e.palette[t].main,.62):Im(e.palette[t].main,.5),rS=vt("span",{name:"MuiLinearProgress",slot:"Root",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.root,t[`color${G(n.color)}`],t[n.variant]]}})(({ownerState:e,theme:t})=>R({position:"relative",overflow:"hidden",display:"block",height:4,zIndex:0,"@media print":{colorAdjust:"exact"},backgroundColor:ju(t,e.color)},e.color==="inherit"&&e.variant!=="buffer"&&{backgroundColor:"none","&::before":{content:'""',position:"absolute",left:0,top:0,right:0,bottom:0,backgroundColor:"currentColor",opacity:.3}},e.variant==="buffer"&&{backgroundColor:"transparent"},e.variant==="query"&&{transform:"rotate(180deg)"})),oS=vt("span",{name:"MuiLinearProgress",slot:"Dashed",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.dashed,t[`dashedColor${G(n.color)}`]]}})(({ownerState:e,theme:t})=>{const n=ju(t,e.color);return R({position:"absolute",marginTop:0,height:"100%",width:"100%"},e.color==="inherit"&&{opacity:.3},{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`,backgroundSize:"10px 10px",backgroundPosition:"0 -23px"})},ko(Nf||(Nf=wr`
animation: ${0} 3s infinite linear;
`),tS)),iS=vt("span",{name:"MuiLinearProgress",slot:"Bar1",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.bar,t[`barColor${G(n.color)}`],(n.variant==="indeterminate"||n.variant==="query")&&t.bar1Indeterminate,n.variant==="determinate"&&t.bar1Determinate,n.variant==="buffer"&&t.bar1Buffer]}})(({ownerState:e,theme:t})=>R({width:"100%",position:"absolute",left:0,bottom:0,top:0,transition:"transform 0.2s linear",transformOrigin:"left",backgroundColor:e.color==="inherit"?"currentColor":(t.vars||t).palette[e.color].main},e.variant==="determinate"&&{transition:`transform .${vs}s linear`},e.variant==="buffer"&&{zIndex:1,transition:`transform .${vs}s linear`}),({ownerState:e})=>(e.variant==="indeterminate"||e.variant==="query")&&ko(Lf||(Lf=wr`
width: auto;
animation: ${0} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
`),Jx)),lS=vt("span",{name:"MuiLinearProgress",slot:"Bar2",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.bar,t[`barColor${G(n.color)}`],(n.variant==="indeterminate"||n.variant==="query")&&t.bar2Indeterminate,n.variant==="buffer"&&t.bar2Buffer]}})(({ownerState:e,theme:t})=>R({width:"100%",position:"absolute",left:0,bottom:0,top:0,transition:"transform 0.2s linear",transformOrigin:"left"},e.variant!=="buffer"&&{backgroundColor:e.color==="inherit"?"currentColor":(t.vars||t).palette[e.color].main},e.color==="inherit"&&{opacity:.3},e.variant==="buffer"&&{backgroundColor:ju(t,e.color),transition:`transform .${vs}s linear`}),({ownerState:e})=>(e.variant==="indeterminate"||e.variant==="query")&&ko(If||(If=wr`
width: auto;
animation: ${0} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
`),eS)),aS=C.forwardRef(function(t,n){const r=vr({props:t,name:"MuiLinearProgress"}),{className:o,color:i="primary",value:l,valueBuffer:a,variant:s="indeterminate"}=r,u=Fe(r,Zx),p=R({},r,{color:i,variant:s}),m=nS(p),d=Lv(),v={},g={bar1:{},bar2:{}};if((s==="determinate"||s==="buffer")&&l!==void 0){v["aria-valuenow"]=Math.round(l),v["aria-valuemin"]=0,v["aria-valuemax"]=100;let y=l-100;d&&(y=-y),g.bar1.transform=`translateX(${y}%)`}if(s==="buffer"&&a!==void 0){let y=(a||0)-100;d&&(y=-y),g.bar2.transform=`translateX(${y}%)`}return b.jsxs(rS,R({className:Oe(m.root,o),ownerState:p,role:"progressbar"},v,{ref:n},u,{children:[s==="buffer"?b.jsx(oS,{className:m.dashed,ownerState:p}):null,b.jsx(iS,{className:m.bar1,ownerState:p,style:g.bar1}),s==="determinate"?null:b.jsx(lS,{className:m.bar2,ownerState:p,style:g.bar2})]}))}),sS=aS;function uS(){return window.crypto.getRandomValues(new Uint32Array(1))[0]}function ws(e,t=!1){const n=uS(),r=`_${n}`;return Object.defineProperty(window,r,{value:o=>(t&&Reflect.deleteProperty(window,r),e==null?void 0:e(o)),writable:!1,configurable:!0}),n}async function cS(e,t={}){return new Promise((n,r)=>{const o=ws(l=>{n(l),Reflect.deleteProperty(window,`_${i}`)},!0),i=ws(l=>{r(l),Reflect.deleteProperty(window,`_${o}`)},!0);window.__TAURI_IPC__({cmd:e,callback:o,error:i,...t})})}async function M(e){return cS("tauri",e)}async function Gm(e,t){return M({__tauriModule:"Event",message:{cmd:"unlisten",event:e,eventId:t}})}async function fS(e,t,n){await M({__tauriModule:"Event",message:{cmd:"emit",event:e,windowLabel:t,payload:n}})}async function Ym(e,t,n){return M({__tauriModule:"Event",message:{cmd:"listen",event:e,windowLabel:t,handler:ws(n)}}).then(r=>async()=>Gm(e,r))}async function dS(e,t,n){return Ym(e,t,r=>{n(r),Gm(e,r.id).catch(()=>{})})}var We;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_FILE_DROP="tauri://file-drop",e.WINDOW_FILE_DROP_HOVER="tauri://file-drop-hover",e.WINDOW_FILE_DROP_CANCELLED="tauri://file-drop-cancelled",e.MENU="tauri://menu",e.CHECK_UPDATE="tauri://update",e.UPDATE_AVAILABLE="tauri://update-available",e.INSTALL_UPDATE="tauri://update-install",e.STATUS_UPDATE="tauri://update-status",e.DOWNLOAD_PROGRESS="tauri://update-download-progress"})(We||(We={}));class pS{constructor(t,n){this.type="Logical",this.width=t,this.height=n}}class xs{constructor(t,n){this.type="Physical",this.width=t,this.height=n}toLogical(t){return new pS(this.width/t,this.height/t)}}class mS{constructor(t,n){this.type="Logical",this.x=t,this.y=n}}class Ss{constructor(t,n){this.type="Physical",this.x=t,this.y=n}toLogical(t){return new mS(this.x/t,this.y/t)}}var ks;(function(e){e[e.Critical=1]="Critical",e[e.Informational=2]="Informational"})(ks||(ks={}));function Df(){return window.__TAURI_METADATA__.__windows.map(e=>new mo(e.label,{skip:!0}))}const Af=["tauri://created","tauri://error"];class hS{constructor(t){this.label=t,this.listeners=Object.create(null)}async listen(t,n){return this._handleTauriEvent(t,n)?Promise.resolve(()=>{const r=this.listeners[t];r.splice(r.indexOf(n),1)}):Ym(t,this.label,n)}async once(t,n){return this._handleTauriEvent(t,n)?Promise.resolve(()=>{const r=this.listeners[t];r.splice(r.indexOf(n),1)}):dS(t,this.label,n)}async emit(t,n){if(Af.includes(t)){for(const r of this.listeners[t]||[])r({event:t,id:-1,windowLabel:this.label,payload:n});return Promise.resolve()}return fS(t,this.label,n)}_handleTauriEvent(t,n){return Af.includes(t)?(t in this.listeners?this.listeners[t].push(n):this.listeners[t]=[n],!0):!1}}class yS extends hS{async scaleFactor(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"scaleFactor"}}}})}async innerPosition(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"innerPosition"}}}}).then(({x:t,y:n})=>new Ss(t,n))}async outerPosition(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"outerPosition"}}}}).then(({x:t,y:n})=>new Ss(t,n))}async innerSize(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"innerSize"}}}}).then(({width:t,height:n})=>new xs(t,n))}async outerSize(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"outerSize"}}}}).then(({width:t,height:n})=>new xs(t,n))}async isFullscreen(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"isFullscreen"}}}})}async isMinimized(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"isMinimized"}}}})}async isMaximized(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cm Line truncated
Note that this is not an issue if running this frontend on a browser instead of a Tauri window.`),ho=new mo("main",{skip:!0}));function vS(e){return new Ss(e.x,e.y)}function wS(e){return new xs(e.width,e.height)}const xS="/assets/icon-674efcbe.svg";function SS(){const[e,t]=C.useState(null);return C.useEffect(()=>{const n=ho.listen("app://update-progress",r=>{t(r.payload)});return()=>{n.then(r=>r())}},[]),e}function kS(){const[e,t]=C.useState(!1);C.useEffect(()=>{const r=ho.listen("app://update-error",()=>{t(!0)});return()=>{r.then(o=>o())}},[]);const n=()=>{t(!1),ho.emit("app://update")};return b.jsxs(b.Fragment,{children:[b.jsx(Xx,{}),b.jsx(Nt,{sx:{position:"absolute",inset:0},display:"flex",alignItems:"center",px:2,"data-tauri-drag-region":!0,children:b.jsxs(Nt,{display:"flex",alignItems:"center",flex:"1","data-tauri-drag-region":!0,children:[b.jsx(Nt,{component:"img",src:xS,alt:"logo",sx:{width:"4rem",height:"4rem"},"data-tauri-drag-region":!0}),b.jsx(Nt,{flex:1,ml:2,children:e?b.jsx(CS,{onRetry:n}):b.jsx(_S,{})})]})})]})}function _S(){const e=SS();return b.jsxs(b.Fragment,{children:[b.jsx(Au,{variant:"h1",fontSize:"1rem","data-tauri-drag-region":!0,children:"Updating the GUI components..."}),b.jsx(Nt,{mt:1,children:b.jsx(ES,{value:e})})]})}function CS({onRetry:e}){return b.jsxs(b.Fragment,{children:[b.jsx(Au,{variant:"h1",fontSize:"1rem","data-tauri-drag-region":!0,children:"Failed to update the GUI components."}),b.jsx(Nt,{mt:1,"data-tauri-drag-region":!0,children:b.jsx(Kx,{variant:"contained",color:"primary",size:"small",onClick:e,sx:{textTransform:"none"},children:"Retry"})})]})}function ES(e){const{value:t}=e;return b.jsxs(Nt,{sx:{display:"flex",alignItems:"center"},children:[b.jsx(Nt,{flex:"1",children:b.jsx(sS,{variant:t===null?"indeterminate":"determinate",value:t??0,sx:{py:1.2,".MuiLinearProgress-bar":{transition:"none"}}})}),t!==null&&b.jsx(Nt,{sx:{minWidth:35,textAlign:"right",ml:1},children:b.jsx(Au,{variant:"body2",color:"text.secondary",children:`${Math.round(t)}%`})})]})}const PS=qp(document.getElementById("root"));PS.render(b.jsx(kS,{}));
+4 -3
View File
@@ -4,9 +4,9 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GP Connect Helper</title>
<script type="module" crossorigin src="/assets/main-CyyZK63u.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-C5muOSVO.css">
<title>GlobalProtect</title>
<script type="module" crossorigin src="/assets/main-c159dd55.js"></script>
<link rel="stylesheet" href="/assets/index-11e7064a.css">
</head>
<body>
<script>
@@ -16,5 +16,6 @@
document.documentElement.style.fontSize = 16 / ratio + "px";
</script>
<div id="root" data-tauri-drag-region></div>
</body>
</html>
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GP Connect Helper</title>
<title>GlobalProtect</title>
</head>
<body>
<script>
+22 -22
View File
@@ -9,29 +9,29 @@
"tauri": "tauri"
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.11",
"@mui/material": "^7.3.11",
"@tauri-apps/api": "^2.11.1",
"react": "^19.2.7",
"react-dom": "^19.2.7"
"@emotion/react": "^11.13.0",
"@emotion/styled": "^11.13.0",
"@mui/icons-material": "^5.16.7",
"@mui/material": "^5.16.7",
"@tauri-apps/api": "^1.6.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@tauri-apps/cli": "^2.11.2",
"@types/node": "^25.9.4",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@typescript-eslint/eslint-plugin": "^8.61.1",
"@typescript-eslint/parser": "^8.61.1",
"@vitejs/plugin-react": "^6.0.2",
"eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "3.8.3",
"typescript": "^6.0.3",
"vite": "^8.0.16"
"@tauri-apps/cli": "^1.6.0",
"@types/node": "^20.14.15",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-react": "^7.35.0",
"eslint-plugin-react-hooks": "^4.6.2",
"prettier": "3.1.0",
"typescript": "^5.5.4",
"vite": "^4.5.3"
},
"packageManager": "pnpm@9.15.1"
"packageManager": "pnpm@8.15.7"
}
+2419 -3203
View File
File diff suppressed because it is too large. Load diff
+4 -6
View File
@@ -1,18 +1,16 @@
[package]
name = "gpgui-helper"
rust-version.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
license.workspace = true
[build-dependencies]
tauri-build = { version = "2", features = [] }
tauri-build = { version = "1.5", features = [] }
[dependencies]
gpapi = { path = "../../../crates/gpapi", features = ["tauri", "clap"] }
tauri.workspace = true
gpapi = { path = "../../../crates/gpapi", features = ["tauri"] }
tauri = { workspace = true, features = ["window-start-dragging"] }
tokio.workspace = true
anyhow.workspace = true
log.workspace = true
@@ -24,4 +22,4 @@ tempfile.workspace = true
reqwest = { workspace = true, features = ["stream"] }
[features]
default = ["tauri/custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
-59
View File
@@ -1,62 +1,3 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPGUI_HELPER_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPGUI_HELPER_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPGUI_HELPER_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
@@ -1,12 +0,0 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:window:allow-start-dragging",
"core:event:allow-listen",
"core:event:allow-emit",
"core:event:allow-unlisten"
]
}
+8 -10
View File
@@ -1,7 +1,8 @@
use std::sync::Arc;
use gpapi::utils::window::WindowExt;
use log::info;
use tauri::{Listener, Manager};
use tauri::Manager;
use crate::updater::{GuiUpdater, Installer, ProgressNotifier};
@@ -24,15 +25,15 @@ impl App {
tauri::Builder::default()
.setup(move |app| {
let win = app.get_webview_window("main").expect("no main window");
let _ = win.hide_menu();
let win = app.get_window("main").expect("no main window");
win.hide_menu();
let notifier = ProgressNotifier::new(win.clone());
let installer = Installer::new(api_key);
let updater = Arc::new(GuiUpdater::new(gui_version, notifier, installer));
let win_clone = win.clone();
app.listen_any("app://update-done", move |_event| {
app.listen_global("app://update-done", move |_event| {
info!("Update done");
let _ = win_clone.close();
});
@@ -40,15 +41,12 @@ impl App {
// Listen for the update event
win.listen("app://update", move |_event| {
let updater = Arc::clone(&updater);
if updater.is_in_progress() {
info!("Update already in progress");
updater.notify_progress();
return;
}
tokio::spawn(async move { updater.update().await });
});
// Update the GUI on startup
win.trigger("app://update", None);
Ok(())
})
.run(tauri::generate_context!())?;
+6 -23
View File
@@ -1,20 +1,10 @@
use clap::Parser;
use gpapi::{
clap::InfoLevelVerbosity,
utils::{base64, env_utils},
};
use log::info;
use gpapi::utils::base64;
use log::{info, LevelFilter};
use crate::app::App;
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPGUI_HELPER_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const GP_API_KEY: &[u8; 32] = &[0; 32];
#[derive(Parser)]
@@ -25,9 +15,6 @@ struct Cli {
#[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")]
gui_version: String,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Cli {
@@ -35,8 +22,6 @@ impl Cli {
let api_key = self.read_api_key()?;
let app = App::new(api_key, &self.gui_version);
env_utils::patch_gui_runtime_env(false);
app.run()
}
@@ -54,16 +39,14 @@ impl Cli {
}
}
fn init_logger(cli: &Cli) {
env_logger::builder()
.filter_level(cli.verbose.log_level_filter())
.init();
fn init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
}
pub fn run() {
let cli = Cli::parse();
init_logger(&cli);
init_logger();
info!("gpgui-helper started: {}", VERSION);
if let Err(e) = cli.run() {
+20 -81
View File
@@ -1,45 +1,39 @@
use std::sync::{Arc, RwLock};
use std::sync::Arc;
use gpapi::{
service::request::UpdateGuiRequest,
utils::{checksum::verify_checksum, crypto::Crypto, endpoint::http_endpoint},
};
use log::{info, warn};
use tauri::{Emitter, WebviewWindow};
use tauri::{Manager, Window};
use crate::downloader::{ChecksumFetcher, FileDownloader};
#[cfg(not(debug_assertions))]
const SNAPSHOT: &str = match option_env!("SNAPSHOT") {
Some(val) => val,
None => "false",
Some(val) => val,
None => "false"
};
#[cfg(target_env = "musl")]
const GUI_LIBC_SUFFIX: &str = "-musl";
#[cfg(not(target_env = "musl"))]
const GUI_LIBC_SUFFIX: &str = "";
pub struct ProgressNotifier {
win: WebviewWindow,
win: Window,
}
impl ProgressNotifier {
pub fn new(win: WebviewWindow) -> Self {
pub fn new(win: Window) -> Self {
Self { win }
}
fn notify(&self, progress: Option<f64>) {
let _ = self.win.emit("app://update-progress", progress);
let _ = self.win.emit_all("app://update-progress", progress);
}
fn notify_error(&self) {
let _ = self.win.emit("app://update-error", ());
let _ = self.win.emit_all("app://update-error", ());
}
fn notify_done(&self) {
let _ = self.win.emit("app://update-done", ());
let _ = self.win.emit_and_trigger("app://update-done", ());
}
}
@@ -78,8 +72,6 @@ pub struct GuiUpdater {
version: String,
notifier: Arc<ProgressNotifier>,
installer: Installer,
in_progress: RwLock<bool>,
progress: Arc<RwLock<Option<f64>>>,
}
impl GuiUpdater {
@@ -88,16 +80,10 @@ impl GuiUpdater {
version,
notifier: Arc::new(notifier),
installer,
in_progress: Default::default(),
progress: Default::default(),
}
}
pub async fn update(&self) {
if !cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
info!("GUI version is not supported on this architecture.");
return;
}
info!("Update GUI, version: {}", self.version);
#[cfg(debug_assertions)]
@@ -109,15 +95,14 @@ impl GuiUpdater {
format!("v{}", self.version)
};
let arch = if cfg!(target_arch = "x86_64") {
"x86_64"
} else {
"aarch64"
};
#[cfg(target_arch = "x86_64")]
let arch = "x86_64";
#[cfg(target_arch = "aarch64")]
let arch = "aarch64";
let file_url = format!(
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}{}.bin.tar.xz",
release_tag, arch, GUI_LIBC_SUFFIX
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz",
release_tag, arch
);
let checksum_url = format!("{}.sha256", file_url);
@@ -127,23 +112,15 @@ impl GuiUpdater {
let cf = ChecksumFetcher::new(&checksum_url);
let notifier = Arc::clone(&self.notifier);
let progress_ref = Arc::clone(&self.progress);
dl.on_progress(move |progress| {
// Save progress to shared state so that it can be notified to the UI when needed
if let Ok(mut guard) = progress_ref.try_write() {
*guard = progress;
}
notifier.notify(progress);
});
dl.on_progress(move |progress| notifier.notify(progress));
self.set_in_progress(true);
let res = tokio::try_join!(dl.download(), cf.fetch());
let (file, checksum) = match res {
Ok((file, checksum)) => (file, checksum),
Err(err) => {
warn!("Download error: {}", err);
self.notify_error();
self.notifier.notify_error();
return;
}
};
@@ -153,7 +130,7 @@ impl GuiUpdater {
if let Err(err) = verify_checksum(&file_path, &checksum) {
warn!("Checksum error: {}", err);
self.notify_error();
self.notifier.notify_error();
return;
}
@@ -161,48 +138,10 @@ impl GuiUpdater {
if let Err(err) = self.installer.install(&file_path, &checksum).await {
warn!("Install error: {}", err);
self.notify_error();
self.notifier.notify_error();
} else {
info!("Install success");
self.notify_done();
self.notifier.notify_done();
}
}
pub fn is_in_progress(&self) -> bool {
if let Ok(guard) = self.in_progress.try_read() {
*guard
} else {
info!("Failed to acquire in_progress lock");
false
}
}
fn set_in_progress(&self, in_progress: bool) {
if let Ok(mut guard) = self.in_progress.try_write() {
*guard = in_progress;
} else {
info!("Failed to acquire in_progress lock");
}
}
fn notify_error(&self) {
self.set_in_progress(false);
self.notifier.notify_error();
}
fn notify_done(&self) {
self.set_in_progress(false);
self.notifier.notify_done();
}
pub fn notify_progress(&self) {
let progress = if let Ok(guard) = self.progress.try_read() {
*guard
} else {
info!("Failed to acquire progress lock");
None
};
self.notifier.notify(progress);
}
}
+28 -19
View File
@@ -1,21 +1,41 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"$schema": "../node_modules/@tauri-apps/cli/schema.json",
"build": {
"beforeDevCommand": "pnpm dev",
"beforeBuildCommand": "pnpm build",
"devUrl": "http://localhost:1421",
"frontendDist": "../dist"
"devPath": "http://localhost:1421",
"distDir": "../dist",
"withGlobalTauri": false
},
"identifier": "com.yuezk.gpgui-helper",
"productName": "gpgui-helper",
"app": {
"withGlobalTauri": false,
"package": {
"productName": "gpgui-helper"
},
"tauri": {
"allowlist": {
"all": false,
"window": {
"all": false,
"startDragging": true
}
},
"bundle": {
"active": false,
"targets": "deb",
"identifier": "com.yuezk.gpgui-helper",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
]
},
"security": {
"csp": null
},
"windows": [
{
"title": "GP Connect Helper",
"title": "GlobalProtect GUI Helper",
"center": true,
"resizable": true,
"width": 500,
@@ -28,16 +48,5 @@
"decorations": false
}
]
},
"bundle": {
"active": false,
"targets": "deb",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
]
}
}
+1 -5
View File
@@ -1,12 +1,10 @@
import { Box, Button, CssBaseline, LinearProgress, Typography } from "@mui/material";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { appWindow } from "@tauri-apps/api/window";
import logo from "../../assets/icon.svg";
import { useEffect, useState } from "react";
import "./styles.css";
const appWindow = getCurrentWindow();
function useUpdateProgress() {
const [progress, setProgress] = useState<number | null>(null);
@@ -27,8 +25,6 @@ export default function App() {
const [error, setError] = useState(false);
useEffect(() => {
appWindow.emit("app://update");
const unlisten = appWindow.listen("app://update-error", () => {
setError(true);
});
+1 -1
View File
@@ -20,7 +20,7 @@ export default defineConfig(async () => {
// https://tauri.app/v1/api/config#buildconfig.beforedevcommand
envPrefix: ["VITE_", "TAURI_"],
build: {
rolldownOptions: {
rollupOptions: {
input: {
main: resolve(__dirname, "index.html"),
},
+1 -2
View File
@@ -5,8 +5,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
gpapi = { path = "../../crates/gpapi" }
openconnect = { path = "../../crates/openconnect" }
clap.workspace = true
anyhow.workspace = true
-60
View File
@@ -1,60 +0,0 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPSERVICE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPSERVICE_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPSERVICE_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+35 -51
View File
@@ -3,27 +3,18 @@ use std::{collections::HashMap, io::Write};
use anyhow::bail;
use clap::Parser;
use common::constants::GP_SERVICE_LOCK_FILE;
use gpapi::clap::InfoLevelVerbosity;
use gpapi::logger;
use gpapi::{
process::gui_launcher::GuiLauncher,
service::{request::WsRequest, vpn_state::VpnState},
utils::{crypto::generate_key, env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
utils::{crypto::generate_key, env_file, lock_file::LockFile, redact::Redaction, shutdown_signal},
GP_SERVICE_LOCK_FILE,
};
use log::{info, warn};
use log::{info, warn, LevelFilter};
use tokio::sync::{mpsc, watch};
use crate::{vpn_task::VpnTask, ws_server::WsServer};
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
#[derive(Parser)]
#[command(version = VERSION)]
@@ -35,16 +26,10 @@ struct Cli {
#[cfg(debug_assertions)]
#[clap(long)]
no_gui: bool,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Cli {
async fn run(&mut self) -> anyhow::Result<()> {
let redaction = self.init_logger();
info!("gpservice started: {}", VERSION);
async fn run(&mut self, redaction: Arc<Redaction>) -> anyhow::Result<()> {
let pid = std::process::id();
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
@@ -87,7 +72,7 @@ impl Cli {
if no_gui {
info!("GUI is disabled");
} else {
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
let envs = self.env_file.as_ref().map(env_file::load_env_vars).transpose()?;
let minimized = self.minimized;
@@ -116,33 +101,6 @@ impl Cli {
Ok(())
}
fn init_logger(&self) -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let redaction_clone = Arc::clone(&redaction);
let inner_logger = env_logger::builder()
// Set the log level to the Trace level, the logs will be filtered
.filter_level(log::LevelFilter::Trace)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {:<5} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
.build();
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
logger::init_with_logger(level, inner_logger);
redaction
}
fn prepare_api_key(&self) -> Vec<u8> {
#[cfg(debug_assertions)]
if self.no_gui {
@@ -153,6 +111,29 @@ impl Cli {
}
}
fn init_logger() -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let redaction_clone = Arc::clone(&redaction);
// let target = Box::new(File::create("log.txt").expect("Can't create file"));
env_logger::builder()
.filter_level(LevelFilter::Info)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
// .target(env_logger::Target::Pipe(target))
.init();
redaction
}
#[cfg(unix)]
mod signals {
use std::sync::Arc;
@@ -164,9 +145,9 @@ mod signals {
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
pub(crate) async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent;
use tokio::signal::unix::{Signal, SignalKind, signal};
use tokio::signal::unix::{signal, Signal, SignalKind};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?;
@@ -229,7 +210,10 @@ async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut
pub async fn run() {
let mut cli = Cli::parse();
if let Err(e) = cli.run().await {
let redaction = init_logger();
info!("gpservice started: {}", VERSION);
if let Err(e) = cli.run(redaction).await {
eprintln!("Error: {}", e);
std::process::exit(1);
}
+9 -4
View File
@@ -1,4 +1,5 @@
use std::{
borrow::Cow,
fs::{File, Permissions},
io::BufReader,
ops::ControlFlow,
@@ -11,17 +12,17 @@ use anyhow::bail;
use axum::{
body::Bytes,
extract::{
ws::{self, CloseFrame, Message, WebSocket},
State, WebSocketUpgrade,
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
},
http::StatusCode,
response::IntoResponse,
};
use common::constants::GP_GUI_BINARY;
use futures::{SinkExt, StreamExt};
use gpapi::{
service::{event::WsEvent, request::UpdateGuiRequest},
utils::checksum::verify_checksum,
GP_GUI_BINARY,
};
use log::{info, warn};
use tar::Archive;
@@ -38,7 +39,11 @@ pub(crate) async fn active_gui(State(ctx): State<Arc<WsServerContext>>) -> impl
ctx.send_event(WsEvent::ActiveGui).await;
}
pub async fn update_gui(State(ctx): State<Arc<WsServerContext>>, body: Bytes) -> Result<(), StatusCode> {
pub(crate) async fn auth_data(State(ctx): State<Arc<WsServerContext>>, body: String) -> impl IntoResponse {
ctx.send_event(WsEvent::AuthData(body)).await;
}
pub(crate) async fn update_gui(State(ctx): State<Arc<WsServerContext>>, body: Bytes) -> Result<(), StatusCode> {
let payload = match ctx.decrypt::<UpdateGuiRequest>(body.to_vec()) {
Ok(payload) => payload,
Err(err) => {
@@ -132,7 +137,7 @@ async fn handle_socket(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
let close_msg = Message::Close(Some(CloseFrame {
code: ws::close_code::NORMAL,
reason: Utf8Bytes::from("Goodbye"),
reason: Cow::from("Goodbye"),
}));
if let Err(err) = sender.send(close_msg).await {
+2 -1
View File
@@ -1,8 +1,8 @@
use std::sync::Arc;
use axum::{
Router,
routing::{get, post},
Router,
};
use crate::{handlers, ws_server::WsServerContext};
@@ -11,6 +11,7 @@ pub(crate) fn routes(ctx: Arc<WsServerContext>) -> Router {
Router::new()
.route("/health", get(handlers::health))
.route("/active-gui", post(handlers::active_gui))
.route("/auth-data", post(handlers::auth_data))
.route("/update-gui", post(handlers::update_gui))
.route("/ws", get(handlers::ws_handler))
.with_state(ctx)
+8 -75
View File
@@ -1,16 +1,12 @@
use std::{sync::Arc, thread};
use gpapi::{
logger,
service::{
request::{ConnectRequest, UpdateLogLevelRequest, WsRequest},
vpn_state::{ConnectedInfo, VpnState},
},
session::{SessionInfo, SessionWarning},
use gpapi::service::{
request::{ConnectRequest, WsRequest},
vpn_state::VpnState,
};
use log::{info, warn};
use openconnect::Vpn;
use tokio::sync::{RwLock, mpsc, oneshot, watch};
use tokio::sync::{mpsc, oneshot, watch, RwLock};
use tokio_util::sync::CancellationToken;
pub(crate) struct VpnTaskContext {
@@ -39,27 +35,19 @@ impl VpnTaskContext {
let info = req.info().clone();
let vpn_handle = Arc::clone(&self.vpn_handle);
let args = req.args();
let allow_extend_session = args.allow_extend_session();
let vpn = match Vpn::builder(req.gateway().server(), args.cookie())
.script(args.vpnc_script())
.user_agent(args.user_agent())
.os(args.openconnect_os())
.os_version(args.os_version())
.client_version(args.client_version())
.host_id(args.host_id())
.certificate(args.certificate())
.sslkey(args.sslkey())
.key_password(args.key_password())
.hip(args.hip())
.csd_uid(args.csd_uid())
.csd_wrapper(args.csd_wrapper())
.reconnect_timeout(args.reconnect_timeout())
.mtu(args.mtu())
.disable_ipv6(args.disable_ipv6())
.no_dtls(args.no_dtls())
.local_hostname(args.local_hostname())
.dpd_interval(args.force_dpd())
.no_xmlpost(args.no_xmlpost())
.build()
{
Ok(vpn) => vpn,
@@ -84,19 +72,9 @@ impl VpnTaskContext {
let vpn_state_tx_clone = vpn_state_tx.clone();
vpn_handle.blocking_read().as_ref().map(|vpn| {
vpn.connect(move |vpn_session_info| {
let session_info = SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
);
info!("VPN session info: {}", session_info.log_summary());
let connected_info = Box::new(ConnectedInfo::new(info.clone(), Some(session_info)));
vpn_state_tx.send(VpnState::Connected(connected_info)).ok();
vpn.connect(move || {
let connect_info = Box::new(info.clone());
vpn_state_tx.send(VpnState::Connected(connect_info)).ok();
})
});
@@ -125,6 +103,7 @@ impl VpnTaskContext {
} else {
info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok();
false
}
}
@@ -187,51 +166,5 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
WsRequest::Disconnect(_) => {
ctx.disconnect().await;
}
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
let level = level.parse().unwrap_or_else(|_| log::Level::Info);
info!("Updating log level to: {}", level);
if let Err(err) = logger::set_max_level(level) {
warn!("Failed to update log level: {}", err);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_openconnect_session_metadata_to_service_session_info() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.expires_in_human.as_deref(), Some("12h"));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_request_session_metadata_keeps_extension_disabled() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert!(!info.allow_extend_session);
}
}
+2 -2
View File
@@ -20,7 +20,7 @@ impl WsConnection {
pub async fn send_event(&self, event: &WsEvent) -> anyhow::Result<()> {
let encrypted = self.crypto.encrypt(event)?;
let msg = Message::Binary(encrypted.into());
let msg = Message::Binary(encrypted);
self.tx.send(msg).await?;
@@ -29,7 +29,7 @@ impl WsConnection {
pub fn recv_msg(&self, msg: Message) -> ControlFlow<(), WsRequest> {
match msg {
Message::Binary(data) => match self.crypto.decrypt(data.into()) {
Message::Binary(data) => match self.crypto.decrypt(data) {
Ok(ws_req) => ControlFlow::Continue(ws_req),
Err(err) => {
info!("Failed to decrypt message: {}", err);
+5 -24
View File
@@ -1,23 +1,15 @@
use std::sync::Arc;
use axum::extract::ws::Message;
use common::constants::GP_AUTH_BINARY;
use gpapi::{
os_profile::HostIdentity,
service::{
event::WsEvent,
request::WsRequest,
vpn_env::{HostInfo, VpnEnv},
vpn_state::VpnState,
},
service::{event::WsEvent, request::WsRequest, vpn_state::VpnState},
utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction},
};
use log::{info, warn};
use openconnect::{find_csd_wrapper, find_vpnc_script};
use serde::de::DeserializeOwned;
use tokio::{
net::TcpListener,
sync::{RwLock, mpsc, watch},
sync::{mpsc, watch, RwLock},
};
use tokio_util::sync::CancellationToken;
@@ -64,20 +56,9 @@ impl WsServerContext {
let conn = Arc::new(WsConnection::new(Arc::clone(&self.crypto), tx));
// Send current VPN state to new client
info!("Sending current environment to new client");
let host_info = HostInfo {
host_identity: HostIdentity::collect(),
};
let vpn_env = VpnEnv {
vpn_state: self.vpn_state_rx.borrow().clone(),
vpnc_script: find_vpnc_script().map(|s| s.to_owned()),
csd_wrapper: find_csd_wrapper().map(|s| s.to_owned()),
auth_executable: GP_AUTH_BINARY.to_owned(),
host_info,
};
if let Err(err) = conn.send_event(&WsEvent::VpnEnv(vpn_env)).await {
info!("Sending current VPN state to new client");
let vpn_state = self.vpn_state_rx.borrow().clone();
if let Err(err) = conn.send_event(&WsEvent::VpnState(vpn_state)).await {
warn!("Failed to send VPN state to new client: {}", err);
}
+8 -103
View File
@@ -1,115 +1,20 @@
# Changelog
## 2.6.0
## 2.3.13 - 2026-04-19
### Added
- Backport the vendored OpenConnect/libxml2 runtime from newer releases, including the updated HIP flow and bundled Linux helper scripts.
- CLI/browser authentication: support `--browser remote` for headless servers, restore the browser flag default behavior, and improve external browser auth handling.
- Support VPN portals and gateways running on custom ports (fix [#404](https://github.com/yuezk/GlobalProtect-openconnect/issues/404)).
- Improve `2.3.x` build and packaging compatibility on current Linux toolchains and Debian/Ubuntu builder environments.
- Added automatic gateway selection with fallback to the next available gateway when early gateway connection steps fail.
- Added optional cookie cache support for faster reconnects.
- Added Microsoft Defender status reporting in HIP reports.
- Added support for portals that require client-side checks before connection.
- Added FreeBSD and OpenBSD package builds and release artifacts.
- Added build provenance attestations for release assets.
## 2.3.11 - 2025-01-21
### Changed
- Update minimal Rust version to 1.71.1, so that the PPA can be built on Ubuntu 18.04.
- Improved compatibility with official GlobalProtect client request behavior.
- Improved SAML authentication behavior in the embedded webview.
- Improved default browser authentication handling.
- Improved host identity consistency across authentication, connection, and HIP flows.
- Improved GUI gateway selection behavior and made the selection list more compact.
- Updated NixOS installation instructions.
### Fixed
- Fixed a crash when opening settings on KDE/Wayland.
- Fixed browser authentication when `gpclient` is started with `sudo`.
- Fixed gateway fallback behavior when using `gpauth | gpclient --cookie-on-stdin`.
- Fixed inconsistent host ID handling between GUI, CLI, OpenConnect, and HIP.
- Fixed portal and gateway authentication cookie handling in several edge cases.
- Fixed GUI connection state issues around gateway switching and cached credentials.
## 2.5.4 - 2026-05-08
- Add Alpine/musl gpgui release assets for x86_64 and aarch64.
- Use the musl gpgui asset when the helper or package build runs on musl Linux.
## 2.5.3 - 2026-05-08
- Fix systemd-resolved DNS routing when no split-DNS domains are provided (fix [#604](https://github.com/yuezk/GlobalProtect-openconnect/issues/604)).
- Log whether systemd-resolved uses server-provided split DNS or global VPN DNS.
## 2.5.2 - 2026-05-06
- Experimental: GUI/CLI add session expiry warnings and support automatic session extension when allowed by the portal.
- GUI/CLI: expose additional OpenConnect connection options.
- Fix Linux packages to vendor the `vpnc-script`.
- Remove OpenConnect from the packaging dependency.
- Fix reconnect handling by preserving GlobalProtect cookie fields.
- Fix auth callback data parsing
- Improve NixOS packaging and user-level installation docs.
- Upgrade Rust, Tauri, Vite, frontend, and Rust dependencies.
## 2.5.1 - 2025-12-22
- Fix the `.deb` package installation issue (fix [#563](https://github.com/yuezk/GlobalProtect-openconnect/issues/563))
- GUI: fix the tray icon size issue on GNOME Flashback (fix [#564](https://github.com/yuezk/GlobalProtect-openconnect/issues/564))
- Improve the HIP report generation logic
## 2.5.0 - 2025-12-08
- GUI/CLI: statically link OpenConnect
- GUI/CLI: support configure the client version
- CLI: add the `-S/--script-tun` option to pass traffic to the `--script` handler
- GUI: update the branding to `GP Connect`
## 2.4.7 - 2025-11-12
- Support NixOS package installation
- Fix the VPNC script location on Void Linux
- Upgrade to Rust 1.85
- `--browser` without argument uses the system default browser
## 2.4.6 - 2025-10-15
- GUI: support the default configuration file for GUI client (fix [#492](https://github.com/yuezk/GlobalProtect-openconnect/issues/492))
- GUI: add the option to not reuse the authentication cookies (fix [#540](https://github.com/yuezk/GlobalProtect-openconnect/issues/540))
- GUI: improve the license validation logic (fix [#502](https://github.com/yuezk/GlobalProtect-openconnect/issues/502))
- CLI: support the `--browser remote` option to use the remote browser for authentication ([#544](https://github.com/yuezk/GlobalProtect-openconnect/pull/544) by [@dark12](https://github.com/dark12))
- CLI: fix gpclient disconnect bailing with client is already running issue ([#542](https://github.com/yuezk/GlobalProtect-openconnect/pull/542) by [@zeroepoch](https://github.com/zeroepoch))
- CLI: fix the `--passwd-on-stdin` reads again on gateway failure ([#546](https://github.com/yuezk/GlobalProtect-openconnect/issues/546))
## 2.4.5 - 2025-07-16
- GUI/CLI: fix the issue that the custom port is not supported issue (fix [#404](https://github.com/yuezk/GlobalProtect-openconnect/issues/404))
- CLI: add the `--force-dpd` option to specify the interval for DPD (Dead Peer Detection).
- CLI: add the `-i/--interface` option to specify the interface to use.
## 2.4.4 - 2025-02-09
- GUI: fix multiple tray icons issue (fix [#464](https://github.com/yuezk/GlobalProtect-openconnect/issues/464))
- CLI: check the cli running state before running the `gpclient` command (fix [#447](https://github.com/yuezk/GlobalProtect-openconnect/issues/447))
## 2.4.3 - 2025-01-21
- Do not use static default value for `--os-version` option.
## 2.4.2 - 2025-01-20
## 2.3.10 - 2025-01-20
- Disconnect the VPN when sleep (fix [#166](https://github.com/yuezk/GlobalProtect-openconnect/issues/166), [#267](https://github.com/yuezk/GlobalProtect-openconnect/issues/267))
## 2.4.1 - 2025-01-09
- Fix the network issue with OpenSSL < 3.0.4
- GUI: fix the Wayland compatibility issue
- Support configure the log level
- Log the detailed error message when network error occurs
## 2.4.0 - 2024-12-26
- Upgrade to Tauri 2.0
- Support Ubuntu 22.04 and later
## 2.3.9 - 2024-11-02
- Enhance the OpenSSL compatibility mode (fix [#437](https://github.com/yuezk/GlobalProtect-openconnect/issues/437))
-60
View File
@@ -1,60 +0,0 @@
[package]
name = "auth"
rust-version.workspace = true
version.workspace = true
authors.workspace = true
homepage.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
common = { path = "../common" }
gpapi = { path = "../gpapi" }
# Shared dependencies
anyhow.workspace = true
log.workspace = true
tokio.workspace = true
# Browser auth dependencies
webbrowser = { version = "1", optional = true }
open = { version = "5", optional = true }
which = { workspace = true, optional = true }
tiny_http = { version = "0.12", optional = true }
uuid = { version = "1", optional = true, features = ["v4"] }
# Webview auth dependencies
tauri = { workspace = true, optional = true }
regex = { workspace = true, optional = true }
tokio-util = { workspace = true, optional = true }
html-escape = { version = "0.2.13", optional = true }
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
webkit2gtk = { version = "2", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
block2 = { version = "0.6", optional = true }
objc2 = { version = "0.6", optional = true }
objc2-foundation = { version = "0.3", optional = true }
objc2-web-kit = { version = "0.3", optional = true }
[features]
browser-auth = [
"dep:webbrowser",
"dep:open",
"dep:which",
"dep:tiny_http",
"dep:uuid",
]
webview-auth = [
"gpapi/tauri",
"dep:tauri",
"dep:regex",
"dep:tokio-util",
"dep:html-escape",
"dep:webkit2gtk",
"dep:block2",
"dep:objc2",
"dep:objc2-foundation",
"dep:objc2-web-kit",
]
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
-4
View File
@@ -1,4 +0,0 @@
mod auth_server;
mod browser_auth;
pub use browser_auth::BrowserAuthenticator;
-61
View File
@@ -1,61 +0,0 @@
use std::io::Cursor;
use log::info;
use tiny_http::{Header, Method, Response, Server};
use uuid::Uuid;
pub(super) struct AuthServer {
server: Server,
auth_id: String,
}
impl AuthServer {
pub fn new(addr: &str) -> anyhow::Result<Self> {
let server = Server::http(addr).map_err(|err| anyhow::anyhow!(err))?;
let auth_id = Uuid::new_v4().to_string();
Ok(Self { server, auth_id })
}
pub fn auth_url(&self) -> String {
format!("http://{}/{}", self.server.server_addr(), self.auth_id)
}
pub fn serve_request(&self, auth_request: &str) {
info!("auth server started at: {}", self.auth_url());
for req in self.server.incoming_requests() {
info!("received request, method: {}, url: {}", req.method(), req.url());
if req.url() != format!("/{}", self.auth_id) {
let forbidden = Response::from_string("forbidden").with_status_code(403);
let _ = req.respond(forbidden);
} else if req.method() == &Method::Head {
if let Err(err) = req.respond(Response::empty(200)) {
info!("failed to respond to HEAD request: {}", err);
}
} else {
let auth_response = build_auth_response(auth_request);
if let Err(err) = req.respond(auth_response) {
info!("failed to respond to request: {}", err);
} else {
info!("stop the auth server");
break;
}
}
}
}
}
fn build_auth_response(auth_request: &str) -> Response<Cursor<Vec<u8>>> {
if auth_request.starts_with("http") {
let header = format!("location: {}", auth_request);
let header: Header = header.parse().unwrap();
Response::from_string("redirect")
.with_status_code(302)
.with_header(header)
} else {
let content_type: Header = "content-type: text/html".parse().unwrap();
Response::from_string(auth_request).with_header(content_type)
}
}
-178
View File
@@ -1,178 +0,0 @@
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
use common::constants::GP_CALLBACK_PORT_FILENAME;
use gpapi::auth::SamlAuthData;
use log::info;
use tokio::{
io::AsyncReadExt,
net::{TcpListener, UdpSocket},
};
use crate::browser::auth_server::AuthServer;
pub enum Browser<'a> {
Default,
Chrome,
Firefox,
Remote,
Other(&'a str),
}
impl<'a> Browser<'a> {
pub fn from_str(browser: &'a str) -> Self {
match browser.to_lowercase().as_str() {
"default" => Browser::Default,
"chrome" => Browser::Chrome,
"firefox" => Browser::Firefox,
"remote" => Browser::Remote,
_ => Browser::Other(browser),
}
}
fn as_str(&self) -> &str {
match self {
Browser::Default => "default",
Browser::Chrome => "chrome",
Browser::Firefox => "firefox",
Browser::Remote => "remote",
Browser::Other(browser) => browser,
}
}
}
pub struct BrowserAuthenticator<'a> {
auth_request: &'a str,
browser: Browser<'a>,
}
impl<'a> BrowserAuthenticator<'a> {
pub fn new(auth_request: &'a str, browser: &'a str) -> Self {
Self {
auth_request,
browser: Browser::from_str(browser),
}
}
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
let addr = self.determine_addr().await?;
let auth_server = AuthServer::new(&addr)?;
let auth_url = auth_server.auth_url();
let auth_request = self.auth_request.to_string();
tokio::spawn(async move {
auth_server.serve_request(&auth_request);
});
match self.browser {
Browser::Remote => {
info!(
r#"
==== Manual Authentication Required ====
Please open the following URL in your browser:
{}
After completing the authentication, please paste the authentication data back to this terminal.
(The data should start with "globalprotectcallback:...")
Note that the URL is only valid for a single use.
"#,
auth_url
);
return read_auth_data_from_stdin();
}
Browser::Default => {
info!("Launching the default browser...");
webbrowser::open(&auth_url)?;
}
_ => {
let app = find_browser_path(&self.browser);
info!("Launching browser: {}", app);
open::with_detached(auth_url, app)?;
}
}
info!("Please continue the authentication process in the default browser");
wait_auth_data().await
}
async fn determine_addr(&self) -> anyhow::Result<String> {
if matches!(self.browser, Browser::Remote) {
let local_ip = detect_local_ip().await?;
Ok(format!("{}:0", local_ip))
} else {
Ok("127.0.0.1:0".to_string())
}
}
}
/// Detect the local IP address by creating a UDP socket and connecting to an external address
async fn detect_local_ip() -> anyhow::Result<String> {
let socket = UdpSocket::bind("0.0.0.0:0").await?;
if let Err(err) = socket.connect("1.1.1.1:80").await {
anyhow::bail!("Failed to connect to external address to determine local IP: {}", err);
}
let local_addr = socket.local_addr()?;
let ip = local_addr.ip().to_string();
info!("Determined local IP address: {}", ip);
Ok(ip.to_string())
}
fn find_browser_path(browser: &Browser) -> String {
match browser {
Browser::Chrome => {
const CHROME_VARIANTS: &[&str] = &["google-chrome-stable", "google-chrome", "chromium"];
CHROME_VARIANTS
.iter()
.find_map(|&browser_name| which::which(browser_name).ok())
.map(|path| path.to_string_lossy().to_string())
.unwrap_or_else(|| browser.as_str().to_string())
}
_ => browser.as_str().to_string(),
}
}
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
// Start a local server to receive the browser authentication data
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME);
// Write the port to a file
fs::write(&port_file, port.to_string())?;
fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?;
// Remove the previous log file
let callback_log = temp_dir().join("gpcallback.log");
let _ = fs::remove_file(&callback_log);
info!("Listening authentication data on port {}", port);
info!(
"If it hangs, please check the logs at `{}` for more information",
callback_log.display()
);
let (mut socket, _) = listener.accept().await?;
info!("Received the browser authentication data from the socket");
let mut data = String::new();
socket.read_to_string(&mut data).await?;
// Remove the port file
fs::remove_file(&port_file)?;
let auth_data = SamlAuthData::from_gpcallback(&data)?;
Ok(auth_data)
}
fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
let mut data = String::new();
std::io::stdin().read_line(&mut data)?;
let auth_data = SamlAuthData::from_gpcallback(data.trim())?;
Ok(auth_data)
}
-30
View File
@@ -1,30 +0,0 @@
use anyhow::bail;
use gpapi::{
gp_params::GpParams,
portal::{Prelogin, PreloginOptions, prelogin},
};
#[cfg(feature = "browser-auth")]
mod browser;
#[cfg(feature = "browser-auth")]
pub use browser::*;
#[cfg(feature = "webview-auth")]
mod webview;
#[cfg(feature = "webview-auth")]
pub use webview::*;
pub async fn auth_prelogin(
server: &str,
gp_params: &GpParams,
external_browser_requested: bool,
) -> anyhow::Result<String> {
// gpauth only performs the initial portal/gateway prelogin. Portal policy is
// not available here, so gateway prelogin stays on the embedded value.
let options = PreloginOptions::default().external_browser_requested(external_browser_requested);
match prelogin(server, gp_params, options).await? {
Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
}
}
-20
View File
@@ -1,20 +0,0 @@
mod auth_messenger;
mod webview_auth;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[path = "webview/gtk.rs"]
mod platform_impl;
#[cfg(target_os = "macos")]
#[path = "webview/macos.rs"]
mod platform_impl;
#[cfg(not(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
)))]
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
pub use webview_auth::WebviewAuthenticator;
-229
View File
@@ -1,229 +0,0 @@
use anyhow::bail;
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
use log::{error, info};
use regex::Regex;
use tokio::sync::{RwLock, mpsc};
use tokio_util::sync::CancellationToken;
#[derive(Debug)]
pub(crate) enum AuthDataLocation {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
Headers,
Body,
}
#[derive(Debug)]
pub(crate) enum AuthError {
/// Failed to load page due to TLS error
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
TlsError,
/// 1. Found auth data in headers/body but it's invalid
/// 2. Loaded an empty page, failed to load page. etc.
Invalid(anyhow::Error, AuthDataLocation),
/// No auth data found in headers/body
NotFound(AuthDataLocation),
}
impl AuthError {
pub fn invalid_from_body(err: anyhow::Error) -> Self {
Self::Invalid(err, AuthDataLocation::Body)
}
pub fn not_found_in_body() -> Self {
Self::NotFound(AuthDataLocation::Body)
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
impl AuthError {
pub fn not_found_in_headers() -> Self {
Self::NotFound(AuthDataLocation::Headers)
}
}
pub(crate) enum AuthEvent {
Data(SamlAuthData, AuthDataLocation),
Error(AuthError),
RaiseWindow,
Close,
}
pub struct AuthMessenger {
tx: mpsc::UnboundedSender<AuthEvent>,
rx: RwLock<mpsc::UnboundedReceiver<AuthEvent>>,
raise_window_cancel_token: RwLock<Option<CancellationToken>>,
}
impl AuthMessenger {
pub fn new() -> Self {
let (tx, rx) = mpsc::unbounded_channel();
Self {
tx,
rx: RwLock::new(rx),
raise_window_cancel_token: Default::default(),
}
}
pub async fn subscribe(&self) -> anyhow::Result<AuthEvent> {
let mut rx = self.rx.write().await;
if let Some(event) = rx.recv().await {
return Ok(event);
}
bail!("Failed to receive auth event");
}
pub fn send_auth_event(&self, event: AuthEvent) {
if let Err(event) = self.tx.send(event) {
error!("Failed to send auth event: {}", event);
}
}
pub fn send_auth_error(&self, err: AuthError) {
self.send_auth_event(AuthEvent::Error(err));
}
fn send_auth_data(&self, data: SamlAuthData, location: AuthDataLocation) {
self.send_auth_event(AuthEvent::Data(data, location));
}
pub fn schedule_raise_window(&self, delay: u64) {
let Ok(mut guard) = self.raise_window_cancel_token.try_write() else {
return;
};
// Return if the previous raise window task is still running
if let Some(token) = guard.as_ref() {
if !token.is_cancelled() {
info!("Raise window task is still running, skipping...");
return;
}
}
let cancel_token = CancellationToken::new();
let cancel_token_clone = cancel_token.clone();
*guard = Some(cancel_token_clone);
let tx = self.tx.clone();
tokio::spawn(async move {
info!("Displaying the window in {} second(s)...", delay);
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_secs(delay)) => {
cancel_token.cancel();
if let Err(err) = tx.send(AuthEvent::RaiseWindow) {
error!("Failed to send raise window event: {}", err);
}
}
_ = cancel_token.cancelled() => {
info!("Cancelled raise window task");
}
}
});
}
pub fn cancel_raise_window(&self) {
if let Ok(mut cancel_token) = self.raise_window_cancel_token.try_write() {
if let Some(token) = cancel_token.take() {
token.cancel();
}
}
}
pub fn read_from_html(&self, html: &str) {
if html.contains("Temporarily Unavailable") {
return self.send_auth_error(AuthError::invalid_from_body(anyhow::anyhow!("Temporarily Unavailable")));
}
let auth_result = SamlAuthData::from_html(html).or_else(|err| {
info!("Read auth data from html failed: {}, extracting gpcallback...", err);
if let Some(gpcallback) = extract_gpcallback(html) {
info!("Found gpcallback from html...");
SamlAuthData::from_gpcallback(&gpcallback)
} else {
Err(err)
}
});
match auth_result {
Ok(data) => self.send_auth_data(data, AuthDataLocation::Body),
Err(AuthDataParseError::Invalid(err)) => self.send_auth_error(AuthError::invalid_from_body(err)),
Err(AuthDataParseError::NotFound) => self.send_auth_error(AuthError::not_found_in_body()),
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) {
use log::warn;
let Some(status) = auth_response.get_header("saml-auth-status") else {
return self.send_auth_error(AuthError::not_found_in_headers());
};
// Do not send auth error when reading from headers, as the html body may contain the auth data
if status != "1" {
warn!("Found invalid saml-auth-status in headers: {}", status);
return;
}
let username = auth_response.get_header("saml-username");
let prelogin_cookie = auth_response.get_header("prelogin-cookie");
let portal_userauthcookie = auth_response.get_header("portal-userauthcookie");
match SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie) {
Ok(auth_data) => self.send_auth_data(auth_data, AuthDataLocation::Headers),
Err(err) => {
warn!("Failed to read auth data from headers: {}", err);
}
}
}
}
fn extract_gpcallback(html: &str) -> Option<String> {
let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap();
re.captures(html)
.and_then(|captures| captures.get(0))
.map(|m| html_escape::decode_html_entities(m.as_str()).to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extract_gpcallback_some() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:PGh0bWw+PCEtLSA8c")
);
}
#[test]
fn extract_gpcallback_cas() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:cas-as=1&amp;[email protected]&amp;token=very_long_string">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:cas-as=1&[email protected]&token=very_long_string")
);
}
#[test]
fn extract_gpcallback_none() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(extract_gpcallback(html), None);
}
}
-125
View File
@@ -1,125 +0,0 @@
use std::sync::Arc;
use anyhow::bail;
use gpapi::utils::redact::redact_uri;
use log::warn;
use tauri::webview::PlatformWebview;
use webkit2gtk::{
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
WebsiteDataManagerExt, gio::Cancellable, glib::GString,
};
use super::{
auth_messenger::AuthError,
webview_auth::{GetHeader, PlatformWebviewExt},
};
impl GetHeader for WebResource {
fn get_header(&self, key: &str) -> Option<String> {
self
.response()
.and_then(|response| response.http_headers())
.and_then(|headers| headers.one(key))
.map(GString::into)
}
}
impl PlatformWebviewExt for PlatformWebview {
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
if let Some(manager) = self.inner().website_data_manager() {
manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore);
return Ok(());
}
bail!("Failed to get website data manager");
}
fn user_agent(&self) -> anyhow::Result<String> {
let Some(settings) = self.inner().settings() else {
bail!("Failed to get webview settings");
};
settings
.user_agent()
.map(GString::into)
.ok_or_else(|| anyhow::anyhow!("Failed to get webview user agent"))
}
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
let Some(settings) = self.inner().settings() else {
bail!("Failed to get webview settings");
};
settings.set_user_agent(Some(user_agent));
Ok(())
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
self.inner().load_uri(url);
Ok(())
}
fn load_html(&self, html: &str) -> anyhow::Result<()> {
self.inner().load_html(html, None);
Ok(())
}
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
let script = "document.documentElement.outerHTML";
self
.inner()
.evaluate_javascript(script, None, None, Cancellable::NONE, move |result| match result {
Ok(value) => callback(Ok(value.to_string())),
Err(err) => callback(Err(anyhow::anyhow!(err))),
});
}
}
pub trait PlatformWebviewOnResponse {
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>);
}
impl PlatformWebviewOnResponse for PlatformWebview {
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>) {
let wv = self.inner();
let callback = Arc::new(callback);
let callback_clone = Arc::clone(&callback);
wv.connect_load_changed(move |wv, event| {
if event != LoadEvent::Finished {
return;
}
let Some(web_resource) = wv.main_resource() else {
return;
};
let uri = web_resource.uri().unwrap_or("".into());
if uri.is_empty() {
callback_clone(Err(AuthError::invalid_from_body(anyhow::anyhow!("Empty URI"))));
} else {
callback_clone(Ok(web_resource));
}
});
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
let redacted_uri = redact_uri(uri);
warn!(
"Failed to load uri: {} with error: {}, cert: {}",
redacted_uri, err, cert
);
callback(Err(AuthError::TlsError));
true
});
wv.connect_load_failed(move |_wv, _event, uri, err| {
let redacted_uri = redact_uri(uri);
if !uri.starts_with("globalprotectcallback:") {
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
}
// NOTE: Don't send error here, since load_changed event will be triggered after this
// true to stop other handlers from being invoked for the event. false to propagate the event further.
true
});
}
}
-82
View File
@@ -1,82 +0,0 @@
use anyhow::bail;
use block2::RcBlock;
use log::warn;
use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSObject, NSObjectNSKeyValueCoding, NSString, NSURL, NSURLRequest};
use objc2_web_kit::WKWebView;
use tauri::webview::PlatformWebview;
use super::webview_auth::PlatformWebviewExt;
impl PlatformWebviewExt for PlatformWebview {
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
warn!("Ignoring TLS errors is not supported on macOS");
Ok(())
}
fn user_agent(&self) -> anyhow::Result<String> {
unsafe {
let wv: &NSObject = &*self.inner().cast();
let Some(value) = wv.valueForKey(&NSString::from_str("userAgent")) else {
bail!("Failed to get webview user agent");
};
let Some(user_agent) = value.downcast_ref::<NSString>() else {
bail!("Webview user agent is not a string");
};
Ok(user_agent.to_string())
}
}
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
wv.setCustomUserAgent(Some(&NSString::from_str(user_agent)));
}
Ok(())
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
let url = NSURL::URLWithString(&NSString::from_str(url)).ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
let request = NSURLRequest::requestWithURL(&url);
wv.loadRequest(&request);
}
Ok(())
}
fn load_html(&self, html: &str) -> anyhow::Result<()> {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
}
Ok(())
}
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
let js_callback = RcBlock::new(move |body: *mut AnyObject, err: *mut NSError| {
if let Some(err) = err.as_ref() {
let code = err.code();
let message = err.localizedDescription();
callback(Err(anyhow::anyhow!("Error {}: {}", code, message)));
} else {
let body: &NSString = &*body.cast();
callback(Ok(body.to_string()));
}
});
wv.evaluateJavaScript_completionHandler(
&NSString::from_str("document.documentElement.outerHTML"),
Some(&js_callback),
);
}
}
}
-472
View File
@@ -1,472 +0,0 @@
use std::{sync::Arc, time::Duration};
use anyhow::bail;
use gpapi::{
auth::SamlAuthData,
gp_params::GpParams,
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
utils::redact::redact_uri,
};
use log::{info, warn};
use tauri::{
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
webview::{PageLoadEvent, PageLoadPayload},
};
use tokio::{sync::oneshot, time};
use crate::auth_prelogin;
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
pub trait PlatformWebviewExt {
fn ignore_tls_errors(&self) -> anyhow::Result<()>;
fn user_agent(&self) -> anyhow::Result<String>;
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()>;
fn load_url(&self, url: &str) -> anyhow::Result<()>;
fn load_html(&self, html: &str) -> anyhow::Result<()>;
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>);
fn load_auth_request(&self, auth_request: &str) -> anyhow::Result<()> {
if auth_request.starts_with("http") {
info!("Loading auth request as URL: {}", redact_uri(auth_request));
self.load_url(auth_request)
} else {
info!("Loading auth request as HTML...");
self.load_html(auth_request)
}
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub trait GetHeader {
fn get_header(&self, key: &str) -> Option<String>;
}
pub struct WebviewAuthenticator<'a> {
server: &'a str,
gp_params: &'a GpParams,
auth_request: Option<&'a str>,
webview_user_agent: Option<WebviewUserAgent>,
clean: bool,
is_retrying: tokio::sync::RwLock<bool>,
}
impl<'a> WebviewAuthenticator<'a> {
pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self {
Self {
server,
gp_params,
auth_request: None,
webview_user_agent: None,
clean: false,
is_retrying: Default::default(),
}
}
pub fn with_auth_request(mut self, auth_request: &'a str) -> Self {
self.auth_request = Some(auth_request);
self
}
pub fn with_webview_user_agent(mut self, user_agent: WebviewUserAgent) -> Self {
self.webview_user_agent = Some(user_agent);
self
}
pub fn with_clean(mut self, clean: bool) -> Self {
self.clean = clean;
self
}
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_messenger = Arc::new(AuthMessenger::new());
let auth_messenger_clone = Arc::clone(&auth_messenger);
let on_page_load = move |auth_window: WebviewWindow, event: PageLoadPayload<'_>| {
let auth_messenger_clone = Arc::clone(&auth_messenger_clone);
let redacted_url = redact_uri(event.url().as_str());
match event.event() {
PageLoadEvent::Started => {
info!("Started loading page: {}", redacted_url);
auth_messenger_clone.cancel_raise_window();
}
PageLoadEvent::Finished => {
info!("Finished loading page: {}", redacted_url);
}
}
// Read auth data from the page no matter whether it's finished loading or not
// Because we found that the finished event may not be triggered in some cases (e.g., on macOS)
let _ = auth_window.with_webview(move |wv| {
wv.get_html(Box::new(move |html| match html {
Ok(html) => auth_messenger_clone.read_from_html(&html),
Err(err) => warn!("Failed to get html: {}", err),
}));
});
};
let title_bar_height = if cfg!(target_os = "macos") { 28.0 } else { 0.0 };
let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
.on_page_load(on_page_load)
.title("GlobalProtect Login")
.inner_size(900.0, 650.0 + title_bar_height)
.focused(true)
// when clean is true, the window is expected to be shown because the cookies are cleared
.visible(self.clean)
.center()
.build()?;
self
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
.await?;
loop {
match auth_messenger.subscribe().await? {
AuthEvent::Close => bail!("Authentication cancelled"),
AuthEvent::RaiseWindow => self.raise_window(&auth_window),
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError),
AuthEvent::Error(AuthError::NotFound(location)) => {
info!(
"No auth data found in {:?}, it may not be the /SAML20/SP/ACS endpoint",
location
);
self.handle_not_found(&auth_window, &auth_messenger);
}
AuthEvent::Error(AuthError::Invalid(err, location)) => {
warn!("Got invalid auth data in {:?}: {}", location, err);
self.retry_auth(&auth_window).await;
}
AuthEvent::Data(auth_data, location) => {
info!("Got auth data from {:?}", location);
auth_window.close()?;
return Ok(auth_data);
}
}
}
}
async fn setup_auth_window(
&self,
auth_window: &WebviewWindow,
auth_messenger: Arc<AuthMessenger>,
) -> anyhow::Result<()> {
info!("Setting up auth window...");
if self.clean {
info!("Clearing all browsing data...");
auth_window.clear_all_browsing_data()?;
}
// Handle window close event
let auth_messenger_clone = Arc::clone(&auth_messenger);
auth_window.on_window_event(move |event| {
if let WindowEvent::CloseRequested { .. } = event {
auth_messenger_clone.send_auth_event(AuthEvent::Close);
}
});
// Show the window after 10 seconds, so that the user can see the window if the auth process is stuck
let auth_messenger_clone = Arc::clone(&auth_messenger);
tokio::spawn(async move {
time::sleep(Duration::from_secs(10)).await;
auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow);
});
let auth_request = match self.auth_request {
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&self.server, &self.gp_params, false).await?,
};
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let ignore_tls_errors = self.gp_params.ignore_tls_errors();
let webview_user_agent = self.webview_user_agent.clone();
// Set up webview
auth_window.with_webview(move |wv| {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
{
use super::platform_impl::PlatformWebviewOnResponse;
wv.on_response(Box::new(move |response| match response {
Ok(response) => auth_messenger.read_from_response(&response),
Err(err) => auth_messenger.send_auth_error(err),
}));
}
let result = || -> anyhow::Result<()> {
if ignore_tls_errors {
wv.ignore_tls_errors()?;
}
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request)
}();
if let Err(result) = tx.send(result) {
warn!("Failed to send setup auth window result: {:?}", result);
}
})?;
rx.await??;
info!("Auth window setup completed");
Ok(())
}
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) {
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
}
auth_messenger.schedule_raise_window(2);
}
async fn retry_auth(&self, auth_window: &WebviewWindow) {
let mut is_retrying = self.is_retrying.write().await;
if *is_retrying {
info!("Already retrying authentication, skipping...");
return;
}
*is_retrying = true;
drop(is_retrying);
if let Err(err) = self.retry_auth_impl(auth_window).await {
warn!("Failed to retry authentication: {}", err);
}
*self.is_retrying.write().await = false;
}
async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> {
info!("Retrying authentication...");
auth_window.eval( r#"
var loading = document.createElement("div");
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
document.body.appendChild(loading);
"#)?;
let auth_request = auth_prelogin(&self.server, &self.gp_params, false).await?;
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let webview_user_agent = self.webview_user_agent.clone();
auth_window.with_webview(move |wv| {
let result = || -> anyhow::Result<()> {
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request)
}();
if let Err(result) = tx.send(result) {
warn!("Failed to send retry auth result: {:?}", result);
}
})?;
rx.await??;
Ok(())
}
fn raise_window(&self, auth_window: &WebviewWindow) {
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
}
info!("Raising auth window...");
#[cfg(target_os = "macos")]
let result = auth_window.show();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let result = {
use gpapi::utils::window::WindowExt;
auth_window.raise()
};
if let Err(err) = result {
warn!("Failed to raise window: {}", err);
}
}
}
fn load_auth_request_with_user_agent(
wv: &impl PlatformWebviewExt,
plan: Option<&WebviewUserAgent>,
auth_request: &str,
) -> anyhow::Result<()> {
if let Some(plan) = plan {
let user_agent = compose_webview_user_agent(plan, || wv.user_agent())?;
wv.set_user_agent(&user_agent)?;
}
wv.load_auth_request(auth_request)
}
fn compose_webview_user_agent(
plan: &WebviewUserAgent,
native_user_agent: impl FnOnce() -> anyhow::Result<String>,
) -> anyhow::Result<String> {
let (prefix, default_user_agent, transform) = match plan {
WebviewUserAgent::Native { prefix, transform } => (prefix.as_str(), native_user_agent()?, *transform),
WebviewUserAgent::Projected {
prefix,
default_user_agent,
} => (
prefix.as_str(),
default_user_agent.clone(),
WebviewUserAgentTransform::None,
),
};
let default_user_agent = apply_webview_user_agent_transform(transform, &default_user_agent);
prepend_webview_user_agent_prefix(prefix, &default_user_agent)
}
fn apply_webview_user_agent_transform(transform: WebviewUserAgentTransform, user_agent: &str) -> String {
match transform {
WebviewUserAgentTransform::None => user_agent.to_string(),
WebviewUserAgentTransform::LinuxPanGpuiVersion => linux_pan_gpui_user_agent(user_agent),
}
}
fn linux_pan_gpui_user_agent(user_agent: &str) -> String {
if user_agent.contains("PanGPUI Version/10.0") {
return user_agent.to_string();
}
let Some(start) = user_agent.find("Version/") else {
return user_agent.to_string();
};
let end = user_agent[start..]
.find(char::is_whitespace)
.map(|offset| start + offset)
.unwrap_or(user_agent.len());
format!("{}PanGPUI Version/10.0{}", &user_agent[..start], &user_agent[end..])
}
fn prepend_webview_user_agent_prefix(prefix: &str, default_user_agent: &str) -> anyhow::Result<String> {
let prefix = prefix.trim();
if prefix.is_empty() {
return Ok(default_user_agent.to_string());
}
let default_user_agent = default_user_agent.trim();
if default_user_agent.is_empty() {
bail!("Failed to read default webview user agent");
}
if default_user_agent.starts_with(prefix) {
return Ok(default_user_agent.to_string());
}
Ok(format!("{} {}", prefix, default_user_agent))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prepends_prefix_to_default_user_agent() {
let user_agent = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "Mozilla/5.0").unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0");
}
#[test]
fn leaves_already_prefixed_user_agent_unchanged() {
let user_agent =
prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "PAN GlobalProtect/6.3.3 Mozilla/5.0").unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0");
}
#[test]
fn blank_prefix_leaves_default_user_agent_unchanged() {
let user_agent = prepend_webview_user_agent_prefix(" ", "Mozilla/5.0").unwrap();
assert_eq!(user_agent, "Mozilla/5.0");
}
#[test]
fn non_blank_prefix_requires_default_user_agent() {
let err = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", " ").unwrap_err();
assert!(err.to_string().contains("default webview user agent"));
}
#[test]
fn native_plan_reads_native_default_user_agent() {
let plan = WebviewUserAgent::Native {
prefix: "PAN GlobalProtect/6.3.3".to_string(),
transform: WebviewUserAgentTransform::None,
};
let user_agent = compose_webview_user_agent(&plan, || Ok("Mozilla/5.0".to_string())).unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0");
}
#[test]
fn linux_transform_replaces_version_token_with_pan_gpui_version() {
let user_agent = linux_pan_gpui_user_agent(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/60.5 Safari/605.1.15",
);
assert_eq!(
user_agent,
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/605.1.15"
);
}
#[test]
fn linux_transform_does_not_duplicate_pan_gpui_version() {
let user_agent = linux_pan_gpui_user_agent(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1",
);
assert_eq!(
user_agent,
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1"
);
}
#[test]
fn native_linux_plan_applies_pan_gpui_transform_before_prefix() {
let plan = WebviewUserAgent::Native {
prefix: "PAN GlobalProtect/6.3.3".to_string(),
transform: WebviewUserAgentTransform::LinuxPanGpuiVersion,
};
let user_agent =
compose_webview_user_agent(&plan, || Ok("Mozilla/5.0 Version/60.5 Safari/605.1.15".to_string())).unwrap();
assert_eq!(
user_agent,
"PAN GlobalProtect/6.3.3 Mozilla/5.0 PanGPUI Version/10.0 Safari/605.1.15"
);
}
#[test]
fn projected_plan_uses_profile_default_user_agent() {
let plan = WebviewUserAgent::Projected {
prefix: "PAN GlobalProtect/6.3.3".to_string(),
default_user_agent: "Mozilla/5.0 projected".to_string(),
};
let user_agent = compose_webview_user_agent(&plan, || {
panic!("projected webview user agent should not read the native default")
})
.unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0 projected");
}
}
+3
View File
@@ -6,3 +6,6 @@ authors.workspace = true
homepage.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
is_executable.workspace = true
-81
View File
@@ -1,81 +0,0 @@
pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619";
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
// Release binaries - macOS (Apple Silicon Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_CLIENT_BINARY: &str = "/opt/homebrew/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_SERVICE_BINARY: &str = "/opt/homebrew/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_GUI_BINARY: &str = "/opt/homebrew/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_GUI_HELPER_BINARY: &str = "/opt/homebrew/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_AUTH_BINARY: &str = "/opt/homebrew/bin/gpauth";
// Release binaries - macOS (Intel Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_AUTH_BINARY: &str = "/usr/local/bin/gpauth";
// Release binaries - BSD package layout
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_AUTH_BINARY: &str = "/usr/local/bin/gpauth";
// Release binaries - Linux
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/bin/gpgui-helper";
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_AUTH_BINARY: &str = "/usr/bin/gpauth";
// Debug binaries are set in build.rs via environment variables
#[cfg(debug_assertions)]
pub const GP_CLIENT_BINARY: &str = env!("GP_CLIENT_BINARY");
#[cfg(debug_assertions)]
pub const GP_SERVICE_BINARY: &str = env!("GP_SERVICE_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_BINARY: &str = env!("GP_GUI_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_HELPER_BINARY: &str = env!("GP_GUI_HELPER_BINARY");
#[cfg(debug_assertions)]
pub const GP_AUTH_BINARY: &str = env!("GP_AUTH_BINARY");
+1 -1
View File
@@ -1 +1 @@
pub mod constants;
pub mod vpn_utils;
@@ -3,7 +3,6 @@ use std::{io, path::Path};
use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/vpnc-script",
"/usr/libexec/gpclient/vpnc-script",
"/usr/lib/gpclient/vpnc-script",
"/usr/local/share/vpnc-scripts/vpnc-script",
@@ -12,45 +11,40 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/sbin/vpnc-script",
"/etc/vpnc/vpnc-script",
"/etc/openconnect/vpnc-script",
"/usr/libexec/vpnc-scripts/vpnc-script",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[cfg(target_os = "macos")]
"/opt/homebrew/etc/vpnc/vpnc-script",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/hipreport.sh",
"/usr/libexec/gpclient/hipreport.sh",
"/usr/lib/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[cfg(target_os = "macos")]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
fn find_executable(locations: &[&str]) -> Option<String> {
for location in locations.iter() {
let path = Path::new(location);
if path.is_executable() {
return Some(*location);
return Some(location.to_string());
}
}
None
}
pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(VPNC_SCRIPT_LOCATIONS)
pub fn find_vpnc_script() -> Option<String> {
find_executable(&VPNC_SCRIPT_LOCATIONS)
}
pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(CSD_WRAPPER_LOCATIONS)
pub fn find_csd_wrapper() -> Option<String> {
find_executable(&CSD_WRAPPER_LOCATIONS)
}
/// If file exists, check if it is executable
+15 -24
View File
@@ -1,23 +1,21 @@
[package]
name = "gpapi"
rust-version.workspace = true
version.workspace = true
edition.workspace = true
license = "MIT"
[dependencies]
common = { path = "../common" }
anyhow.workspace = true
base64.workspace = true
dns-lookup.workspace = true
log.workspace = true
reqwest.workspace = true
openssl.workspace = true
version-compare = "0.2"
pem.workspace = true
xmltree.workspace = true
serde.workspace = true
specta = { workspace = true, features = ["derive"] }
specta.workspace = true
specta-macros.workspace = true
urlencoding.workspace = true
tokio = { workspace = true, features = ["process", "signal", "macros"] }
serde_json.workspace = true
@@ -32,29 +30,22 @@ uzers.workspace = true
serde_urlencoded.workspace = true
md5.workspace = true
sha256.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
netdev.workspace = true
os_info = { version = "3", default-features = false }
which.workspace = true
machine-uid = "0.5"
uuid = { version = "1", features = ["v5"] }
# Pin the version of home because the latest version requires Rust 1.81
home = "=0.5.9"
# Optional dependencies for features
tauri = { workspace = true, optional = true }
clap = { workspace = true, optional = true }
clap-verbosity-flag = { workspace = true, optional = true }
open = { version = "5", optional = true }
webbrowser = { version = "1", optional = true }
env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", optional = true }
# Dependencies for Linux and other OSes only
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = { version = "0.18", optional = true }
[dev-dependencies]
proptest.workspace = true
[target.'cfg(any(target_os="macos", target_os="windows"))'.dependencies]
os_info = { version = "3", default-features = false }
[features]
tauri = ["dep:tauri", "dep:gtk"]
clap = ["dep:clap", "dep:clap-verbosity-flag"]
webview-auth = []
logger = ["dep:env_logger", "dep:log-reload"]
tauri = ["dep:tauri"]
clap = ["dep:clap"]
browser-auth = ["dep:open", "dep:webbrowser"]
@@ -14,9 +14,6 @@ fn main() {
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display());
println!("cargo:rustc-env=GP_AUTH_BINARY={}", gp_auth_binary.display());
println!(
"cargo:rustc-env=GP_GUI_HELPER_BINARY={}",
gp_gui_helper_binary.display()
);
println!("cargo:rustc-env=GP_GUI_HELPER_BINARY={}", gp_gui_helper_binary.display());
println!("cargo:rustc-env=GP_GUI_BINARY={}", gp_gui_binary.display());
}
+42 -120
View File
@@ -1,15 +1,12 @@
use std::borrow::{Borrow, Cow};
use anyhow::bail;
use log::{info, warn};
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
#[derive(Debug, Serialize, Deserialize, Clone)]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SamlAuthData {
#[serde(alias = "un")]
@@ -17,11 +14,9 @@ pub struct SamlAuthData {
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
host_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SamlAuthResult {
Success(SamlAuthData),
@@ -35,77 +30,42 @@ impl SamlAuthResult {
SamlAuthResult::Failure(_) => false,
}
}
pub fn host_id(&self) -> Option<&str> {
match self {
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
SamlAuthResult::Failure(_) => None,
}
}
}
impl SamlAuthData {
pub fn new(
username: Option<String>,
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
) -> anyhow::Result<Self> {
let username = username.unwrap_or_default();
if username.is_empty() {
bail!("Invalid username: <empty>");
}
let prelogin_cookie = prelogin_cookie.unwrap_or_default();
let portal_userauthcookie = portal_userauthcookie.unwrap_or_default();
if prelogin_cookie.len() <= 5 && portal_userauthcookie.len() <= 5 {
bail!(
"Invalid prelogin-cookie: {}, portal-userauthcookie: {}",
prelogin_cookie,
portal_userauthcookie
);
}
Ok(Self {
pub fn new(username: String, prelogin_cookie: Option<String>, portal_userauthcookie: Option<String>) -> Self {
Self {
username,
prelogin_cookie: Some(prelogin_cookie),
portal_userauthcookie: Some(portal_userauthcookie),
prelogin_cookie,
portal_userauthcookie,
token: None,
host_id: None,
})
}
}
pub fn with_host_id(mut self, host_id: impl Into<String>) -> Self {
let host_id = host_id.into();
self.host_id = (!host_id.trim().is_empty()).then_some(host_id);
self
}
pub fn from_html(html: &str) -> AuthDataParseResult {
pub fn from_html(html: &str) -> anyhow::Result<SamlAuthData, AuthDataParseError> {
match parse_xml_tag(html, "saml-auth-status") {
Some(status) if status == "1" => {
Some(saml_status) if saml_status == "1" => {
let username = parse_xml_tag(html, "saml-username");
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
let auth_data =
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?;
auth_data.log_summary("html");
Ok(auth_data)
if SamlAuthData::check(&username, &prelogin_cookie, &portal_userauthcookie) {
Ok(SamlAuthData::new(
username.unwrap(),
prelogin_cookie,
portal_userauthcookie,
))
} else {
Err(AuthDataParseError::Invalid)
}
}
Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!(
"SAML auth status: {}",
status
))),
Some(_) => Err(AuthDataParseError::Invalid),
None => Err(AuthDataParseError::NotFound),
}
}
pub fn from_gpcallback(data: &str) -> anyhow::Result<SamlAuthData, AuthDataParseError> {
let auth_data = data.trim_start_matches("globalprotectcallback:");
// Further remove the leading "/" if it exists, because some versions of GP may include it
let auth_data = auth_data.trim_start_matches('/');
if auth_data.starts_with("cas-as") {
info!("Got CAS auth data from globalprotectcallback");
@@ -119,16 +79,15 @@ impl SamlAuthData {
let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| {
warn!("Failed to parse token auth data: {}", e);
warn!("Auth data: {}", auth_data);
AuthDataParseError::Invalid(anyhow::anyhow!(e))
AuthDataParseError::Invalid
})?;
auth_data.log_summary("gpcallback-cas");
return Ok(auth_data);
}
let auth_data = decode_to_string(auth_data).map_err(|e| {
warn!("Failed to decode SAML auth data: {}, data: {}", e, data);
AuthDataParseError::Invalid(anyhow::anyhow!(e))
warn!("Failed to decode SAML auth data: {}", e);
AuthDataParseError::Invalid
})?;
let auth_data = Self::from_html(&auth_data)?;
@@ -143,35 +102,33 @@ impl SamlAuthData {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
pub fn host_id(&self) -> Option<&str> {
self.host_id.as_deref()
}
pub fn check(
username: &Option<String>,
prelogin_cookie: &Option<String>,
portal_userauthcookie: &Option<String>,
) -> bool {
let username_valid = username.as_ref().is_some_and(|username| !username.is_empty());
let prelogin_cookie_valid = prelogin_cookie.as_ref().is_some_and(|val| val.len() > 5);
let portal_userauthcookie_valid = portal_userauthcookie.as_ref().is_some_and(|val| val.len() > 5);
fn log_summary(&self, source: &str) {
info!(
"Parsed SAML auth data: source={}, username_present={}, prelogin_cookie_len={}, portal_userauthcookie_len={}, token_len={}",
source,
!self.username.is_empty(),
optional_len(self.prelogin_cookie.as_deref()),
optional_len(self.portal_userauthcookie.as_deref()),
optional_len(self.token.as_deref())
);
let is_valid = username_valid && (prelogin_cookie_valid || portal_userauthcookie_valid);
if !is_valid {
warn!(
"Invalid SAML auth data: username: {:?}, prelogin-cookie: {:?}, portal-userauthcookie: {:?}",
username, prelogin_cookie, portal_userauthcookie
);
}
is_valid
}
}
fn optional_len(value: Option<&str>) -> usize {
value.unwrap_or_default().len()
}
fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
pub fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
let re = Regex::new(&format!("<{}>(.*)</{}>", tag, tag)).unwrap();
re.captures(html)
.and_then(|captures| captures.get(1))
@@ -204,46 +161,11 @@ mod tests {
#[test]
fn auth_data_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHBvcnRhbC11c2VyYXV0aGNvb2tpZT5wb3J0YWwtdXNlcmF1dGhjb29raWU8L3BvcnRhbC11c2VyYXV0aGNvb2tpZT48c2FtbC11c2VybmFtZT54eXpAZW1haWwuY29tPC9zYW1sLXVzZXJuYW1lPjxzYW1sLXNsbz5ubzwvc2FtbC1zbG8+IC0tPjwvaHRtbD4=";
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "[email protected]");
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(auth_data.portal_userauthcookie(), Some("portal-userauthcookie"));
}
#[test]
fn auth_result_success_can_carry_host_id() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
None,
)
.unwrap()
.with_host_id("host-seed");
let result = SamlAuthResult::Success(auth_data);
assert_eq!(result.host_id(), Some("host-seed"));
let value = serde_json::to_value(result).unwrap();
assert_eq!(value["success"]["hostId"], "host-seed");
}
#[test]
fn auth_result_success_omits_empty_host_id() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
None,
)
.unwrap()
.with_host_id(" ");
let result = SamlAuthResult::Success(auth_data);
assert_eq!(result.host_id(), None);
let value = serde_json::to_value(result).unwrap();
assert!(value["success"].get("hostId").is_none());
}
}
+38 -39
View File
@@ -1,22 +1,37 @@
use clap::{ValueEnum, builder::PossibleValue};
use clap::{builder::PossibleValue, ValueEnum};
use crate::{
gp_params::CscMode,
os_profile::{ClientOs, runtime_client_os},
};
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[derive(Debug, Clone)]
pub enum Os {
#[value(name = "Linux")]
Linux,
#[value(name = "Windows")]
Windows,
#[value(name = "Mac")]
Mac,
}
impl From<Os> for ClientOs {
fn from(value: Os) -> Self {
impl Os {
pub fn as_str(&self) -> &'static str {
match self {
Os::Linux => "Linux",
Os::Windows => "Windows",
Os::Mac => "Mac",
}
}
}
impl From<&str> for Os {
fn from(os: &str) -> Self {
match os.to_lowercase().as_str() {
"linux" => Os::Linux,
"windows" => Os::Windows,
"mac" => Os::Mac,
_ => Os::Linux,
}
}
}
impl From<&Os> for ClientOs {
fn from(value: &Os) -> Self {
match value {
Os::Linux => ClientOs::Linux,
Os::Windows => ClientOs::Windows,
@@ -25,41 +40,25 @@ impl From<Os> for ClientOs {
}
}
impl Default for Os {
fn default() -> Self {
match runtime_client_os() {
ClientOs::Linux => Os::Linux,
ClientOs::Windows => Os::Windows,
ClientOs::Mac => Os::Mac,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_os_uses_runtime_client_os() {
assert_eq!(ClientOs::from(Os::default()), runtime_client_os());
}
}
impl ValueEnum for CscMode {
impl ValueEnum for Os {
fn value_variants<'a>() -> &'a [Self] {
&[CscMode::Auto, CscMode::Yes, CscMode::No]
&[Os::Linux, Os::Windows, Os::Mac]
}
fn to_possible_value(&self) -> Option<PossibleValue> {
Some(PossibleValue::new(self.as_str()))
fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
match self {
Os::Linux => Some(PossibleValue::new("Linux")),
Os::Windows => Some(PossibleValue::new("Windows")),
Os::Mac => Some(PossibleValue::new("Mac")),
}
}
fn from_str(input: &str, _: bool) -> Result<Self, String> {
match input.to_lowercase().as_str() {
"auto" => Ok(CscMode::Auto),
"yes" => Ok(CscMode::Yes),
"no" => Ok(CscMode::No),
_ => Err(format!("Invalid CSC mode: {}", input)),
"linux" => Ok(Os::Linux),
"windows" => Ok(Os::Windows),
"mac" => Ok(Os::Mac),
_ => Err(format!("Invalid OS: {}", input)),
}
}
}
-80
View File
@@ -1,81 +1 @@
use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
use log::Level;
use crate::error::PortalError;
pub mod args;
pub trait Args {
fn fix_openssl(&self) -> bool;
fn ignore_tls_errors(&self) -> bool;
}
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
eprintln!("\nError: {:?}", err);
let Some(err) = err.downcast_ref::<PortalError>() else {
return;
};
if err.is_legacy_openssl_error() && !args.fix_openssl() {
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
}
if err.is_tls_error() && !args.ignore_tls_errors() {
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
}
}
#[derive(Debug)]
pub struct InfoLevel;
pub type InfoLevelVerbosity = Verbosity<InfoLevel>;
impl LogLevel for InfoLevel {
fn default_filter() -> VerbosityFilter {
VerbosityFilter::Info
}
fn verbose_help() -> Option<&'static str> {
Some("Enable verbose output, -v for debug, -vv for trace")
}
fn quiet_help() -> Option<&'static str> {
Some("Decrease logging verbosity, -q for warnings, -qq for errors")
}
}
pub trait ToVerboseArg {
fn to_verbose_arg(&self) -> Option<&'static str>;
}
/// Convert the verbosity to the CLI argument value
/// The default verbosity is `Info`, which means no argument is needed
impl ToVerboseArg for InfoLevelVerbosity {
fn to_verbose_arg(&self) -> Option<&'static str> {
match self.filter() {
VerbosityFilter::Off => Some("-qqq"),
VerbosityFilter::Error => Some("-qq"),
VerbosityFilter::Warn => Some("-q"),
VerbosityFilter::Info => None,
VerbosityFilter::Debug => Some("-v"),
VerbosityFilter::Trace => Some("-vv"),
}
}
}
impl ToVerboseArg for Level {
fn to_verbose_arg(&self) -> Option<&'static str> {
match self {
Level::Error => Some("-qq"),
Level::Warn => Some("-q"),
Level::Info => None,
Level::Debug => Some("-v"),
Level::Trace => Some("-vv"),
}
}
}
-190
View File
@@ -1,190 +0,0 @@
use std::{
fs,
io::Write,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use crate::credential::AuthCookieCredential;
const STORE_VERSION: u32 = 1;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StoredCookie {
pub version: u32,
pub server: String,
pub username: String,
pub host_id: String,
pub last_gateway: String,
pub auth_cookie: AuthCookieCredential,
pub saved_at: u64,
}
impl StoredCookie {
pub fn new(
server: String,
username: String,
host_id: String,
last_gateway: String,
auth_cookie: AuthCookieCredential,
) -> Self {
let saved_at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
Self {
version: STORE_VERSION,
server,
username,
host_id,
last_gateway,
auth_cookie,
saved_at,
}
}
}
pub fn cookie_path(custom: Option<&str>) -> PathBuf {
if let Some(p) = custom {
return PathBuf::from(p);
}
let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
PathBuf::from(home).join(".config/gpclient/cookie.json")
}
pub fn load(path: &Path, server: &str, host_id: &str) -> Option<StoredCookie> {
let bytes = fs::read(path).ok()?;
let stored: StoredCookie = serde_json::from_slice(&bytes).ok()?;
if stored.version != STORE_VERSION || stored.server != server || stored.host_id != host_id {
return None;
}
Some(stored)
}
pub fn save(path: &Path, stored: &StoredCookie) -> anyhow::Result<()> {
let parent = path
.parent()
.ok_or_else(|| anyhow::anyhow!("cookie path has no parent directory"))?;
fs::create_dir_all(parent)?;
set_private_dir_permissions(parent)?;
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(&serde_json::to_vec(stored)?)?;
tmp.flush()?;
set_private_file_permissions(tmp.path())?;
tmp.persist(path)?;
Ok(())
}
pub fn clear(path: &Path) {
let _ = fs::remove_file(path);
}
use permissions::{set_private_dir_permissions, set_private_file_permissions};
mod permissions {
use std::path::Path;
#[cfg(unix)]
mod unix {
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
pub(super) fn set_private_dir(path: &Path) -> anyhow::Result<()> {
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
Ok(())
}
pub(super) fn set_private_file(path: &Path) -> anyhow::Result<()> {
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
Ok(())
}
#[cfg(test)]
pub(super) fn file_mode(path: &Path) -> Option<u32> {
Some(fs::metadata(path).ok()?.permissions().mode() & 0o777)
}
}
pub(super) fn set_private_dir_permissions(path: &Path) -> anyhow::Result<()> {
#[cfg(unix)]
unix::set_private_dir(path)?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
pub(super) fn set_private_file_permissions(path: &Path) -> anyhow::Result<()> {
#[cfg(unix)]
unix::set_private_file(path)?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
#[cfg(test)]
pub(super) fn file_mode(path: &Path) -> Option<u32> {
#[cfg(unix)]
return unix::file_mode(path);
#[cfg(not(unix))]
{
let _ = path;
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> StoredCookie {
StoredCookie::new(
"vpn.example.com".to_string(),
"alice".to_string(),
"host-1".to_string(),
"gw1.example.com".to_string(),
AuthCookieCredential::new("alice", "user-auth", "prelogon-auth"),
)
}
#[test]
fn roundtrip_and_mode_0600() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("cookie.json");
let s = sample();
save(&path, &s).unwrap();
if let Some(mode) = permissions::file_mode(&path) {
assert_eq!(mode, 0o600, "cookie file must be mode 0600, got {:o}", mode);
}
let loaded = load(&path, "vpn.example.com", "host-1").unwrap();
assert_eq!(loaded.username, "alice");
assert_eq!(loaded.host_id, "host-1");
assert_eq!(loaded.last_gateway, "gw1.example.com");
assert_eq!(loaded.auth_cookie.user_auth_cookie(), "user-auth");
assert!(
load(&path, "other.example.com", "host-1").is_none(),
"must reject mismatched server"
);
assert!(
load(&path, "vpn.example.com", "host-2").is_none(),
"must reject mismatched host id"
);
clear(&path);
assert!(!path.exists());
}
#[test]
fn rejects_version_mismatch() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("cookie.json");
let mut s = sample();
s.version = STORE_VERSION + 1;
save(&path, &s).unwrap();
assert!(load(&path, "vpn.example.com", "host-1").is_none());
}
}
+38 -139
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use anyhow::bail;
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -39,21 +41,14 @@ impl From<&CachedCredential> for PasswordCredential {
pub struct PreloginCredential {
username: String,
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>,
}
impl PreloginCredential {
pub fn new(
username: &str,
prelogin_cookie: Option<&str>,
portal_userauthcookie: Option<&str>,
token: Option<&str>,
) -> Self {
pub fn new(username: &str, prelogin_cookie: Option<&str>, token: Option<&str>) -> Self {
Self {
username: username.to_string(),
prelogin_cookie: prelogin_cookie.map(|s| s.to_string()),
portal_userauthcookie: portal_userauthcookie.map(|s| s.to_string()),
token: token.map(|s| s.to_string()),
}
}
@@ -66,10 +61,6 @@ impl PreloginCredential {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
@@ -79,10 +70,9 @@ impl From<SamlAuthData> for PreloginCredential {
fn from(value: SamlAuthData) -> Self {
let username = value.username().to_string();
let prelogin_cookie = value.prelogin_cookie();
let portal_userauthcookie = value.portal_userauthcookie();
let token = value.token();
Self::new(&username, prelogin_cookie, portal_userauthcookie, token)
Self::new(&username, prelogin_cookie, token)
}
}
@@ -92,8 +82,6 @@ pub struct AuthCookieCredential {
username: String,
user_auth_cookie: String,
prelogon_user_auth_cookie: String,
#[serde(skip)]
password: Option<String>,
}
impl AuthCookieCredential {
@@ -102,16 +90,9 @@ impl AuthCookieCredential {
username: username.to_string(),
user_auth_cookie: user_auth_cookie.to_string(),
prelogon_user_auth_cookie: prelogon_user_auth_cookie.to_string(),
password: None,
}
}
pub fn with_password(mut self, password: impl Into<String>) -> Self {
let password = password.into();
self.password = (!password.trim().is_empty()).then_some(password);
self
}
pub fn username(&self) -> &str {
&self.username
}
@@ -123,19 +104,6 @@ impl AuthCookieCredential {
pub fn prelogon_user_auth_cookie(&self) -> &str {
&self.prelogon_user_auth_cookie
}
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
pub fn can_authenticate_gateway(&self) -> bool {
is_gateway_auth_cookie(&self.user_auth_cookie) || is_gateway_auth_cookie(&self.prelogon_user_auth_cookie)
}
}
fn is_gateway_auth_cookie(value: &str) -> bool {
let value = value.trim();
!value.is_empty() && value != "empty"
}
#[derive(Debug, Serialize, Deserialize, Type, Clone)]
@@ -167,13 +135,6 @@ impl CachedCredential {
self.auth_cookie.as_ref()
}
pub fn can_authenticate_gateway(&self) -> bool {
self
.auth_cookie
.as_ref()
.is_some_and(AuthCookieCredential::can_authenticate_gateway)
}
pub fn set_auth_cookie(&mut self, auth_cookie: AuthCookieCredential) {
self.auth_cookie = Some(auth_cookie);
}
@@ -219,20 +180,42 @@ impl Credential {
}
}
pub fn password(&self) -> Option<&str> {
match self {
Credential::Password(cred) => Some(cred.password()),
Credential::Cached(cred) => cred.password(),
Credential::Prelogin(_) | Credential::AuthCookie(_) => None,
}
}
pub fn to_params(&self) -> HashMap<&str, &str> {
let mut params = HashMap::new();
params.insert("user", self.username());
pub fn can_authenticate_gateway(&self) -> bool {
match self {
Credential::AuthCookie(cred) => cred.can_authenticate_gateway(),
Credential::Cached(cred) => cred.can_authenticate_gateway(),
Credential::Password(_) | Credential::Prelogin(_) => true,
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (None, cred.prelogin_cookie(), None, None, cred.token()),
Credential::AuthCookie(cred) => (
None,
None,
Some(cred.user_auth_cookie()),
Some(cred.prelogon_user_auth_cookie()),
None,
),
Credential::Cached(cred) => (
cred.password(),
None,
cred.auth_cookie.as_ref().map(|c| c.user_auth_cookie()),
cred.auth_cookie.as_ref().map(|c| c.prelogon_user_auth_cookie()),
None,
),
};
params.insert("passwd", passwd.unwrap_or_default());
params.insert("prelogin-cookie", prelogin_cookie.unwrap_or_default());
params.insert("portal-userauthcookie", portal_userauthcookie.unwrap_or_default());
params.insert(
"portal-prelogonuserauthcookie",
portal_prelogonuserauthcookie.unwrap_or_default(),
);
if let Some(token) = token {
params.insert("token", token);
}
params
}
}
@@ -272,87 +255,3 @@ impl From<&CachedCredential> for Credential {
Self::Cached(value.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prelogin_credential_keeps_saml_cookies() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
Some("portal-userauthcookie".to_string()),
)
.unwrap();
let cred = Credential::from(auth_data);
let Credential::Prelogin(prelogin) = cred else {
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]");
assert_eq!(prelogin.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(prelogin.portal_userauthcookie(), Some("portal-userauthcookie"));
assert_eq!(prelogin.token(), None);
}
#[test]
fn prelogin_credential_keeps_cas_token_without_cookies() {
let auth_data =
SamlAuthData::from_gpcallback("globalprotectcallback:cas-as=1&[email protected]&token=cas-token").unwrap();
let cred = Credential::from(auth_data);
let Credential::Prelogin(prelogin) = cred else {
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]");
assert_eq!(prelogin.prelogin_cookie(), None);
assert_eq!(prelogin.portal_userauthcookie(), None);
assert_eq!(prelogin.token(), Some("cas-token"));
}
#[test]
fn auth_cookie_runtime_password_is_not_serialized() {
let value = serde_json::to_value(
AuthCookieCredential::new("alice", "user-cookie", "prelogon-cookie").with_password("secret"),
)
.unwrap();
assert_eq!(value.get("password"), None);
}
#[test]
fn auth_cookie_with_empty_sentinels_cannot_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "empty", "empty");
assert!(!cred.can_authenticate_gateway());
}
#[test]
fn auth_cookie_with_blank_values_cannot_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "", " ");
assert!(!cred.can_authenticate_gateway());
}
#[test]
fn auth_cookie_with_real_cookie_can_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "empty", "portal-prelogon-cookie");
assert!(cred.can_authenticate_gateway());
}
#[test]
fn cached_credential_without_real_auth_cookie_cannot_authenticate_gateway() {
let cred = CachedCredential::new(
"alice".to_string(),
None,
Some(AuthCookieCredential::new("alice", "empty", "empty")),
);
assert!(!cred.can_authenticate_gateway());
assert!(!Credential::from(&cred).can_authenticate_gateway());
}
}
+4 -25
View File
@@ -4,37 +4,16 @@ use thiserror::Error;
pub enum PortalError {
#[error("Prelogin error: {0}")]
PreloginError(String),
#[error("Portal config error: {0}")]
ConfigError(String),
#[error(transparent)]
NetworkError(#[from] reqwest::Error),
#[error("TLS error")]
TlsError,
}
impl PortalError {
pub fn is_legacy_openssl_error(&self) -> bool {
format!("{:?}", self).contains("unsafe legacy renegotiation")
}
pub fn is_tls_error(&self) -> bool {
matches!(self, PortalError::TlsError) || format!("{:?}", self).contains("certificate verify failed")
}
#[error("Network error: {0}")]
NetworkError(String),
}
#[derive(Error, Debug)]
pub enum AuthDataParseError {
#[error("No auth data found")]
NotFound,
#[error(transparent)]
Invalid(#[from] anyhow::Error),
}
impl AuthDataParseError {
pub fn is_invalid(&self) -> bool {
matches!(self, AuthDataParseError::Invalid(_))
}
#[error("Invalid auth data")]
Invalid,
}
+171
View File
@@ -0,0 +1,171 @@
use std::collections::HashMap;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
gp_params::GpParams,
process::hip_launcher::HipLauncher,
utils::{normalize_server, xml::ElementExt},
};
struct HipReporter<'a> {
server: String,
cookie: &'a str,
md5: &'a str,
csd_wrapper: &'a str,
gp_params: &'a GpParams,
client: Client,
}
impl HipReporter<'_> {
async fn report(&self) -> anyhow::Result<()> {
let client_ip = self.retrieve_client_ip().await?;
let hip_needed = match self.check_hip(&client_ip).await {
Ok(hip_needed) => hip_needed,
Err(err) => {
warn!("Failed to check HIP: {}", err);
return Ok(());
}
};
if !hip_needed {
info!("HIP report not needed");
return Ok(());
}
info!("HIP report needed, generating report...");
let report = self.generate_report(&client_ip).await?;
if let Err(err) = self.submit_hip(&client_ip, &report).await {
warn!("Failed to submit HIP report: {}", err);
}
Ok(())
}
async fn retrieve_client_ip(&self) -> anyhow::Result<String> {
let config_url = format!("{}/ssl-vpn/getconfig.esp", self.server);
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("client-type", "1");
params.insert("protocol-version", "p1");
params.insert("internal", "no");
params.insert("ipv6-support", "yes");
params.insert("clientos", self.gp_params.client_os());
params.insert("hmac-algo", "sha1,md5,sha256");
params.insert("enc-algo", "aes-128-cbc,aes-256-cbc");
if let Some(os_version) = self.gp_params.os_version() {
params.insert("os-version", os_version);
}
if let Some(client_version) = self.gp_params.client_version() {
params.insert("app-version", client_version);
}
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&config_url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
let root = Element::parse(res_xml.as_bytes())?;
let ip = root
.descendant_text("ip-address")
.ok_or_else(|| anyhow::anyhow!("ip-address not found"))?;
Ok(ip)
}
async fn check_hip(&self, client_ip: &str) -> anyhow::Result<bool> {
let url = format!("{}/ssl-vpn/hipreportcheck.esp", self.server);
let mut params = HashMap::new();
params.insert("client-role", "global-protect-full");
params.insert("client-ip", client_ip);
params.insert("md5", self.md5);
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
is_hip_needed(&res_xml)
}
async fn generate_report(&self, client_ip: &str) -> anyhow::Result<String> {
let launcher = HipLauncher::new(self.csd_wrapper)
.cookie(self.cookie)
.md5(self.md5)
.client_ip(client_ip)
.client_os(self.gp_params.client_os())
.client_version(self.gp_params.client_version());
launcher.launch().await
}
async fn submit_hip(&self, client_ip: &str, report: &str) -> anyhow::Result<()> {
let url = format!("{}/ssl-vpn/hipreport.esp", self.server);
let mut params = HashMap::new();
params.insert("client-role", "global-protect-full");
params.insert("client-ip", client_ip);
params.insert("report", report);
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
info!("HIP check response: {}", res_xml);
Ok(())
}
}
fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> {
let root = Element::parse(res_xml.as_bytes())?;
let hip_needed = root
.descendant_text("hip-report-needed")
.ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?;
Ok(hip_needed == "yes")
}
fn merge_cookie_params(cookie: &str, params: &HashMap<&str, &str>) -> anyhow::Result<HashMap<String, String>> {
let cookie_params = serde_urlencoded::from_str::<HashMap<String, String>>(cookie)?;
let params = params
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.chain(cookie_params)
.collect::<HashMap<String, String>>();
Ok(params)
}
// Compute md5 for fields except authcookie,preferred-ip,preferred-ipv6
fn build_csd_token(cookie: &str) -> anyhow::Result<String> {
let mut cookie_params = serde_urlencoded::from_str::<Vec<(String, String)>>(cookie)?;
cookie_params.retain(|(k, _)| k != "authcookie" && k != "preferred-ip" && k != "preferred-ipv6");
let token = serde_urlencoded::to_string(cookie_params)?;
let md5 = format!("{:x}", md5::compute(token));
Ok(md5)
}
pub async fn hip_report(gateway: &str, cookie: &str, csd_wrapper: &str, gp_params: &GpParams) -> anyhow::Result<()> {
let client = Client::try_from(gp_params)?;
let md5 = build_csd_token(cookie)?;
info!("Submit HIP report md5: {}", md5);
let reporter = HipReporter {
server: normalize_server(gateway)?,
cookie,
md5: &md5,
csd_wrapper,
gp_params,
client,
};
reporter.report().await
}
+25 -214
View File
@@ -1,17 +1,13 @@
use std::{borrow::Cow, net::UdpSocket};
use anyhow::bail;
use log::{debug, info, warn};
use log::{info, warn};
use reqwest::Client;
use urlencoding::{decode, encode};
use urlencoding::encode;
use xmltree::Element;
use crate::{
credential::Credential,
error::PortalError,
gateway::GatewayLoginContext,
gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
@@ -21,78 +17,32 @@ pub enum GatewayLogin {
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, false).await
}
pub async fn gateway_login_with_context(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: &GatewayLoginContext,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(|ip| ip.to_string())
.or_else(|| detect_local_ipv4(context.host()))
});
let request_params = gateway_login::build(&GatewayLoginInput {
gp_params,
cred,
gateway_host: &gateway,
context,
client_ip: client_ip.as_deref(),
extend_lifetime,
});
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &gateway);
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
let res = client
.post(&login_url)
.form(&request_params.body)
.form(&params)
.send()
.await
.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
.map_err(|e| anyhow::anyhow!(PortalError::NetworkError(e.to_string())))?;
let res = parse_gp_response(res).await.map_err(|err| {
warn!("{err}");
anyhow::anyhow!("Gateway login error: {}", err.reason)
})?;
// It's possible to get an empty response, log the response headers for debugging
if res.trim().is_empty() {
info!("Empty gateway login response headers: {:?}", res);
bail!("Got empty gateway login response");
}
// MFA detected
if res.contains("Challenge") {
let Some((message, input_str)) = parse_mfa(&res) else {
@@ -102,60 +52,27 @@ async fn gateway_login_with_options(
return Ok(GatewayLogin::Mfa(message, input_str));
}
debug!("Gateway login response: {}", res);
let root = Element::parse(res.as_bytes())?;
let cookie = build_gateway_token(&root, gp_params.computer())?;
Ok(GatewayLogin::Cookie(cookie))
}
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
}
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
let Some(context) = context else {
return;
};
info!(
"Gateway login context: host_present={}, gateway_name_present={}, connect_method_present={}, selection_type={}, internal={}, clientgpversion_present={}, client_ip_present={}",
!context.host().is_empty(),
!context.name().is_empty(),
context.connect_method().is_some(),
context.selection().as_login_param(),
context.kind().as_login_param(),
gp_params.client_version().is_some(),
client_ip.is_some()
);
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
fn build_gateway_token(root: &Element, computer: &str) -> anyhow::Result<String> {
let args = root
.descendants("argument")
.iter()
.map(|e| e.get_text().unwrap_or_default())
.map(|element| element.get_text().unwrap_or_default().to_string())
.collect::<Vec<_>>();
let mut params = vec![
read_required_arg(&args, 1, "authcookie")?,
read_optional_arg(&args, 2, "persistent-cookie")?,
read_optional_arg(&args, 3, "portal")?,
read_required_arg(&args, 4, "user")?,
read_optional_arg(&args, 7, "domain")?,
read_optional_arg(&args, 15, "preferred-ip")?,
read_optional_arg(&args, 18, "preferred-ipv6")?,
]
.into_iter()
.flatten()
.collect::<Vec<_>>();
params.push(("computer", computer.to_string()));
let params = [
read_args(&args, 1, "authcookie")?,
read_args(&args, 3, "portal")?,
read_args(&args, 4, "user")?,
read_args(&args, 7, "domain")?,
read_args(&args, 15, "preferred-ip")?,
("computer", computer),
];
let token = params
.iter()
@@ -166,43 +83,11 @@ fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<Stri
Ok(token)
}
fn read_required_arg(
args: &[Cow<'_, str>],
index: usize,
key: &'static str,
) -> anyhow::Result<Option<(&'static str, String)>> {
let Some(value) = read_arg_value(args, index)? else {
bail!("Failed to read {key} from args");
};
Ok(Some((key, value)))
}
fn read_optional_arg(
args: &[Cow<'_, str>],
index: usize,
key: &'static str,
) -> anyhow::Result<Option<(&'static str, String)>> {
Ok(read_arg_value(args, index)?.map(|value| (key, value)))
}
fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<String>> {
Ok(
args
.get(index)
.map(|s| normalize_arg_value(s.as_ref()))
.transpose()
.map_err(|err| anyhow::anyhow!("Failed to decode gateway login argument {index}: {err}"))?
.flatten(),
)
}
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
if value.is_empty() || value == "(null)" || value == "-1" {
return Ok(None);
}
Ok(Some(decode(value)?.into_owned()))
fn read_args<'a>(args: &'a [String], index: usize, key: &'a str) -> anyhow::Result<(&'a str, &'a str)> {
args
.get(index)
.ok_or_else(|| anyhow::anyhow!("Failed to read {key} from args"))
.map(|s| (key, s.as_ref()))
}
fn parse_mfa(res: &str) -> Option<(String, String)> {
@@ -233,78 +118,4 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(message, "MFA message");
assert_eq!(input_str, "5ef64e83000119ed");
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument>PERSISTENTCOOKIE</argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>%28empty_domain%29</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument>10.0.0.10</argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>2001:db8::10</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&persistent-cookie=PERSISTENTCOOKIE&portal=vpn.example.com&user=alice&domain=%28empty_domain%29&preferred-ip=10.0.0.10&preferred-ipv6=2001%3Adb8%3A%3A10&computer=metalklesk"
);
}
#[test]
fn gateway_token_omits_empty_optional_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument></argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>-1</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument></argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>(null)</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&portal=vpn.example.com&user=alice&computer=metalklesk"
);
}
}
+1 -136
View File
@@ -1,10 +1,9 @@
mod login;
mod parse_gateways;
pub mod session;
pub mod hip;
pub use login::*;
pub(crate) use parse_gateways::*;
pub use session::*;
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -22,119 +21,10 @@ pub(crate) struct PriorityRule {
pub struct Gateway {
pub(crate) name: String,
pub(crate) address: String,
#[serde(default)]
pub(crate) kind: GatewayKind,
pub(crate) priority: u32,
pub(crate) priority_rules: Vec<PriorityRule>,
}
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewayKind {
Internal,
External,
}
impl GatewayKind {
pub fn as_login_param(self) -> &'static str {
match self {
GatewayKind::Internal => "yes",
GatewayKind::External => "no",
}
}
}
impl Default for GatewayKind {
fn default() -> Self {
Self::External
}
}
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewaySelection {
Auto,
Manual,
}
impl GatewaySelection {
pub fn as_login_param(self) -> &'static str {
match self {
GatewaySelection::Auto => "auto",
GatewaySelection::Manual => "manual",
}
}
}
impl Default for GatewaySelection {
fn default() -> Self {
Self::Auto
}
}
#[derive(Debug, Clone)]
pub struct GatewayLoginContext {
host: String,
name: String,
kind: GatewayKind,
selection: GatewaySelection,
connect_method: Option<String>,
client_ip: Option<String>,
}
impl GatewayLoginContext {
pub fn new(gateway: &Gateway, selection: GatewaySelection) -> Self {
let name = if gateway.name().is_empty() {
gateway.server()
} else {
gateway.name()
};
Self {
host: gateway.server().to_string(),
name: name.to_string(),
kind: gateway.kind(),
selection,
connect_method: None,
client_ip: None,
}
}
pub fn with_connect_method(mut self, connect_method: Option<&str>) -> Self {
self.connect_method = connect_method.filter(|s| !s.is_empty()).map(|s| s.to_string());
self
}
pub fn with_client_ip(mut self, client_ip: Option<String>) -> Self {
self.client_ip = client_ip.filter(|s| !s.is_empty());
self
}
pub(crate) fn host(&self) -> &str {
&self.host
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn kind(&self) -> GatewayKind {
self.kind
}
pub(crate) fn selection(&self) -> GatewaySelection {
self.selection
}
pub(crate) fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub(crate) fn client_ip(&self) -> Option<&str> {
self.client_ip.as_deref()
}
}
impl Display for Gateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.name, self.address)
@@ -146,7 +36,6 @@ impl Gateway {
Self {
name,
address,
kind: GatewayKind::External,
priority: 0,
priority_rules: vec![],
}
@@ -159,28 +48,4 @@ impl Gateway {
pub fn server(&self) -> &str {
&self.address
}
pub fn kind(&self) -> GatewayKind {
self.kind
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserializes_gateway_without_kind_as_external() {
let gateway: Gateway = serde_json::from_str(
r#"{
"name": "US East",
"address": "us-east.example.com",
"priority": 1,
"priorityRules": []
}"#,
)
.unwrap();
assert_eq!(gateway.kind(), GatewayKind::External);
}
}
+25 -87
View File
@@ -3,45 +3,54 @@ use xmltree::Element;
use crate::utils::xml::ElementExt;
use super::{Gateway, GatewayKind, PriorityRule};
use super::{Gateway, PriorityRule};
pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = element.descendant("gateways")?;
pub(crate) fn parse_gateways(root: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = root.descendant("gateways")?;
let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways...");
node_gateways
.descendant("internal")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::Internal))
node_gateways.descendant("internal").and_then(|node| node.child("list"))
} else {
None
};
let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways...");
node_gateways
.descendant("external")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::External))
node_gateways.descendant("external").and_then(|node| node.child("list"))
})?;
let (gateway_list, kind) = gateway_list;
let gateways = gateway_list
.children("entry")
.iter()
.map(|gateway_item| {
let address = gateway_item.attr("name").map(|s| s.to_string()).unwrap_or_default();
let address = gateway_item.attr("name").unwrap_or_default().to_string();
let name = gateway_item.child_text("description").unwrap_or_default();
let priority = parse_priority(gateway_item);
let priority = gateway_item
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX);
let priority_rules = gateway_item
.child("priority-rule")
.map(parse_priority_rules)
.map(|node| {
node
.children("entry")
.iter()
.map(|entry| {
let name = entry.attr("name").unwrap_or_default().to_string();
let priority: u32 = entry
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX);
PriorityRule { name, priority }
})
.collect()
})
.unwrap_or_default();
Gateway {
name,
address,
kind,
priority,
priority_rules,
}
@@ -50,74 +59,3 @@ pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option
Some(gateways)
}
fn parse_priority_rules(element: &Element) -> Vec<PriorityRule> {
element
.children("entry")
.iter()
.map(|n| {
let name = n.attr("name").map(|s| s.to_string()).unwrap_or_default();
let priority: u32 = parse_priority(n);
PriorityRule { name, priority }
})
.collect()
}
fn parse_priority(element: &Element) -> u32 {
element
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_external_gateways_marks_gateway_kind() {
let xml = r#"
<policy>
<gateways>
<external>
<list>
<entry name="us1.vpn.example.com">
<description>US_East</description>
</entry>
</list>
</external>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, false).unwrap();
assert_eq!(gateways[0].name(), "US_East");
assert_eq!(gateways[0].server(), "us1.vpn.example.com");
assert_eq!(gateways[0].kind(), GatewayKind::External);
}
#[test]
fn parse_internal_gateways_marks_gateway_kind_when_preferred() {
let xml = r#"
<policy>
<gateways>
<internal>
<list>
<entry name="internal.vpn.example.com">
<description>Internal</description>
</entry>
</list>
</internal>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, true).unwrap();
assert_eq!(gateways[0].kind(), GatewayKind::Internal);
}
}
-259
View File
@@ -1,259 +0,0 @@
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
}
}
impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone)]
pub struct SessionContext {
server: String,
portal: String,
session_args: SessionRequestArgs,
extension_auth: Option<SessionExtensionAuth>,
}
impl SessionContext {
pub fn new(server: String, portal: String, session_args: SessionRequestArgs) -> Self {
Self {
server,
portal,
session_args,
extension_auth: None,
}
}
pub fn with_extension_auth(mut self, extension_auth: SessionExtensionAuth) -> Self {
self.extension_auth = Some(extension_auth);
self
}
pub fn server(&self) -> &str {
&self.server
}
pub fn portal(&self) -> &str {
&self.portal
}
pub fn session_args(&self) -> &SessionRequestArgs {
&self.session_args
}
fn extension_auth(&self) -> Option<&SessionExtensionAuth> {
self.extension_auth.as_ref()
}
}
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let form = build_extend_session_form(ctx)?;
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
info!("Sending extend-session request");
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root, &response)?;
info!("Extend-session gateway response status: {}", status);
match status.as_str() {
"success" => Ok(()),
status => bail!("Extend session rejected: {status}"),
}
}
async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = Client::builder();
if let Some(user_agent) = args.user_agent() {
builder = builder.user_agent(user_agent);
}
if let Some(cert) = args.certificate() {
info!("Using client certificate authentication...");
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
builder = builder.identity(identity);
}
Ok(builder.build()?)
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<String, String>> {
let mut form = parse_cookie_form(ctx.session_args())?;
form.insert("portal".to_string(), ctx.portal().to_string());
form.insert("timestamp".to_string(), unix_timestamp().to_string());
form.insert("message".to_string(), EXTEND_SESSION_MESSAGE.to_string());
form.insert("comment".to_string(), EXTEND_SESSION_COMMENT.to_string());
Ok(form)
}
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
match root.attr("status") {
Some(status) => Ok(status.to_string()),
None => {
warn!("Malformed extend-session response body: {}", response.trim());
bail!("Malformed extend session response")
}
}
}
fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
mod tests {
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
session::SessionRequestArgs,
};
use super::*;
fn build_session_args() -> SessionRequestArgs {
let profile = OsProfile::builder(ClientOs::Mac)
.host_identity(HostIdentity::new(
"test-mac".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.client_version("6.3.1-12".to_string())
.build();
SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_user_agent(profile.user_agent().to_string())
.with_disable_ipv6(true)
}
#[test]
fn active_session_context_preserves_connect_args_for_extension() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = parse_cookie_form(ctx.session_args()).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("vpn.example.com"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
assert_eq!(form.get("preferred-ip").map(String::as_str), Some("10.0.0.10"));
}
#[test]
fn builds_extend_session_form() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = build_extend_session_form(&ctx).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("portal.example.com"));
assert_eq!(form.get("message").map(String::as_str), Some(EXTEND_SESSION_MESSAGE));
assert_eq!(form.get("comment").map(String::as_str), Some(EXTEND_SESSION_COMMENT));
assert!(form.contains_key("timestamp"));
}
#[test]
fn parses_extend_session_status_attribute() {
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
}
#[test]
fn rejects_extend_session_response_without_status() {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
"Malformed extend session response"
);
}
#[test]
fn rejects_extension_login_mfa_challenge() {
assert_eq!(
validate_extension_login(GatewayLogin::Mfa("MFA required".to_string(), "input".to_string()))
.unwrap_err()
.to_string(),
"Session extension requires an interactive gateway challenge"
);
}
}
+129 -414
View File
@@ -1,59 +1,69 @@
use std::collections::HashMap;
use log::info;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::create_identity,
};
use crate::{utils::request::create_identity, GP_USER_AGENT};
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
#[serde(rename_all = "lowercase")]
pub enum CscMode {
#[derive(Debug, Serialize, Deserialize, Clone, Type, Default)]
pub enum ClientOs {
#[default]
Auto,
Yes,
No,
Linux,
Windows,
Mac,
}
impl CscMode {
pub fn effective(self, client_os: ClientOs) -> bool {
match self {
CscMode::Auto => client_os.default_csc_support(),
CscMode::Yes => true,
CscMode::No => false,
}
}
pub fn as_str(self) -> &'static str {
match self {
CscMode::Auto => "auto",
CscMode::Yes => "yes",
CscMode::No => "no",
impl From<&str> for ClientOs {
fn from(os: &str) -> Self {
match os {
"Linux" => ClientOs::Linux,
"Windows" => ClientOs::Windows,
"Mac" => ClientOs::Mac,
_ => ClientOs::Linux,
}
}
}
#[derive(Debug, Clone)]
impl ClientOs {
pub fn as_str(&self) -> &str {
match self {
ClientOs::Linux => "Linux",
ClientOs::Windows => "Windows",
ClientOs::Mac => "Mac",
}
}
pub fn to_openconnect_os(&self) -> &str {
match self {
ClientOs::Linux => "linux",
ClientOs::Windows => "win",
ClientOs::Mac => "mac-intel",
}
}
}
#[derive(Debug, Serialize, Deserialize, Type, Default, Clone)]
pub struct GpParams {
os_profile: OsProfile,
// Transport
is_gateway: bool,
user_agent: String,
client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
ignore_tls_errors: bool,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
// Feature
csc_mode: CscMode,
// Per-request state
is_gateway: bool,
// Used for MFA
input_str: Option<String>,
otp: Option<String>,
}
impl GpParams {
pub fn builder(os_profile: OsProfile) -> GpParamsBuilder {
GpParamsBuilder::new(os_profile)
pub fn builder() -> GpParamsBuilder {
GpParamsBuilder::new()
}
pub(crate) fn is_gateway(&self) -> bool {
@@ -65,63 +75,27 @@ impl GpParams {
}
pub(crate) fn user_agent(&self) -> &str {
self.os_profile.user_agent()
&self.user_agent
}
pub(crate) fn computer(&self) -> &str {
&self.computer
}
pub fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
// ─── OsProfile accessor ─────────────────────────────────────────────────
pub fn os_profile(&self) -> &OsProfile {
&self.os_profile
}
// ─── Delegated identity accessors ────────────────────────────────────────
pub fn client_os(&self) -> &str {
self.os_profile.client_os().as_str()
}
pub(crate) fn computer(&self) -> &str {
self.os_profile.computer()
self.client_os.as_str()
}
pub fn os_version(&self) -> Option<&str> {
Some(self.os_profile.os_version())
self.os_version.as_deref()
}
pub fn client_version(&self) -> Option<&str> {
Some(self.os_profile.client_version())
}
pub(crate) fn host_id(&self) -> &str {
self.os_profile.host_id()
}
pub(crate) fn serialno(&self) -> &str {
self.os_profile.serialno()
}
pub fn host_identity(&self) -> &HostIdentity {
self.os_profile.host_identity()
}
// ─── Feature accessors ──────────────────────────────────────────────────
pub(crate) fn effective_csc_support(&self) -> bool {
self.csc_mode.effective(self.os_profile.client_os())
}
pub fn csc_mode(&self) -> CscMode {
self.csc_mode
}
// ─── Per-request state ──────────────────────────────────────────────────
pub(crate) fn input_str(&self) -> Option<&str> {
self.input_str.as_deref()
self.client_version.as_deref()
}
pub fn set_input_str(&mut self, input_str: &str) {
@@ -132,15 +106,46 @@ impl GpParams {
self.otp = Some(otp.to_string());
}
pub(crate) fn otp(&self) -> Option<&str> {
self.otp.as_deref()
pub(crate) fn to_params(&self) -> HashMap<&str, &str> {
let mut params: HashMap<&str, &str> = HashMap::new();
let client_os = self.client_os.as_str();
// Common params
params.insert("prot", "https:");
params.insert("jnlpReady", "jnlpReady");
params.insert("ok", "Login");
params.insert("direct", "yes");
params.insert("ipv6-support", "yes");
params.insert("clientVer", "4100");
params.insert("clientos", client_os);
params.insert("computer", &self.computer);
// MFA
params.insert("inputStr", self.input_str.as_deref().unwrap_or_default());
if let Some(otp) = &self.otp {
params.insert("passwd", otp);
}
if let Some(os_version) = &self.os_version {
params.insert("os-version", os_version);
}
// NOTE: Do not include clientgpversion for now
// if let Some(client_version) = &self.client_version {
// params.insert("clientgpversion", client_version);
// }
params
}
}
pub struct GpParamsBuilder {
is_gateway: bool,
os_profile: OsProfile,
csc_mode: CscMode,
user_agent: String,
client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
ignore_tls_errors: bool,
certificate: Option<String>,
sslkey: Option<String>,
@@ -148,11 +153,16 @@ pub struct GpParamsBuilder {
}
impl GpParamsBuilder {
pub fn new(os_profile: OsProfile) -> Self {
pub fn new() -> Self {
let computer = whoami::fallible::hostname().unwrap_or_else(|_| String::from("localhost"));
Self {
is_gateway: false,
os_profile,
csc_mode: Default::default(),
user_agent: GP_USER_AGENT.to_string(),
client_os: ClientOs::Linux,
os_version: Default::default(),
client_version: Default::default(),
computer,
ignore_tls_errors: false,
certificate: Default::default(),
sslkey: Default::default(),
@@ -165,8 +175,28 @@ impl GpParamsBuilder {
self
}
pub fn csc_mode(&mut self, csc_mode: CscMode) -> &mut Self {
self.csc_mode = csc_mode;
pub fn user_agent(&mut self, user_agent: &str) -> &mut Self {
self.user_agent = user_agent.to_string();
self
}
pub fn client_os(&mut self, client_os: ClientOs) -> &mut Self {
self.client_os = client_os;
self
}
pub fn os_version<T: Into<Option<String>>>(&mut self, os_version: T) -> &mut Self {
self.os_version = os_version.into();
self
}
pub fn client_version<T: Into<Option<String>>>(&mut self, client_version: T) -> &mut Self {
self.client_version = client_version.into();
self
}
pub fn computer(&mut self, computer: &str) -> &mut Self {
self.computer = computer.to_string();
self
}
@@ -192,26 +222,35 @@ impl GpParamsBuilder {
pub fn build(&self) -> GpParams {
GpParams {
os_profile: self.os_profile.clone(),
is_gateway: self.is_gateway,
user_agent: self.user_agent.clone(),
client_os: self.client_os.clone(),
os_version: self.os_version.clone(),
client_version: self.client_version.clone(),
computer: self.computer.clone(),
ignore_tls_errors: self.ignore_tls_errors,
certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(),
csc_mode: self.csc_mode,
is_gateway: self.is_gateway,
input_str: Default::default(),
otp: Default::default(),
}
}
}
impl Default for GpParamsBuilder {
fn default() -> Self {
Self::new()
}
}
impl TryFrom<&GpParams> for Client {
type Error = anyhow::Error;
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
let mut builder = Client::builder()
.danger_accept_invalid_certs(value.ignore_tls_errors)
.user_agent(value.user_agent());
.user_agent(&value.user_agent);
if let Some(cert) = value.certificate.as_deref() {
info!("Using client certificate authentication...");
@@ -223,327 +262,3 @@ impl TryFrom<&GpParams> for Client {
Ok(client)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::runtime_client_os;
fn profile(client_os: ClientOs) -> OsProfile {
OsProfile::builder(client_os).build()
}
#[test]
fn default_client_versions_match_observed_official_clients() {
assert_eq!(ClientOs::Linux.default_client_version(), "6.3.3-619");
assert_eq!(ClientOs::Windows.default_client_version(), "6.3.3-650");
assert_eq!(ClientOs::Mac.default_client_version(), "6.3.3-915");
}
#[test]
fn builder_uses_os_profile_client_version_when_unspecified() {
let params = GpParams::builder(profile(ClientOs::Mac)).build();
assert_eq!(params.client_version(), Some("6.3.3-915"));
}
#[test]
fn builder_keeps_explicit_client_version() {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.2.9-1".to_string())
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.client_version(), Some("6.2.9-1"));
}
#[test]
fn builder_uses_os_profile_version_when_unspecified() {
let params = GpParams::builder(profile(ClientOs::Mac)).build();
let default_os_version = ClientOs::Mac.default_os_version();
assert_eq!(params.os_version(), Some(default_os_version.as_str()));
}
#[test]
fn os_profile_accessor_returns_profile() {
let params = GpParams::builder(profile(ClientOs::Linux)).build();
let profile = params.os_profile();
assert_eq!(profile.client_os(), ClientOs::Linux);
}
#[test]
fn delegates_identity_to_os_profile() {
let identity = HostIdentity::new(
"test-computer".to_string(),
"test-host-id".to_string(),
"test-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).host_identity(identity).build()).build();
assert!(!params.host_id().is_empty());
assert_eq!(params.host_identity().host_id(), "test-host-id");
assert_eq!(params.host_identity().serialno(), "test-serial");
assert_eq!(params.host_identity().mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn builder_accepts_pre_built_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyMac")
.build();
let expected_os_version = profile.os_version().to_string();
let params = GpParams::builder(profile).build();
assert_eq!(params.computer(), "MyMac");
assert_eq!(params.os_version(), Some(expected_os_version.as_str()));
assert_eq!(params.client_os(), "Mac");
}
// ─── Delegation tests (Requirement 4.1) ──────────────────────────────────
#[test]
fn delegates_computer_to_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyComputer")
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.computer(), "MyComputer");
assert_eq!(params.computer(), params.os_profile().computer());
}
#[test]
fn delegates_client_os_string_to_os_profile() {
let params = GpParams::builder(profile(ClientOs::Windows)).build();
assert_eq!(params.client_os(), "Windows");
assert_eq!(params.client_os(), params.os_profile().client_os().as_str());
}
#[test]
fn delegates_host_identity_to_os_profile() {
let identity = HostIdentity::new(
"delegated-computer".to_string(),
"delegated-host".to_string(),
"delegated-serial".to_string(),
"01:02:03:04:05:06".to_string(),
);
let params = GpParams::builder(
OsProfile::builder(ClientOs::Linux)
.host_identity(identity.clone())
.build(),
)
.build();
// The accessor returns the same HostIdentity stored on the inner OsProfile
assert_eq!(params.host_identity(), params.os_profile().host_identity());
assert_eq!(params.host_identity().host_id(), "delegated-host");
assert_eq!(params.host_identity().serialno(), "delegated-serial");
assert_eq!(params.host_identity().mac_addr(), "01:02:03:04:05:06");
}
// ─── Builder constructs OsProfile from individual fields (Req 4.1) ───────
#[test]
fn builder_uses_provided_os_profile() {
let identity = HostIdentity::new(
"identity-host".to_string(),
"host-7".to_string(),
"serial-7".to_string(),
"aa:bb:cc:11:22:33".to_string(),
);
let profile = OsProfile::builder(ClientOs::Linux)
.computer_name_override("linux-host")
.client_version("6.0.0-1".to_string())
.host_identity(identity)
.build();
let params = GpParams::builder(profile).build();
let profile = params.os_profile();
assert_eq!(profile.client_os(), ClientOs::Linux);
assert_eq!(profile.computer(), "linux-host");
assert_eq!(profile.os_version(), ClientOs::Linux.default_os_version());
assert_eq!(profile.client_version(), "6.0.0-1");
assert_eq!(profile.host_identity().host_id(), "host-7");
assert_eq!(profile.host_identity().serialno(), "serial-7");
assert_eq!(profile.host_identity().mac_addr(), "aa:bb:cc:11:22:33");
assert!(!profile.host_id().is_empty());
assert!(!profile.serialno().is_empty());
assert!(!profile.mac_addr().is_empty());
}
// ─── TryFrom<&GpParams> for Client (Requirement 4.7) ─────────────────────
#[test]
fn try_from_gp_params_constructs_reqwest_client() {
let params = GpParams::builder(profile(runtime_client_os())).build();
let client = Client::try_from(&params);
assert!(client.is_ok(), "Client construction should succeed with default params");
}
#[test]
fn try_from_gp_params_with_ignore_tls_errors() {
let params = GpParams::builder(profile(runtime_client_os()))
.ignore_tls_errors(true)
.build();
let client = Client::try_from(&params);
assert!(
client.is_ok(),
"Client should construct successfully with ignore_tls_errors enabled"
);
}
#[test]
fn try_from_gp_params_with_custom_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
.user_agent("custom-agent/1.0")
.build(),
)
.build();
let client = Client::try_from(&params);
assert!(client.is_ok(), "Client should construct with a custom user agent");
}
#[test]
fn try_from_gp_params_with_invalid_certificate_returns_error() {
// When a certificate path is provided but the file does not exist or is malformed,
// Client construction should fail rather than silently succeed.
let params = GpParams::builder(profile(runtime_client_os()))
.certificate("/nonexistent/path/to/cert.pem".to_string())
.build();
let client = Client::try_from(&params);
assert!(
client.is_err(),
"Client construction should fail when certificate path is invalid"
);
}
// ─── User Agent Delegation Tests (Requirements 3.2, 3.3, 3.4, 3.5, 3.6) ──
#[test]
fn user_agent_delegates_to_os_profile_for_default_build() {
let params = GpParams::builder(profile(runtime_client_os())).build();
assert_eq!(
params.user_agent(),
params.os_profile().user_agent(),
"GpParams::user_agent() should delegate to os_profile().user_agent()"
);
}
#[test]
fn builder_uses_profile_user_agent() {
let params = GpParams::builder(OsProfile::builder(runtime_client_os()).user_agent("custom").build()).build();
assert_eq!(params.user_agent(), "custom");
}
#[test]
fn builder_os_profile_without_user_agent_delegates_to_profile() {
let profile = OsProfile::builder(ClientOs::Mac).client_version("6.1.0").build();
let expected_ua = profile.user_agent().to_string();
let params = GpParams::builder(profile).build();
assert_eq!(params.user_agent(), expected_ua);
}
#[test]
fn profile_user_agent_override_wins_before_gp_params_construction() {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.1.0")
.user_agent("override")
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.user_agent(), "override");
}
#[test]
fn try_from_gp_params_succeeds_with_delegated_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
.user_agent("delegated-agent/2.0")
.build(),
)
.build();
let client = Client::try_from(&params);
assert!(
client.is_ok(),
"TryFrom<&GpParams> for Client should succeed with delegated user_agent"
);
}
// ─── Property-Based Tests ─────────────────────────────────────────────────
mod prop_tests {
use super::*;
use proptest::prelude::*;
fn arb_client_os() -> impl Strategy<Value = ClientOs> {
prop_oneof![Just(ClientOs::Linux), Just(ClientOs::Windows), Just(ClientOs::Mac),]
}
// **Validates: Requirements 3.2, 3.4**
//
// Property 4: GpParams delegates user_agent to OsProfile
// For any GpParams instance (whether built from individual fields or from a
// pre-built OsProfile, with or without a user_agent override),
// gp_params.user_agent() == gp_params.os_profile().user_agent().
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
#[test]
fn gp_params_delegates_user_agent_to_os_profile(
client_os in arb_client_os(),
user_agent_override in proptest::option::of("[a-zA-Z0-9/_.-]{1,30}"),
) {
let identity = HostIdentity::new(
"prop-computer".to_string(),
"prop-host".to_string(),
"prop-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let mut profile_builder = OsProfile::builder(client_os)
.client_version("6.1.0-1")
.computer_name_override("test-host")
.host_identity(identity);
if let Some(ref ua) = user_agent_override {
profile_builder = profile_builder.user_agent(ua);
}
let params = GpParams::builder(profile_builder.build()).build();
prop_assert_eq!(
params.user_agent(),
params.os_profile().user_agent(),
"GpParams::user_agent() must always equal GpParams::os_profile().user_agent()"
);
}
}
// **Validates: Requirements 3.3**
//
// Property 5: GpParams uses the user agent from OsProfile.
// For any non-empty string set via OsProfileBuilder::user_agent(), the resulting
// GpParams::user_agent() returns that override value.
proptest! {
#[test]
fn builder_uses_profile_user_agent(ua in "[^\\s]{1,50}") {
let profile = OsProfile::builder(runtime_client_os()).user_agent(&ua).build();
let params = GpParams::builder(profile).build();
prop_assert_eq!(params.user_agent(), ua.as_str());
}
}
}
}
+25 -7
View File
@@ -1,22 +1,40 @@
pub mod auth;
pub mod cookie_store;
pub mod credential;
pub mod error;
pub mod gateway;
pub mod gp_params;
pub mod os_profile;
pub mod params;
pub mod portal;
pub mod process;
pub mod service;
pub mod session;
pub mod utils;
#[cfg(feature = "logger")]
pub mod logger;
#[cfg(feature = "clap")]
pub mod clap;
#[cfg(debug_assertions)]
pub const GP_API_KEY: &[u8; 32] = &[0; 32];
pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
#[cfg(not(debug_assertions))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
#[cfg(not(debug_assertions))]
pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
#[cfg(not(debug_assertions))]
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
#[cfg(not(debug_assertions))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/bin/gpgui-helper";
#[cfg(not(debug_assertions))]
pub(crate) const GP_AUTH_BINARY: &str = "/usr/bin/gpauth";
#[cfg(debug_assertions)]
pub const GP_CLIENT_BINARY: &str = env!("GP_CLIENT_BINARY");
#[cfg(debug_assertions)]
pub const GP_SERVICE_BINARY: &str = env!("GP_SERVICE_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_BINARY: &str = env!("GP_GUI_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_HELPER_BINARY: &str = env!("GP_GUI_HELPER_BINARY");
#[cfg(debug_assertions)]
pub(crate) const GP_AUTH_BINARY: &str = env!("GP_AUTH_BINARY");
-44
View File
@@ -1,44 +0,0 @@
use std::sync::OnceLock;
use anyhow::bail;
use env_logger::Logger;
use log::{Level, warn};
use log_reload::{ReloadHandle, ReloadLog};
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
pub fn init(level: Level) {
// Initialize the env_logger and global max level to trace, the logs will be
// filtered by the outer logger
let logger = env_logger::builder().filter_level(log::LevelFilter::Trace).build();
init_with_logger(level, logger);
}
pub fn init_with_logger(level: Level, logger: Logger) {
if let Some(_) = LOG_HANDLE.get() {
warn!("Logger already initialized");
return;
}
log::set_max_level(log::LevelFilter::Trace);
// Create a new logger that will filter the logs based on the max level
let level_filter_logger = log_reload::LevelFilter::new(level, logger);
let reload_log = ReloadLog::new(level_filter_logger);
let handle = reload_log.handle();
// Register the logger to be used by the log crate
let _ = log::set_boxed_logger(Box::new(reload_log));
let _ = LOG_HANDLE.set(handle);
}
pub fn set_max_level(level: Level) -> anyhow::Result<()> {
let Some(handle) = LOG_HANDLE.get() else {
bail!("Logger not initialized")
};
handle
.modify(|logger| logger.set_level(level))
.map_err(|e| anyhow::anyhow!(e))
}
@@ -1,581 +0,0 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use super::{ClientOs, serial_number};
use platform::RuntimeNativeHostIdentity;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostIdentity {
computer: String,
host_id: String,
#[serde(rename = "serialno")]
serial_number: String,
#[serde(rename = "macAddr")]
mac_address: String,
}
impl HostIdentity {
pub fn collect() -> Self {
Self::collect_with_host_id(None)
}
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
}
#[cfg(test)]
pub(crate) fn new(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
Self::from_parts(computer, host_id, serialno, mac_addr)
}
pub(crate) fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id));
Self {
computer,
host_id,
serial_number,
mac_address,
}
}
pub fn computer(&self) -> &str {
&self.computer
}
pub fn host_id(&self) -> &str {
&self.host_id
}
pub fn serialno(&self) -> &str {
&self.serial_number
}
pub fn mac_addr(&self) -> &str {
&self.mac_address
}
pub fn with_computer(mut self, computer: String) -> Self {
if !computer.trim().is_empty() {
self.computer = computer;
}
self
}
pub(crate) fn runtime_os() -> ClientOs {
RuntimeNativeHostIdentity::runtime_os()
}
}
pub(super) fn fallback_hostname() -> String {
whoami::hostname().unwrap_or_else(|_| String::from("localhost"))
}
#[derive(Debug, Clone)]
struct NativeHostIdentitySnapshot {
host_id: String,
computer: String,
serial_number: Option<String>,
mac_address: Option<String>,
}
impl NativeHostIdentitySnapshot {
fn into_host_identity(self) -> HostIdentity {
let host_id = non_empty(self.host_id, fallback_host_id());
HostIdentity::from_parts(
self.computer,
host_id.clone(),
self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)),
self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)),
)
}
}
fn non_empty(value: String, fallback: String) -> String {
if value.trim().is_empty() { fallback } else { value }
}
fn fallback_host_id() -> String {
derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"])
}
fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String {
host_id_override
.filter(|value| !value.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(collect)
}
fn derive_serial_number(host_id: &str) -> String {
serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| {
let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]);
serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial")
})
}
fn derive_mac_address(host_id: &str) -> String {
let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
bytes.join(":")
}
fn normalize_mac_colon(value: &str) -> Option<String> {
let compact = value
.trim()
.replace('-', ":")
.split(':')
.map(|part| part.to_lowercase())
.collect::<Vec<_>>();
let valid = compact.len() == 6
&& compact
.iter()
.all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit()));
valid.then(|| compact.join(":"))
}
fn primary_mac_colon() -> Option<String> {
netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.and_then(|mac| normalize_mac_colon(&mac))
}
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
#[cfg(target_os = "macos")]
mod platform {
use std::process::Command;
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
primary_mac_colon, resolve_host_id,
};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Mac
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
NativeHostIdentitySnapshot {
host_id,
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
serial_number: collect_macos_serial_number(),
mac_address: native_mac,
}
}
}
fn macos_computer_name() -> Option<String> {
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
let output = Command::new("scutil").args(["--get", name]).output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
})
}
fn macos_builtin_mac() -> Option<String> {
macos_networksetup_mac("Wi-Fi")
.or_else(|| macos_networksetup_mac("AirPort"))
.or_else(macos_system_profiler_wifi_mac)
}
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
let output = Command::new("networksetup")
.arg("-listallhardwareports")
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == port_name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac() -> Option<String> {
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
})
}
}
#[cfg(target_os = "windows")]
mod platform {
use std::process::Command;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Windows
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_windows_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
windows_machine_seed().unwrap_or_else(fallback_hostname)
}
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "UUID")
.map(str::to_string)
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
parts.last().map(str::to_string)
})
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod platform {
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
};
use log::debug;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Linux
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_linux_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
if let Some(host_id) = collect_linux_product_uuid() {
debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id);
return host_id;
}
let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| {
let hostname = fallback_hostname();
("hostname", hostname)
});
let host_id = derive_uuid_from_seed(&source, &[]);
debug!("Runtime host-id source: derived from {} ({})", source_name, host_id);
host_id
}
}
fn collect_linux_product_uuid() -> Option<String> {
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
}
fn normalize_uuid(value: &str) -> Option<String> {
uuid::Uuid::parse_str(value.trim())
.ok()
.map(|uuid| uuid.hyphenated().to_string())
}
fn collect_linux_fallback_seed() -> Option<(&'static str, String)> {
["/etc/machine-id", "/var/lib/dbus/machine-id"]
.iter()
.find_map(|path| read_linux_identity_file(path).map(|value| (*path, value)))
}
fn read_linux_identity_file(path: &str) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| is_usable_linux_identity_value(value))
}
fn is_usable_linux_identity_value(value: &str) -> bool {
!value.is_empty() && value != "None" && value != "To Be Filled By O.E.M."
}
fn collect_linux_serial_number() -> Option<String> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.iter()
.find_map(|path| read_linux_identity_file(path))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_uuid_preserves_real_uuid_identity() {
assert_eq!(
normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"),
Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string())
);
assert_eq!(normalize_uuid("not-a-uuid"), None);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collect_produces_non_empty_identity() {
let identity = HostIdentity::collect();
assert!(!identity.computer().is_empty());
assert!(!identity.host_id().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn collect_with_host_id_uses_provided_host_id() {
let identity = HostIdentity::collect_with_host_id(Some("provided-host-id"));
assert_eq!(identity.host_id(), "provided-host-id");
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
#[test]
fn collect_with_blank_host_id_falls_back_to_runtime_host_id() {
let identity = HostIdentity::collect_with_host_id(Some(" "));
assert!(!identity.host_id().is_empty());
assert_ne!(identity.host_id(), " ");
}
#[test]
fn resolve_host_id_does_not_collect_when_override_is_provided() {
let host_id = resolve_host_id(Some("provided-host-id"), || {
panic!("runtime host id should not be collected")
});
assert_eq!(host_id, "provided-host-id");
}
#[test]
fn host_identity_normalizes_mac_to_lowercase_colon_format() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"AA-BB-CC-DD-EE-FF".to_string(),
);
assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native = RuntimeNativeHostIdentity::collect(None);
assert!(!native.host_id.is_empty());
}
#[test]
fn serialization_keeps_globalprotect_field_names() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let value = serde_json::to_value(identity).unwrap();
assert_eq!(value["hostId"], "host-id");
assert_eq!(value["computer"], "computer");
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert_eq!(value["serialno"], "serial-number");
assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_identity_falls_back_to_derived_values_when_missing() {
let native = NativeHostIdentitySnapshot {
host_id: "native-host-id".to_string(),
computer: "native-computer".to_string(),
serial_number: None,
mac_address: None,
};
let identity = native.into_host_identity();
assert_eq!(identity.computer(), "native-computer");
assert_eq!(identity.host_id(), "native-host-id");
assert!(identity.serialno().starts_with("VMware-"));
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() {
let identity = HostIdentity::new(
"computer".to_string(),
"5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(),
String::new(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
assert_eq!(
identity.serialno(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn empty_host_id_falls_back_to_non_empty_value() {
let identity = HostIdentity::new(String::new(), String::new(), String::new(), String::new());
assert!(!identity.host_id().is_empty());
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
fn assert_mac(value: &str, separator: char) {
let parts: Vec<&str> = value.split(separator).collect();
assert_eq!(parts.len(), 6, "MAC should have 6 octets");
for part in &parts {
assert_eq!(part.len(), 2);
assert!(part.chars().all(|c| c.is_ascii_hexdigit()));
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,78 +0,0 @@
pub(super) fn vmware_from_uuid(uuid: &str) -> Option<String> {
let parts: Vec<&str> = uuid.split('-').collect();
if parts.len() != 5
|| parts[0].len() != 8
|| parts[1].len() != 4
|| parts[2].len() != 4
|| parts[3].len() != 4
|| parts[4].len() != 12
|| !parts.iter().all(|part| part.chars().all(|ch| ch.is_ascii_hexdigit()))
{
return None;
}
let compact = [
reverse_hex_bytes(parts[0]),
reverse_hex_bytes(parts[1]),
reverse_hex_bytes(parts[2]),
parts[3].to_lowercase(),
parts[4].to_lowercase(),
]
.concat();
vmware_from_compact_hex(&compact)
}
pub(super) fn vmware_from_compact_hex(compact: &str) -> Option<String> {
let compact = compact.trim().to_lowercase();
if compact.len() != 32 || !compact.chars().all(|ch| ch.is_ascii_hexdigit()) {
return None;
}
Some(format!(
"VMware-{} {} {} {} {} {} {} {}-{} {} {} {} {} {} {} {}",
&compact[0..2],
&compact[2..4],
&compact[4..6],
&compact[6..8],
&compact[8..10],
&compact[10..12],
&compact[12..14],
&compact[14..16],
&compact[16..18],
&compact[18..20],
&compact[20..22],
&compact[22..24],
&compact[24..26],
&compact[26..28],
&compact[28..30],
&compact[30..32]
))
}
fn reverse_hex_bytes(value: &str) -> String {
value
.as_bytes()
.chunks(2)
.rev()
.map(|chunk| std::str::from_utf8(chunk).unwrap_or_default().to_lowercase())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vmware_serial_from_uuid_uses_smbios_byte_order() {
assert_eq!(
vmware_from_uuid("5a784d56-6461-19ac-9ea9-d36a3b9c6cef").unwrap(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn invalid_uuid_is_rejected() {
assert_eq!(vmware_from_uuid("not-a-uuid"), None);
}
}
-62
View File
@@ -1,62 +0,0 @@
use crate::{credential::Credential, gp_params::GpParams};
const EMPTY_PORTAL_COOKIE: &str = "empty";
fn portal_cookie_param(value: Option<&str>) -> String {
match value {
Some(value) if !value.is_empty() => value.to_string(),
_ => EMPTY_PORTAL_COOKIE.to_string(),
}
}
pub(crate) fn build(cred: &Credential, gp_params: &GpParams) -> Vec<(String, String)> {
let mut params = Vec::new();
params.push(("user".to_string(), cred.username().to_string()));
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match cred {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (
Some(gp_params.os_profile().saml_password()),
cred.prelogin_cookie(),
cred.portal_userauthcookie(),
None,
cred.token(),
),
Credential::AuthCookie(cred) => (
Some(
cred
.password()
.unwrap_or_else(|| gp_params.os_profile().saml_password()),
),
None,
Some(cred.user_auth_cookie()),
Some(cred.prelogon_user_auth_cookie()),
None,
),
Credential::Cached(cred) => (
cred.password(),
None,
cred.auth_cookie().map(|cred| cred.user_auth_cookie()),
cred.auth_cookie().map(|cred| cred.prelogon_user_auth_cookie()),
None,
),
};
params.push(("passwd".to_string(), passwd.unwrap_or_default().to_string()));
params.push((
"prelogin-cookie".to_string(),
prelogin_cookie.unwrap_or_default().to_string(),
));
params.push((
"portal-userauthcookie".to_string(),
portal_cookie_param(portal_userauthcookie),
));
params.push((
"portal-prelogonuserauthcookie".to_string(),
portal_cookie_param(portal_prelogonuserauthcookie),
));
params.push(("token".to_string(), token.unwrap_or_default().to_string()));
params
}
-487
View File
@@ -1,487 +0,0 @@
use std::net::ToSocketAddrs;
use super::{RequestParams, credential as credential_params};
use crate::{credential::Credential, gateway::GatewayLoginContext, gp_params::GpParams};
/// Inputs required to build gateway login request parameters.
pub(crate) struct GatewayLoginInput<'a> {
pub gp_params: &'a GpParams,
pub cred: &'a Credential,
pub gateway_host: &'a str,
pub context: Option<&'a GatewayLoginContext>,
pub client_ip: Option<&'a str>,
pub extend_lifetime: bool,
}
/// Build request parameters for the gateway login endpoint.
///
/// Resolves the `server` parameter to an IPv4 address when
/// `profile.gateway_server_uses_resolved_ipv4()` is true.
/// Sets `gw` and `gateway-name` to the gateway FQDN.
pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams {
let profile = input.gp_params.os_profile();
let mut body: Vec<(String, String)> = Vec::new();
// Credential params (user, passwd, prelogin-cookie, portal-userauthcookie, etc.)
body.extend(credential_params::build(input.cred, input.gp_params));
// Common login params
body.push(("prot".into(), "https:".into()));
body.push(("jnlpReady".into(), "jnlpReady".into()));
body.push(("ok".into(), "Login".into()));
body.push(("direct".into(), "yes".into()));
body.push(("ipv6-support".into(), "yes".into()));
body.push(("clientVer".into(), "4100".into()));
body.push(("clientos".into(), profile.client_os().as_str().into()));
body.push(("computer".into(), profile.computer().into()));
body.push((
"inputStr".into(),
input.gp_params.input_str().unwrap_or_default().into(),
));
if let Some(otp) = input.gp_params.otp() {
body.push(("passwd".into(), otp.into()));
}
if let Some(os_version) = input.gp_params.os_version() {
body.push(("os-version".into(), os_version.into()));
}
// Server — resolve to IPv4 when profile requires it
let server = resolve_server(input);
body.push(("server".into(), server));
// Identity fields
body.push(("host-id".into(), profile.host_id().into()));
body.push(("serialno".into(), profile.serialno().into()));
body.push(("preferred-ip".into(), String::new()));
body.push(("preferred-ipv6".into(), String::new()));
// Client version
if let Some(client_version) = input.gp_params.client_version() {
body.push(("clientgpversion".into(), client_version.to_string()));
}
// Context-dependent fields
if let Some(context) = input.context {
let gateway_host = context.host().to_string();
body.push(("host".into(), gateway_host.clone()));
body.push(("gw".into(), gateway_host.clone()));
body.push(("gateway-name".into(), gateway_host));
body.push(("internal".into(), context.kind().as_login_param().to_string()));
body.push((
"selection-type".into(),
context.selection().as_login_param().to_string(),
));
body.push(("client-ipv6".into(), String::new()));
if let Some(connect_method) = context.connect_method() {
body.push(("connect-method".into(), connect_method.to_string()));
}
if let Some(client_version) = input.gp_params.client_version() {
// Ensure clientgpversion is set in the context block (override earlier value if present)
if let Some(pos) = body.iter().position(|(k, _)| k == "clientgpversion") {
body[pos].1 = client_version.to_string();
} else {
body.push(("clientgpversion".into(), client_version.to_string()));
}
}
if let Some(client_ip) = input.client_ip {
body.push(("client-ip".into(), client_ip.to_string()));
}
}
// Extend lifetime
if input.extend_lifetime {
body.push(("extend-lifetime".into(), "true".into()));
}
RequestParams { body, query: vec![] }
}
/// Resolve the gateway server to an IPv4 address if the profile requires it.
///
/// Falls back to the original gateway host if resolution fails.
fn resolve_server(input: &GatewayLoginInput) -> String {
if !input.gp_params.os_profile().gateway_server_uses_resolved_ipv4() {
return input.gateway_host.to_string();
}
if let Some(context) = input.context {
resolve_to_ipv4(context.host()).unwrap_or_else(|| input.gateway_host.to_string())
} else {
input.gateway_host.to_string()
}
}
/// Attempt DNS resolution of a hostname to its first IPv4 address.
fn resolve_to_ipv4(host: &str) -> Option<String> {
(host, 443)
.to_socket_addrs()
.ok()?
.find(|addr| addr.ip().is_ipv4())
.map(|addr| addr.ip().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
credential::{AuthCookieCredential, PasswordCredential},
gateway::{Gateway, GatewayKind, GatewaySelection},
os_profile::{ClientOs, HostIdentity, OsProfile},
};
fn test_identity() -> HostIdentity {
HostIdentity::new(
"test-computer".to_string(),
"host-id-123".to_string(),
"serial-456".to_string(),
"aa-bb-cc-dd-ee-ff".to_string(),
)
}
fn test_profile(os: ClientOs) -> OsProfile {
OsProfile::builder(os).host_identity(test_identity()).build()
}
fn make_gp_params() -> GpParams {
GpParams::builder(test_profile(ClientOs::Linux)).build()
}
fn make_credential() -> Credential {
Credential::Password(PasswordCredential::new("alice", "secret"))
}
#[test]
fn build_without_context_includes_identity_fields() {
let profile = test_profile(ClientOs::Linux);
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("host-id"), Some(profile.host_id()));
assert_eq!(find("serialno"), Some(profile.serialno()));
assert_eq!(find("preferred-ip"), Some(""));
assert_eq!(find("preferred-ipv6"), Some(""));
assert_eq!(find("token"), Some(""));
assert_eq!(find("server"), Some("vpn.example.com"));
}
#[test]
fn build_without_context_excludes_context_fields() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let has_key = |key: &str| result.body.iter().any(|(k, _)| k == key);
assert!(!has_key("host"));
assert!(!has_key("gw"));
assert!(!has_key("gateway-name"));
assert!(!has_key("internal"));
assert!(!has_key("selection-type"));
assert!(!has_key("connect-method"));
assert!(!has_key("client-ip"));
assert!(!has_key("client-ipv6"));
}
#[test]
fn build_with_context_includes_gateway_fqdn() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway {
name: "US_East".to_string(),
address: "us1.vpn.example.com".to_string(),
kind: GatewayKind::External,
priority: 1,
priority_rules: vec![],
};
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "us1.vpn.example.com",
context: Some(&context),
client_ip: Some("192.168.0.10"),
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("gw"), Some("us1.vpn.example.com"));
assert_eq!(find("gateway-name"), Some("us1.vpn.example.com"));
assert_eq!(find("host"), Some("us1.vpn.example.com"));
assert_eq!(find("internal"), Some("no"));
assert_eq!(find("selection-type"), Some("auto"));
assert_eq!(find("client-ip"), Some("192.168.0.10"));
assert_eq!(find("client-ipv6"), Some(""));
}
#[test]
fn mac_profile_uses_fqdn_for_gateway_display() {
let gp_params = GpParams::builder(test_profile(ClientOs::Mac)).build();
let cred = make_credential();
let gateway = Gateway {
name: "US_East".to_string(),
address: "us1.vpn.example.com".to_string(),
kind: GatewayKind::External,
priority: 1,
priority_rules: vec![],
};
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "us1.vpn.example.com",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("gw"), Some("us1.vpn.example.com"));
assert_eq!(find("gateway-name"), Some("us1.vpn.example.com"));
}
#[test]
fn linux_prelogin_credential_uses_profile_saml_password() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::Prelogin(crate::credential::PreloginCredential::new(
"alice",
Some("prelogin-cookie"),
None,
None,
));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some("SAMLPASS"));
}
#[test]
fn portal_auth_cookie_login_leaves_gateway_prelogin_cookie_empty() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::AuthCookie(AuthCookieCredential::new("alice", "empty", "empty"));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("passwd"), Some("SAMLPASS"));
assert_eq!(find("prelogin-cookie"), Some(""));
assert_eq!(find("portal-userauthcookie"), Some("empty"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("empty"));
}
#[test]
fn portal_auth_cookie_login_reuses_portal_password_when_available() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::AuthCookie(
AuthCookieCredential::new("alice", "portal-user-cookie", "portal-prelogon-cookie").with_password("secret"),
);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("passwd"), Some("secret"));
assert_eq!(find("prelogin-cookie"), Some(""));
assert_eq!(find("portal-userauthcookie"), Some("portal-user-cookie"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("portal-prelogon-cookie"));
}
#[test]
fn extend_lifetime_adds_param() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: true,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("extend-lifetime"), Some("true"));
}
#[test]
fn no_extend_lifetime_omits_param() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let has_key = |key: &str| result.body.iter().any(|(k, _)| k == key);
assert!(!has_key("extend-lifetime"));
}
#[test]
fn context_connect_method_included_when_present() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("GW".to_string(), "vpn.example.com".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual).with_connect_method(Some("on-demand"));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("connect-method"), Some("on-demand"));
assert_eq!(find("selection-type"), Some("manual"));
}
#[test]
fn all_params_in_body_not_query() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
assert!(result.query.is_empty());
assert!(!result.body.is_empty());
}
#[test]
fn server_resolves_to_ipv4_with_context_using_localhost() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("Local".to_string(), "localhost".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "localhost",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let server = result
.body
.iter()
.find(|(k, _)| k == "server")
.map(|(_, v)| v.as_str())
.expect("server param should exist");
// localhost resolves to 127.0.0.1 (IPv4)
assert_eq!(server, "127.0.0.1");
}
#[test]
fn server_falls_back_to_host_when_resolution_fails() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("GW".to_string(), "nonexistent.invalid.test".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "nonexistent.invalid.test",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let server = result
.body
.iter()
.find(|(k, _)| k == "server")
.map(|(_, v)| v.as_str())
.expect("server param should exist");
// Falls back to the original gateway host when DNS resolution fails
assert_eq!(server, "nonexistent.invalid.test");
}
}
-125
View File
@@ -1,125 +0,0 @@
use super::RequestParams;
use crate::os_profile::{OsProfile, PreloginBrowserMode, PreloginParamLocation};
/// Build request parameters for the gateway prelogin endpoint.
///
/// Same as portal prelogin but uses the gateway-specific embedded browser value.
pub(crate) fn build(profile: &OsProfile, browser_mode: PreloginBrowserMode) -> RequestParams {
let default_browser = profile.gateway_default_browser(browser_mode);
let params: Vec<(String, String)> = vec![
("tmp".into(), "tmp".into()),
("clientVer".into(), "4100".into()),
("clientos".into(), profile.client_os().as_str().into()),
("os-version".into(), profile.os_version().into()),
("host-id".into(), profile.host_id().into()),
("ipv6-support".into(), "yes".into()),
("default-browser".into(), default_browser.into()),
("cas-support".into(), "yes".into()),
("data".into(), "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9".into()),
];
let mut query: Vec<(String, String)> = vec![];
if profile.kerberos_support_in_query() {
query.push(("kerberos-support".into(), "yes".into()));
}
match profile.prelogin_param_location() {
PreloginParamLocation::Body => RequestParams { body: params, query },
PreloginParamLocation::Query => RequestParams {
body: vec![],
query: params.into_iter().chain(query).collect(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::ClientOs;
#[test]
fn linux_places_params_in_body() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert!(result.query.is_empty());
}
#[test]
fn mac_places_params_in_body_with_kerberos_query() {
let profile = OsProfile::builder(ClientOs::Mac).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert_eq!(result.query.len(), 1);
assert_eq!(result.query[0], ("kerberos-support".into(), "yes".into()));
}
#[test]
fn windows_places_all_params_in_query() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(result.body.is_empty());
// 9 base params + 1 kerberos-support
assert_eq!(result.query.len(), 10);
}
#[test]
fn uses_embedded_gateway_default_browser_value() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "0");
}
#[test]
fn uses_target_value_when_external_browser_is_requested() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::External);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "4");
}
#[test]
fn includes_all_required_params() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"tmp"));
assert!(keys.contains(&"clientVer"));
assert!(keys.contains(&"clientos"));
assert!(keys.contains(&"os-version"));
assert!(keys.contains(&"host-id"));
assert!(keys.contains(&"ipv6-support"));
assert!(keys.contains(&"default-browser"));
assert!(keys.contains(&"cas-support"));
assert!(keys.contains(&"data"));
}
#[test]
fn data_param_is_cas_embedded_browser_base64() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let data_param = result
.body
.iter()
.find(|(k, _)| k == "data")
.expect("data param should exist");
assert_eq!(data_param.1, "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9");
}
}
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more