Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16dcb3aa6c | ||
|
|
7ae09aad8c | ||
|
|
40b35804e7 | ||
|
|
6999b2725e | ||
|
|
0a528b4aae | ||
|
|
7134d92ee8 | ||
|
|
d21b909a0d | ||
|
|
e066362c92 | ||
|
|
fd9b48cd90 | ||
|
|
2c29dda2ac | ||
|
|
d3845678ab | ||
|
|
355f8d82aa | ||
|
|
2ca6b80728 | ||
|
|
c0c517806e | ||
|
|
537e12d706 | ||
|
|
4197927f56 | ||
|
|
1b7380d2f2 | ||
|
|
090e479e20 | ||
|
|
cbce8b5609 | ||
|
|
6edd3408aa | ||
|
|
5da7b45407 | ||
|
|
bd064713a8 | ||
|
|
822d10528f | ||
|
|
ce8cc5b8dd | ||
|
|
b407c56239 | ||
|
|
9c1428fb72 | ||
|
|
ce97729984 | ||
|
|
3817227942 | ||
|
|
88975379bf | ||
|
|
11b410f1d9 | ||
|
|
917e1091a1 | ||
|
|
68f35cc582 | ||
|
|
293cd56930 | ||
|
|
ca221e3488 | ||
|
|
6e01164a56 | ||
|
|
d83bb22c58 | ||
|
|
e808ccbdb5 | ||
|
|
f17dd27d55 | ||
|
|
2b7b97f0e4 | ||
|
|
3a2398e677 | ||
|
|
7a373813ce | ||
|
|
8a41765c53 | ||
|
|
7a16e6bce8 | ||
|
|
6d23d41797 | ||
|
|
5263c03889 | ||
|
|
c44be546c3 | ||
|
|
63c873a906 | ||
|
|
3c16026acc | ||
|
|
81fcd253d3 | ||
|
|
4f94a28ad2 | ||
|
|
f403f19164 | ||
|
|
ab10af726b | ||
|
|
52f719d192 | ||
|
|
6723685385 | ||
|
|
aa14c67e92 | ||
|
|
fa14b94520 | ||
|
|
ded66586b2 | ||
|
|
cb1716ba9c | ||
|
|
25cca2831b |
No files matched your search
@@ -10,6 +10,11 @@ on:
|
||||
description: 'gpgui branch to use for the snapshot release'
|
||||
required: true
|
||||
default: dev
|
||||
build_macos:
|
||||
description: 'Build Apple Silicon artifacts for the snapshot release'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_bsd:
|
||||
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
|
||||
required: true
|
||||
@@ -39,6 +44,27 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test-gp:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- 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: Run Rust tests in Docker
|
||||
run: |
|
||||
docker run --rm \
|
||||
--user root \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e LIBXML2_STATIC=1 \
|
||||
-v "$(pwd):/workspace" \
|
||||
-w /workspace \
|
||||
yuezk/gpdev:binary-builder-tauri2 \
|
||||
cargo test --workspace
|
||||
|
||||
tarball:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -278,6 +304,9 @@ jobs:
|
||||
repository: yuezk/gpgui
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||
path: gpgui-source/gpgui
|
||||
- name: Verify Linux desktop assets
|
||||
if: matrix.os.arch == 'amd64' && matrix.libc.name == 'glibc'
|
||||
run: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
|
||||
- name: Tarball
|
||||
run: |
|
||||
cd gpgui-source
|
||||
@@ -304,6 +333,233 @@ jobs:
|
||||
gpgui-source/*.bin.tar.xz
|
||||
gpgui-source/*.bin.tar.xz.sha256
|
||||
|
||||
build-gpgui-macos:
|
||||
if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.build_macos) }}
|
||||
runs-on: macos-26
|
||||
environment: macos-release
|
||||
name: build-gpgui (macOS, arm64)
|
||||
outputs:
|
||||
archive_name: ${{ steps.release.outputs.archive_name }}
|
||||
steps:
|
||||
- name: Verify runner architecture
|
||||
run: test "$(uname -m)" = arm64
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 9.15.1
|
||||
|
||||
- name: Prepare workspace
|
||||
run: rm -rf gpgui-source && mkdir gpgui-source
|
||||
|
||||
- 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-source/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-source/gpgui
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: gpgui-source/gpgui/app/pnpm-lock.yaml
|
||||
|
||||
- name: Validate release versions
|
||||
id: release
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
gp_version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' gpgui-source/gp/Cargo.toml | head -1)"
|
||||
gpgui_version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' gpgui-source/gpgui/Cargo.toml | head -1)"
|
||||
if [[ -z "$gp_version" || "$gp_version" != "$gpgui_version" ]]; then
|
||||
echo "gp and gpgui versions must match: gp=$gp_version, gpgui=$gpgui_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
build_number="${{ github.run_number }}.${{ github.run_attempt }}"
|
||||
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
channel="snapshot"
|
||||
release_tag="snapshot"
|
||||
artifact_version="$gpgui_version-snapshot.$build_number"
|
||||
feed_url="https://github.com/${{ github.repository }}/releases/download/snapshot/appcast.xml"
|
||||
else
|
||||
channel="stable"
|
||||
release_tag="${{ github.ref_name }}"
|
||||
artifact_version="$gpgui_version"
|
||||
feed_url="https://github.com/${{ github.repository }}/releases/latest/download/appcast.xml"
|
||||
if [[ "$release_tag" != "v$gpgui_version" ]]; then
|
||||
echo "Release tag $release_tag does not match gpgui version $gpgui_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
archive_name="GPConnect_${artifact_version}_arm64.zip"
|
||||
{
|
||||
echo "MACOS_BUILD_NUMBER=$build_number"
|
||||
echo "MACOS_ARTIFACT_VERSION=$artifact_version"
|
||||
echo "SPARKLE_FEED_URL=$feed_url"
|
||||
echo "RELEASE_TAG=$release_tag"
|
||||
echo "UPDATE_CHANNEL=$channel"
|
||||
} >> "$GITHUB_ENV"
|
||||
echo "archive_name=$archive_name" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install build dependencies
|
||||
run: |
|
||||
brew install \
|
||||
autoconf \
|
||||
automake \
|
||||
create-dmg \
|
||||
dylibbundler \
|
||||
gettext \
|
||||
gmp \
|
||||
gnutls \
|
||||
libidn2 \
|
||||
libtool \
|
||||
libtasn1 \
|
||||
libunistring \
|
||||
lz4 \
|
||||
nettle \
|
||||
openssl@3 \
|
||||
p11-kit \
|
||||
pkgconf
|
||||
|
||||
- name: Import signing identity
|
||||
env:
|
||||
MACOS_CERTIFICATE_P12: ${{ secrets.MACOS_CERTIFICATE_P12 }}
|
||||
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
|
||||
APPLE_NOTARY_KEY_P8: ${{ secrets.APPLE_NOTARY_KEY_P8 }}
|
||||
APPLE_NOTARY_KEY_ID: ${{ secrets.APPLE_NOTARY_KEY_ID }}
|
||||
APPLE_NOTARY_ISSUER_ID: ${{ secrets.APPLE_NOTARY_ISSUER_ID }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
for variable in \
|
||||
MACOS_CERTIFICATE_P12 \
|
||||
MACOS_CERTIFICATE_PASSWORD; do
|
||||
if [[ -z "${!variable:-}" ]]; then
|
||||
echo "$variable is not configured" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [[ "$UPDATE_CHANNEL" == "stable" ]]; then
|
||||
for variable in \
|
||||
APPLE_NOTARY_KEY_P8 \
|
||||
APPLE_NOTARY_KEY_ID \
|
||||
APPLE_NOTARY_ISSUER_ID; do
|
||||
if [[ -z "${!variable:-}" ]]; then
|
||||
echo "$variable is not configured" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
keychain="$RUNNER_TEMP/gp-connect.keychain-db"
|
||||
keychain_password="$(openssl rand -hex 24)"
|
||||
certificate="$RUNNER_TEMP/signing-identity.p12"
|
||||
|
||||
printf '%s' "$MACOS_CERTIFICATE_P12" | base64 -D > "$certificate"
|
||||
chmod 600 "$certificate"
|
||||
|
||||
security create-keychain -p "$keychain_password" "$keychain"
|
||||
security set-keychain-settings -lut 21600 "$keychain"
|
||||
security unlock-keychain -p "$keychain_password" "$keychain"
|
||||
security import "$certificate" -k "$keychain" \
|
||||
-P "$MACOS_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12
|
||||
security set-key-partition-list -S apple-tool:,apple: \
|
||||
-s -k "$keychain_password" "$keychain"
|
||||
security list-keychains -d user -s "$keychain" login.keychain-db
|
||||
|
||||
if [[ "$UPDATE_CHANNEL" == "stable" ]]; then
|
||||
identity="$(security find-identity -v -p codesigning "$keychain" \
|
||||
| sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -1)"
|
||||
else
|
||||
identity="$(security find-identity -v -p codesigning "$keychain" \
|
||||
| sed -n \
|
||||
-e 's/.*"\(Developer ID Application:.*\)"/\1/p' \
|
||||
-e 's/.*"\(Apple Development:.*\)"/\1/p' \
|
||||
| head -1)"
|
||||
fi
|
||||
if [[ -z "$identity" ]]; then
|
||||
echo "A compatible Apple code-signing identity was not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
{
|
||||
echo "CI_KEYCHAIN=$keychain"
|
||||
echo "MACOS_SIGN_IDENTITY=$identity"
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
if [[ "$UPDATE_CHANNEL" == "stable" ]]; then
|
||||
notary_key="$RUNNER_TEMP/AuthKey.p8"
|
||||
notary_profile="gp-connect-ci"
|
||||
printf '%s' "$APPLE_NOTARY_KEY_P8" > "$notary_key"
|
||||
chmod 600 "$notary_key"
|
||||
xcrun notarytool store-credentials "$notary_profile" \
|
||||
--key "$notary_key" \
|
||||
--key-id "$APPLE_NOTARY_KEY_ID" \
|
||||
--issuer "$APPLE_NOTARY_ISSUER_ID" \
|
||||
--keychain "$keychain"
|
||||
{
|
||||
echo "APPLE_NOTARY_PROFILE=$notary_profile"
|
||||
echo "APPLE_NOTARY_KEYCHAIN=$keychain"
|
||||
} >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Build macOS release artifacts
|
||||
env:
|
||||
SPARKLE_PUBLIC_KEY: ${{ vars.SPARKLE_PUBLIC_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd gpgui-source/gpgui
|
||||
if [[ "$UPDATE_CHANNEL" == "stable" ]]; then
|
||||
build_mode="release"
|
||||
else
|
||||
build_mode="development"
|
||||
export SPARKLE_CREATE_UPDATE_ARCHIVE=1
|
||||
fi
|
||||
./scripts/build-macos.sh dmg "$build_mode"
|
||||
|
||||
- name: Prepare release assets
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
artifact_dir="gpgui-source/artifacts"
|
||||
mkdir -p "$artifact_dir"
|
||||
dmg_name="GPConnect_${MACOS_ARTIFACT_VERSION}_arm64.dmg"
|
||||
archive_name="GPConnect_${MACOS_ARTIFACT_VERSION}_arm64.zip"
|
||||
mv "gpgui-source/gpgui/target/release/bundle/dmg/GP Connect.dmg" \
|
||||
"$artifact_dir/$dmg_name"
|
||||
mv "gpgui-source/gpgui/target/release/bundle/sparkle/$archive_name" \
|
||||
"$artifact_dir/$archive_name"
|
||||
|
||||
for file in "$artifact_dir"/*; do
|
||||
shasum -a 256 "$file" > "$file.sha256"
|
||||
done
|
||||
|
||||
- name: Upload macOS artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: artifact-gpgui-macos-arm64
|
||||
if-no-files-found: error
|
||||
path: gpgui-source/artifacts/*
|
||||
|
||||
- name: Remove signing keychain
|
||||
if: ${{ always() }}
|
||||
run: |
|
||||
if [[ -n "${CI_KEYCHAIN:-}" && -f "$CI_KEYCHAIN" ]]; then
|
||||
security delete-keychain "$CI_KEYCHAIN"
|
||||
fi
|
||||
|
||||
setup-bsd-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
@@ -421,7 +677,7 @@ jobs:
|
||||
if: ${{ matrix.os == 'freebsd' }}
|
||||
uses: vmactions/freebsd-vm@v1
|
||||
with:
|
||||
release: "14.3"
|
||||
release: "14.4"
|
||||
arch: ${{ matrix.arch }}
|
||||
usesh: true
|
||||
prepare: |
|
||||
@@ -537,6 +793,7 @@ jobs:
|
||||
- build-gp
|
||||
- build-docker-image
|
||||
- build-gpgui
|
||||
- build-gpgui-macos
|
||||
- setup-bsd-matrix
|
||||
- build-gpgui-frontend
|
||||
- build-bsd
|
||||
@@ -546,6 +803,7 @@ jobs:
|
||||
env:
|
||||
NEEDS_JSON: ${{ toJson(needs) }}
|
||||
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
||||
MACOS_BUILD_ENABLED: ${{ startsWith(github.ref, 'refs/tags/') || inputs.build_macos }}
|
||||
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
@@ -555,6 +813,7 @@ jobs:
|
||||
|
||||
needs = json.loads(os.environ["NEEDS_JSON"])
|
||||
bsd_matrix_enabled = os.environ["BSD_MATRIX_ENABLED"] == "true"
|
||||
macos_build_enabled = os.environ["MACOS_BUILD_ENABLED"] == "true"
|
||||
is_tag = os.environ["IS_TAG"] == "true"
|
||||
failed = []
|
||||
|
||||
@@ -566,6 +825,8 @@ jobs:
|
||||
continue
|
||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||
continue
|
||||
elif name == "build-gpgui-macos" and result == "skipped" and not macos_build_enabled:
|
||||
continue
|
||||
elif result == "skipped":
|
||||
failed.append(f"{name}: {result}")
|
||||
|
||||
@@ -632,6 +893,20 @@ jobs:
|
||||
run: |
|
||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
||||
|
||||
publish-macos-appcast:
|
||||
if: ${{ always() && needs.gh-release.result == 'success' && needs.build-gpgui-macos.result == 'success' }}
|
||||
permissions:
|
||||
contents: write
|
||||
needs:
|
||||
- gh-release
|
||||
- build-gpgui-macos
|
||||
uses: ./.github/workflows/publish-macos-appcast.yaml
|
||||
with:
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
release_tag: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
archive_name: ${{ needs.build-gpgui-macos.outputs.archive_name }}
|
||||
secrets: inherit
|
||||
|
||||
publish-docker-image:
|
||||
needs:
|
||||
- build-docker-image
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
name: Publish macOS appcast
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
archive_name:
|
||||
required: false
|
||||
type: string
|
||||
default: ''
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: Update channel
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- stable
|
||||
- snapshot
|
||||
release_tag:
|
||||
description: Release containing the macOS update archive
|
||||
required: true
|
||||
type: string
|
||||
archive_name:
|
||||
description: Exact ZIP asset name; leave empty when the release has one macOS update archive
|
||||
required: false
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: macos-appcast-${{ inputs.channel }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: macos-15
|
||||
environment: macos-release
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
REQUESTED_ARCHIVE: ${{ inputs.archive_name }}
|
||||
SPARKLE_VERSION: 2.9.2
|
||||
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
|
||||
steps:
|
||||
- name: Validate inputs
|
||||
env:
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$CHANNEL" != "stable" && "$CHANNEL" != "snapshot" ]]; then
|
||||
echo "channel must be stable or snapshot" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
|
||||
echo "The snapshot channel must publish to the snapshot release" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CHANNEL" == "stable" && "$RELEASE_TAG" == "snapshot" ]]; then
|
||||
echo "The stable channel cannot publish to the snapshot release" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "$SPARKLE_PRIVATE_KEY" ]]; then
|
||||
echo "SPARKLE_PRIVATE_KEY is not configured" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Prepare Sparkle tools
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
archive="$RUNNER_TEMP/Sparkle.zip"
|
||||
curl --fail --location --silent --show-error \
|
||||
"https://github.com/sparkle-project/Sparkle/releases/download/$SPARKLE_VERSION/Sparkle-for-Swift-Package-Manager.zip" \
|
||||
--output "$archive"
|
||||
echo "$SPARKLE_ARCHIVE_SHA256 $archive" | shasum -a 256 --check
|
||||
ditto -x -k "$archive" "$RUNNER_TEMP/sparkle"
|
||||
test -x "$RUNNER_TEMP/sparkle/bin/generate_appcast"
|
||||
|
||||
- name: Download update archive
|
||||
id: archive
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
mkdir -p "$RUNNER_TEMP/updates"
|
||||
archive_name="$REQUESTED_ARCHIVE"
|
||||
if [[ -z "$archive_name" ]]; then
|
||||
archives="$(gh release view "$RELEASE_TAG" --repo "$REPOSITORY" --json assets \
|
||||
--jq '.assets[].name | select(test("^GPConnect_[0-9A-Za-z._-]+_arm64\\.zip$"))')"
|
||||
archive_count="$(printf '%s\n' "$archives" | sed '/^$/d' | wc -l | tr -d ' ')"
|
||||
if [[ "$archive_count" != "1" ]]; then
|
||||
echo "Expected one macOS update archive on $RELEASE_TAG, found $archive_count" >&2
|
||||
printf '%s\n' "$archives" >&2
|
||||
exit 1
|
||||
fi
|
||||
archive_name="$archives"
|
||||
fi
|
||||
|
||||
if [[ ! "$archive_name" =~ ^GPConnect_[0-9A-Za-z._-]+_arm64\.zip$ ]]; then
|
||||
echo "Invalid macOS update archive name: $archive_name" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh release download "$RELEASE_TAG" --repo "$REPOSITORY" \
|
||||
--pattern "$archive_name" --dir "$RUNNER_TEMP/updates"
|
||||
echo "name=$archive_name" >> "$GITHUB_OUTPUT"
|
||||
echo "path=$RUNNER_TEMP/updates/$archive_name" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify update archive
|
||||
id: bundle
|
||||
env:
|
||||
ARCHIVE_PATH: ${{ steps.archive.outputs.path }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
extract_dir="$RUNNER_TEMP/extracted"
|
||||
ditto -x -k "$ARCHIVE_PATH" "$extract_dir"
|
||||
app="$extract_dir/GP Connect.app"
|
||||
test -d "$app"
|
||||
codesign --verify --deep --strict --verbose=2 "$app"
|
||||
|
||||
signing_info="$(codesign -d --verbose=4 "$app" 2>&1)"
|
||||
if [[ "$CHANNEL" == "stable" ]]; then
|
||||
xcrun stapler validate "$app"
|
||||
grep -q '^Authority=Developer ID Application:' <<<"$signing_info"
|
||||
grep -q '^CodeDirectory .*flags=.*runtime' <<<"$signing_info"
|
||||
else
|
||||
grep -E -q '^Authority=(Apple Development|Developer ID Application):' \
|
||||
<<<"$signing_info"
|
||||
fi
|
||||
team_identifier="$(sed -n 's/^TeamIdentifier=//p' <<<"$signing_info")"
|
||||
if [[ -z "$team_identifier" || "$team_identifier" == "not set" ]]; then
|
||||
echo "Signed application has no Team Identifier" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
identifier="$(sed -n 's/^Identifier=//p' <<<"$signing_info")"
|
||||
if [[ "$identifier" != "com.yuezk.gpgui" ]]; then
|
||||
echo "Unexpected bundle identifier: $identifier" >&2
|
||||
exit 1
|
||||
fi
|
||||
file "$app/Contents/MacOS/gpgui" | grep -q 'arm64'
|
||||
|
||||
feed_url="$(plutil -extract SUFeedURL raw "$app/Contents/Info.plist")"
|
||||
expected_feed="https://github.com/$REPOSITORY/releases/latest/download/appcast.xml"
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
expected_feed="https://github.com/$REPOSITORY/releases/download/snapshot/appcast.xml"
|
||||
fi
|
||||
if [[ "$feed_url" != "$expected_feed" ]]; then
|
||||
echo "Unexpected Sparkle feed URL: $feed_url" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
bundle_version="$(plutil -extract CFBundleVersion raw "$app/Contents/Info.plist")"
|
||||
short_version="$(plutil -extract CFBundleShortVersionString raw "$app/Contents/Info.plist")"
|
||||
if [[ ! "$bundle_version" =~ ^[0-9]+(\.[0-9]+){0,2}$ ]]; then
|
||||
echo "Invalid bundle version: $bundle_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "version=$bundle_version" >> "$GITHUB_OUTPUT"
|
||||
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Prepare release notes
|
||||
env:
|
||||
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
notes="$RUNNER_TEMP/updates/${ARCHIVE_NAME%.zip}.md"
|
||||
gh release view "$RELEASE_TAG" --repo "$REPOSITORY" --json body --jq '.body // ""' > "$notes"
|
||||
if [[ ! -s "$notes" ]]; then
|
||||
printf 'GP Connect %s\n' '${{ steps.bundle.outputs.short_version }}' > "$notes"
|
||||
fi
|
||||
|
||||
- name: Generate appcast
|
||||
env:
|
||||
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
embedded_public_key="$(plutil -extract SUPublicEDKey raw \
|
||||
"$RUNNER_TEMP/extracted/GP Connect.app/Contents/Info.plist")"
|
||||
derived_public_key="$(swift -e '
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
let encoded = ProcessInfo.processInfo.environment["SPARKLE_PRIVATE_KEY"]!
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let privateKey = try Curve25519.Signing.PrivateKey(
|
||||
rawRepresentation: Data(base64Encoded: encoded)!)
|
||||
print(privateKey.publicKey.rawRepresentation.base64EncodedString())
|
||||
')"
|
||||
if [[ "$derived_public_key" != "$embedded_public_key" ]]; then
|
||||
echo "Sparkle private key does not match the public key embedded in the application" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
download_prefix="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/"
|
||||
printf '%s' "$SPARKLE_PRIVATE_KEY" | \
|
||||
"$RUNNER_TEMP/sparkle/bin/generate_appcast" \
|
||||
--download-url-prefix "$download_prefix" \
|
||||
--maximum-deltas 0 \
|
||||
--embed-release-notes \
|
||||
--ed-key-file - \
|
||||
"$RUNNER_TEMP/updates"
|
||||
|
||||
appcast="$RUNNER_TEMP/updates/appcast.xml"
|
||||
test -s "$appcast"
|
||||
grep -Fq "sparkle:version>${{ steps.bundle.outputs.version }}<" "$appcast"
|
||||
grep -Fq "sparkle:shortVersionString>${{ steps.bundle.outputs.short_version }}<" "$appcast"
|
||||
grep -Fq "url=\"$download_prefix$ARCHIVE_NAME\"" "$appcast"
|
||||
grep -q 'sparkle:edSignature=' "$appcast"
|
||||
|
||||
- name: Publish appcast
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
gh release upload "$RELEASE_TAG" "$RUNNER_TEMP/updates/appcast.xml" \
|
||||
--repo "$REPOSITORY" --clobber
|
||||
|
||||
- name: Verify published appcast
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$CHANNEL" == "stable" ]]; then
|
||||
feed_url="https://github.com/$REPOSITORY/releases/latest/download/appcast.xml"
|
||||
else
|
||||
feed_url="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/appcast.xml"
|
||||
fi
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
published_appcast="$(curl --fail --location --silent --show-error "$feed_url" || true)"
|
||||
if grep -Fq "sparkle:version>${{ steps.bundle.outputs.version }}<" <<<"$published_appcast"; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
echo "Published appcast did not become available at $feed_url" >&2
|
||||
exit 1
|
||||
@@ -15,3 +15,5 @@ gen
|
||||
|
||||
# Nix files
|
||||
result
|
||||
|
||||
.DS_Store
|
||||
@@ -1,6 +1,7 @@
|
||||
[submodule "crates/openconnect/deps/openconnect"]
|
||||
path = crates/openconnect/deps/openconnect
|
||||
url = https://gitlab.com/openconnect/openconnect.git
|
||||
url = https://github.com/yuezk/openconnect.git
|
||||
branch = globalprotect
|
||||
[submodule "crates/openconnect/deps/libxml2"]
|
||||
path = crates/openconnect/deps/libxml2
|
||||
url = https://gitlab.gnome.org/GNOME/libxml2.git
|
||||
url = https://github.com/GNOME/libxml2.git
|
||||
@@ -31,7 +31,7 @@ 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.13", default-features = false, features = ["native-tls", "charset", "http2", "system-proxy", "json", "form", "query"] }
|
||||
openssl = "0.10"
|
||||
pem = "3"
|
||||
xmltree = { version = "0.12", features = ["attribute-order"] }
|
||||
@@ -59,6 +59,8 @@ which = "8"
|
||||
uuid = "1"
|
||||
netdev = "0.40"
|
||||
humantime = "2"
|
||||
snow = { version = "0.10", default-features = false, features = ["std", "use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
|
||||
zeroize = "1"
|
||||
|
||||
# Tauri dependencies
|
||||
tauri = { version = "2" }
|
||||
|
||||
@@ -64,6 +64,9 @@ endif
|
||||
|
||||
default: build
|
||||
|
||||
dev-service:
|
||||
./scripts/dev-service.sh
|
||||
|
||||
version:
|
||||
@echo $(VERSION)
|
||||
|
||||
@@ -142,6 +145,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 -Dm755 target/release/gp-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
|
||||
|
||||
# Install the GUI components if BUILD_GUI_HELPER is set to 1
|
||||
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
|
||||
@@ -160,9 +164,11 @@ install:
|
||||
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
|
||||
|
||||
install -Dm644 packaging/files/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
|
||||
install -Dm644 packaging/files/usr/share/applications/gpauth.desktop $(DESTDIR)/usr/share/applications/gpauth.desktop
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256/apps/gpgui.png
|
||||
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
|
||||
|
||||
@@ -183,6 +189,7 @@ install-bsd:
|
||||
fi
|
||||
|
||||
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
|
||||
install -m 755 target/release/gp-vpnc-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-vpnc-script-installer
|
||||
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
|
||||
|
||||
@@ -191,10 +198,12 @@ install-bsd:
|
||||
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/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/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/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
|
||||
@@ -216,7 +225,7 @@ bsd-gpgui-tarball:
|
||||
package-freebsd: BSD_FLAVOR=freebsd
|
||||
package-freebsd: clean-bsd-package
|
||||
test -x "$(GPGUI_BINARY)"
|
||||
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts
|
||||
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts .build/freebsd/metadata
|
||||
$(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/\..*//'); \
|
||||
@@ -227,8 +236,9 @@ package-freebsd: clean-bsd-package
|
||||
-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
|
||||
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/metadata/+MANIFEST
|
||||
cp packaging/bsd/freebsd/POST_DEINSTALL .build/freebsd/metadata/+POST_DEINSTALL
|
||||
pkg create -r .build/freebsd/pkgroot -M .build/freebsd/metadata -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)"
|
||||
@@ -240,7 +250,11 @@ package-openbsd: clean-bsd-package
|
||||
$(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
|
||||
{ \
|
||||
echo '@unexec-delete /bin/rm -f /var/db/gpclient/scripts/vpnc-script /var/db/gpclient/scripts/vpnc-script.metadata || echo "Warning: failed to remove the installed VPN script" >&2'; \
|
||||
echo '@unexec-delete /bin/rmdir /var/db/gpclient/scripts 2>/dev/null || true'; \
|
||||
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); \
|
||||
@@ -269,17 +283,25 @@ uninstall:
|
||||
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
|
||||
|
||||
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
|
||||
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
|
||||
|
||||
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
|
||||
rm -f $(DESTDIR)/usr/share/applications/gpauth.desktop
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||
|
||||
rm -f $(DESTDIR)/var/lib/gpclient/scripts/vpnc-script \
|
||||
$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script.metadata || \
|
||||
echo "Warning: failed to remove the installed VPN script" >&2
|
||||
rmdir $(DESTDIR)/var/lib/gpclient/scripts 2>/dev/null || true
|
||||
|
||||
clean-debian:
|
||||
rm -rf .build/deb
|
||||
|
||||
@@ -386,6 +408,7 @@ init-pkgbuild: clean-pkgbuild tarball
|
||||
|
||||
cp .build/tarball/${PKG}.tar.gz .build/pkgbuild
|
||||
cp packaging/pkgbuild/PKGBUILD.in .build/pkgbuild/PKGBUILD
|
||||
cp packaging/pkgbuild/gp.install .build/pkgbuild/gp.install
|
||||
|
||||
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/pkgbuild/PKGBUILD
|
||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/pkgbuild/PKGBUILD
|
||||
@@ -402,6 +425,7 @@ init-apk: clean-apk tarball
|
||||
|
||||
cp .build/tarball/${PKG}.tar.gz .build/apk
|
||||
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
|
||||
cp packaging/apk/post-deinstall .build/apk/$(PKG_NAME).post-deinstall
|
||||
|
||||
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/apk/APKBUILD
|
||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/apk/APKBUILD
|
||||
|
||||
@@ -27,6 +27,7 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
|
||||
- [Other Distributions](#other-distributions)
|
||||
- [Building from Source](#building-from-source)
|
||||
- [Frequently Asked Questions](#frequently-asked-questions)
|
||||
- [NetworkManager Integration](#networkmanager-integration)
|
||||
- [License](#license)
|
||||
|
||||
## Features
|
||||
@@ -282,9 +283,13 @@ After logging back in to GNOME, enable AppIndicator support if needed:
|
||||
gnome-extensions enable [email protected]
|
||||
```
|
||||
|
||||
NixOS does not run an imperative package-uninstall hook when a package is
|
||||
removed from the system configuration. Remove an installed replacement VPN
|
||||
script from the app settings before removing the package.
|
||||
|
||||
### Official Docker Image
|
||||
|
||||
The official Docker image provides the CLI tools on Alpine Linux:
|
||||
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
|
||||
|
||||
```bash
|
||||
docker pull yuezk/globalprotect-openconnect:<version>
|
||||
@@ -468,6 +473,11 @@ sudo -E gpclient connect <portal>
|
||||
|
||||
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
## NetworkManager Integration
|
||||
|
||||
- [WMP/GlobalProtect-SAML-NetworkManager](https://github.com/WMP/GlobalProtect-SAML-NetworkManager) – NetworkManager VPN plugin with SAML/SSO support for GNOME and KDE Plasma
|
||||
- [jdpipe/networkmanager-gpclient](https://github.com/jdpipe/networkmanager-gpclient) – NetworkManager VPN plugin that uses `gpclient`
|
||||
|
||||
## Licensing
|
||||
|
||||
### Trial and Pricing
|
||||
@@ -482,8 +492,10 @@ 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) |
|
||||
| [openconnect](./crates/openconnect) | Rust wrapper crate | [MIT](./crates/openconnect/LICENSE) |
|
||||
| [upstream OpenConnect](./crates/openconnect/deps/openconnect) | C library | [LGPL-2.1](./crates/openconnect/deps/openconnect/COPYING.LGPL) |
|
||||
| [common](./crates/common) | Crate | [MIT](./crates/common/LICENSE) |
|
||||
| [browser-launcher](./crates/browser-launcher) | Crate | [MIT](./crates/browser-launcher/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) |
|
||||
|
||||
@@ -11,14 +11,13 @@ tauri-build = { version = "2", features = [], optional = true }
|
||||
|
||||
[dependencies]
|
||||
common = { path = "../../crates/common" }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
|
||||
|
||||
auth = { path = "../../crates/auth", features = ["browser-auth"] }
|
||||
|
||||
# Shared dependencies
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
env_logger.workspace = true
|
||||
log.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
@@ -34,3 +33,4 @@ tauri = { workspace = true, optional = true }
|
||||
[features]
|
||||
default = ["webview-auth"]
|
||||
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
|
||||
release-devtools = ["auth/release-devtools"]
|
||||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 83 KiB After Width: | Height: | Size: 57 KiB |
@@ -1,7 +1,9 @@
|
||||
use auth::{BrowserAuthenticator, auth_prelogin};
|
||||
use clap::Parser;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use gpapi::auth::AuthWindowTheme;
|
||||
use gpapi::{
|
||||
auth::{SamlAuthData, SamlAuthResult},
|
||||
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
|
||||
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
@@ -96,6 +98,14 @@ struct Cli {
|
||||
#[arg(long, help = "Clean the cache of the embedded browser")]
|
||||
pub clean: bool,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "Set the embedded authentication window title")]
|
||||
window_title: Option<String>,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, value_enum, default_value_t = AuthWindowTheme::default(), help = "Set the embedded authentication window appearance")]
|
||||
window_theme: AuthWindowTheme,
|
||||
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
@@ -166,7 +176,16 @@ impl Cli {
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
crate::webview_auth::authenticate(server, gp_params, auth_request, self.clean, openssl_conf).await?;
|
||||
crate::webview_auth::authenticate(
|
||||
server,
|
||||
gp_params,
|
||||
auth_request,
|
||||
self.clean,
|
||||
self.window_title.clone(),
|
||||
self.window_theme,
|
||||
openssl_conf,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -206,9 +225,11 @@ impl Cli {
|
||||
}
|
||||
|
||||
fn init_logger(cli: &Cli) {
|
||||
env_logger::builder()
|
||||
.filter_level(cli.verbose.log_level_filter())
|
||||
.init();
|
||||
if let Some(level) = cli.verbose.log_level_filter().to_level() {
|
||||
gpapi::logger::init(level, "com.yuezk.gpgui", "gpauth");
|
||||
} else {
|
||||
log::set_max_level(log::LevelFilter::Off);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run() {
|
||||
@@ -232,6 +253,7 @@ pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Opt
|
||||
};
|
||||
SamlAuthResult::Success(auth_data)
|
||||
}
|
||||
Err(err) if err.downcast_ref::<AuthenticationCancelled>().is_some() => SamlAuthResult::Cancelled,
|
||||
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
|
||||
};
|
||||
|
||||
@@ -311,4 +333,21 @@ mod tests {
|
||||
assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key"));
|
||||
assert_eq!(cli.key_password.as_deref(), Some("secret"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn auth_window_options_parse() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
"portal.example.com",
|
||||
"--window-title",
|
||||
"GP Connect Login",
|
||||
"--window-theme",
|
||||
"dark",
|
||||
])
|
||||
.expect("gpauth window options should parse");
|
||||
|
||||
assert_eq!(cli.window_title.as_deref(), Some("GP Connect Login"));
|
||||
assert_eq!(cli.window_theme, AuthWindowTheme::Dark);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use auth::WebviewAuthenticator;
|
||||
use gpapi::gp_params::GpParams;
|
||||
use auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
|
||||
use log::info;
|
||||
use tauri::RunEvent;
|
||||
use tempfile::NamedTempFile;
|
||||
@@ -11,19 +11,24 @@ pub async fn authenticate(
|
||||
gp_params: GpParams,
|
||||
auth_request: String,
|
||||
clean: bool,
|
||||
window_title: Option<String>,
|
||||
window_theme: AuthWindowTheme,
|
||||
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| {
|
||||
apply_auth_theme(app.handle(), window_theme);
|
||||
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);
|
||||
.with_clean(clean)
|
||||
.with_window_title(window_title.as_deref().unwrap_or("GlobalProtect Login"))
|
||||
.with_window_theme(window_theme);
|
||||
|
||||
let auth_result = authenticator.authenticate(&app_handle).await;
|
||||
print_auth_result(auth_result, Some(&auth_host_id));
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
"beforeBuildCommand": ""
|
||||
},
|
||||
"identifier": "com.yuezk.gpauth",
|
||||
"productName": "gpauth",
|
||||
"productName": "GP Connect Login",
|
||||
"app": {
|
||||
"withGlobalTauri": false,
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"icon": ["icons/icon.png"]
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
use std::{env::temp_dir, fs::File, str::FromStr};
|
||||
use std::{
|
||||
env::temp_dir,
|
||||
fs::File,
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
@@ -31,6 +36,7 @@ const VERSION: &str = concat!(
|
||||
pub(crate) struct SharedArgs<'a> {
|
||||
pub(crate) fix_openssl: bool,
|
||||
pub(crate) ignore_tls_errors: bool,
|
||||
pub(crate) lock_file: &'a Path,
|
||||
pub(crate) verbose: &'a InfoLevelVerbosity,
|
||||
}
|
||||
|
||||
@@ -75,6 +81,13 @@ struct Cli {
|
||||
fix_openssl: bool,
|
||||
#[arg(long, help = "Ignore the TLS errors")]
|
||||
ignore_tls_errors: bool,
|
||||
#[arg(
|
||||
long,
|
||||
global = true,
|
||||
default_value = GP_CLIENT_LOCK_FILE,
|
||||
help = "Path to the gpclient PID lock file"
|
||||
)]
|
||||
lock_file: PathBuf,
|
||||
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
@@ -92,7 +105,7 @@ impl Args for Cli {
|
||||
|
||||
impl Cli {
|
||||
async fn is_running(&self) -> bool {
|
||||
let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE).await else {
|
||||
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -131,6 +144,7 @@ impl Cli {
|
||||
let shared_args = SharedArgs {
|
||||
fix_openssl: self.fix_openssl,
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
lock_file: &self.lock_file,
|
||||
verbose: &self.verbose,
|
||||
};
|
||||
|
||||
@@ -140,7 +154,7 @@ impl Cli {
|
||||
|
||||
match &self.command {
|
||||
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
|
||||
CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await,
|
||||
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
|
||||
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
||||
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
||||
}
|
||||
@@ -177,3 +191,29 @@ pub(crate) async fn run() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lock_file_defaults_to_standard_path() {
|
||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
|
||||
|
||||
assert_eq!(cli.lock_file, PathBuf::from(GP_CLIENT_LOCK_FILE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_file_can_be_overridden_after_subcommand() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"connect",
|
||||
"portal.example.com",
|
||||
"--lock-file",
|
||||
"/tmp/gpclient-portal.lock",
|
||||
])
|
||||
.expect("global lock file option should parse after subcommand");
|
||||
|
||||
assert_eq!(cli.lock_file, PathBuf::from("/tmp/gpclient-portal.lock"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::Path,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
@@ -21,9 +22,8 @@ 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 crate::session::{
|
||||
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
|
||||
};
|
||||
|
||||
use super::{ConnectHandler, args::cookie_cache_path};
|
||||
@@ -384,9 +384,12 @@ impl ConnectHandler<'_> {
|
||||
vpn_clone.disconnect();
|
||||
});
|
||||
|
||||
let lock_file = self.shared_args.lock_file.to_path_buf();
|
||||
let lock_file_on_connect = lock_file.clone();
|
||||
|
||||
let connect_result = vpn.connect(move |vpn_session_info| {
|
||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||
write_pid_file();
|
||||
write_pid_file(&lock_file_on_connect);
|
||||
|
||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||
return;
|
||||
@@ -403,9 +406,9 @@ impl ConnectHandler<'_> {
|
||||
task.abort();
|
||||
}
|
||||
|
||||
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
|
||||
if fs::metadata(&lock_file).is_ok() {
|
||||
info!("Removing PID file");
|
||||
fs::remove_file(GP_CLIENT_LOCK_FILE).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
|
||||
fs::remove_file(&lock_file).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
|
||||
}
|
||||
|
||||
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
|
||||
@@ -458,13 +461,13 @@ fn direct_gateway_command(gateway: &str) -> String {
|
||||
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
||||
}
|
||||
|
||||
fn write_pid_file() {
|
||||
fn write_pid_file(lock_file: &Path) {
|
||||
let pid = std::process::id();
|
||||
|
||||
if let Err(err) = fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()) {
|
||||
if let Err(err) = fs::write(lock_file, pid.to_string()) {
|
||||
warn!("Failed to write PID file: {}", err);
|
||||
} else {
|
||||
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
|
||||
info!("Wrote PID {} to {}", pid, lock_file.display());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use crate::GP_CLIENT_LOCK_FILE;
|
||||
use clap::Args;
|
||||
use gpapi::utils::lock_file::gpservice_lock_info;
|
||||
use log::{info, warn};
|
||||
use std::{fs, str::FromStr, thread, time::Duration};
|
||||
use std::{fs, path::Path, str::FromStr, thread, time::Duration};
|
||||
use sysinfo::{Pid, Signal, System};
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -17,16 +16,17 @@ pub struct DisconnectArgs {
|
||||
|
||||
pub struct DisconnectHandler<'a> {
|
||||
args: &'a DisconnectArgs,
|
||||
lock_file: &'a Path,
|
||||
}
|
||||
|
||||
impl<'a> DisconnectHandler<'a> {
|
||||
pub fn new(args: &'a DisconnectArgs) -> Self {
|
||||
Self { args }
|
||||
pub fn new(args: &'a DisconnectArgs, lock_file: &'a Path) -> Self {
|
||||
Self { args, lock_file }
|
||||
}
|
||||
|
||||
pub async fn handle(&self) -> anyhow::Result<()> {
|
||||
// Try to disconnect the CLI client
|
||||
if let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE) {
|
||||
if let Ok(c) = fs::read_to_string(self.lock_file) {
|
||||
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
|
||||
warn!("Failed to send signal to client: {}", err);
|
||||
});
|
||||
|
||||
@@ -213,6 +213,7 @@ mod tests {
|
||||
prior_secs: 1_800,
|
||||
message: "Session expires soon".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
true,
|
||||
);
|
||||
@@ -233,6 +234,7 @@ mod tests {
|
||||
prior_secs: 1_800,
|
||||
message: "Session expires soon".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
false,
|
||||
);
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
version="1.1"
|
||||
id="Layer_1"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 96 96"
|
||||
style="enable-background:new 0 0 96 96;"
|
||||
xml:space="preserve"
|
||||
sodipodi:docname="com.yuezk.qt.gpclient.svg"
|
||||
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
|
||||
id="metadata14"><rdf:RDF><cc:Work
|
||||
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
|
||||
id="defs12" /><sodipodi:namedview
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1"
|
||||
objecttolerance="10"
|
||||
gridtolerance="10"
|
||||
guidetolerance="10"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:window-width="1920"
|
||||
inkscape:window-height="1006"
|
||||
id="namedview10"
|
||||
showgrid="false"
|
||||
inkscape:zoom="6.9532168"
|
||||
inkscape:cx="7.9545315"
|
||||
inkscape:cy="59.062386"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="g8499" />
|
||||
<style
|
||||
type="text/css"
|
||||
id="style2">
|
||||
.st0{fill:#2980B9;}
|
||||
.st1{fill:#3498DB;}
|
||||
.st2{fill:#2ECC71;}
|
||||
.st3{fill:#27AE60;}
|
||||
</style>
|
||||
|
||||
<g
|
||||
id="g8499"
|
||||
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
|
||||
id="XMLID_1_">
|
||||
<circle
|
||||
r="32.5"
|
||||
cy="48"
|
||||
cx="48"
|
||||
class="st0"
|
||||
id="XMLID_3_"
|
||||
style="fill:#2980b9" />
|
||||
<path
|
||||
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
|
||||
class="st1"
|
||||
id="XMLID_4_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#3498db" />
|
||||
<path
|
||||
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
|
||||
class="st2"
|
||||
id="XMLID_13_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#2ecc71" />
|
||||
<path
|
||||
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
|
||||
class="st3"
|
||||
id="XMLID_20_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#27ae60" />
|
||||
</g><g
|
||||
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
|
||||
id="g7664"><path
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_6_"
|
||||
class="st3"
|
||||
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
|
||||
style="fill:#f1aa27;fill-opacity:1" /><path
|
||||
style="fill:#e6e6e6"
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_7_"
|
||||
class="st4"
|
||||
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
|
||||
style="fill:#e6e6e6;fill-opacity:1"
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_8_"
|
||||
class="st5"
|
||||
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>
|
||||
|
Before Width: | Height: | Size: 6.7 KiB |
@@ -0,0 +1,43 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#579bc1"/>
|
||||
<stop offset=".52" stop-color="#438fbd"/>
|
||||
<stop offset="1" stop-color="#2f719e"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#56c78a"/>
|
||||
<stop offset=".55" stop-color="#3bbf78"/>
|
||||
<stop offset="1" stop-color="#279b5d"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#f3b84c"/>
|
||||
<stop offset=".55" stop-color="#e8a12f"/>
|
||||
<stop offset="1" stop-color="#d4871e"/>
|
||||
</linearGradient>
|
||||
<clipPath id="globe-clip">
|
||||
<circle cx="512" cy="455" r="315"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
|
||||
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
|
||||
<g clip-path="url(#globe-clip)" fill="url(#land)">
|
||||
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
|
||||
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
|
||||
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
|
||||
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
|
||||
</g>
|
||||
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".4"/>
|
||||
|
||||
<g transform="translate(512 490) scale(.82) translate(-512 -490)">
|
||||
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
|
||||
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
|
||||
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".45"/>
|
||||
<g fill="#85500f" opacity=".85">
|
||||
<path d="M501 538h22l16 69h-54Z"/>
|
||||
<circle cx="512" cy="521" r="27"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -1,12 +1,12 @@
|
||||
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
|
||||
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),e=null),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.
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(`
|
||||
`+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
|
||||
`+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)};
|
||||
|
||||
@@ -14,7 +14,7 @@ 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
|
||||
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,o?p(`palette-error-light`):t.error.light,.6)),B(t.Alert,`infoColor`,r(F,o?p(`palette-info-light`):t.info.light,.6)),B(t.Alert,`successColor`,r(F,o?p(`palette-success-light`):t.success.light,.6)),B(t.Alert,`warningColor`,r(F,o?p(`palette-warning-light`):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,o?p(`palette-error-light`):t.error.light,.9)),B(t.Alert,`infoStandardBg`,r(I,o?p(`palette-info-light`):t.info.light,.9)),B(t.Alert,`successStandardBg`,r(I,o?p(`palette-success-light`):t.success.light,.9)),B(t.Alert,`warningStandardBg`,r(I,o?p(`palette-warning-light`):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,o?p(`palette-primary-main`):t.primary.main,.62)),B(t.LinearProgress,`secondaryBg`,r(I,o?p(`palette-secondary-main`):t.secondary.main,.62)),B(t.LinearProgress,`errorBg`,r(I,o?p(`palette-error-main`):t.error.main,.62)),B(t.LinearProgress,`infoBg`,r(I,o?p(`palette-info-main`):t.info.main,.62)),B(t.LinearProgress,`successBg`,r(I,o?p(`palette-success-main`):t.success.main,.62)),B(t.LinearProgress,`warningBg`,r(I,o?p(`palette-warning-light`):t.warning.main,.62)),B(t.Skeleton,`bg`,b?r(xi,o?p(`palette-text-primary`):t.text.primary,.11):`rgba(${n(`palette-text-primaryChannel`)} / 0.11)`),B(t.Slider,`primaryTrack`,r(I,o?p(`palette-primary-main`):t.primary.main,.62)),B(t.Slider,`secondaryTrack`,r(I,o?p(`palette-secondary-main`):t.secondary.main,.62)),B(t.Slider,`errorTrack`,r(I,o?p(`palette-error-main`):t.error.main,.62)),B(t.Slider,`infoTrack`,r(I,o?p(`palette-info-main`):t.info.main,.62)),B(t.Slider,`successTrack`,r(I,o?p(`palette-success-main`):t.succLine truncated
|
||||
0% {
|
||||
transform: scale(0);
|
||||
opacity: 0.1;
|
||||
@@ -87,7 +87,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
||||
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
|
||||
`,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 e?e.tagName===`BUTTON`?!1:!(e.tagName===`A`&&e.href):s&&s!==`button`},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&&!c&&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
Line truncated
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
@@ -114,7 +114,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
||||
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
|
||||
`,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%;
|
||||
@@ -165,4 +165,4 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
||||
}
|
||||
`,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
|
||||
`,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
|
||||
@@ -2,10 +2,10 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/assets/icon-small-BO4dlTNl.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>
|
||||
<script type="module" crossorigin src="/assets/main-yAo_rN_V.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/main-C5muOSVO.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/src/assets/icon-small.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>GP Connect Helper</title>
|
||||
</head>
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
@@ -20,6 +20,9 @@ clap.workspace = true
|
||||
compile-time.workspace = true
|
||||
env_logger.workspace = true
|
||||
futures-util.workspace = true
|
||||
uuid.workspace = true
|
||||
zeroize.workspace = true
|
||||
tokio-tungstenite = "0.30"
|
||||
tempfile.workspace = true
|
||||
reqwest = { workspace = true, features = ["stream"] }
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 83 KiB After Width: | Height: | Size: 57 KiB |
@@ -1,99 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#579bc1"/>
|
||||
<stop offset=".52" stop-color="#438fbd"/>
|
||||
<stop offset="1" stop-color="#2f719e"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#56c78a"/>
|
||||
<stop offset=".55" stop-color="#3bbf78"/>
|
||||
<stop offset="1" stop-color="#279b5d"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#f3b84c"/>
|
||||
<stop offset=".55" stop-color="#e8a12f"/>
|
||||
<stop offset="1" stop-color="#d4871e"/>
|
||||
</linearGradient>
|
||||
<clipPath id="globe-clip">
|
||||
<circle cx="512" cy="455" r="315"/>
|
||||
</clipPath>
|
||||
<filter id="globe-shadow" x="150" y="90" width="730" height="760" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
||||
<feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#174d6f" flood-opacity=".14"/>
|
||||
</filter>
|
||||
<filter id="lock-shadow" x="280" y="210" width="470" height="540" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
||||
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#70430c" flood-opacity=".2"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
version="1.1"
|
||||
id="Layer_1"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 96 96"
|
||||
style="enable-background:new 0 0 96 96;"
|
||||
xml:space="preserve"
|
||||
sodipodi:docname="com.yuezk.qt.gpclient.svg"
|
||||
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
|
||||
id="metadata14"><rdf:RDF><cc:Work
|
||||
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
|
||||
id="defs12" /><sodipodi:namedview
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1"
|
||||
objecttolerance="10"
|
||||
gridtolerance="10"
|
||||
guidetolerance="10"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:window-width="1920"
|
||||
inkscape:window-height="1006"
|
||||
id="namedview10"
|
||||
showgrid="false"
|
||||
inkscape:zoom="6.9532168"
|
||||
inkscape:cx="7.9545315"
|
||||
inkscape:cy="59.062386"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="g8499" />
|
||||
<style
|
||||
type="text/css"
|
||||
id="style2">
|
||||
.st0{fill:#2980B9;}
|
||||
.st1{fill:#3498DB;}
|
||||
.st2{fill:#2ECC71;}
|
||||
.st3{fill:#27AE60;}
|
||||
</style>
|
||||
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
|
||||
<g filter="url(#globe-shadow)">
|
||||
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
|
||||
<g clip-path="url(#globe-clip)" fill="url(#land)">
|
||||
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
|
||||
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
|
||||
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
|
||||
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
|
||||
</g>
|
||||
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".24"/>
|
||||
</g>
|
||||
|
||||
<g
|
||||
id="g8499"
|
||||
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
|
||||
id="XMLID_1_">
|
||||
<circle
|
||||
r="32.5"
|
||||
cy="48"
|
||||
cx="48"
|
||||
class="st0"
|
||||
id="XMLID_3_"
|
||||
style="fill:#2980b9" />
|
||||
<path
|
||||
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
|
||||
class="st1"
|
||||
id="XMLID_4_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#3498db" />
|
||||
<path
|
||||
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
|
||||
class="st2"
|
||||
id="XMLID_13_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#2ecc71" />
|
||||
<path
|
||||
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
|
||||
class="st3"
|
||||
id="XMLID_20_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#27ae60" />
|
||||
</g><g
|
||||
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
|
||||
id="g7664"><path
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_6_"
|
||||
class="st3"
|
||||
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
|
||||
style="fill:#f1aa27;fill-opacity:1" /><path
|
||||
style="fill:#e6e6e6"
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_7_"
|
||||
class="st4"
|
||||
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
|
||||
style="fill:#e6e6e6;fill-opacity:1"
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_8_"
|
||||
class="st5"
|
||||
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>
|
||||
<g transform="translate(512 490) scale(.82) translate(-512 -490)" filter="url(#lock-shadow)">
|
||||
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
|
||||
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
|
||||
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".3"/>
|
||||
<g fill="#85500f" opacity=".78">
|
||||
<path d="M501 538h22l16 69h-54Z"/>
|
||||
<circle cx="512" cy="521" r="27"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 2.8 KiB |
@@ -1,26 +1,31 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpapi::service::transport::SessionCredential;
|
||||
use log::info;
|
||||
use tauri::{Listener, Manager};
|
||||
use tokio::sync::watch;
|
||||
|
||||
use crate::updater::{GuiUpdater, Installer, ProgressNotifier};
|
||||
|
||||
pub struct App {
|
||||
api_key: Vec<u8>,
|
||||
credential: Arc<SessionCredential>,
|
||||
credential_lease: watch::Receiver<bool>,
|
||||
gui_version: String,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(api_key: Vec<u8>, gui_version: &str) -> Self {
|
||||
pub fn new(credential: Arc<SessionCredential>, credential_lease: watch::Receiver<bool>, gui_version: &str) -> Self {
|
||||
Self {
|
||||
api_key,
|
||||
credential,
|
||||
credential_lease,
|
||||
gui_version: gui_version.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self) -> anyhow::Result<()> {
|
||||
let gui_version = self.gui_version.clone();
|
||||
let api_key = self.api_key.clone();
|
||||
let credential = Arc::clone(&self.credential);
|
||||
let credential_lease = self.credential_lease.clone();
|
||||
|
||||
tauri::Builder::default()
|
||||
.setup(move |app| {
|
||||
@@ -28,9 +33,21 @@ impl App {
|
||||
let _ = win.hide_menu();
|
||||
|
||||
let notifier = ProgressNotifier::new(win.clone());
|
||||
let installer = Installer::new(api_key);
|
||||
let installer = Installer::new(credential, credential_lease.clone());
|
||||
let updater = Arc::new(GuiUpdater::new(gui_version, notifier, installer));
|
||||
|
||||
let app_handle = app.handle().clone();
|
||||
let mut app_credential_lease = credential_lease;
|
||||
tokio::spawn(async move {
|
||||
while *app_credential_lease.borrow() {
|
||||
if app_credential_lease.changed().await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
info!("Service credential lease ended");
|
||||
app_handle.exit(0);
|
||||
});
|
||||
|
||||
let win_clone = win.clone();
|
||||
app.listen_any("app://update-done", move |_event| {
|
||||
info!("Update done");
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
use clap::Parser;
|
||||
use std::{io::Read, sync::Arc};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::{
|
||||
clap::InfoLevelVerbosity,
|
||||
utils::{base64, env_utils},
|
||||
service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential},
|
||||
utils::env_utils,
|
||||
};
|
||||
use log::info;
|
||||
use tokio::sync::watch;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
@@ -15,13 +21,11 @@ const VERSION: &str = concat!(
|
||||
compile_time::date_str!(),
|
||||
")"
|
||||
);
|
||||
const GP_API_KEY: &[u8; 32] = &[0; 32];
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version = VERSION)]
|
||||
struct Cli {
|
||||
#[arg(long, help = "Read the API key from stdin")]
|
||||
api_key_on_stdin: bool,
|
||||
#[arg(long, help = "Read the service credential from stdin")]
|
||||
service_credential_on_stdin: bool,
|
||||
|
||||
#[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")]
|
||||
gui_version: String,
|
||||
@@ -32,28 +36,56 @@ struct Cli {
|
||||
|
||||
impl Cli {
|
||||
fn run(&self) -> anyhow::Result<()> {
|
||||
let api_key = self.read_api_key()?;
|
||||
let app = App::new(api_key, &self.gui_version);
|
||||
let credential = self.read_credential()?;
|
||||
let credential_lease = monitor_credential_lease().context("Failed to monitor service credential lifetime")?;
|
||||
let app = App::new(Arc::new(credential), credential_lease, &self.gui_version);
|
||||
|
||||
env_utils::patch_gui_runtime_env(false);
|
||||
|
||||
app.run()
|
||||
}
|
||||
|
||||
fn read_api_key(&self) -> anyhow::Result<Vec<u8>> {
|
||||
if self.api_key_on_stdin {
|
||||
let mut api_key = String::new();
|
||||
std::io::stdin().read_line(&mut api_key)?;
|
||||
|
||||
let api_key = base64::decode_to_vec(api_key.trim())?;
|
||||
|
||||
Ok(api_key)
|
||||
} else {
|
||||
Ok(GP_API_KEY.to_vec())
|
||||
fn read_credential(&self) -> anyhow::Result<SessionCredential> {
|
||||
if !self.service_credential_on_stdin {
|
||||
bail!("Service credential must be provided via --service-credential-on-stdin");
|
||||
}
|
||||
let stdin = std::io::stdin();
|
||||
let mut input = stdin.lock();
|
||||
let mut header = [0_u8; 2];
|
||||
input
|
||||
.read_exact(&mut header)
|
||||
.context("Failed to read service credential header")?;
|
||||
let payload_len = u16::from_be_bytes(header) as usize;
|
||||
if payload_len == 0 || payload_len + header.len() > MAX_CREDENTIAL_FRAME {
|
||||
bail!("Invalid service credential length");
|
||||
}
|
||||
let mut frame = Zeroizing::new(Vec::with_capacity(payload_len + header.len()));
|
||||
frame.extend_from_slice(&header);
|
||||
frame.resize(payload_len + header.len(), 0);
|
||||
input
|
||||
.read_exact(&mut frame[header.len()..])
|
||||
.context("Failed to read service credential")?;
|
||||
SessionCredential::decode_frame(&frame).context("Invalid service credential")
|
||||
}
|
||||
}
|
||||
|
||||
fn monitor_credential_lease() -> std::io::Result<watch::Receiver<bool>> {
|
||||
let (lease_tx, lease_rx) = watch::channel(true);
|
||||
std::thread::Builder::new()
|
||||
.name("credential-lease".to_owned())
|
||||
.spawn(move || {
|
||||
let stdin = std::io::stdin();
|
||||
close_credential_lease_at_eof(stdin.lock(), lease_tx);
|
||||
})?;
|
||||
Ok(lease_rx)
|
||||
}
|
||||
|
||||
fn close_credential_lease_at_eof(mut input: impl Read, lease_tx: watch::Sender<bool>) {
|
||||
let mut buffer = [0_u8; 256];
|
||||
while matches!(input.read(&mut buffer), Ok(len) if len > 0) {}
|
||||
let _ = lease_tx.send(false);
|
||||
}
|
||||
|
||||
fn init_logger(cli: &Cli) {
|
||||
env_logger::builder()
|
||||
.filter_level(cli.verbose.log_level_filter())
|
||||
@@ -71,3 +103,17 @@ pub fn run() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Cursor;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_lease_closes_at_eof() {
|
||||
let (lease_tx, lease_rx) = watch::channel(true);
|
||||
close_credential_lease_at_eof(Cursor::new(b"ignored lease bytes"), lease_tx);
|
||||
assert!(!*lease_rx.borrow());
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,31 @@
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::{
|
||||
error::Error,
|
||||
fmt::{self, Display, Formatter},
|
||||
sync::{Arc, RwLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use gpapi::{
|
||||
service::request::UpdateGuiRequest,
|
||||
utils::{checksum::verify_checksum, crypto::Crypto, endpoint::http_endpoint},
|
||||
service::{
|
||||
request::{UpdateGuiRequest, WsRequest},
|
||||
transport::{
|
||||
ClientMessage, ClientPrelude, MAX_WS_MESSAGE, NoiseInitiator, NoiseTransport, ServerMessage, ServerPrelude,
|
||||
ServiceResult, SessionCredential,
|
||||
},
|
||||
},
|
||||
utils::{checksum::verify_checksum, endpoint::ws_endpoint},
|
||||
};
|
||||
use log::{info, warn};
|
||||
use tauri::{Emitter, WebviewWindow};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio_tungstenite::{
|
||||
MaybeTlsStream, WebSocketStream, connect_async_with_config,
|
||||
tungstenite::{Message, protocol::WebSocketConfig},
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::downloader::{ChecksumFetcher, FileDownloader};
|
||||
|
||||
@@ -44,33 +64,285 @@ impl ProgressNotifier {
|
||||
}
|
||||
|
||||
pub struct Installer {
|
||||
crypto: Crypto,
|
||||
command_tx: mpsc::Sender<InstallCommand>,
|
||||
}
|
||||
|
||||
struct InstallCommand {
|
||||
request: UpdateGuiRequest,
|
||||
reply: oneshot::Sender<anyhow::Result<()>>,
|
||||
}
|
||||
|
||||
impl Installer {
|
||||
pub fn new(api_key: Vec<u8>) -> Self {
|
||||
Self {
|
||||
crypto: Crypto::new(api_key),
|
||||
}
|
||||
pub fn new(credential: Arc<SessionCredential>, credential_lease: watch::Receiver<bool>) -> Self {
|
||||
let (command_tx, command_rx) = mpsc::channel(1);
|
||||
tokio::spawn(async move {
|
||||
run_installer(credential, credential_lease, command_rx).await;
|
||||
});
|
||||
Self { command_tx }
|
||||
}
|
||||
|
||||
async fn install(&self, path: &str, checksum: &str) -> anyhow::Result<()> {
|
||||
let service_endpoint = http_endpoint().await?;
|
||||
|
||||
let request = UpdateGuiRequest {
|
||||
path: path.to_string(),
|
||||
checksum: checksum.to_string(),
|
||||
};
|
||||
let payload = self.crypto.encrypt(&request)?;
|
||||
let (reply, result) = oneshot::channel();
|
||||
self
|
||||
.command_tx
|
||||
.send(InstallCommand { request, reply })
|
||||
.await
|
||||
.context("Authenticated GUI installer is unavailable")?;
|
||||
tokio::time::timeout(Duration::from_secs(60), result)
|
||||
.await
|
||||
.context("Service update request timed out")?
|
||||
.context("Authenticated GUI installer stopped before replying")?
|
||||
}
|
||||
}
|
||||
|
||||
reqwest::Client::default()
|
||||
.post(format!("{}/update-gui", service_endpoint))
|
||||
.body(payload)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
||||
|
||||
Ok(())
|
||||
#[derive(Debug)]
|
||||
struct TerminalConnectError(String);
|
||||
|
||||
impl Display for TerminalConnectError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for TerminalConnectError {}
|
||||
|
||||
async fn run_installer(
|
||||
credential: Arc<SessionCredential>,
|
||||
mut credential_lease: watch::Receiver<bool>,
|
||||
mut commands: mpsc::Receiver<InstallCommand>,
|
||||
) {
|
||||
let mut pending = None;
|
||||
|
||||
loop {
|
||||
if !*credential_lease.borrow() {
|
||||
return;
|
||||
}
|
||||
|
||||
let connection = tokio::select! {
|
||||
changed = credential_lease.changed() => {
|
||||
if changed.is_err() || !*credential_lease.borrow() {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
result = tokio::time::timeout(Duration::from_secs(5), connect_installer(&credential)) => {
|
||||
match result {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err(anyhow::anyhow!("Authenticated GUI installer handshake timed out")),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match connection {
|
||||
Ok((mut socket, mut noise)) => {
|
||||
info!("Authenticated GUI installer connected");
|
||||
match run_installer_connection(
|
||||
&mut socket,
|
||||
&mut noise,
|
||||
&mut credential_lease,
|
||||
&mut commands,
|
||||
&mut pending,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(ConnectionEnd::CredentialLeaseEnded | ConnectionEnd::CommandsClosed) => return,
|
||||
Err(err) => warn!("Authenticated GUI installer connection lost: {err}"),
|
||||
}
|
||||
}
|
||||
Err(err) if err.is::<TerminalConnectError>() => {
|
||||
warn!("Authenticated GUI installer stopped: {err}");
|
||||
return;
|
||||
}
|
||||
Err(err) => warn!("Authenticated GUI installer connection failed: {err}"),
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
changed = credential_lease.changed() => {
|
||||
if changed.is_err() || !*credential_lease.borrow() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(Duration::from_millis(100)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ConnectionEnd {
|
||||
CredentialLeaseEnded,
|
||||
CommandsClosed,
|
||||
}
|
||||
|
||||
async fn run_installer_connection(
|
||||
socket: &mut Socket,
|
||||
noise: &mut NoiseTransport,
|
||||
credential_lease: &mut watch::Receiver<bool>,
|
||||
commands: &mut mpsc::Receiver<InstallCommand>,
|
||||
pending: &mut Option<InstallCommand>,
|
||||
) -> anyhow::Result<ConnectionEnd> {
|
||||
if pending.as_ref().is_some_and(|command| command.reply.is_closed()) {
|
||||
pending.take();
|
||||
}
|
||||
let mut pending_id = match pending.as_ref() {
|
||||
Some(command) => Some(send_install_command(socket, noise, command).await?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
changed = credential_lease.changed() => {
|
||||
if changed.is_err() || !*credential_lease.borrow() {
|
||||
return Ok(ConnectionEnd::CredentialLeaseEnded);
|
||||
}
|
||||
}
|
||||
command = commands.recv() => {
|
||||
let Some(command) = command else { return Ok(ConnectionEnd::CommandsClosed) };
|
||||
if command.reply.is_closed() {
|
||||
continue;
|
||||
}
|
||||
if pending.is_some() {
|
||||
let _ = command.reply.send(Err(anyhow::anyhow!("GUI installation is already pending")));
|
||||
continue;
|
||||
}
|
||||
*pending = Some(command);
|
||||
pending_id = Some(send_install_command(socket, noise, pending.as_ref().unwrap()).await?);
|
||||
}
|
||||
frame = socket.next() => {
|
||||
match frame.context("Service closed the authenticated GUI installer")?? {
|
||||
Message::Binary(data) => match noise.decrypt::<ServerMessage>(&data)? {
|
||||
ServerMessage::Reply { id, result } => {
|
||||
if pending_id != Some(id) {
|
||||
bail!("Service sent a mismatched GUI installation reply");
|
||||
}
|
||||
let Some(command) = pending.take() else {
|
||||
bail!("Service sent an unexpected GUI installation reply");
|
||||
};
|
||||
pending_id = None;
|
||||
let result = match result {
|
||||
ServiceResult::Accepted => Ok(()),
|
||||
ServiceResult::Rejected(rejection) => Err(anyhow::anyhow!(
|
||||
"Service rejected GUI installation ({:?}): {}",
|
||||
rejection.code(),
|
||||
rejection.message()
|
||||
)),
|
||||
ServiceResult::VpncScriptMetadata(_) => {
|
||||
Err(anyhow::anyhow!("Service sent an unexpected VPNC script metadata reply"))
|
||||
}
|
||||
};
|
||||
let _ = command.reply.send(result);
|
||||
}
|
||||
ServerMessage::Event { .. } | ServerMessage::Snapshot { .. } => {}
|
||||
ServerMessage::Attached { .. } => bail!("Service sent a duplicate attach response"),
|
||||
},
|
||||
Message::Ping(data) => socket.send(Message::Pong(data)).await?,
|
||||
Message::Pong(_) => {}
|
||||
Message::Close(_) => bail!("Service closed the authenticated GUI installer"),
|
||||
_ => bail!("Service sent an unexpected WebSocket frame"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_install_command(
|
||||
socket: &mut Socket,
|
||||
noise: &mut NoiseTransport,
|
||||
command: &InstallCommand,
|
||||
) -> anyhow::Result<Uuid> {
|
||||
let id = Uuid::new_v4();
|
||||
send_client_message(
|
||||
socket,
|
||||
noise,
|
||||
&ClientMessage::Request {
|
||||
id,
|
||||
request: WsRequest::UpdateGui(command.request.clone()),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
async fn connect_installer(credential: &SessionCredential) -> anyhow::Result<(Socket, NoiseTransport)> {
|
||||
let endpoint = ws_endpoint().await?;
|
||||
connect_installer_at(credential, &endpoint).await
|
||||
}
|
||||
|
||||
async fn connect_installer_at(
|
||||
credential: &SessionCredential,
|
||||
endpoint: &str,
|
||||
) -> anyhow::Result<(Socket, NoiseTransport)> {
|
||||
if credential.product_version() != env!("CARGO_PKG_VERSION") {
|
||||
return Err(TerminalConnectError("Service credential version does not match gpgui-helper".to_owned()).into());
|
||||
}
|
||||
let config = WebSocketConfig::default()
|
||||
.max_message_size(Some(MAX_WS_MESSAGE))
|
||||
.max_frame_size(Some(MAX_WS_MESSAGE));
|
||||
let (mut socket, _) = connect_async_with_config(endpoint, Some(config), false).await?;
|
||||
let prelude = ClientPrelude {
|
||||
product_version: credential.product_version().to_owned(),
|
||||
service_instance_id: credential.service_instance_id(),
|
||||
session_id: credential.session_id(),
|
||||
};
|
||||
socket.send(Message::Binary(prelude.encode()?.into())).await?;
|
||||
let server_prelude = ServerPrelude::decode(&receive_binary(&mut socket).await?)
|
||||
.map_err(|err| TerminalConnectError(format!("Service sent an invalid update-session response: {err}")))?;
|
||||
match server_prelude {
|
||||
ServerPrelude::Ready => {}
|
||||
ServerPrelude::Rejected(reason) => {
|
||||
return Err(TerminalConnectError(format!("Service rejected the update session: {reason:?}")).into());
|
||||
}
|
||||
}
|
||||
|
||||
let mut initiator = NoiseInitiator::new(
|
||||
credential.product_version(),
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.secret(),
|
||||
)?;
|
||||
socket.send(Message::Binary(initiator.write_first()?.into())).await?;
|
||||
let mut noise = initiator.read_response(&receive_binary(&mut socket).await?)?;
|
||||
send_client_message(
|
||||
&mut socket,
|
||||
&mut noise,
|
||||
&ClientMessage::Attach {
|
||||
last_event_revision: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
if !matches!(
|
||||
receive_server_message(&mut socket, &mut noise).await?,
|
||||
ServerMessage::Attached { .. }
|
||||
) {
|
||||
bail!("Service did not attach the update session");
|
||||
}
|
||||
|
||||
Ok((socket, noise))
|
||||
}
|
||||
|
||||
async fn send_client_message(
|
||||
socket: &mut Socket,
|
||||
noise: &mut NoiseTransport,
|
||||
message: &ClientMessage,
|
||||
) -> anyhow::Result<()> {
|
||||
socket.send(Message::Binary(noise.encrypt(message)?.into())).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive_server_message(socket: &mut Socket, noise: &mut NoiseTransport) -> anyhow::Result<ServerMessage> {
|
||||
Ok(noise.decrypt(&receive_binary(socket).await?)?)
|
||||
}
|
||||
|
||||
async fn receive_binary(socket: &mut Socket) -> anyhow::Result<Vec<u8>> {
|
||||
match socket.next().await {
|
||||
Some(Ok(Message::Binary(data))) => Ok(data.to_vec()),
|
||||
Some(Ok(_)) => bail!("Service sent an unexpected handshake frame"),
|
||||
Some(Err(err)) => Err(err.into()),
|
||||
None => bail!("Service closed during handshake"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,3 +478,168 @@ impl GuiUpdater {
|
||||
self.notifier.notify(progress);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpapi::{
|
||||
os_profile::HostIdentity,
|
||||
service::{
|
||||
transport::{ClientPrelude, NoiseResponder},
|
||||
vpn_env::{HostInfo, VpnEnv},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::accept_async;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_install_reconnects_with_a_fresh_handshake() {
|
||||
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), env!("CARGO_PKG_VERSION")).unwrap());
|
||||
let (command_tx, mut commands) = mpsc::channel(1);
|
||||
let (reply_tx, reply_rx) = oneshot::channel();
|
||||
command_tx
|
||||
.send(InstallCommand {
|
||||
request: UpdateGuiRequest {
|
||||
path: "/tmp/gpgui-update".to_owned(),
|
||||
checksum: "checksum".to_owned(),
|
||||
},
|
||||
reply: reply_tx,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let (_lease_tx, mut credential_lease) = watch::channel(true);
|
||||
let mut pending = None;
|
||||
|
||||
let (first_endpoint, first_service) = spawn_test_service(Arc::clone(&credential), false).await;
|
||||
let (mut socket, mut noise) = connect_installer_at(&credential, &first_endpoint).await.unwrap();
|
||||
assert!(
|
||||
run_installer_connection(
|
||||
&mut socket,
|
||||
&mut noise,
|
||||
&mut credential_lease,
|
||||
&mut commands,
|
||||
&mut pending,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
first_service.await.unwrap();
|
||||
assert!(pending.is_some());
|
||||
|
||||
let (second_endpoint, second_service) = spawn_test_service(Arc::clone(&credential), true).await;
|
||||
let (mut socket, mut noise) = connect_installer_at(&credential, &second_endpoint).await.unwrap();
|
||||
assert!(
|
||||
run_installer_connection(
|
||||
&mut socket,
|
||||
&mut noise,
|
||||
&mut credential_lease,
|
||||
&mut commands,
|
||||
&mut pending,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
second_service.await.unwrap();
|
||||
assert!(pending.is_none());
|
||||
assert!(reply_rx.await.unwrap().is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_version_mismatch_is_terminal() {
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "different-version").unwrap();
|
||||
let Err(err) = connect_installer_at(&credential, "ws://127.0.0.1:1/ws").await else {
|
||||
panic!("version mismatch should fail before connecting");
|
||||
};
|
||||
assert!(err.is::<TerminalConnectError>());
|
||||
}
|
||||
|
||||
async fn spawn_test_service(
|
||||
credential: Arc<SessionCredential>,
|
||||
reply: bool,
|
||||
) -> (String, tokio::task::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = format!("ws://{}/ws", listener.local_addr().unwrap());
|
||||
let service = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut socket = accept_async(stream).await.unwrap();
|
||||
let prelude = match socket.next().await.unwrap().unwrap() {
|
||||
Message::Binary(data) => ClientPrelude::decode(&data).unwrap(),
|
||||
frame => panic!("unexpected prelude frame: {frame:?}"),
|
||||
};
|
||||
assert_eq!(prelude.service_instance_id, credential.service_instance_id());
|
||||
assert_eq!(prelude.session_id, credential.session_id());
|
||||
socket
|
||||
.send(Message::Binary(ServerPrelude::Ready.encode().unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut responder = NoiseResponder::new(
|
||||
credential.product_version(),
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.secret(),
|
||||
)
|
||||
.unwrap();
|
||||
let first = match socket.next().await.unwrap().unwrap() {
|
||||
Message::Binary(data) => data,
|
||||
frame => panic!("unexpected handshake frame: {frame:?}"),
|
||||
};
|
||||
responder.read_first(&first).unwrap();
|
||||
let (response, mut noise) = responder.write_response().unwrap();
|
||||
socket.send(Message::Binary(response.into())).await.unwrap();
|
||||
|
||||
let attach = match socket.next().await.unwrap().unwrap() {
|
||||
Message::Binary(data) => data,
|
||||
frame => panic!("unexpected attach frame: {frame:?}"),
|
||||
};
|
||||
assert!(matches!(
|
||||
noise.decrypt::<ClientMessage>(&attach).unwrap(),
|
||||
ClientMessage::Attach { .. }
|
||||
));
|
||||
let attached = ServerMessage::Attached {
|
||||
connection_id: Uuid::new_v4(),
|
||||
current_revision: 0,
|
||||
snapshot: VpnEnv {
|
||||
vpn_state: VpnState::Disconnected,
|
||||
vpnc_script: None,
|
||||
csd_wrapper: None,
|
||||
auth_executable: String::new(),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
},
|
||||
},
|
||||
};
|
||||
socket
|
||||
.send(Message::Binary(noise.encrypt(&attached).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let request = match socket.next().await.unwrap().unwrap() {
|
||||
Message::Binary(data) => noise.decrypt::<ClientMessage>(&data).unwrap(),
|
||||
frame => panic!("unexpected request frame: {frame:?}"),
|
||||
};
|
||||
let ClientMessage::Request {
|
||||
id,
|
||||
request: WsRequest::UpdateGui(update),
|
||||
} = request
|
||||
else {
|
||||
panic!("unexpected installer request");
|
||||
};
|
||||
assert_eq!(update.path, "/tmp/gpgui-update");
|
||||
if reply {
|
||||
let message = ServerMessage::Reply {
|
||||
id,
|
||||
result: ServiceResult::Accepted,
|
||||
};
|
||||
socket
|
||||
.send(Message::Binary(noise.encrypt(&message).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
socket.close(None).await.unwrap();
|
||||
});
|
||||
(endpoint, service)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#579bc1"/>
|
||||
<stop offset=".52" stop-color="#438fbd"/>
|
||||
<stop offset="1" stop-color="#2f719e"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#56c78a"/>
|
||||
<stop offset=".55" stop-color="#3bbf78"/>
|
||||
<stop offset="1" stop-color="#279b5d"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#f3b84c"/>
|
||||
<stop offset=".55" stop-color="#e8a12f"/>
|
||||
<stop offset="1" stop-color="#d4871e"/>
|
||||
</linearGradient>
|
||||
<clipPath id="globe-clip">
|
||||
<circle cx="512" cy="455" r="315"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
|
||||
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
|
||||
<g clip-path="url(#globe-clip)" fill="url(#land)">
|
||||
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
|
||||
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
|
||||
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
|
||||
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
|
||||
</g>
|
||||
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".4"/>
|
||||
|
||||
<g transform="translate(512 490) scale(.82) translate(-512 -490)">
|
||||
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
|
||||
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
|
||||
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".45"/>
|
||||
<g fill="#85500f" opacity=".85">
|
||||
<path d="M501 538h22l16 69h-54Z"/>
|
||||
<circle cx="512" cy="521" r="27"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -1,99 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
version="1.1"
|
||||
id="Layer_1"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 96 96"
|
||||
style="enable-background:new 0 0 96 96;"
|
||||
xml:space="preserve"
|
||||
sodipodi:docname="com.yuezk.qt.gpclient.svg"
|
||||
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
|
||||
id="metadata14"><rdf:RDF><cc:Work
|
||||
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
|
||||
id="defs12" /><sodipodi:namedview
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1"
|
||||
objecttolerance="10"
|
||||
gridtolerance="10"
|
||||
guidetolerance="10"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:window-width="1920"
|
||||
inkscape:window-height="1006"
|
||||
id="namedview10"
|
||||
showgrid="false"
|
||||
inkscape:zoom="6.9532168"
|
||||
inkscape:cx="7.9545315"
|
||||
inkscape:cy="59.062386"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="g8499" />
|
||||
<style
|
||||
type="text/css"
|
||||
id="style2">
|
||||
.st0{fill:#2980B9;}
|
||||
.st1{fill:#3498DB;}
|
||||
.st2{fill:#2ECC71;}
|
||||
.st3{fill:#27AE60;}
|
||||
</style>
|
||||
|
||||
<g
|
||||
id="g8499"
|
||||
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
|
||||
id="XMLID_1_">
|
||||
<circle
|
||||
r="32.5"
|
||||
cy="48"
|
||||
cx="48"
|
||||
class="st0"
|
||||
id="XMLID_3_"
|
||||
style="fill:#2980b9" />
|
||||
<path
|
||||
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
|
||||
class="st1"
|
||||
id="XMLID_4_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#3498db" />
|
||||
<path
|
||||
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
|
||||
class="st2"
|
||||
id="XMLID_13_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#2ecc71" />
|
||||
<path
|
||||
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
|
||||
class="st3"
|
||||
id="XMLID_20_"
|
||||
inkscape:connector-curvature="0"
|
||||
style="fill:#27ae60" />
|
||||
</g><g
|
||||
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
|
||||
id="g7664"><path
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_6_"
|
||||
class="st3"
|
||||
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
|
||||
style="fill:#f1aa27;fill-opacity:1" /><path
|
||||
style="fill:#e6e6e6"
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_7_"
|
||||
class="st4"
|
||||
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
|
||||
style="fill:#e6e6e6;fill-opacity:1"
|
||||
inkscape:connector-curvature="0"
|
||||
id="XMLID_8_"
|
||||
class="st5"
|
||||
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>
|
||||
|
Before Width: | Height: | Size: 6.7 KiB |
@@ -1,6 +1,6 @@
|
||||
import { Box, Button, CssBaseline, LinearProgress, Typography } from "@mui/material";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import logo from "../../assets/icon.svg";
|
||||
import logo from "../../assets/icon-small.svg";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import "./styles.css";
|
||||
|
||||
@@ -21,3 +21,13 @@ log.workspace = true
|
||||
compile-time.workspace = true
|
||||
xz2 = "0.1"
|
||||
tar = "0.4"
|
||||
thiserror.workspace = true
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
zeroize.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-tungstenite = "0.29"
|
||||
@@ -0,0 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod platform;
|
||||
|
||||
fn main() {
|
||||
platform::run();
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use std::io::Read;
|
||||
|
||||
use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpapi::service::vpnc_script::InstallVpncScriptRequest;
|
||||
use nix::unistd::Uid;
|
||||
|
||||
const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
Install,
|
||||
Remove,
|
||||
}
|
||||
|
||||
fn try_run() -> anyhow::Result<()> {
|
||||
if !Uid::effective().is_root() {
|
||||
bail!("The VPNC script installer must run as root");
|
||||
}
|
||||
|
||||
match Cli::parse().command {
|
||||
Command::Install => {
|
||||
let input = std::io::stdin().lock().take(MAX_INSTALL_REQUEST_SIZE);
|
||||
let request = serde_json::from_reader::<_, InstallVpncScriptRequest>(input)?;
|
||||
gpservice::vpnc_script::install(request)
|
||||
}
|
||||
Command::Remove => gpservice::vpnc_script::remove(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run() {
|
||||
if let Err(err) = try_run() {
|
||||
eprintln!("Error: {err:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub(super) fn run() {
|
||||
eprintln!("The VPNC script installer is only available on Linux, FreeBSD, and OpenBSD");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -1,20 +1,33 @@
|
||||
use std::sync::Arc;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::time::Duration;
|
||||
use std::{collections::HashMap, io::Write};
|
||||
|
||||
use anyhow::bail;
|
||||
use anyhow::{Context, bail};
|
||||
use clap::Parser;
|
||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||
use gpapi::clap::InfoLevelVerbosity;
|
||||
use gpapi::logger;
|
||||
#[cfg(debug_assertions)]
|
||||
use gpapi::utils::lock_file::dev_service_lock_file_path;
|
||||
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::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use log::{Log, Metadata, Record};
|
||||
use log::{info, warn};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{vpn_task::VpnTask, ws_server::WsServer};
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
||||
};
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
@@ -25,6 +38,28 @@ const VERSION: &str = concat!(
|
||||
")"
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
struct RedactingMacosLogger {
|
||||
logger: logger::MacosLogger,
|
||||
redaction: Arc<Redaction>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Log for RedactingMacosLogger {
|
||||
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
|
||||
self.logger.enabled(metadata)
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record<'_>) {
|
||||
if self.enabled(record.metadata()) {
|
||||
let message = self.redaction.redact_str(&record.args().to_string());
|
||||
self.logger.write(record.level(), record.target(), &message);
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version = VERSION)]
|
||||
struct Cli {
|
||||
@@ -33,9 +68,17 @@ struct Cli {
|
||||
#[clap(long)]
|
||||
env_file: Option<String>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long)]
|
||||
no_gui: bool,
|
||||
|
||||
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
|
||||
dev_standalone: bool,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long, requires = "dev_standalone")]
|
||||
dev_uid: Option<u32>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long, requires = "dev_standalone")]
|
||||
dev_bootstrap_socket: Option<PathBuf>,
|
||||
#[cfg(target_os = "macos")]
|
||||
#[clap(long, conflicts_with = "dev_standalone")]
|
||||
macos_brokered: bool,
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
@@ -46,27 +89,94 @@ impl Cli {
|
||||
info!("gpservice started: {}", VERSION);
|
||||
|
||||
let pid = std::process::id();
|
||||
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
|
||||
let lock_file = Arc::new(LockFile::new(self.service_lock_file_path()?, pid));
|
||||
|
||||
if lock_file.check_health().await {
|
||||
bail!("Another instance of the service is already running");
|
||||
}
|
||||
|
||||
let api_key = self.prepare_api_key();
|
||||
|
||||
// Channel for sending requests to the VPN task
|
||||
let (ws_req_tx, ws_req_rx) = mpsc::channel::<WsRequest>(32);
|
||||
// Channel for receiving the VPN state from the VPN task
|
||||
let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let gui_restart_requested = Arc::new(AtomicBool::new(false));
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let externally_brokered = self.externally_brokered();
|
||||
let trusted_csd_uid = crate::runtime_user::trusted_csd_uid()?;
|
||||
let brokered_scripts_dir = if externally_brokered {
|
||||
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
|
||||
let contents_dir = executable
|
||||
.parent()
|
||||
.and_then(std::path::Path::parent)
|
||||
.context("gpservice is not inside a macOS application bundle")?;
|
||||
Some(contents_dir.join("Resources/Scripts"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
ws_req_tx.clone(),
|
||||
Arc::clone(&gui_restart_requested),
|
||||
Arc::clone(&redaction),
|
||||
!externally_brokered,
|
||||
brokered_scripts_dir,
|
||||
));
|
||||
|
||||
let mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx);
|
||||
let ws_server = WsServer::new(api_key.clone(), ws_req_tx, vpn_state_rx, lock_file.clone(), redaction);
|
||||
let mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx, externally_brokered, trusted_csd_uid);
|
||||
#[cfg(target_os = "macos")]
|
||||
let idle_vpn_state_rx = vpn_state_rx.clone();
|
||||
let ws_server = WsServer::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Arc::clone(®istry),
|
||||
dispatcher,
|
||||
vpn_state_rx,
|
||||
lock_file.clone(),
|
||||
);
|
||||
|
||||
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
|
||||
let shutdown_tx_clone = shutdown_tx.clone();
|
||||
let vpn_task_cancel_token = vpn_task.cancel_token();
|
||||
let server_token = ws_server.cancel_token();
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if externally_brokered {
|
||||
let credential_server = crate::macos_broker::CredentialServer::new(Arc::clone(®istry));
|
||||
let credential_token = server_token.clone();
|
||||
let credential_shutdown = shutdown_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = credential_server.start(credential_token).await {
|
||||
warn!("Broker credential server stopped: {err}");
|
||||
let _ = credential_shutdown.send(()).await;
|
||||
}
|
||||
});
|
||||
|
||||
let idle_registry = Arc::clone(®istry);
|
||||
let idle_shutdown = shutdown_tx.clone();
|
||||
let idle_token = server_token.clone();
|
||||
tokio::spawn(async move {
|
||||
wait_for_brokered_idle(idle_vpn_state_rx, idle_registry, idle_token).await;
|
||||
let _ = idle_shutdown.send(()).await;
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
if self.dev_standalone {
|
||||
let Some(dev_bootstrap_socket) = self.dev_bootstrap_socket.clone() else {
|
||||
bail!("--dev-bootstrap-socket is required with --dev-standalone");
|
||||
};
|
||||
let Some(dev_uid) = self.dev_uid else {
|
||||
bail!("--dev-uid is required with --dev-standalone");
|
||||
};
|
||||
let bootstrap = crate::dev_bootstrap::DevBootstrap::new(dev_bootstrap_socket, dev_uid, Arc::clone(®istry));
|
||||
let bootstrap_token = server_token.clone();
|
||||
let bootstrap_shutdown = shutdown_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = bootstrap.start(bootstrap_token).await {
|
||||
warn!("Debug bootstrap stopped: {err}");
|
||||
let _ = bootstrap_shutdown.send(()).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let vpn_ctx = vpn_task.context();
|
||||
@@ -76,25 +186,24 @@ impl Cli {
|
||||
}
|
||||
|
||||
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
|
||||
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone).await });
|
||||
let (ws_ready_tx, ws_ready_rx) = tokio::sync::oneshot::channel();
|
||||
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone, ws_ready_tx).await });
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
let no_gui = self.no_gui;
|
||||
|
||||
let launch_managed_gui = !self.dev_standalone && !externally_brokered;
|
||||
#[cfg(not(debug_assertions))]
|
||||
let no_gui = false;
|
||||
let launch_managed_gui = !externally_brokered;
|
||||
|
||||
if no_gui {
|
||||
info!("GUI is disabled");
|
||||
} else {
|
||||
if launch_managed_gui {
|
||||
ws_ready_rx.await.context("WebSocket server failed to start")?;
|
||||
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
|
||||
|
||||
let minimized = self.minimized;
|
||||
|
||||
tokio::spawn(async move {
|
||||
launch_gui(envs, api_key, minimized).await;
|
||||
launch_gui(envs, registry, minimized, gui_restart_requested).await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
});
|
||||
} else {
|
||||
info!("Running with a separately started debug GUI");
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
@@ -116,8 +225,43 @@ impl Cli {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn externally_brokered(&self) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
return self.macos_brokered;
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
false
|
||||
}
|
||||
|
||||
fn service_lock_file_path(&self) -> anyhow::Result<PathBuf> {
|
||||
#[cfg(debug_assertions)]
|
||||
if self.dev_standalone {
|
||||
let socket = self
|
||||
.dev_bootstrap_socket
|
||||
.as_ref()
|
||||
.context("--dev-bootstrap-socket is required with --dev-standalone")?;
|
||||
return Ok(dev_service_lock_file_path(socket));
|
||||
}
|
||||
|
||||
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
|
||||
}
|
||||
|
||||
fn init_logger(&self) -> Arc<Redaction> {
|
||||
let redaction = Arc::new(Redaction::new());
|
||||
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if logger::macos_unified_log_enabled() {
|
||||
logger::init_with_logger(
|
||||
level,
|
||||
RedactingMacosLogger {
|
||||
logger: logger::MacosLogger::new("com.yuezk.gpgui", "gpservice"),
|
||||
redaction: Arc::clone(&redaction),
|
||||
},
|
||||
);
|
||||
return redaction;
|
||||
}
|
||||
|
||||
let redaction_clone = Arc::clone(&redaction);
|
||||
|
||||
let inner_logger = env_logger::builder()
|
||||
@@ -136,20 +280,41 @@ impl Cli {
|
||||
})
|
||||
.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 {
|
||||
return gpapi::GP_API_KEY.to_vec();
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn wait_for_brokered_idle(
|
||||
mut vpn_state_rx: watch::Receiver<VpnState>,
|
||||
registry: Arc<SessionRegistry>,
|
||||
cancel: tokio_util::sync::CancellationToken,
|
||||
) {
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const CHECK_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
let mut idle_since = None;
|
||||
let mut interval = tokio::time::interval(CHECK_INTERVAL);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
_ = vpn_state_rx.changed() => {},
|
||||
_ = interval.tick() => {},
|
||||
}
|
||||
|
||||
generate_key().to_vec()
|
||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected) && registry.is_empty();
|
||||
if !idle {
|
||||
idle_since = None;
|
||||
continue;
|
||||
}
|
||||
|
||||
let started = idle_since.get_or_insert_with(tokio::time::Instant::now);
|
||||
if started.elapsed() >= IDLE_TIMEOUT {
|
||||
info!("Brokered service idle timeout reached");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,24 +366,39 @@ mod signals {
|
||||
}
|
||||
}
|
||||
|
||||
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
|
||||
async fn launch_gui(
|
||||
envs: Option<HashMap<String, String>>,
|
||||
registry: Arc<SessionRegistry>,
|
||||
mut minimized: bool,
|
||||
restart_requested: Arc<AtomicBool>,
|
||||
) {
|
||||
loop {
|
||||
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), &api_key)
|
||||
let credential = match registry.issue(env!("CARGO_PKG_VERSION")) {
|
||||
Ok(credential) => credential,
|
||||
Err(err) => {
|
||||
warn!("Failed to issue GUI credential: {err}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let session_id = credential.session_id();
|
||||
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), credential)
|
||||
.envs(envs.clone())
|
||||
.minimized(minimized);
|
||||
|
||||
match gui_launcher.launch().await {
|
||||
Ok(exit_status) => {
|
||||
// Exit code 99 means that the GUI needs to be restarted
|
||||
if exit_status.code() != Some(99) {
|
||||
registry.revoke(session_id);
|
||||
let should_restart = restart_requested.swap(false, Ordering::SeqCst);
|
||||
if !should_restart {
|
||||
info!("GUI exited with code {:?}", exit_status.code());
|
||||
break;
|
||||
}
|
||||
|
||||
info!("GUI exited with code 99, restarting");
|
||||
info!("GUI restart requested, restarting");
|
||||
minimized = false;
|
||||
}
|
||||
Err(err) => {
|
||||
registry.revoke(session_id);
|
||||
warn!("Failed to launch GUI: {}", err);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::UnixStream,
|
||||
};
|
||||
|
||||
use crate::session_registry::SessionRegistry;
|
||||
|
||||
pub(crate) async fn serve(mut stream: UnixStream, registry: Arc<SessionRegistry>) -> anyhow::Result<()> {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"))?;
|
||||
let session_id = credential.session_id();
|
||||
let result = async {
|
||||
stream.write_all(&credential.encode_frame()?).await?;
|
||||
|
||||
let mut buffer = [0_u8; 1];
|
||||
loop {
|
||||
match stream.read(&mut buffer).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => continue,
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
registry.revoke(session_id);
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
use std::{
|
||||
os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use log::{info, warn};
|
||||
use nix::unistd::{Uid, chown};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{credential_lease, session_registry::SessionRegistry};
|
||||
|
||||
pub struct DevBootstrap {
|
||||
path: PathBuf,
|
||||
allowed_uid: u32,
|
||||
registry: Arc<SessionRegistry>,
|
||||
}
|
||||
|
||||
impl DevBootstrap {
|
||||
pub fn new(path: PathBuf, allowed_uid: u32, registry: Arc<SessionRegistry>) -> Self {
|
||||
Self {
|
||||
path,
|
||||
allowed_uid,
|
||||
registry,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
|
||||
create_default_parent(&self.path, self.allowed_uid)?;
|
||||
let path = prepare_socket_path(&self.path, self.allowed_uid)?;
|
||||
let listener = UnixListener::bind(&path)
|
||||
.with_context(|| format!("Failed to bind debug bootstrap socket at {}", path.display()))?;
|
||||
chown(&path, Some(Uid::from_raw(self.allowed_uid)), None)?;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
||||
info!("Debug credential bootstrap listening at {}", path.display());
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break,
|
||||
accepted = listener.accept() => {
|
||||
let (stream, _) = accepted?;
|
||||
let peer_uid = match peer_uid(&stream) {
|
||||
Ok(uid) => uid,
|
||||
Err(err) => {
|
||||
warn!("Could not verify debug credential client UID: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if peer_uid != self.allowed_uid {
|
||||
warn!("Rejected debug credential client with unexpected UID");
|
||||
continue;
|
||||
}
|
||||
let registry = Arc::clone(&self.registry);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = credential_lease::serve(stream, registry).await {
|
||||
warn!("Debug credential client ended: {err}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if path.exists() {
|
||||
std::fs::remove_file(&path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn create_default_parent(path: &Path, allowed_uid: u32) -> anyhow::Result<()> {
|
||||
let default = default_socket_path(allowed_uid);
|
||||
if path != default {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("Debug bootstrap socket has no parent directory")?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o711))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn default_socket_path(allowed_uid: u32) -> PathBuf {
|
||||
PathBuf::from(format!("/var/run/gpservice-dev-{allowed_uid}/dev-bootstrap.sock"))
|
||||
}
|
||||
|
||||
fn prepare_socket_path(path: &Path, allowed_uid: u32) -> anyhow::Result<PathBuf> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("Debug bootstrap socket has no parent directory")?;
|
||||
let parent = std::fs::canonicalize(parent)
|
||||
.with_context(|| format!("Debug bootstrap directory does not exist: {}", parent.display()))?;
|
||||
let metadata = std::fs::symlink_metadata(&parent)?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
||||
bail!("Debug bootstrap parent must be a real directory");
|
||||
}
|
||||
if metadata.uid() != 0 || metadata.permissions().mode() & 0o777 != 0o711 {
|
||||
bail!("Debug bootstrap parent must be owned by root with mode 0711");
|
||||
}
|
||||
|
||||
let file_name = path.file_name().context("Debug bootstrap socket has no file name")?;
|
||||
let path = parent.join(file_name);
|
||||
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => {
|
||||
if metadata.file_type().is_symlink()
|
||||
|| !metadata.file_type().is_socket()
|
||||
|| metadata.uid() != allowed_uid
|
||||
|| metadata.permissions().mode() & 0o777 != 0o600
|
||||
{
|
||||
bail!("Refusing unsafe existing debug bootstrap path");
|
||||
}
|
||||
std::fs::remove_file(&path)?;
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
||||
use nix::sys::socket::{getsockopt, sockopt};
|
||||
|
||||
let credentials = getsockopt(stream, sockopt::PeerCredentials)?;
|
||||
Ok(credentials.uid())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
||||
let (uid, _) = nix::unistd::getpeereid(stream)?;
|
||||
Ok(uid.as_raw())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
|
||||
use gpapi::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
|
||||
use tokio::io::AsyncReadExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_developer_owned_parent() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let socket = temp.path().join("bootstrap.sock");
|
||||
|
||||
assert!(prepare_socket_path(&socket, Uid::current().as_raw()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlink_socket_path() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let target = temp.path().join("target");
|
||||
std::fs::write(&target, "not a socket").unwrap();
|
||||
let socket = temp.path().join("bootstrap.sock");
|
||||
symlink(target, &socket).unwrap();
|
||||
|
||||
assert!(prepare_socket_path(&socket, Uid::current().as_raw()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_parent_is_not_created_by_the_service() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let parent = temp.path().join("missing");
|
||||
let socket = parent.join("bootstrap.sock");
|
||||
|
||||
create_default_parent(&socket, Uid::current().as_raw()).unwrap();
|
||||
|
||||
assert!(!parent.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_socket_path_is_stable() {
|
||||
assert_eq!(
|
||||
default_socket_path(1234),
|
||||
PathBuf::from("/var/run/gpservice-dev-1234/dev-bootstrap.sock")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anchor_eof_revokes_issued_credential() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let (service, mut client) = UnixStream::pair().unwrap();
|
||||
let task = tokio::spawn(credential_lease::serve(service, Arc::clone(®istry)));
|
||||
|
||||
let mut header = [0_u8; 2];
|
||||
client.read_exact(&mut header).await.unwrap();
|
||||
let payload_len = u16::from_be_bytes(header) as usize;
|
||||
assert!(payload_len + 2 <= MAX_CREDENTIAL_FRAME);
|
||||
let mut frame = vec![0_u8; payload_len + 2];
|
||||
frame[..2].copy_from_slice(&header);
|
||||
client.read_exact(&mut frame[2..]).await.unwrap();
|
||||
let credential = SessionCredential::decode_frame(&frame).unwrap();
|
||||
drop(client);
|
||||
task.await.unwrap().unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
registry.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version()
|
||||
),
|
||||
Err(crate::session_registry::SessionError::Unauthorized)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_uid_matches_current_process() {
|
||||
let (stream, _peer) = UnixStream::pair().unwrap();
|
||||
assert_eq!(peer_uid(&stream).unwrap(), Uid::current().as_raw());
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,12 @@
|
||||
use std::{
|
||||
fs::{File, Permissions},
|
||||
io::BufReader,
|
||||
ops::ControlFlow,
|
||||
os::unix::fs::PermissionsExt,
|
||||
sync::Arc,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::bail;
|
||||
use axum::{
|
||||
body::Bytes,
|
||||
extract::{
|
||||
State, WebSocketUpgrade,
|
||||
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
|
||||
},
|
||||
http::StatusCode,
|
||||
extract::{State, WebSocketUpgrade},
|
||||
response::IntoResponse,
|
||||
};
|
||||
use common::binary_paths;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use gpapi::{
|
||||
service::{event::WsEvent, request::UpdateGuiRequest},
|
||||
utils::checksum::verify_checksum,
|
||||
};
|
||||
use log::{info, warn};
|
||||
use tar::Archive;
|
||||
use tokio::fs;
|
||||
use xz2::read::XzDecoder;
|
||||
use gpapi::service::{event::WsEvent, transport::MAX_WS_MESSAGE};
|
||||
|
||||
use crate::ws_server::WsServerContext;
|
||||
use crate::{ws_connection::WsConnection, ws_server::WsServerContext};
|
||||
|
||||
pub(crate) async fn health() -> impl IntoResponse {
|
||||
"OK"
|
||||
@@ -37,133 +16,8 @@ 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> {
|
||||
let payload = match ctx.decrypt::<UpdateGuiRequest>(body.to_vec()) {
|
||||
Ok(payload) => payload,
|
||||
Err(err) => {
|
||||
warn!("Failed to decrypt update payload: {}", err);
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
};
|
||||
|
||||
info!("Update GUI: {:?}", payload);
|
||||
let UpdateGuiRequest { path, checksum } = payload;
|
||||
|
||||
info!("Verifying checksum");
|
||||
verify_checksum(&path, &checksum).map_err(|err| {
|
||||
warn!("Failed to verify checksum: {}", err);
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
info!("Installing GUI");
|
||||
install_gui(&path).await.map_err(|err| {
|
||||
warn!("Failed to install GUI: {}", err);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Unpack GPGUI archive, gpgui_2.0.0_{arch}.bin.tar.xz and install it
|
||||
async fn install_gui(src: &str) -> anyhow::Result<()> {
|
||||
let target = binary_paths::gpgui();
|
||||
let Some(dir) = target.parent() else {
|
||||
bail!("Failed to get parent directory of GUI binary");
|
||||
};
|
||||
|
||||
fs::create_dir_all(dir).await?;
|
||||
|
||||
// Unpack the archive
|
||||
info!("Unpacking GUI archive");
|
||||
let tar = XzDecoder::new(BufReader::new(File::open(src)?));
|
||||
let mut ar = Archive::new(tar);
|
||||
|
||||
for entry in ar.entries()? {
|
||||
let mut entry = entry?;
|
||||
let entry_path = entry.path()?;
|
||||
|
||||
if let Some(name) = entry_path.file_name() {
|
||||
let name = name.to_string_lossy();
|
||||
|
||||
if name == "gpgui" {
|
||||
let mut file = File::create(&target)?;
|
||||
std::io::copy(&mut entry, &mut file)?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make the binary executable
|
||||
fs::set_permissions(target, Permissions::from_mode(0o755)).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn ws_handler(ws: WebSocketUpgrade, State(ctx): State<Arc<WsServerContext>>) -> impl IntoResponse {
|
||||
ws.on_upgrade(move |socket| handle_socket(socket, ctx))
|
||||
}
|
||||
|
||||
async fn handle_socket(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
|
||||
// Send ping message
|
||||
if let Err(err) = socket.send(Message::Ping("Hi".into())).await {
|
||||
warn!("Failed to send ping: {}", err);
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for pong message
|
||||
if socket.recv().await.is_none() {
|
||||
warn!("Failed to receive pong");
|
||||
return;
|
||||
}
|
||||
|
||||
info!("New client connected");
|
||||
|
||||
let (mut sender, mut receiver) = socket.split();
|
||||
let (connection, mut msg_rx) = ctx.add_connection().await;
|
||||
|
||||
let send_task = tokio::spawn(async move {
|
||||
while let Some(msg) = msg_rx.recv().await {
|
||||
if let Err(err) = sender.send(msg).await {
|
||||
info!("Failed to send message: {}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let close_msg = Message::Close(Some(CloseFrame {
|
||||
code: ws::close_code::NORMAL,
|
||||
reason: Utf8Bytes::from("Goodbye"),
|
||||
}));
|
||||
|
||||
if let Err(err) = sender.send(close_msg).await {
|
||||
warn!("Failed to close socket: {}", err);
|
||||
}
|
||||
});
|
||||
|
||||
let conn = Arc::clone(&connection);
|
||||
let ctx_clone = Arc::clone(&ctx);
|
||||
let recv_task = tokio::spawn(async move {
|
||||
while let Some(Ok(msg)) = receiver.next().await {
|
||||
let ControlFlow::Continue(ws_req) = conn.recv_msg(msg) else {
|
||||
break;
|
||||
};
|
||||
|
||||
if let Err(err) = ctx_clone.forward_req(ws_req).await {
|
||||
info!("Failed to forward request: {}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
tokio::select! {
|
||||
_ = send_task => {
|
||||
info!("WS server send task completed");
|
||||
},
|
||||
_ = recv_task => {
|
||||
info!("WS server recv task completed");
|
||||
}
|
||||
}
|
||||
|
||||
info!("Client disconnected");
|
||||
|
||||
ctx.remove_connection(connection).await;
|
||||
ws.max_message_size(MAX_WS_MESSAGE)
|
||||
.max_frame_size(MAX_WS_MESSAGE)
|
||||
.on_upgrade(move |socket| WsConnection::accept(socket, ctx))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub mod vpnc_script;
|
||||
@@ -0,0 +1,122 @@
|
||||
use std::{
|
||||
os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use log::{info, warn};
|
||||
use nix::unistd::Uid;
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{credential_lease, session_registry::SessionRegistry};
|
||||
|
||||
pub(crate) const CREDENTIAL_SOCKET: &str = "/var/run/com.yuezk.gpgui/credential.sock";
|
||||
|
||||
pub(crate) struct CredentialServer {
|
||||
registry: Arc<SessionRegistry>,
|
||||
}
|
||||
|
||||
impl CredentialServer {
|
||||
pub(crate) fn new(registry: Arc<SessionRegistry>) -> Self {
|
||||
Self { registry }
|
||||
}
|
||||
|
||||
pub(crate) async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
|
||||
if !Uid::effective().is_root() {
|
||||
bail!("macOS brokered mode requires root privileges");
|
||||
}
|
||||
|
||||
let path = prepare_socket(Path::new(CREDENTIAL_SOCKET), 0)?;
|
||||
let listener = UnixListener::bind(&path)
|
||||
.with_context(|| format!("Failed to bind broker credential socket at {}", path.display()))?;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
||||
info!("Broker credential socket listening at {}", path.display());
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break,
|
||||
accepted = listener.accept() => {
|
||||
let (stream, _) = accepted?;
|
||||
if peer_uid(&stream)? != 0 {
|
||||
warn!("Rejected non-root broker credential client");
|
||||
continue;
|
||||
}
|
||||
let registry = Arc::clone(&self.registry);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = credential_lease::serve(stream, registry).await {
|
||||
warn!("Broker credential lease ended: {err}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
drop(listener);
|
||||
remove_socket(&path, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_socket(path: &Path, owner_uid: u32) -> anyhow::Result<PathBuf> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("Broker credential socket has no parent directory")?;
|
||||
if !parent.exists() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let metadata = std::fs::symlink_metadata(parent)?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() || metadata.uid() != owner_uid {
|
||||
bail!("Broker credential directory must be a real root-owned directory");
|
||||
}
|
||||
if metadata.permissions().mode() & 0o077 != 0 {
|
||||
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
|
||||
remove_socket(path, owner_uid)?;
|
||||
Ok(path.to_path_buf())
|
||||
}
|
||||
|
||||
fn remove_socket(path: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_socket() && metadata.uid() == owner_uid => {
|
||||
std::fs::remove_file(path)?;
|
||||
}
|
||||
Ok(_) => bail!("Refusing to replace an unsafe broker credential path"),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
||||
let (uid, _) = nix::unistd::getpeereid(stream)?;
|
||||
Ok(uid.as_raw())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prepares_private_owner_directory_and_removes_owned_socket_only() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let owner = Uid::current().as_raw();
|
||||
let parent = temp.path().join("runtime");
|
||||
let socket = parent.join("credential.sock");
|
||||
|
||||
assert_eq!(prepare_socket(&socket, owner).unwrap(), socket);
|
||||
assert_eq!(std::fs::metadata(&parent).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
|
||||
std::fs::write(&socket, "not a socket").unwrap();
|
||||
assert!(prepare_socket(&socket, owner).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_uid_matches_current_process() {
|
||||
let (stream, _peer) = UnixStream::pair().unwrap();
|
||||
assert_eq!(peer_uid(&stream).unwrap(), Uid::current().as_raw());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
mod cli;
|
||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||
mod credential_lease;
|
||||
#[cfg(debug_assertions)]
|
||||
mod dev_bootstrap;
|
||||
mod handlers;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_broker;
|
||||
mod request_dispatcher;
|
||||
mod routes;
|
||||
mod runtime_user;
|
||||
mod session_registry;
|
||||
mod vpn_script;
|
||||
mod vpn_task;
|
||||
mod ws_connection;
|
||||
mod ws_server;
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions, Permissions},
|
||||
io::{BufReader, Read, Write},
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
sync::{Arc, atomic::AtomicBool},
|
||||
};
|
||||
|
||||
use common::binary_paths;
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, WsRequest},
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
utils::{checksum::verify_checksum, redact::Redaction},
|
||||
};
|
||||
use log::{info, warn};
|
||||
use tar::Archive;
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use xz2::read::XzDecoder;
|
||||
|
||||
const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
|
||||
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
|
||||
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
||||
|
||||
pub struct RequestDispatcher {
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
install_lock: Mutex<()>,
|
||||
gui_management_enabled: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl RequestDispatcher {
|
||||
pub fn new(
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
gui_management_enabled: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
ws_req_tx,
|
||||
gui_restart_requested,
|
||||
redaction,
|
||||
install_lock: Mutex::new(()),
|
||||
gui_management_enabled,
|
||||
brokered_scripts_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
||||
match request {
|
||||
WsRequest::RestartGui => {
|
||||
if !self.gui_management_enabled {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "GUI restart is unavailable on macOS");
|
||||
}
|
||||
info!("GUI restart requested");
|
||||
self
|
||||
.gui_restart_requested
|
||||
.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
ServiceResult::Accepted
|
||||
}
|
||||
WsRequest::UpdateGui(request) => {
|
||||
if !self.gui_management_enabled {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "GUI update is unavailable on macOS");
|
||||
}
|
||||
self.update_gui(request).await
|
||||
}
|
||||
WsRequest::GetVpncScriptMetadata => {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
match gpservice::vpnc_script::metadata() {
|
||||
Ok(metadata) => ServiceResult::VpncScriptMetadata(metadata),
|
||||
Err(err) => {
|
||||
warn!("Failed to read VPNC script metadata: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "Failed to read VPNC script metadata")
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
ServiceResult::VpncScriptMetadata(None)
|
||||
}
|
||||
}
|
||||
request => {
|
||||
if let WsRequest::Connect(ref connect) = request {
|
||||
if let Err(message) = self.validate_connect_paths(connect) {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message);
|
||||
}
|
||||
if let Err(err) = self
|
||||
.redaction
|
||||
.add_values(&[connect.gateway().server(), connect.args().cookie()])
|
||||
{
|
||||
warn!("Failed to update log redaction: {err}");
|
||||
return ServiceResult::rejected(ServiceErrorCode::Internal, "Request could not be accepted");
|
||||
}
|
||||
}
|
||||
|
||||
match self.ws_req_tx.try_send(request) {
|
||||
Ok(()) => ServiceResult::Accepted,
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
ServiceResult::rejected(ServiceErrorCode::Busy, "Service request queue is full")
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "VPN task is unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_connect_paths(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
let Some(scripts) = &self.brokered_scripts_dir else {
|
||||
return Ok(());
|
||||
};
|
||||
let expected_script = scripts.join("vpnc-script").to_string_lossy().into_owned();
|
||||
let expected_wrapper = scripts.join("hipreport.sh").to_string_lossy().into_owned();
|
||||
if request.args().vpnc_script().as_deref() != Some(expected_script.as_str()) {
|
||||
return Err("macOS VPN script must be the bundled script");
|
||||
}
|
||||
if request.args().csd_wrapper().as_deref() != Some(expected_wrapper.as_str()) {
|
||||
return Err("macOS HIP wrapper must be the bundled wrapper");
|
||||
}
|
||||
if request.args().certificate().is_some() || request.args().sslkey().is_some() {
|
||||
return Err("macOS client identity must be provided as protected data, not root-readable paths");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
||||
let _install = self.install_lock.lock().await;
|
||||
let path = request.path;
|
||||
let checksum = request.checksum;
|
||||
let installed = tokio::task::spawn_blocking(move || install_gui(&path, &checksum)).await;
|
||||
match installed {
|
||||
Ok(Ok(())) => ServiceResult::Accepted,
|
||||
Ok(Err(GuiInstallError::Checksum(err))) => {
|
||||
warn!("Failed to verify GUI update checksum: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
|
||||
}
|
||||
Ok(Err(GuiInstallError::Install(err))) => {
|
||||
warn!("Failed to install GUI update: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("GUI update task failed: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GuiInstallError {
|
||||
Checksum(anyhow::Error),
|
||||
Install(anyhow::Error),
|
||||
}
|
||||
|
||||
fn install_gui(src: &str, checksum: &str) -> Result<(), GuiInstallError> {
|
||||
let target = binary_paths::gpgui();
|
||||
let Some(dir) = target.parent() else {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"Failed to get parent directory of GUI binary"
|
||||
)));
|
||||
};
|
||||
fs::create_dir_all(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
|
||||
let staged_archive = stage_gui_archive(Path::new(src), dir)?;
|
||||
let archive_path = staged_archive.path().to_string_lossy();
|
||||
verify_checksum(&archive_path, checksum).map_err(GuiInstallError::Checksum)?;
|
||||
|
||||
let tar = XzDecoder::new(BufReader::new(
|
||||
staged_archive
|
||||
.reopen()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?,
|
||||
))
|
||||
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
|
||||
let mut archive = Archive::new(tar);
|
||||
let file = extract_gui_binary(&mut archive, dir)?;
|
||||
file
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(0o755))
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
file
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
file
|
||||
.persist(&target)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
File::open(dir)
|
||||
.and_then(|directory| directory.sync_all())
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
||||
let mut source = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
|
||||
.open(src)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let metadata = source.metadata().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let source_size = metadata.len();
|
||||
if !metadata.file_type().is_file() || source_size == 0 || source_size > MAX_GUI_ARCHIVE_SIZE {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive must be a non-empty regular file no larger than {MAX_GUI_ARCHIVE_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut staged = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
if copied != source_size {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive changed while it was being read"
|
||||
)));
|
||||
}
|
||||
staged.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
staged
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
||||
for entry in archive.entries().map_err(|err| GuiInstallError::Install(err.into()))? {
|
||||
let mut entry = entry.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let is_gui = entry
|
||||
.path()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?
|
||||
.file_name()
|
||||
.is_some_and(|name| name == "gpgui");
|
||||
if is_gui && entry.header().entry_type().is_file() {
|
||||
let declared_size = entry.size();
|
||||
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary must be non-empty and no larger than {MAX_GUI_BINARY_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
let mut file = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
if copied != declared_size {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary size does not match its archive header"
|
||||
)));
|
||||
}
|
||||
file.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
return Ok(file);
|
||||
}
|
||||
}
|
||||
Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive does not contain a non-empty regular gpgui file"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Cursor;
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
service::{
|
||||
request::ConnectRequest,
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
};
|
||||
use tar::{Builder, EntryType, Header};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
{
|
||||
let mut builder = Builder::new(&mut data);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(entry_type);
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
builder.append_data(&mut header, "gpgui", contents).unwrap();
|
||||
builder.finish().unwrap();
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_file_and_empty_gui_entries() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
|
||||
let data = archive_with_entry(entry_type, contents);
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_non_empty_regular_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let data = archive_with_entry(EntryType::Regular, b"gui binary");
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
let extracted = extract_gui_binary(&mut archive, output.path()).unwrap();
|
||||
let contents = std::fs::read(extracted.path()).unwrap();
|
||||
assert_eq!(contents, b"gui binary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_archive_sources() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
assert!(stage_gui_archive(output.path(), output.path()).is_err());
|
||||
|
||||
let oversized = output.path().join("oversized.tar.xz");
|
||||
File::create(&oversized)
|
||||
.unwrap()
|
||||
.set_len(MAX_GUI_ARCHIVE_SIZE + 1)
|
||||
.unwrap();
|
||||
assert!(stage_gui_archive(&oversized, output.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(EntryType::Regular);
|
||||
header.set_size(MAX_GUI_BINARY_SIZE + 1);
|
||||
header.set_mode(0o755);
|
||||
header.set_path("gpgui").unwrap();
|
||||
header.set_cksum();
|
||||
let mut data = header.as_bytes().to_vec();
|
||||
data.resize(512 * 3, 0);
|
||||
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
);
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::RestartGui).await else {
|
||||
panic!("brokered mode accepted GUI restart");
|
||||
};
|
||||
assert_eq!(rejection.code(), ServiceErrorCode::InvalidRequest);
|
||||
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let request = ConnectRequest::new(info, "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string()))
|
||||
.with_certificate(Some("/Users/example/client.pem".to_string()));
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else {
|
||||
panic!("brokered mode accepted a root-readable identity path");
|
||||
};
|
||||
assert_eq!(rejection.code(), ServiceErrorCode::InvalidRequest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brokered_mode_accepts_only_resource_script_paths() {
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
);
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let bundled = ConnectRequest::new(info.clone(), "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string()));
|
||||
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
||||
|
||||
let old_layout = ConnectRequest::new(info, "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()))
|
||||
.with_csd_wrapper(Some("/app/Contents/Helpers/hipreport.sh".to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_paths(&old_layout),
|
||||
Err("macOS VPN script must be the bundled script")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ pub(crate) fn routes(ctx: Arc<WsServerContext>) -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(handlers::health))
|
||||
.route("/active-gui", post(handlers::active_gui))
|
||||
.route("/update-gui", post(handlers::update_gui))
|
||||
.route("/ws", get(handlers::ws_handler))
|
||||
.with_state(ctx)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub(crate) fn trusted_csd_uid() -> anyhow::Result<Option<u32>> {
|
||||
Ok(None)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
|
||||
pub(crate) use platform::trusted_csd_uid;
|
||||
@@ -0,0 +1,7 @@
|
||||
pub(crate) fn trusted_csd_uid() -> anyhow::Result<Option<u32>> {
|
||||
let uid = gpapi::process::users::get_non_root_user()?.uid();
|
||||
if uid == 0 {
|
||||
anyhow::bail!("The HIP script user must not be root");
|
||||
}
|
||||
Ok(Some(uid))
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex, Weak},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use gpapi::service::transport::SessionCredential;
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::ws_connection::ConnectionControl;
|
||||
|
||||
const ACTIVATION_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const MAX_PENDING_SESSIONS: usize = 16;
|
||||
|
||||
pub struct HandshakePermit {
|
||||
pub session_id: Uuid,
|
||||
pub observed_generation: u64,
|
||||
pub secret: Zeroizing<[u8; 32]>,
|
||||
token: Uuid,
|
||||
registry: Weak<SessionRegistry>,
|
||||
}
|
||||
|
||||
pub struct PreparedAttach {
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum SessionError {
|
||||
#[error("credential belongs to another service instance")]
|
||||
ServiceRestarted { service_instance_id: Uuid },
|
||||
#[error("session is unauthorized")]
|
||||
Unauthorized,
|
||||
#[error("too many pending sessions")]
|
||||
TooManyPending,
|
||||
#[error("another reconnect completed first")]
|
||||
ReconnectSuperseded,
|
||||
#[error("session registry is unavailable")]
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
enum SessionStatus {
|
||||
Pending {
|
||||
activation_deadline: Instant,
|
||||
handshake_token: Option<Uuid>,
|
||||
},
|
||||
Active {
|
||||
generation: u64,
|
||||
connection: Option<ConnectionControl>,
|
||||
reconnect_token: Option<Uuid>,
|
||||
},
|
||||
}
|
||||
|
||||
struct SessionRecord {
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
product_version: String,
|
||||
status: SessionStatus,
|
||||
}
|
||||
|
||||
pub struct SessionRegistry {
|
||||
service_instance_id: Uuid,
|
||||
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
|
||||
}
|
||||
|
||||
impl SessionRegistry {
|
||||
pub fn new(service_instance_id: Uuid) -> Self {
|
||||
Self {
|
||||
service_instance_id,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn issue(&self, product_version: &str) -> Result<Arc<SessionCredential>, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let now = Instant::now();
|
||||
sessions.retain(|_, record| {
|
||||
!matches!(
|
||||
record.status,
|
||||
SessionStatus::Pending {
|
||||
activation_deadline, ..
|
||||
} if now > activation_deadline
|
||||
)
|
||||
});
|
||||
let pending = sessions
|
||||
.values()
|
||||
.filter(|record| matches!(record.status, SessionStatus::Pending { .. }))
|
||||
.count();
|
||||
if pending >= MAX_PENDING_SESSIONS {
|
||||
return Err(SessionError::TooManyPending);
|
||||
}
|
||||
|
||||
let credential = Arc::new(
|
||||
SessionCredential::generate(self.service_instance_id, product_version).map_err(|_| SessionError::Unavailable)?,
|
||||
);
|
||||
sessions.insert(
|
||||
credential.session_id(),
|
||||
SessionRecord {
|
||||
secret: Zeroizing::new(*credential.secret()),
|
||||
product_version: credential.product_version().to_owned(),
|
||||
status: SessionStatus::Pending {
|
||||
activation_deadline: Instant::now() + ACTIVATION_TIMEOUT,
|
||||
handshake_token: None,
|
||||
},
|
||||
},
|
||||
);
|
||||
Ok(credential)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return false;
|
||||
};
|
||||
let now = Instant::now();
|
||||
sessions.retain(|_, record| {
|
||||
!matches!(
|
||||
record.status,
|
||||
SessionStatus::Pending {
|
||||
activation_deadline, ..
|
||||
} if now > activation_deadline
|
||||
)
|
||||
});
|
||||
sessions.is_empty()
|
||||
}
|
||||
|
||||
pub fn begin_handshake(
|
||||
self: &Arc<Self>,
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
product_version: &str,
|
||||
) -> Result<HandshakePermit, SessionError> {
|
||||
if service_instance_id != self.service_instance_id {
|
||||
return Err(SessionError::ServiceRestarted {
|
||||
service_instance_id: self.service_instance_id,
|
||||
});
|
||||
}
|
||||
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let Some(record) = sessions.get_mut(&session_id) else {
|
||||
return Err(SessionError::Unauthorized);
|
||||
};
|
||||
if record.product_version != product_version {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
|
||||
let token = Uuid::new_v4();
|
||||
let observed_generation = match &mut record.status {
|
||||
SessionStatus::Pending {
|
||||
activation_deadline,
|
||||
handshake_token,
|
||||
} => {
|
||||
if Instant::now() > *activation_deadline {
|
||||
sessions.remove(&session_id);
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
if handshake_token.is_some() {
|
||||
return Err(SessionError::ReconnectSuperseded);
|
||||
}
|
||||
*handshake_token = Some(token);
|
||||
0
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
reconnect_token,
|
||||
..
|
||||
} => {
|
||||
if reconnect_token.is_some() {
|
||||
return Err(SessionError::ReconnectSuperseded);
|
||||
}
|
||||
*reconnect_token = Some(token);
|
||||
*generation
|
||||
}
|
||||
};
|
||||
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
Ok(HandshakePermit {
|
||||
session_id,
|
||||
observed_generation,
|
||||
secret: Zeroizing::new(*record.secret),
|
||||
token,
|
||||
registry: Arc::downgrade(self),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn prepare_attach(&self, permit: &HandshakePermit) -> Result<PreparedAttach, SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&permit.session_id).ok_or(SessionError::Unauthorized)?;
|
||||
let generation = match &record.status {
|
||||
SessionStatus::Pending { handshake_token, .. }
|
||||
if permit.observed_generation == 0 && *handshake_token == Some(permit.token) =>
|
||||
{
|
||||
1
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
reconnect_token,
|
||||
..
|
||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
||||
generation.checked_add(1).ok_or(SessionError::Unavailable)?
|
||||
}
|
||||
_ => return Err(SessionError::ReconnectSuperseded),
|
||||
};
|
||||
Ok(PreparedAttach { generation })
|
||||
}
|
||||
|
||||
pub fn commit_attach(
|
||||
&self,
|
||||
permit: &HandshakePermit,
|
||||
connection: ConnectionControl,
|
||||
) -> Result<Option<ConnectionControl>, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&permit.session_id).ok_or(SessionError::Unauthorized)?;
|
||||
|
||||
match &mut record.status {
|
||||
SessionStatus::Pending { handshake_token, .. }
|
||||
if permit.observed_generation == 0 && *handshake_token == Some(permit.token) =>
|
||||
{
|
||||
record.status = SessionStatus::Active {
|
||||
generation: 1,
|
||||
connection: Some(connection),
|
||||
reconnect_token: None,
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
connection: current,
|
||||
reconnect_token,
|
||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
||||
*generation = generation.checked_add(1).ok_or(SessionError::Unavailable)?;
|
||||
*reconnect_token = None;
|
||||
Ok(current.replace(connection))
|
||||
}
|
||||
_ => Err(SessionError::ReconnectSuperseded),
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_handshake(&self, session_id: Uuid, observed_generation: u64, token: Uuid) {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return;
|
||||
};
|
||||
let Some(record) = sessions.get_mut(&session_id) else {
|
||||
return;
|
||||
};
|
||||
match &mut record.status {
|
||||
SessionStatus::Pending { handshake_token, .. } if observed_generation == 0 && *handshake_token == Some(token) => {
|
||||
sessions.remove(&session_id);
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
reconnect_token,
|
||||
..
|
||||
} if *generation == observed_generation && *reconnect_token == Some(token) => {
|
||||
*reconnect_token = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_current(&self, session_id: Uuid, generation: u64) -> bool {
|
||||
let Ok(sessions) = self.sessions.lock() else {
|
||||
return false;
|
||||
};
|
||||
matches!(
|
||||
sessions.get(&session_id).map(|record| &record.status),
|
||||
Some(SessionStatus::Active { generation: current, .. }) if *current == generation
|
||||
)
|
||||
}
|
||||
|
||||
pub fn disconnect_if_current(&self, session_id: Uuid, generation: u64) {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return;
|
||||
};
|
||||
if let Some(SessionRecord {
|
||||
status: SessionStatus::Active {
|
||||
generation: current,
|
||||
connection,
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = sessions.get_mut(&session_id)
|
||||
&& *current == generation
|
||||
{
|
||||
connection.take();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn revoke(&self, session_id: Uuid) {
|
||||
let connection = self
|
||||
.sessions
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut sessions| sessions.remove(&session_id))
|
||||
.and_then(|record| match record.status {
|
||||
SessionStatus::Active { connection, .. } => connection,
|
||||
SessionStatus::Pending { .. } => None,
|
||||
});
|
||||
if let Some(connection) = connection {
|
||||
connection.close(gpapi::service::transport::CloseReason::Unauthorized);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HandshakePermit {
|
||||
fn drop(&mut self) {
|
||||
if let Some(registry) = self.registry.upgrade() {
|
||||
registry.cancel_handshake(self.session_id, self.observed_generation, self.token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::*;
|
||||
use crate::ws_connection::ConnectionCommand;
|
||||
|
||||
fn control() -> ConnectionControl {
|
||||
let (tx, _rx) = mpsc::channel::<ConnectionCommand>(1);
|
||||
ConnectionControl::new(Uuid::new_v4(), tx).0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnect_uses_generation_compare_and_swap() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
assert_eq!(registry.prepare_attach(&first).unwrap().generation, 1);
|
||||
registry.commit_attach(&first, control()).unwrap();
|
||||
|
||||
let candidate_a = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
registry.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4"),
|
||||
Err(SessionError::ReconnectSuperseded)
|
||||
));
|
||||
assert_eq!(registry.prepare_attach(&candidate_a).unwrap().generation, 2);
|
||||
registry.commit_attach(&candidate_a, control()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_initial_handshake_only_revokes_its_own_reservation() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
drop(first);
|
||||
assert!(matches!(
|
||||
registry.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4"),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_reconnect_keeps_active_connection_authoritative() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
registry.commit_attach(&first, control()).unwrap();
|
||||
|
||||
let reconnect = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
drop(reconnect);
|
||||
assert!(registry.is_current(credential.session_id(), 1));
|
||||
assert!(
|
||||
registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
use gpapi::service::request::ConnectArgs;
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
||||
Ok(Vpn::builder(server, cookie).script_path(args.vpnc_script()))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
mod selection;
|
||||
|
||||
pub(crate) use platform::builder;
|
||||
@@ -0,0 +1,16 @@
|
||||
use gpapi::service::request::ConnectArgs;
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
use super::selection::{ScriptSource, select};
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
||||
let installed = gpservice::vpnc_script::installed_script()?;
|
||||
let legacy = args.vpnc_script();
|
||||
match select(installed.as_deref(), legacy.as_deref()) {
|
||||
ScriptSource::Installed(path) => {
|
||||
Ok(Vpn::builder(server, cookie).script_path(Some(path.to_string_lossy().into_owned())))
|
||||
}
|
||||
ScriptSource::Legacy(script) => Ok(Vpn::builder(server, cookie).script(Some(script.to_owned()))),
|
||||
ScriptSource::Default => Ok(Vpn::builder(server, cookie).script_path(None)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum ScriptSource<'a> {
|
||||
Installed(&'a Path),
|
||||
Legacy(&'a str),
|
||||
Default,
|
||||
}
|
||||
|
||||
pub(super) fn select<'a>(installed: Option<&'a Path>, legacy: Option<&'a str>) -> ScriptSource<'a> {
|
||||
if let Some(path) = installed {
|
||||
return ScriptSource::Installed(path);
|
||||
}
|
||||
if let Some(script) = legacy {
|
||||
return ScriptSource::Legacy(script);
|
||||
}
|
||||
ScriptSource::Default
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installed_script_takes_precedence_over_legacy() {
|
||||
let installed = Path::new("/var/lib/gpclient/scripts/vpnc-script");
|
||||
assert_eq!(
|
||||
select(Some(installed), Some("legacy-command")),
|
||||
ScriptSource::Installed(installed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_script_is_used_before_default() {
|
||||
assert_eq!(
|
||||
select(None, Some("legacy-command")),
|
||||
ScriptSource::Legacy("legacy-command")
|
||||
);
|
||||
assert_eq!(select(None, None), ScriptSource::Default);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::{sync::Arc, thread};
|
||||
use std::{io::Write, os::unix::fs::PermissionsExt, sync::Arc, thread};
|
||||
|
||||
use gpapi::{
|
||||
logger,
|
||||
service::{
|
||||
request::{ConnectRequest, UpdateLogLevelRequest, WsRequest},
|
||||
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA, UpdateLogLevelRequest, WsRequest},
|
||||
vpn_state::{ConnectedInfo, VpnState},
|
||||
},
|
||||
session::{SessionInfo, SessionWarning},
|
||||
@@ -12,19 +12,26 @@ use log::{info, warn};
|
||||
use openconnect::Vpn;
|
||||
use tokio::sync::{RwLock, mpsc, oneshot, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub(crate) struct VpnTaskContext {
|
||||
vpn_handle: Arc<RwLock<Option<Vpn>>>,
|
||||
vpn_state_tx: Arc<watch::Sender<VpnState>>,
|
||||
disconnect_rx: RwLock<Option<oneshot::Receiver<()>>>,
|
||||
brokered_macos: bool,
|
||||
trusted_csd_uid: Option<u32>,
|
||||
identity_files: Arc<RwLock<Vec<tempfile::NamedTempFile>>>,
|
||||
}
|
||||
|
||||
impl VpnTaskContext {
|
||||
pub fn new(vpn_state_tx: watch::Sender<VpnState>) -> Self {
|
||||
pub fn new(vpn_state_tx: watch::Sender<VpnState>, brokered_macos: bool, trusted_csd_uid: Option<u32>) -> Self {
|
||||
Self {
|
||||
vpn_handle: Default::default(),
|
||||
vpn_state_tx: Arc::new(vpn_state_tx),
|
||||
disconnect_rx: Default::default(),
|
||||
brokered_macos,
|
||||
trusted_csd_uid,
|
||||
identity_files: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,19 +46,42 @@ impl VpnTaskContext {
|
||||
let info = req.info().clone();
|
||||
let vpn_handle = Arc::clone(&self.vpn_handle);
|
||||
let args = req.args();
|
||||
let identity = match prepare_identity(args, self.brokered_macos) {
|
||||
Ok(identity) => identity,
|
||||
Err(err) => {
|
||||
warn!("Failed to prepare client identity: {err}");
|
||||
vpn_state_tx.send(VpnState::Disconnected).ok();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let allow_extend_session = args.allow_extend_session();
|
||||
let vpn = match Vpn::builder(req.gateway().server(), args.cookie())
|
||||
.script(args.vpnc_script())
|
||||
let vpn_builder = match crate::vpn_script::builder(req.gateway().server(), args.cookie(), args) {
|
||||
Ok(builder) => builder,
|
||||
Err(err) => {
|
||||
warn!("Failed to select the VPNC script: {err}");
|
||||
vpn_state_tx.send(VpnState::Disconnected).ok();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let csd_uid = match resolve_csd_uid(self.trusted_csd_uid, args.csd_uid(), args.hip()) {
|
||||
Ok(uid) => uid,
|
||||
Err(err) => {
|
||||
warn!("Failed to select the HIP script user: {err}");
|
||||
vpn_state_tx.send(VpnState::Disconnected).ok();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let vpn = match vpn_builder
|
||||
.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())
|
||||
.certificate(identity.certificate.clone())
|
||||
.sslkey(identity.sslkey.clone())
|
||||
.key_password(args.key_password())
|
||||
.hip(args.hip())
|
||||
.csd_uid(args.csd_uid())
|
||||
.csd_uid(csd_uid)
|
||||
.csd_wrapper(args.csd_wrapper())
|
||||
.reconnect_timeout(args.reconnect_timeout())
|
||||
.mtu(args.mtu())
|
||||
@@ -72,11 +102,13 @@ impl VpnTaskContext {
|
||||
|
||||
// Save the VPN handle
|
||||
vpn_handle.write().await.replace(vpn);
|
||||
*self.identity_files.write().await = identity.files;
|
||||
let connect_info = Box::new(info.clone());
|
||||
vpn_state_tx.send(VpnState::Connecting(connect_info)).ok();
|
||||
|
||||
let (disconnect_tx, disconnect_rx) = oneshot::channel::<()>();
|
||||
self.disconnect_rx.write().await.replace(disconnect_rx);
|
||||
let identity_files = Arc::clone(&self.identity_files);
|
||||
|
||||
// Spawn a new thread to process the VPN connection, cannot use tokio::spawn here.
|
||||
// Otherwise, it will block the tokio runtime and cannot send the VPN state to the channel
|
||||
@@ -104,6 +136,7 @@ impl VpnTaskContext {
|
||||
vpn_state_tx_clone.send(VpnState::Disconnected).ok();
|
||||
// Remove the VPN handle
|
||||
vpn_handle.blocking_write().take();
|
||||
identity_files.blocking_write().clear();
|
||||
|
||||
disconnect_tx.send(()).ok();
|
||||
});
|
||||
@@ -137,8 +170,13 @@ pub(crate) struct VpnTask {
|
||||
}
|
||||
|
||||
impl VpnTask {
|
||||
pub fn new(ws_req_rx: mpsc::Receiver<WsRequest>, vpn_state_tx: watch::Sender<VpnState>) -> Self {
|
||||
let ctx = Arc::new(VpnTaskContext::new(vpn_state_tx));
|
||||
pub fn new(
|
||||
ws_req_rx: mpsc::Receiver<WsRequest>,
|
||||
vpn_state_tx: watch::Sender<VpnState>,
|
||||
brokered_macos: bool,
|
||||
trusted_csd_uid: Option<u32>,
|
||||
) -> Self {
|
||||
let ctx = Arc::new(VpnTaskContext::new(vpn_state_tx, brokered_macos, trusted_csd_uid));
|
||||
let cancel_token = CancellationToken::new();
|
||||
|
||||
Self {
|
||||
@@ -169,7 +207,7 @@ impl VpnTask {
|
||||
}
|
||||
|
||||
pub fn context(&self) -> Arc<VpnTaskContext> {
|
||||
return Arc::clone(&self.ctx);
|
||||
Arc::clone(&self.ctx)
|
||||
}
|
||||
|
||||
async fn recv(&mut self) {
|
||||
@@ -179,6 +217,63 @@ impl VpnTask {
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_csd_uid(trusted_uid: Option<u32>, requested_uid: u32, hip_enabled: bool) -> anyhow::Result<u32> {
|
||||
let uid = trusted_uid.unwrap_or(requested_uid);
|
||||
if hip_enabled && uid == 0 {
|
||||
anyhow::bail!("HIP scripts must not run as root");
|
||||
}
|
||||
Ok(uid)
|
||||
}
|
||||
|
||||
struct PreparedIdentity {
|
||||
certificate: Option<String>,
|
||||
sslkey: Option<String>,
|
||||
files: Vec<tempfile::NamedTempFile>,
|
||||
}
|
||||
|
||||
fn prepare_identity(
|
||||
args: &gpapi::service::request::ConnectArgs,
|
||||
brokered_macos: bool,
|
||||
) -> anyhow::Result<PreparedIdentity> {
|
||||
if !brokered_macos {
|
||||
return Ok(PreparedIdentity {
|
||||
certificate: args.certificate(),
|
||||
sslkey: args.sslkey(),
|
||||
files: vec![],
|
||||
});
|
||||
}
|
||||
|
||||
let certificate = args.certificate_data()?.map(Zeroizing::new);
|
||||
let sslkey = args.sslkey_data()?.map(Zeroizing::new);
|
||||
let total_size = certificate.as_ref().map_or(0, |data| data.len()) + sslkey.as_ref().map_or(0, |data| data.len());
|
||||
if total_size > MAX_CLIENT_IDENTITY_DATA {
|
||||
anyhow::bail!("Client certificate and key exceed the macOS size limit");
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
let certificate = write_identity_file(certificate, &mut files)?;
|
||||
let sslkey = write_identity_file(sslkey, &mut files)?;
|
||||
Ok(PreparedIdentity {
|
||||
certificate,
|
||||
sslkey,
|
||||
files,
|
||||
})
|
||||
}
|
||||
|
||||
fn write_identity_file(
|
||||
data: Option<Zeroizing<Vec<u8>>>,
|
||||
files: &mut Vec<tempfile::NamedTempFile>,
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
let Some(data) = data else { return Ok(None) };
|
||||
let mut file = tempfile::NamedTempFile::new_in("/var/run/com.yuezk.gpgui")?;
|
||||
file.as_file().set_permissions(std::fs::Permissions::from_mode(0o600))?;
|
||||
file.write_all(&data)?;
|
||||
file.flush()?;
|
||||
let path = file.path().to_string_lossy().into_owned();
|
||||
files.push(file);
|
||||
Ok(Some(path))
|
||||
}
|
||||
|
||||
async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
|
||||
match req {
|
||||
WsRequest::Connect(req) => {
|
||||
@@ -188,12 +283,15 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
|
||||
ctx.disconnect().await;
|
||||
}
|
||||
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
|
||||
let level = level.parse().unwrap_or_else(|_| log::Level::Info);
|
||||
let level = level.parse().unwrap_or(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);
|
||||
}
|
||||
}
|
||||
WsRequest::RestartGui | WsRequest::UpdateGui(_) | WsRequest::GetVpncScriptMetadata => {
|
||||
warn!("Non-VPN request reached the VPN task");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,6 +299,17 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn trusted_csd_uid_overrides_request_uid() {
|
||||
assert_eq!(resolve_csd_uid(Some(1000), 0, true).unwrap(), 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_csd_uid_is_rejected_when_hip_is_enabled() {
|
||||
assert!(resolve_csd_uid(None, 0, true).is_err());
|
||||
assert_eq!(resolve_csd_uid(None, 0, false).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_openconnect_session_metadata_to_service_session_info() {
|
||||
let info = SessionInfo::from_vpn_session_fields(
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
use std::{
|
||||
fs::{self, File, Metadata, Permissions},
|
||||
io::{self, Read, Write},
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use common::constants::{INSTALLED_VPNC_SCRIPT, INSTALLED_VPNC_SCRIPT_METADATA, MAX_VPNC_SCRIPT_SIZE};
|
||||
use gpapi::service::vpnc_script::{InstallVpncScriptRequest, VpncScriptMetadata};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
const DIRECTORY_MODE: u32 = 0o755;
|
||||
const SCRIPT_MODE: u32 = 0o755;
|
||||
const METADATA_MODE: u32 = 0o600;
|
||||
const METADATA_VERSION: u8 = 1;
|
||||
const MAX_METADATA_SIZE: u64 = 40 * 1024;
|
||||
const ROOT_UID: u32 = 0;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct StoredMetadata {
|
||||
version: u8,
|
||||
metadata: VpncScriptMetadata,
|
||||
}
|
||||
|
||||
pub fn installed_script() -> anyhow::Result<Option<PathBuf>> {
|
||||
let path = PathBuf::from(INSTALLED_VPNC_SCRIPT);
|
||||
match fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => {
|
||||
validate_script(&path, &metadata, ROOT_UID)?;
|
||||
let directory = path.parent().context("Installed VPNC script has no parent directory")?;
|
||||
validate_directory(directory, ROOT_UID)?;
|
||||
validate_directory(
|
||||
directory
|
||||
.parent()
|
||||
.context("Installed VPNC script directory has no parent directory")?,
|
||||
ROOT_UID,
|
||||
)?;
|
||||
Ok(Some(path))
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(err) => Err(err).context("Failed to inspect the installed VPNC script"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn metadata() -> anyhow::Result<Option<VpncScriptMetadata>> {
|
||||
if installed_script()?.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
read_metadata_at(Path::new(INSTALLED_VPNC_SCRIPT_METADATA), ROOT_UID)
|
||||
}
|
||||
|
||||
pub fn install(request: InstallVpncScriptRequest) -> anyhow::Result<()> {
|
||||
request.metadata.validate()?;
|
||||
let contents = request.contents()?;
|
||||
let target = Path::new(INSTALLED_VPNC_SCRIPT);
|
||||
let metadata_target = Path::new(INSTALLED_VPNC_SCRIPT_METADATA);
|
||||
let directory = target
|
||||
.parent()
|
||||
.context("Installed VPNC script has no parent directory")?;
|
||||
let state_directory = directory
|
||||
.parent()
|
||||
.context("Installed VPNC script directory has no parent directory")?;
|
||||
let state_parent = state_directory
|
||||
.parent()
|
||||
.context("VPNC script state directory has no parent directory")?;
|
||||
validate_directory(state_parent, ROOT_UID)?;
|
||||
ensure_directory(state_directory, ROOT_UID)?;
|
||||
ensure_directory(directory, ROOT_UID)?;
|
||||
install_at(&contents, &request.metadata, target, metadata_target, ROOT_UID)
|
||||
}
|
||||
|
||||
pub fn remove() -> anyhow::Result<()> {
|
||||
if installed_script()?.is_some() {
|
||||
remove_at(Path::new(INSTALLED_VPNC_SCRIPT), ROOT_UID, validate_script)?;
|
||||
}
|
||||
remove_at(Path::new(INSTALLED_VPNC_SCRIPT_METADATA), ROOT_UID, validate_metadata)
|
||||
}
|
||||
|
||||
fn install_at(
|
||||
contents: &[u8],
|
||||
metadata: &VpncScriptMetadata,
|
||||
target: &Path,
|
||||
metadata_target: &Path,
|
||||
owner_uid: u32,
|
||||
) -> anyhow::Result<()> {
|
||||
let directory = target
|
||||
.parent()
|
||||
.context("Installed VPNC script has no parent directory")?;
|
||||
ensure_directory(directory, owner_uid)?;
|
||||
|
||||
if let Ok(existing) = fs::symlink_metadata(target) {
|
||||
validate_script(target, &existing, owner_uid)?;
|
||||
}
|
||||
if let Ok(existing) = fs::symlink_metadata(metadata_target) {
|
||||
validate_metadata(metadata_target, &existing, owner_uid)?;
|
||||
}
|
||||
if contents.is_empty() {
|
||||
bail!("VPNC script is empty");
|
||||
}
|
||||
if contents.len() > MAX_VPNC_SCRIPT_SIZE {
|
||||
bail!("VPNC script exceeds the {} byte limit", MAX_VPNC_SCRIPT_SIZE);
|
||||
}
|
||||
metadata.validate()?;
|
||||
|
||||
let mut staged_script = NamedTempFile::new_in(directory).context("Failed to stage the VPNC script")?;
|
||||
staged_script
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(SCRIPT_MODE))
|
||||
.context("Failed to set VPNC script permissions")?;
|
||||
staged_script
|
||||
.write_all(contents)
|
||||
.context("Failed to write the VPNC script")?;
|
||||
staged_script
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.context("Failed to sync the VPNC script")?;
|
||||
|
||||
let stored_metadata = StoredMetadata {
|
||||
version: METADATA_VERSION,
|
||||
metadata: metadata.clone(),
|
||||
};
|
||||
let mut staged_metadata = NamedTempFile::new_in(directory).context("Failed to stage VPNC script metadata")?;
|
||||
staged_metadata
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(METADATA_MODE))
|
||||
.context("Failed to set VPNC script metadata permissions")?;
|
||||
serde_json::to_writer(&mut staged_metadata, &stored_metadata).context("Failed to write VPNC script metadata")?;
|
||||
staged_metadata
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.context("Failed to sync VPNC script metadata")?;
|
||||
|
||||
staged_script
|
||||
.persist(target)
|
||||
.map_err(|err| err.error)
|
||||
.context("Failed to install the VPNC script")?;
|
||||
staged_metadata
|
||||
.persist(metadata_target)
|
||||
.map_err(|err| err.error)
|
||||
.context("Failed to install VPNC script metadata")?;
|
||||
sync_directory(directory)?;
|
||||
|
||||
let script_metadata = fs::symlink_metadata(target).context("Failed to inspect the installed VPNC script")?;
|
||||
validate_script(target, &script_metadata, owner_uid)?;
|
||||
let installed_metadata = fs::symlink_metadata(metadata_target).context("Failed to inspect VPNC script metadata")?;
|
||||
validate_metadata(metadata_target, &installed_metadata, owner_uid)
|
||||
}
|
||||
|
||||
fn read_metadata_at(target: &Path, owner_uid: u32) -> anyhow::Result<Option<VpncScriptMetadata>> {
|
||||
let metadata = match fs::symlink_metadata(target) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => return Err(err).context("Failed to inspect VPNC script metadata"),
|
||||
};
|
||||
validate_metadata(target, &metadata, owner_uid)?;
|
||||
|
||||
let file = File::open(target).context("Failed to open VPNC script metadata")?;
|
||||
let stored: StoredMetadata =
|
||||
serde_json::from_reader(file.take(MAX_METADATA_SIZE)).context("Failed to parse VPNC script metadata")?;
|
||||
if stored.version != METADATA_VERSION {
|
||||
bail!("Unsupported VPNC script metadata version {}", stored.version);
|
||||
}
|
||||
stored.metadata.validate()?;
|
||||
Ok(Some(stored.metadata))
|
||||
}
|
||||
|
||||
fn remove_at(
|
||||
target: &Path,
|
||||
owner_uid: u32,
|
||||
validate: fn(&Path, &Metadata, u32) -> anyhow::Result<()>,
|
||||
) -> anyhow::Result<()> {
|
||||
let directory = target
|
||||
.parent()
|
||||
.context("VPNC script state file has no parent directory")?;
|
||||
validate_directory(directory, owner_uid)?;
|
||||
|
||||
match fs::symlink_metadata(target) {
|
||||
Ok(metadata) => {
|
||||
validate(target, &metadata, owner_uid)?;
|
||||
fs::remove_file(target).context("Failed to remove VPNC script state")?;
|
||||
sync_directory(directory)
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err).context("Failed to inspect VPNC script state"),
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_directory(directory: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
match fs::symlink_metadata(directory) {
|
||||
Ok(_) => validate_directory(directory, owner_uid),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
if let Some(parent) = directory.parent() {
|
||||
ensure_directory(parent, owner_uid)?;
|
||||
}
|
||||
fs::create_dir(directory).context("Failed to create the VPNC script directory")?;
|
||||
fs::set_permissions(directory, Permissions::from_mode(DIRECTORY_MODE))
|
||||
.context("Failed to set VPNC script directory permissions")?;
|
||||
validate_directory(directory, owner_uid)
|
||||
}
|
||||
Err(err) => Err(err).context("Failed to inspect the VPNC script directory"),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_directory(path: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(path)
|
||||
.with_context(|| format!("Failed to inspect VPNC script directory {}", path.display()))?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
||||
bail!("VPNC script directory {} is not a real directory", path.display());
|
||||
}
|
||||
validate_ownership_and_mode(path, &metadata, owner_uid)
|
||||
}
|
||||
|
||||
fn validate_script(path: &Path, metadata: &Metadata, owner_uid: u32) -> anyhow::Result<()> {
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
bail!("Installed VPNC script {} is not a regular file", path.display());
|
||||
}
|
||||
validate_ownership_and_mode(path, metadata, owner_uid)?;
|
||||
if metadata.mode() & 0o111 == 0 {
|
||||
bail!("Installed VPNC script {} is not executable", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_metadata(path: &Path, metadata: &Metadata, owner_uid: u32) -> anyhow::Result<()> {
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
bail!("VPNC script metadata {} is not a regular file", path.display());
|
||||
}
|
||||
validate_ownership_and_mode(path, metadata, owner_uid)?;
|
||||
if metadata.mode() & 0o777 != METADATA_MODE {
|
||||
bail!("VPNC script metadata {} must have mode 0600", path.display());
|
||||
}
|
||||
if metadata.len() > MAX_METADATA_SIZE {
|
||||
bail!("VPNC script metadata {} is too large", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_ownership_and_mode(path: &Path, metadata: &Metadata, owner_uid: u32) -> anyhow::Result<()> {
|
||||
if metadata.uid() != owner_uid {
|
||||
bail!("{} must be owned by uid {}", path.display(), owner_uid);
|
||||
}
|
||||
if metadata.mode() & 0o022 != 0 {
|
||||
bail!("{} must not be writable by group or other users", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_directory(directory: &Path) -> anyhow::Result<()> {
|
||||
File::open(directory)
|
||||
.and_then(|file| file.sync_all())
|
||||
.context("Failed to sync the VPNC script directory")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpapi::service::vpnc_script::VpncScriptSource;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn source(value: &str) -> VpncScriptMetadata {
|
||||
VpncScriptMetadata::new(VpncScriptSource::Command, value.to_owned()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_metadata_and_removes_both_files() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
let owner_uid = metadata.uid();
|
||||
let directory = temp.path().join("scripts");
|
||||
let target = directory.join("vpnc-script");
|
||||
let metadata_target = directory.join("vpnc-script.metadata");
|
||||
let source = source("exit 0");
|
||||
|
||||
install_at(b"#!/bin/sh\nexit 0\n", &source, &target, &metadata_target, owner_uid).unwrap();
|
||||
let metadata = fs::symlink_metadata(&target).unwrap();
|
||||
assert!(metadata.is_file());
|
||||
assert_eq!(metadata.mode() & 0o777, SCRIPT_MODE);
|
||||
assert_eq!(read_metadata_at(&metadata_target, owner_uid).unwrap(), Some(source));
|
||||
|
||||
remove_at(&target, owner_uid, validate_script).unwrap();
|
||||
remove_at(&metadata_target, owner_uid, validate_metadata).unwrap();
|
||||
assert!(!target.exists());
|
||||
assert!(!metadata_target.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_metadata_is_allowed() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
read_metadata_at(&temp.path().join("missing"), metadata.uid()).unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_script() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
let owner_uid = metadata.uid();
|
||||
let target = temp.path().join("scripts/vpnc-script");
|
||||
let metadata_target = temp.path().join("scripts/vpnc-script.metadata");
|
||||
let input = vec![b'x'; MAX_VPNC_SCRIPT_SIZE + 1];
|
||||
|
||||
assert!(install_at(&input, &source("/tmp/script"), &target, &metadata_target, owner_uid).is_err());
|
||||
assert!(!target.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlink_target() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
let owner_uid = metadata.uid();
|
||||
let directory = temp.path().join("scripts");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let target = directory.join("vpnc-script");
|
||||
let metadata_target = directory.join("vpnc-script.metadata");
|
||||
symlink("/bin/sh", &target).unwrap();
|
||||
|
||||
assert!(
|
||||
install_at(
|
||||
b"exit 0\n",
|
||||
&source("/tmp/script"),
|
||||
&target,
|
||||
&metadata_target,
|
||||
owner_uid
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,526 @@
|
||||
use std::{ops::ControlFlow, sync::Arc};
|
||||
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||
|
||||
use axum::extract::ws::{CloseFrame, Message};
|
||||
use gpapi::{
|
||||
service::{event::WsEvent, request::WsRequest},
|
||||
utils::crypto::Crypto,
|
||||
use axum::extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket};
|
||||
use futures::StreamExt;
|
||||
use gpapi::service::transport::{
|
||||
ClientMessage, ClientPrelude, CloseReason, HandshakeRejection, NoiseResponder, NoiseTransport, ServerMessage,
|
||||
ServerPrelude, ServiceResult,
|
||||
};
|
||||
use log::{info, warn};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::Instant;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) struct WsConnection {
|
||||
crypto: Arc<Crypto>,
|
||||
tx: mpsc::Sender<Message>,
|
||||
use crate::{
|
||||
session_registry::{HandshakePermit, SessionError},
|
||||
ws_server::WsServerContext,
|
||||
};
|
||||
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const WRITE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);
|
||||
const PONG_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CONNECTION_QUEUE: usize = 64;
|
||||
const MAX_PENDING_REQUESTS: usize = 64;
|
||||
|
||||
pub(crate) enum ConnectionCommand {
|
||||
Send(ServerMessage),
|
||||
Reply { id: Uuid, result: ServiceResult },
|
||||
}
|
||||
|
||||
impl WsConnection {
|
||||
pub fn new(crypto: Arc<Crypto>, tx: mpsc::Sender<Message>) -> Self {
|
||||
Self { crypto, tx }
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ConnectionControl {
|
||||
connection_id: Uuid,
|
||||
tx: mpsc::Sender<ConnectionCommand>,
|
||||
close_tx: watch::Sender<Option<CloseReason>>,
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: &WsEvent) -> anyhow::Result<()> {
|
||||
let encrypted = self.crypto.encrypt(event)?;
|
||||
let msg = Message::Binary(encrypted.into());
|
||||
|
||||
self.tx.send(msg).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn recv_msg(&self, msg: Message) -> ControlFlow<(), WsRequest> {
|
||||
match msg {
|
||||
Message::Binary(data) => match self.crypto.decrypt(data.into()) {
|
||||
Ok(ws_req) => ControlFlow::Continue(ws_req),
|
||||
Err(err) => {
|
||||
info!("Failed to decrypt message: {}", err);
|
||||
ControlFlow::Break(())
|
||||
}
|
||||
impl ConnectionControl {
|
||||
pub fn new(connection_id: Uuid, tx: mpsc::Sender<ConnectionCommand>) -> (Self, watch::Receiver<Option<CloseReason>>) {
|
||||
let (close_tx, close_rx) = watch::channel(None);
|
||||
(
|
||||
Self {
|
||||
connection_id,
|
||||
tx,
|
||||
close_tx,
|
||||
},
|
||||
Message::Close(cf) => {
|
||||
if let Some(CloseFrame { code, reason }) = cf {
|
||||
info!("Client sent close, code {} and reason `{}`", code, reason);
|
||||
} else {
|
||||
info!("Client somehow sent close message without CloseFrame");
|
||||
close_rx,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn connection_id(&self) -> Uuid {
|
||||
self.connection_id
|
||||
}
|
||||
|
||||
pub fn send(&self, command: ConnectionCommand) -> Result<(), ()> {
|
||||
self.tx.try_send(command).map_err(|_| ())
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.tx.is_closed()
|
||||
}
|
||||
|
||||
pub fn close(&self, reason: CloseReason) {
|
||||
let _ = self.close_tx.send(Some(reason));
|
||||
}
|
||||
|
||||
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
||||
let _ = self.tx.send(ConnectionCommand::Reply { id, result }).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WsConnection;
|
||||
|
||||
impl WsConnection {
|
||||
pub async fn accept(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
|
||||
let Some(slot) = ctx.try_handshake_slot() else {
|
||||
send_close(&mut socket, CloseReason::InternalError).await;
|
||||
return;
|
||||
};
|
||||
|
||||
let established = tokio::time::timeout(HANDSHAKE_TIMEOUT, establish(&mut socket, &ctx)).await;
|
||||
let (mut noise, permit, control, mut command_rx, mut close_rx, generation) = match established {
|
||||
Ok(Ok(established)) => established,
|
||||
Ok(Err(reason)) => {
|
||||
send_close(&mut socket, reason).await;
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
ctx.remove_closed_connections().await;
|
||||
send_close(&mut socket, CloseReason::HandshakeTimeout).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
drop(slot);
|
||||
|
||||
info!("Authenticated GUI connection {}", control.connection_id());
|
||||
let mut pending_requests = HashSet::new();
|
||||
let mut heartbeat = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut last_outbound = Instant::now();
|
||||
let mut pong_deadline = None;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
command = command_rx.recv() => {
|
||||
let Some(command) = command else { break };
|
||||
match command {
|
||||
ConnectionCommand::Send(message) => {
|
||||
if send_encrypted(&mut socket, &mut noise, &message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
last_outbound = Instant::now();
|
||||
}
|
||||
ConnectionCommand::Reply { id, result } => {
|
||||
if !pending_requests.remove(&id) {
|
||||
send_close(&mut socket, CloseReason::MalformedMessage).await;
|
||||
break;
|
||||
}
|
||||
let message = ServerMessage::Reply { id, result };
|
||||
if send_encrypted(&mut socket, &mut noise, &message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
last_outbound = Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
changed = close_rx.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
let reason = *close_rx.borrow_and_update();
|
||||
if let Some(reason) = reason {
|
||||
send_close(&mut socket, reason).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
frame = socket.next() => {
|
||||
let Some(frame) = frame else { break };
|
||||
match frame {
|
||||
Ok(Message::Binary(data)) => {
|
||||
let message = match noise.decrypt::<ClientMessage>(&data) {
|
||||
Ok(message) => message,
|
||||
Err(err) => {
|
||||
warn!("Failed to authenticate WS message: {err}");
|
||||
send_close(&mut socket, CloseReason::AuthenticationFailed).await;
|
||||
break;
|
||||
}
|
||||
};
|
||||
if handle_client_message(
|
||||
message,
|
||||
&ctx,
|
||||
&control,
|
||||
permit.session_id,
|
||||
generation,
|
||||
&mut pending_requests,
|
||||
).await.is_err() {
|
||||
send_close(&mut socket, CloseReason::MalformedMessage).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Message::Ping(data)) => {
|
||||
if send_frame(&mut socket, Message::Pong(data)).await.is_err() { break; }
|
||||
last_outbound = Instant::now();
|
||||
}
|
||||
Ok(Message::Pong(_)) => pong_deadline = None,
|
||||
Ok(Message::Close(_)) | Err(_) => break,
|
||||
Ok(_) => {
|
||||
send_close(&mut socket, CloseReason::MalformedMessage).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = heartbeat.tick() => {
|
||||
let now = Instant::now();
|
||||
if pong_deadline.is_some_and(|deadline| now >= deadline) {
|
||||
send_close(&mut socket, CloseReason::HeartbeatTimeout).await;
|
||||
break;
|
||||
}
|
||||
if pong_deadline.is_none() && now.duration_since(last_outbound) >= HEARTBEAT_INTERVAL {
|
||||
if send_frame(&mut socket, Message::Ping(Vec::new().into())).await.is_err() { break; }
|
||||
last_outbound = now;
|
||||
pong_deadline = Some(now + PONG_TIMEOUT);
|
||||
}
|
||||
}
|
||||
ControlFlow::Break(())
|
||||
}
|
||||
_ => {
|
||||
warn!("WS server received unexpected message: {:?}", msg);
|
||||
ControlFlow::Break(())
|
||||
}
|
||||
|
||||
ctx
|
||||
.remove_connection(control.connection_id(), permit.session_id, generation)
|
||||
.await;
|
||||
info!("GUI connection {} closed", control.connection_id());
|
||||
}
|
||||
}
|
||||
|
||||
async fn establish(
|
||||
socket: &mut WebSocket,
|
||||
ctx: &Arc<WsServerContext>,
|
||||
) -> Result<
|
||||
(
|
||||
NoiseTransport,
|
||||
HandshakePermit,
|
||||
ConnectionControl,
|
||||
mpsc::Receiver<ConnectionCommand>,
|
||||
watch::Receiver<Option<CloseReason>>,
|
||||
u64,
|
||||
),
|
||||
CloseReason,
|
||||
> {
|
||||
let prelude = receive_prelude(socket).await?;
|
||||
if prelude.product_version != ctx.product_version() {
|
||||
send_server_prelude(
|
||||
socket,
|
||||
ServerPrelude::Rejected(HandshakeRejection::VersionMismatch {
|
||||
client: prelude.product_version,
|
||||
service: ctx.product_version().to_owned(),
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
return Err(CloseReason::VersionMismatch);
|
||||
}
|
||||
|
||||
let permit = match ctx.registry().begin_handshake(
|
||||
prelude.service_instance_id,
|
||||
prelude.session_id,
|
||||
&prelude.product_version,
|
||||
) {
|
||||
Ok(permit) => permit,
|
||||
Err(SessionError::ServiceRestarted { service_instance_id }) => {
|
||||
send_server_prelude(
|
||||
socket,
|
||||
ServerPrelude::Rejected(HandshakeRejection::ServiceRestarted { service_instance_id }),
|
||||
)
|
||||
.await?;
|
||||
return Err(CloseReason::ServiceRestarted);
|
||||
}
|
||||
Err(SessionError::ReconnectSuperseded) => {
|
||||
send_server_prelude(socket, ServerPrelude::Rejected(HandshakeRejection::ReconnectSuperseded)).await?;
|
||||
return Err(CloseReason::ReconnectSuperseded);
|
||||
}
|
||||
Err(_) => {
|
||||
send_server_prelude(socket, ServerPrelude::Rejected(HandshakeRejection::Unauthorized)).await?;
|
||||
return Err(CloseReason::Unauthorized);
|
||||
}
|
||||
};
|
||||
|
||||
send_server_prelude(socket, ServerPrelude::Ready).await?;
|
||||
let handshake = async {
|
||||
let mut responder = NoiseResponder::new(
|
||||
ctx.product_version(),
|
||||
prelude.service_instance_id,
|
||||
prelude.session_id,
|
||||
&permit.secret,
|
||||
)
|
||||
.map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
let first = receive_binary(socket).await?;
|
||||
responder.read_first(&first).map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
let (response, mut noise) = responder.write_response().map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
socket
|
||||
.send(Message::Binary(response.into()))
|
||||
.await
|
||||
.map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
|
||||
let attach = receive_binary(socket).await?;
|
||||
match noise
|
||||
.decrypt::<ClientMessage>(&attach)
|
||||
.map_err(|_| CloseReason::AuthenticationFailed)?
|
||||
{
|
||||
ClientMessage::Attach { .. } => {}
|
||||
_ => return Err(CloseReason::MalformedMessage),
|
||||
}
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(CONNECTION_QUEUE);
|
||||
let (control, close_rx) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
let prepared = ctx
|
||||
.prepare_connection(&permit, control.clone())
|
||||
.await
|
||||
.map_err(|err| match err {
|
||||
SessionError::ReconnectSuperseded => CloseReason::ReconnectSuperseded,
|
||||
SessionError::Unauthorized => CloseReason::Unauthorized,
|
||||
_ => CloseReason::InternalError,
|
||||
})?;
|
||||
|
||||
let Some(ConnectionCommand::Send(attached @ ServerMessage::Attached { .. })) = rx.recv().await else {
|
||||
ctx.abandon_connection(control.connection_id()).await;
|
||||
return Err(CloseReason::InternalError);
|
||||
};
|
||||
if send_encrypted(socket, &mut noise, &attached).await.is_err() {
|
||||
ctx.abandon_connection(control.connection_id()).await;
|
||||
return Err(CloseReason::InternalError);
|
||||
}
|
||||
let replaced = ctx
|
||||
.commit_connection(&permit, &control)
|
||||
.await
|
||||
.map_err(|err| match err {
|
||||
SessionError::ReconnectSuperseded => CloseReason::ReconnectSuperseded,
|
||||
SessionError::Unauthorized => CloseReason::Unauthorized,
|
||||
_ => CloseReason::InternalError,
|
||||
})?;
|
||||
if let Some(replaced) = replaced {
|
||||
replaced.close(CloseReason::SessionReplaced);
|
||||
}
|
||||
Ok((noise, control, rx, close_rx, prepared.generation))
|
||||
}
|
||||
.await;
|
||||
|
||||
handshake.map(|(noise, control, rx, close_rx, generation)| (noise, permit, control, rx, close_rx, generation))
|
||||
}
|
||||
|
||||
async fn handle_client_message(
|
||||
message: ClientMessage,
|
||||
ctx: &Arc<WsServerContext>,
|
||||
control: &ConnectionControl,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
pending_requests: &mut HashSet<Uuid>,
|
||||
) -> Result<(), ()> {
|
||||
match message {
|
||||
ClientMessage::Attach { .. } => Err(()),
|
||||
ClientMessage::Resync { .. } => ctx.send_snapshot(control).await,
|
||||
ClientMessage::Request { id, request } => {
|
||||
if pending_requests.len() >= MAX_PENDING_REQUESTS || !pending_requests.insert(id) {
|
||||
return Err(());
|
||||
}
|
||||
if !ctx.registry().is_current(session_id, generation) {
|
||||
pending_requests.remove(&id);
|
||||
return Err(());
|
||||
}
|
||||
|
||||
let dispatcher = ctx.dispatcher();
|
||||
let control = control.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = dispatcher.dispatch(request).await;
|
||||
control.send_reply(id, result).await;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn receive_prelude(socket: &mut WebSocket) -> Result<ClientPrelude, CloseReason> {
|
||||
let data = receive_binary(socket).await?;
|
||||
ClientPrelude::decode(&data).map_err(|_| CloseReason::MalformedMessage)
|
||||
}
|
||||
|
||||
async fn receive_binary(socket: &mut WebSocket) -> Result<Vec<u8>, CloseReason> {
|
||||
match socket.next().await {
|
||||
Some(Ok(Message::Binary(data))) => Ok(data.to_vec()),
|
||||
Some(Ok(_)) => Err(CloseReason::MalformedMessage),
|
||||
Some(Err(_)) | None => Err(CloseReason::HandshakeFailed),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_server_prelude(socket: &mut WebSocket, prelude: ServerPrelude) -> Result<(), CloseReason> {
|
||||
let data = prelude.encode().map_err(|_| CloseReason::InternalError)?;
|
||||
socket
|
||||
.send(Message::Binary(data.into()))
|
||||
.await
|
||||
.map_err(|_| CloseReason::HandshakeFailed)
|
||||
}
|
||||
|
||||
async fn send_encrypted(
|
||||
socket: &mut WebSocket,
|
||||
noise: &mut NoiseTransport,
|
||||
message: &ServerMessage,
|
||||
) -> anyhow::Result<()> {
|
||||
let encrypted = noise.encrypt(message)?;
|
||||
send_frame(socket, Message::Binary(encrypted.into())).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_frame(socket: &mut WebSocket, frame: Message) -> anyhow::Result<()> {
|
||||
tokio::time::timeout(WRITE_TIMEOUT, socket.send(frame))
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("WebSocket write timed out"))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_close(socket: &mut WebSocket, reason: CloseReason) {
|
||||
let _ = send_frame(
|
||||
socket,
|
||||
Message::Close(Some(CloseFrame {
|
||||
code: reason.code(),
|
||||
reason: Utf8Bytes::from_static(reason.reason()),
|
||||
})),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||
transport::{ClientMessage, ClientPrelude, NoiseInitiator, ServerMessage, ServerPrelude, ServiceResult},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
utils::redact::Redaction,
|
||||
};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientFrame};
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher, routes, session_registry::SessionRegistry, ws_server::WsServerContext,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticates_attaches_and_replies_to_a_request() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||
let (request_tx, mut request_rx) = mpsc::channel(4);
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Arc::clone(®istry),
|
||||
dispatcher,
|
||||
&state_rx,
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, routes::routes(context)).await.unwrap();
|
||||
});
|
||||
|
||||
let (mut socket, _) = connect_async(format!("ws://{address}/ws")).await.unwrap();
|
||||
let prelude = ClientPrelude {
|
||||
product_version: env!("CARGO_PKG_VERSION").to_owned(),
|
||||
service_instance_id: credential.service_instance_id(),
|
||||
session_id: credential.session_id(),
|
||||
};
|
||||
socket
|
||||
.send(ClientFrame::Binary(prelude.encode().unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let ready = receive_client_binary(&mut socket).await;
|
||||
assert_eq!(ServerPrelude::decode(&ready).unwrap(), ServerPrelude::Ready);
|
||||
|
||||
let mut initiator = NoiseInitiator::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.secret(),
|
||||
)
|
||||
.unwrap();
|
||||
socket
|
||||
.send(ClientFrame::Binary(initiator.write_first().unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let response = receive_client_binary(&mut socket).await;
|
||||
let mut noise = initiator.read_response(&response).unwrap();
|
||||
let attach = noise
|
||||
.encrypt(&ClientMessage::Attach {
|
||||
last_event_revision: None,
|
||||
})
|
||||
.unwrap();
|
||||
socket.send(ClientFrame::Binary(attach.into())).await.unwrap();
|
||||
let attached = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
assert!(matches!(attached, ServerMessage::Attached { .. }));
|
||||
|
||||
let request_id = Uuid::new_v4();
|
||||
let request = ClientMessage::Request {
|
||||
id: request_id,
|
||||
request: WsRequest::UpdateLogLevel(UpdateLogLevelRequest("info".to_owned())),
|
||||
};
|
||||
socket
|
||||
.send(ClientFrame::Binary(noise.encrypt(&request).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(request_rx.recv().await, Some(WsRequest::UpdateLogLevel(_))));
|
||||
let reply = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
reply,
|
||||
ServerMessage::Reply {
|
||||
id,
|
||||
result: ServiceResult::Accepted,
|
||||
} if id == request_id
|
||||
));
|
||||
|
||||
let update_id = Uuid::new_v4();
|
||||
let update_file = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(update_file.path(), b"invalid archive").unwrap();
|
||||
let update = ClientMessage::Request {
|
||||
id: update_id,
|
||||
request: WsRequest::UpdateGui(UpdateGuiRequest {
|
||||
path: update_file.path().to_string_lossy().into_owned(),
|
||||
checksum: "invalid".to_owned(),
|
||||
}),
|
||||
};
|
||||
socket
|
||||
.send(ClientFrame::Binary(noise.encrypt(&update).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let reply = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
reply,
|
||||
ServerMessage::Reply {
|
||||
id,
|
||||
result: ServiceResult::Rejected(ref rejection),
|
||||
} if id == update_id && rejection.code() == gpapi::service::transport::ServiceErrorCode::ChecksumFailed
|
||||
));
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
async fn receive_client_binary(
|
||||
socket: &mut tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
|
||||
) -> Vec<u8> {
|
||||
match socket.next().await.unwrap().unwrap() {
|
||||
ClientFrame::Binary(data) => data.to_vec(),
|
||||
frame => panic!("unexpected frame: {frame:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,110 +1,185 @@
|
||||
use std::sync::Arc;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use axum::extract::ws::Message;
|
||||
use common::binary_paths;
|
||||
use gpapi::{
|
||||
os_profile::HostIdentity,
|
||||
service::{
|
||||
event::WsEvent,
|
||||
request::WsRequest,
|
||||
transport::{CloseReason, ServerMessage},
|
||||
vpn_env::{HostInfo, VpnEnv},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction},
|
||||
utils::lock_file::LockFile,
|
||||
};
|
||||
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::{Mutex, Semaphore, mpsc, oneshot, watch},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{routes, ws_connection::WsConnection};
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher,
|
||||
routes,
|
||||
session_registry::{HandshakePermit, PreparedAttach, SessionError, SessionRegistry},
|
||||
ws_connection::{ConnectionCommand, ConnectionControl},
|
||||
};
|
||||
|
||||
struct ServiceState {
|
||||
revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
connections: HashMap<Uuid, ConnectionControl>,
|
||||
}
|
||||
|
||||
pub(crate) struct WsServerContext {
|
||||
crypto: Arc<Crypto>,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
redaction: Arc<Redaction>,
|
||||
connections: RwLock<Vec<Arc<WsConnection>>>,
|
||||
product_version: &'static str,
|
||||
registry: Arc<SessionRegistry>,
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
state: Mutex<ServiceState>,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl WsServerContext {
|
||||
pub fn new(
|
||||
api_key: Vec<u8>,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
redaction: Arc<Redaction>,
|
||||
product_version: &'static str,
|
||||
registry: Arc<SessionRegistry>,
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
vpn_state_rx: &watch::Receiver<VpnState>,
|
||||
) -> Self {
|
||||
Self {
|
||||
crypto: Arc::new(Crypto::new(api_key)),
|
||||
ws_req_tx,
|
||||
vpn_state_rx,
|
||||
redaction,
|
||||
connections: Default::default(),
|
||||
product_version,
|
||||
registry,
|
||||
dispatcher,
|
||||
state: Mutex::new(ServiceState {
|
||||
revision: 0,
|
||||
snapshot: build_snapshot(vpn_state_rx.borrow().clone()),
|
||||
connections: HashMap::new(),
|
||||
}),
|
||||
handshake_slots: Arc::new(Semaphore::new(16)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decrypt<T: DeserializeOwned>(&self, encrypted: Vec<u8>) -> anyhow::Result<T> {
|
||||
self.crypto.decrypt(encrypted)
|
||||
pub fn product_version(&self) -> &'static str {
|
||||
self.product_version
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Arc<SessionRegistry> {
|
||||
&self.registry
|
||||
}
|
||||
|
||||
pub fn dispatcher(&self) -> Arc<RequestDispatcher> {
|
||||
Arc::clone(&self.dispatcher)
|
||||
}
|
||||
|
||||
pub fn try_handshake_slot(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
|
||||
Arc::clone(&self.handshake_slots).try_acquire_owned().ok()
|
||||
}
|
||||
|
||||
pub async fn prepare_connection(
|
||||
&self,
|
||||
permit: &HandshakePermit,
|
||||
control: ConnectionControl,
|
||||
) -> Result<PreparedAttach, SessionError> {
|
||||
let mut state = self.state.lock().await;
|
||||
let prepared = self.registry.prepare_attach(permit)?;
|
||||
|
||||
control
|
||||
.send(ConnectionCommand::Send(ServerMessage::Attached {
|
||||
connection_id: control.connection_id(),
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
.map_err(|_| SessionError::Unavailable)?;
|
||||
state.connections.insert(control.connection_id(), control);
|
||||
Ok(prepared)
|
||||
}
|
||||
|
||||
pub async fn commit_connection(
|
||||
&self,
|
||||
permit: &HandshakePermit,
|
||||
connection: &ConnectionControl,
|
||||
) -> Result<Option<ConnectionControl>, SessionError> {
|
||||
let mut state = self.state.lock().await;
|
||||
if !state
|
||||
.connections
|
||||
.get(&connection.connection_id())
|
||||
.is_some_and(|candidate| !candidate.is_closed())
|
||||
{
|
||||
return Err(SessionError::Unavailable);
|
||||
}
|
||||
match self.registry.commit_attach(permit, connection.clone()) {
|
||||
Ok(replaced) => {
|
||||
if let Some(replaced) = &replaced {
|
||||
state.connections.remove(&replaced.connection_id());
|
||||
}
|
||||
Ok(replaced)
|
||||
}
|
||||
Err(err) => {
|
||||
state.connections.remove(&connection.connection_id());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn abandon_connection(&self, connection_id: Uuid) {
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
}
|
||||
|
||||
pub async fn remove_closed_connections(&self) {
|
||||
self
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.connections
|
||||
.retain(|_, connection| !connection.is_closed());
|
||||
}
|
||||
|
||||
pub async fn send_snapshot(&self, control: &ConnectionControl) -> Result<(), ()> {
|
||||
let state = self.state.lock().await;
|
||||
control.send(ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: WsEvent) {
|
||||
let connections = self.connections.read().await;
|
||||
|
||||
for conn in connections.iter() {
|
||||
let _ = conn.send_event(&event).await;
|
||||
let mut state = self.state.lock().await;
|
||||
if let WsEvent::VpnEnv(env) = &event {
|
||||
state.snapshot = env.clone();
|
||||
} else if let WsEvent::VpnState(vpn_state) = &event {
|
||||
state.snapshot.vpn_state = vpn_state.clone();
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn add_connection(&self) -> (Arc<WsConnection>, mpsc::Receiver<Message>) {
|
||||
let (tx, rx) = mpsc::channel::<Message>(32);
|
||||
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 Some(revision) = state.revision.checked_add(1) else {
|
||||
for connection in state.connections.values() {
|
||||
connection.close(CloseReason::InternalError);
|
||||
}
|
||||
state.connections.clear();
|
||||
return;
|
||||
};
|
||||
state.revision = revision;
|
||||
|
||||
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: binary_paths::gpauth().to_string_lossy().into_owned(),
|
||||
host_info,
|
||||
};
|
||||
|
||||
if let Err(err) = conn.send_event(&WsEvent::VpnEnv(vpn_env)).await {
|
||||
warn!("Failed to send VPN state to new client: {}", err);
|
||||
}
|
||||
|
||||
self.connections.write().await.push(Arc::clone(&conn));
|
||||
|
||||
(conn, rx)
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, conn: Arc<WsConnection>) {
|
||||
let mut connections = self.connections.write().await;
|
||||
connections.retain(|c| !Arc::ptr_eq(c, &conn));
|
||||
}
|
||||
|
||||
fn vpn_state_rx(&self) -> watch::Receiver<VpnState> {
|
||||
self.vpn_state_rx.clone()
|
||||
}
|
||||
|
||||
pub async fn forward_req(&self, req: WsRequest) -> anyhow::Result<()> {
|
||||
if let WsRequest::Connect(ref req) = req {
|
||||
self
|
||||
.redaction
|
||||
.add_values(&[req.gateway().server(), req.args().cookie()])?
|
||||
}
|
||||
|
||||
self.ws_req_tx.send(req).await?;
|
||||
|
||||
Ok(())
|
||||
state.connections.retain(|_, connection| {
|
||||
if connection
|
||||
.send(ConnectionCommand::Send(ServerMessage::Event {
|
||||
revision,
|
||||
event: event.clone(),
|
||||
}))
|
||||
.is_ok()
|
||||
{
|
||||
true
|
||||
} else {
|
||||
connection.close(CloseReason::InternalError);
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,23 +187,27 @@ pub(crate) struct WsServer {
|
||||
ctx: Arc<WsServerContext>,
|
||||
cancel_token: CancellationToken,
|
||||
lock_file: Arc<LockFile>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
}
|
||||
|
||||
impl WsServer {
|
||||
pub fn new(
|
||||
api_key: Vec<u8>,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
product_version: &'static str,
|
||||
registry: Arc<SessionRegistry>,
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
lock_file: Arc<LockFile>,
|
||||
redaction: Arc<Redaction>,
|
||||
) -> Self {
|
||||
let ctx = Arc::new(WsServerContext::new(api_key, ws_req_tx, vpn_state_rx, redaction));
|
||||
let cancel_token = CancellationToken::new();
|
||||
|
||||
Self {
|
||||
ctx,
|
||||
cancel_token,
|
||||
ctx: Arc::new(WsServerContext::new(
|
||||
product_version,
|
||||
registry,
|
||||
dispatcher,
|
||||
&vpn_state_rx,
|
||||
)),
|
||||
cancel_token: CancellationToken::new(),
|
||||
lock_file,
|
||||
vpn_state_rx,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,55 +219,177 @@ impl WsServer {
|
||||
self.cancel_token.clone()
|
||||
}
|
||||
|
||||
pub async fn start(&self, shutdown_tx: mpsc::Sender<()>) {
|
||||
pub async fn start(&self, shutdown_tx: mpsc::Sender<()>, ready_tx: oneshot::Sender<()>) {
|
||||
let listener = match self.start_tcp_server().await {
|
||||
Ok(listener) => listener,
|
||||
Err(err) => {
|
||||
warn!("Failed to start WS server: {}", err);
|
||||
warn!("Failed to start WS server: {err}");
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = ready_tx.send(());
|
||||
|
||||
tokio::select! {
|
||||
_ = watch_vpn_state(self.ctx.vpn_state_rx(), Arc::clone(&self.ctx)) => {
|
||||
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
|
||||
info!("VPN state watch task completed");
|
||||
}
|
||||
_ = start_server(listener, self.ctx.clone()) => {
|
||||
info!("WS server stopped");
|
||||
result = axum::serve(listener, routes::routes(Arc::clone(&self.ctx))) => {
|
||||
if let Err(err) = result {
|
||||
warn!("WS server stopped: {err}");
|
||||
}
|
||||
}
|
||||
_ = self.cancel_token.cancelled() => {
|
||||
info!("WS server cancelled");
|
||||
}
|
||||
}
|
||||
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
|
||||
async fn start_tcp_server(&self) -> anyhow::Result<TcpListener> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let local_addr = listener.local_addr()?;
|
||||
let port = local_addr.port();
|
||||
|
||||
info!("WS server listening on port: {}", port);
|
||||
|
||||
let port = listener.local_addr()?.port();
|
||||
info!("WS server listening on port: {port}");
|
||||
self.lock_file.lock(&port.to_string())?;
|
||||
|
||||
Ok(listener)
|
||||
}
|
||||
}
|
||||
|
||||
fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
|
||||
VpnEnv {
|
||||
vpn_state,
|
||||
vpnc_script: find_vpnc_script().map(ToOwned::to_owned),
|
||||
csd_wrapper: find_csd_wrapper().map(ToOwned::to_owned),
|
||||
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
|
||||
use gpapi::{
|
||||
service::{event::WsEvent, transport::ServerMessage},
|
||||
utils::redact::Redaction,
|
||||
};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn resync_snapshot_is_ordered_with_state_events() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
registry,
|
||||
dispatcher,
|
||||
&state_rx,
|
||||
));
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
let (control, _close_rx) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
context.prepare_connection(&permit, control.clone()).await.unwrap();
|
||||
assert!(matches!(
|
||||
rx.recv().await,
|
||||
Some(ConnectionCommand::Send(ServerMessage::Attached { .. }))
|
||||
));
|
||||
|
||||
let (snapshot_result, ()) = tokio::join!(
|
||||
context.send_snapshot(&control),
|
||||
context.send_event(WsEvent::VpnState(VpnState::Disconnected)),
|
||||
);
|
||||
snapshot_result.unwrap();
|
||||
let first = rx.recv().await.unwrap();
|
||||
let second = rx.recv().await.unwrap();
|
||||
match (first, second) {
|
||||
(
|
||||
ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
current_revision: 0, ..
|
||||
}),
|
||||
ConnectionCommand::Send(ServerMessage::Event { revision: 1, .. }),
|
||||
)
|
||||
| (
|
||||
ConnectionCommand::Send(ServerMessage::Event { revision: 1, .. }),
|
||||
ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
current_revision: 1, ..
|
||||
}),
|
||||
) => {}
|
||||
_ => panic!("snapshot and event were not atomically ordered"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn removed_prepared_candidate_cannot_commit_takeover() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Arc::clone(®istry),
|
||||
dispatcher,
|
||||
&state_rx,
|
||||
));
|
||||
|
||||
let first = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let (first_tx, mut first_rx) = mpsc::channel(4);
|
||||
let (first_control, _first_close) = ConnectionControl::new(Uuid::new_v4(), first_tx);
|
||||
context.prepare_connection(&first, first_control.clone()).await.unwrap();
|
||||
first_rx.recv().await.unwrap();
|
||||
context.commit_connection(&first, &first_control).await.unwrap();
|
||||
|
||||
let reconnect = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let (candidate_tx, _candidate_rx) = mpsc::channel(1);
|
||||
let (candidate, _candidate_close) = ConnectionControl::new(Uuid::new_v4(), candidate_tx);
|
||||
context.prepare_connection(&reconnect, candidate.clone()).await.unwrap();
|
||||
context.send_event(WsEvent::VpnState(VpnState::Disconnected)).await;
|
||||
|
||||
assert!(context.commit_connection(&reconnect, &candidate).await.is_err());
|
||||
assert!(registry.is_current(credential.session_id(), 1));
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch_vpn_state(mut vpn_state_rx: watch::Receiver<VpnState>, ctx: Arc<WsServerContext>) {
|
||||
while vpn_state_rx.changed().await.is_ok() {
|
||||
let vpn_state = vpn_state_rx.borrow().clone();
|
||||
ctx.send_event(WsEvent::VpnState(vpn_state)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_server(listener: TcpListener, ctx: Arc<WsServerContext>) -> anyhow::Result<()> {
|
||||
let routes = routes::routes(ctx);
|
||||
|
||||
axum::serve(listener, routes).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -17,9 +17,7 @@ log.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
# Browser auth dependencies
|
||||
webbrowser = { version = "1", optional = true }
|
||||
open = { version = "5", optional = true }
|
||||
which = { workspace = true, optional = true }
|
||||
browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true }
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
uuid = { version = "1", optional = true, features = ["v4"] }
|
||||
|
||||
@@ -40,9 +38,7 @@ objc2-web-kit = { version = "0.3", optional = true }
|
||||
|
||||
[features]
|
||||
browser-auth = [
|
||||
"dep:webbrowser",
|
||||
"dep:open",
|
||||
"dep:which",
|
||||
"dep:browser-launcher",
|
||||
"dep:tiny_http",
|
||||
"dep:uuid",
|
||||
]
|
||||
@@ -58,3 +54,4 @@ webview-auth = [
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-web-kit",
|
||||
]
|
||||
release-devtools = ["webview-auth", "tauri/devtools"]
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
use browser_launcher::Browser as LaunchBrowser;
|
||||
use common::constants::GP_CALLBACK_PORT_FILENAME;
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use log::info;
|
||||
@@ -10,50 +11,14 @@ use tokio::{
|
||||
|
||||
use crate::browser::auth_server::AuthServer;
|
||||
|
||||
pub enum Browser<'a> {
|
||||
Auto,
|
||||
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() {
|
||||
"auto" => Browser::Auto,
|
||||
"default" => Browser::Default,
|
||||
"chrome" => Browser::Chrome,
|
||||
"firefox" => Browser::Firefox,
|
||||
"remote" => Browser::Remote,
|
||||
_ => Browser::Other(browser),
|
||||
}
|
||||
}
|
||||
|
||||
fn as_str(&self) -> &str {
|
||||
match self {
|
||||
Browser::Auto => "auto",
|
||||
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>,
|
||||
browser: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> BrowserAuthenticator<'a> {
|
||||
pub fn new(auth_request: &'a str, browser: &'a str) -> Self {
|
||||
Self {
|
||||
auth_request,
|
||||
browser: Browser::from_str(browser),
|
||||
}
|
||||
Self { auth_request, browser }
|
||||
}
|
||||
|
||||
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
|
||||
@@ -66,10 +31,9 @@ impl<'a> BrowserAuthenticator<'a> {
|
||||
auth_server.serve_request(&auth_request);
|
||||
});
|
||||
|
||||
match self.browser {
|
||||
Browser::Remote => {
|
||||
info!(
|
||||
r#"
|
||||
if is_remote_browser(self.browser) {
|
||||
info!(
|
||||
r#"
|
||||
|
||||
==== Manual Authentication Required ====
|
||||
|
||||
@@ -82,37 +46,19 @@ After completing the authentication, please paste the authentication data back t
|
||||
|
||||
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)?;
|
||||
}
|
||||
Browser::Auto => {
|
||||
if let Some(app) = find_auto_browser_path() {
|
||||
info!("Launching browser: {}", app);
|
||||
open::with_detached(&auth_url, app)?;
|
||||
} else {
|
||||
info!("No preferred browser found; 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)?;
|
||||
}
|
||||
auth_url
|
||||
);
|
||||
return read_auth_data_from_stdin();
|
||||
}
|
||||
|
||||
browser_launcher::open_url(&auth_url, LaunchBrowser::from_name(self.browser))?;
|
||||
|
||||
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) {
|
||||
if is_remote_browser(self.browser) {
|
||||
let local_ip = detect_local_ip().await?;
|
||||
Ok(format!("{}:0", local_ip))
|
||||
} else {
|
||||
@@ -121,6 +67,10 @@ Note that the URL is only valid for a single use.
|
||||
}
|
||||
}
|
||||
|
||||
fn is_remote_browser(browser: &str) -> bool {
|
||||
browser.eq_ignore_ascii_case("remote")
|
||||
}
|
||||
|
||||
/// 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?;
|
||||
@@ -134,27 +84,6 @@ async fn detect_local_ip() -> anyhow::Result<String> {
|
||||
Ok(ip.to_string())
|
||||
}
|
||||
|
||||
fn find_browser_path(browser: &Browser) -> String {
|
||||
match browser {
|
||||
Browser::Chrome => find_chrome_path().unwrap_or_else(|| browser.as_str().to_string()),
|
||||
_ => browser.as_str().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn find_auto_browser_path() -> Option<String> {
|
||||
find_chrome_path().or_else(|| find_program_path("firefox"))
|
||||
}
|
||||
|
||||
fn find_chrome_path() -> Option<String> {
|
||||
["google-chrome-stable", "google-chrome", "chromium"]
|
||||
.iter()
|
||||
.find_map(|browser_name| find_program_path(browser_name))
|
||||
}
|
||||
|
||||
fn find_program_path(name: &str) -> Option<String> {
|
||||
which::which(name).ok().map(|path| path.to_string_lossy().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?;
|
||||
@@ -200,8 +129,15 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn browser_auto_is_distinct_from_system_default() {
|
||||
assert!(matches!(Browser::from_str("auto"), Browser::Auto));
|
||||
assert!(matches!(Browser::from_str("default"), Browser::Default));
|
||||
fn shared_launcher_keeps_auto_distinct_from_system_default() {
|
||||
assert_eq!(LaunchBrowser::from_name("auto"), LaunchBrowser::Auto);
|
||||
assert_eq!(LaunchBrowser::from_name("default"), LaunchBrowser::Default);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_remote_remains_auth_specific() {
|
||||
assert!(is_remote_browser("remote"));
|
||||
assert!(is_remote_browser("REMOTE"));
|
||||
assert_ne!(LaunchBrowser::from_name("remote"), LaunchBrowser::Default);
|
||||
}
|
||||
}
|
||||
@@ -17,4 +17,4 @@ mod platform_impl;
|
||||
)))]
|
||||
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
|
||||
|
||||
pub use webview_auth::WebviewAuthenticator;
|
||||
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
@@ -1,17 +1,147 @@
|
||||
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 std::{ffi::c_void, ptr};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use block2::{DynBlock, RcBlock};
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject, Sel},
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest,
|
||||
NSURLSessionAuthChallengeDisposition,
|
||||
};
|
||||
use objc2_web_kit::{WKNavigationDelegate, WKWebView};
|
||||
use tauri::webview::PlatformWebview;
|
||||
|
||||
use super::webview_auth::PlatformWebviewExt;
|
||||
|
||||
static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
|
||||
struct TlsNavigationDelegateIvars {
|
||||
original: Retained<ProtocolObject<dyn WKNavigationDelegate>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = TlsNavigationDelegateIvars]
|
||||
struct TlsNavigationDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for TlsNavigationDelegate {}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
unsafe impl WKNavigationDelegate for TlsNavigationDelegate {
|
||||
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
|
||||
unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler(
|
||||
&self,
|
||||
_webview: &WKWebView,
|
||||
challenge: &NSURLAuthenticationChallenge,
|
||||
completion_handler: &DynBlock<dyn Fn(NSURLSessionAuthChallengeDisposition, *mut NSURLCredential)>,
|
||||
) {
|
||||
let protection_space = challenge.protectionSpace();
|
||||
let is_server_trust = protection_space
|
||||
.authenticationMethod()
|
||||
.isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
|
||||
if !is_server_trust {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
}
|
||||
|
||||
let server_trust: *mut AnyObject = msg_send![&*protection_space, serverTrust];
|
||||
if server_trust.is_null() {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
}
|
||||
|
||||
let credential: Retained<NSURLCredential> =
|
||||
msg_send![objc2::class!(NSURLCredential), credentialForTrust: server_trust];
|
||||
completion_handler.call((challenge_disposition(true), Retained::as_ptr(&credential).cast_mut()));
|
||||
}
|
||||
}
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
#[unsafe(method(respondsToSelector:))]
|
||||
fn responds_to_selector(&self, selector: Sel) -> bool {
|
||||
let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
|
||||
responds || self.ivars().original.respondsToSelector(selector)
|
||||
}
|
||||
|
||||
#[unsafe(method(forwardingTargetForSelector:))]
|
||||
fn forwarding_target_for_selector(&self, selector: Sel) -> *mut AnyObject {
|
||||
if self.ivars().original.respondsToSelector(selector) {
|
||||
Retained::as_ptr(&self.ivars().original).cast_mut().cast()
|
||||
} else {
|
||||
unsafe { msg_send![super(self), forwardingTargetForSelector: selector] }
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
fn new(original: Retained<ProtocolObject<dyn WKNavigationDelegate>>, mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(TlsNavigationDelegateIvars { original });
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
}
|
||||
|
||||
fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisposition {
|
||||
if is_server_trust {
|
||||
NSURLSessionAuthChallengeDisposition::UseCredential
|
||||
} else {
|
||||
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
|
||||
}
|
||||
}
|
||||
|
||||
fn install_tls_navigation_delegate(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let original = unsafe { webview.navigationDelegate() }.context("WebView navigation delegate is unavailable")?;
|
||||
let mtm = MainThreadMarker::new().context("WebView must be configured on the main thread")?;
|
||||
let delegate = TlsNavigationDelegate::new(original, mtm);
|
||||
|
||||
unsafe {
|
||||
objc_setAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
webview.setNavigationDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use objc2_foundation::NSURLSessionAuthChallengeDisposition;
|
||||
|
||||
use super::challenge_disposition;
|
||||
|
||||
#[test]
|
||||
fn accepts_server_trust_challenges() {
|
||||
assert_eq!(
|
||||
challenge_disposition(true),
|
||||
NSURLSessionAuthChallengeDisposition::UseCredential
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_default_handling_for_other_challenges() {
|
||||
assert_eq!(
|
||||
challenge_disposition(false),
|
||||
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
warn!("Ignoring TLS errors is not supported on macOS");
|
||||
Ok(())
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
install_tls_navigation_delegate(webview)
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
|
||||
@@ -2,10 +2,10 @@ use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::bail;
|
||||
use gpapi::{
|
||||
auth::SamlAuthData,
|
||||
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
|
||||
gp_params::GpParams,
|
||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||
utils::redact::redact_uri,
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
};
|
||||
use log::{info, warn};
|
||||
use tauri::{
|
||||
@@ -53,10 +53,28 @@ pub struct WebviewAuthenticator<'a> {
|
||||
auth_request: Option<&'a str>,
|
||||
webview_user_agent: Option<WebviewUserAgent>,
|
||||
clean: bool,
|
||||
window_title: &'a str,
|
||||
window_theme: AuthWindowTheme,
|
||||
|
||||
is_retrying: tokio::sync::RwLock<bool>,
|
||||
}
|
||||
|
||||
fn native_theme(theme: AuthWindowTheme) -> Option<tauri::Theme> {
|
||||
match theme {
|
||||
AuthWindowTheme::System => None,
|
||||
AuthWindowTheme::Light => Some(tauri::Theme::Light),
|
||||
AuthWindowTheme::Dark => Some(tauri::Theme::Dark),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_auth_theme(app_handle: &AppHandle, theme: AuthWindowTheme) {
|
||||
app_handle.set_theme(native_theme(theme));
|
||||
}
|
||||
|
||||
fn present_after_setup(clean: bool) -> bool {
|
||||
clean
|
||||
}
|
||||
|
||||
impl<'a> WebviewAuthenticator<'a> {
|
||||
pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self {
|
||||
Self {
|
||||
@@ -65,6 +83,8 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
auth_request: None,
|
||||
webview_user_agent: None,
|
||||
clean: false,
|
||||
window_title: "GlobalProtect Login",
|
||||
window_theme: AuthWindowTheme::System,
|
||||
is_retrying: Default::default(),
|
||||
}
|
||||
}
|
||||
@@ -84,6 +104,16 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_window_title(mut self, window_title: &'a str) -> Self {
|
||||
self.window_title = window_title;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
|
||||
self.window_theme = window_theme;
|
||||
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);
|
||||
@@ -112,15 +142,15 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
});
|
||||
};
|
||||
|
||||
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())
|
||||
let auth_window_builder = 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)
|
||||
.title(self.window_title)
|
||||
.theme(native_theme(self.window_theme))
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
let auth_window = auth_window_builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height())
|
||||
.focused(true)
|
||||
// when clean is true, the window is expected to be shown because the cookies are cleared
|
||||
.visible(self.clean)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?;
|
||||
|
||||
@@ -128,9 +158,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
|
||||
if present_after_setup(self.clean) {
|
||||
self.raise_window(&auth_window);
|
||||
}
|
||||
|
||||
loop {
|
||||
match auth_messenger.subscribe().await? {
|
||||
AuthEvent::Close => bail!("Authentication cancelled"),
|
||||
AuthEvent::Close => bail!(AuthenticationCancelled),
|
||||
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),
|
||||
@@ -284,14 +318,8 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
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()
|
||||
};
|
||||
use gpapi::utils::window::WindowExt;
|
||||
let result = auth_window.raise();
|
||||
|
||||
if let Err(err) = result {
|
||||
warn!("Failed to raise window: {}", err);
|
||||
@@ -377,6 +405,19 @@ fn prepend_webview_user_agent_prefix(prefix: &str, default_user_agent: &str) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maps_auth_window_theme_to_native_theme() {
|
||||
assert_eq!(native_theme(AuthWindowTheme::System), None);
|
||||
assert_eq!(native_theme(AuthWindowTheme::Light), Some(tauri::Theme::Light));
|
||||
assert_eq!(native_theme(AuthWindowTheme::Dark), Some(tauri::Theme::Dark));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presents_clean_auth_after_setup() {
|
||||
assert!(present_after_setup(true));
|
||||
assert!(!present_after_setup(false));
|
||||
}
|
||||
|
||||
#[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();
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "browser-launcher"
|
||||
rust-version.workspace = true
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
open = { version = "5", optional = true }
|
||||
webbrowser = { version = "1", optional = true }
|
||||
which = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
launcher = ["dep:open", "dep:webbrowser", "dep:which"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Kevin Yue
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,89 @@
|
||||
#[cfg(all(feature = "launcher", target_os = "macos"))]
|
||||
#[path = "platform/macos.rs"]
|
||||
mod platform;
|
||||
|
||||
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
|
||||
#[path = "platform/generic.rs"]
|
||||
mod platform;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Browser<'a> {
|
||||
Auto,
|
||||
Default,
|
||||
Chrome,
|
||||
Edge,
|
||||
Firefox,
|
||||
Safari,
|
||||
Other(&'a str),
|
||||
}
|
||||
|
||||
impl<'a> Browser<'a> {
|
||||
pub fn from_config(value: Option<&'a str>) -> Self {
|
||||
let Some(value) = value.filter(|value| !value.trim().is_empty()) else {
|
||||
return Browser::Auto;
|
||||
};
|
||||
|
||||
Self::from_name(value)
|
||||
}
|
||||
|
||||
pub fn from_name(value: &'a str) -> Self {
|
||||
match value.trim().to_lowercase().as_str() {
|
||||
"auto" => Browser::Auto,
|
||||
"default" => Browser::Default,
|
||||
"chrome" => Browser::Chrome,
|
||||
"edge" => Browser::Edge,
|
||||
"firefox" => Browser::Firefox,
|
||||
"safari" => Browser::Safari,
|
||||
_ => Browser::Other(value),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
|
||||
pub(crate) fn as_str(&self) -> &str {
|
||||
match self {
|
||||
Browser::Auto => "auto",
|
||||
Browser::Default => "default",
|
||||
Browser::Chrome => "chrome",
|
||||
Browser::Edge => "edge",
|
||||
Browser::Firefox => "firefox",
|
||||
Browser::Safari => "safari",
|
||||
Browser::Other(browser) => browser,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "launcher")]
|
||||
pub fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
|
||||
platform::open_url(url, browser)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_config_uses_auto() {
|
||||
assert_eq!(Browser::from_config(None), Browser::Auto);
|
||||
assert_eq!(Browser::from_config(Some("")), Browser::Auto);
|
||||
assert_eq!(Browser::from_config(Some(" ")), Browser::Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_browser_names_are_case_insensitive() {
|
||||
assert_eq!(Browser::from_name("AUTO"), Browser::Auto);
|
||||
assert_eq!(Browser::from_name("Default"), Browser::Default);
|
||||
assert_eq!(Browser::from_name("Chrome"), Browser::Chrome);
|
||||
assert_eq!(Browser::from_name("EDGE"), Browser::Edge);
|
||||
assert_eq!(Browser::from_name("Firefox"), Browser::Firefox);
|
||||
assert_eq!(Browser::from_name("Safari"), Browser::Safari);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_browser_names_are_preserved() {
|
||||
assert_eq!(Browser::from_name("/opt/browser"), Browser::Other("/opt/browser"));
|
||||
assert_eq!(
|
||||
Browser::from_config(Some(" custom-browser ")),
|
||||
Browser::Other(" custom-browser ")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use log::{debug, info, warn};
|
||||
|
||||
use crate::Browser;
|
||||
|
||||
const GOOGLE_CHROME_BROWSERS: &[&str] = &["google-chrome-stable", "google-chrome"];
|
||||
const CHROMIUM_BROWSERS: &[&str] = &["chromium", "chromium-browser"];
|
||||
const EDGE_BROWSERS: &[&str] = &["microsoft-edge-stable", "microsoft-edge"];
|
||||
const EDGE_BETA_BROWSERS: &[&str] = &["microsoft-edge-beta"];
|
||||
const EDGE_DEV_BROWSERS: &[&str] = &["microsoft-edge-dev"];
|
||||
const FIREFOX_BROWSERS: &[&str] = &["firefox"];
|
||||
const FIREFOX_ESR_BROWSERS: &[&str] = &["firefox-esr"];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum LauncherSpec {
|
||||
Programs(&'static [&'static str]),
|
||||
Flatpak(&'static str),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum BrowserLauncher {
|
||||
Executable(String),
|
||||
Flatpak { executable: String, app_id: &'static str },
|
||||
}
|
||||
|
||||
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
|
||||
match browser {
|
||||
Browser::Auto => open_auto_browser(url),
|
||||
Browser::Default => open_default_browser(url),
|
||||
Browser::Chrome => {
|
||||
let browser = find_chrome_browser().unwrap_or_else(|| browser.as_str().to_string());
|
||||
open_with_browser(url, &browser)
|
||||
}
|
||||
Browser::Edge => {
|
||||
let browser = find_edge_browser().unwrap_or_else(|| browser.as_str().to_string());
|
||||
open_with_browser(url, &browser)
|
||||
}
|
||||
Browser::Firefox => {
|
||||
let browser = find_firefox_browser().unwrap_or_else(|| browser.as_str().to_string());
|
||||
open_with_browser(url, &browser)
|
||||
}
|
||||
Browser::Safari | Browser::Other(_) => open_with_browser(url, browser.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_auto_browser(url: &str) -> anyhow::Result<()> {
|
||||
let default_launcher = find_default_browser_launcher();
|
||||
if let Some(launcher) = default_launcher.as_ref() {
|
||||
if let Err(err) = open_with_launcher(url, launcher) {
|
||||
warn!("Failed to launch recognized default browser: {err}");
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(launcher) = find_auto_browser_launcher()
|
||||
&& Some(&launcher) != default_launcher.as_ref()
|
||||
{
|
||||
if let Err(err) = open_with_launcher(url, &launcher) {
|
||||
warn!("Failed to launch an automatically detected browser: {err}");
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
warn!("Falling back to the system URL handler");
|
||||
open_default_browser(url)
|
||||
}
|
||||
|
||||
fn open_default_browser(url: &str) -> anyhow::Result<()> {
|
||||
if webbrowser::open(url).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
open::that_detached(url).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn open_with_browser(url: &str, browser: &str) -> anyhow::Result<()> {
|
||||
info!("Launching browser: {}", browser);
|
||||
open::with_detached(url, browser).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn open_with_launcher(url: &str, launcher: &BrowserLauncher) -> anyhow::Result<()> {
|
||||
match launcher {
|
||||
BrowserLauncher::Executable(executable) => open_with_browser(url, executable),
|
||||
BrowserLauncher::Flatpak { executable, app_id } => {
|
||||
info!("Launching Flatpak browser: {app_id}");
|
||||
Command::new(executable)
|
||||
.args(["run", app_id, url])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_default_browser_launcher() -> Option<BrowserLauncher> {
|
||||
let desktop_id = default_browser_desktop_id()?;
|
||||
let Some(spec) = launcher_spec_for_desktop_id(&desktop_id) else {
|
||||
warn!("Default browser desktop ID is not recognized: {desktop_id}");
|
||||
return None;
|
||||
};
|
||||
|
||||
let launcher = resolve_launcher(spec);
|
||||
if launcher.is_none() {
|
||||
warn!("Default browser is recognized but its launcher is unavailable: {desktop_id}");
|
||||
}
|
||||
launcher
|
||||
}
|
||||
|
||||
fn default_browser_desktop_id() -> Option<String> {
|
||||
let output = match Command::new("xdg-settings")
|
||||
.args(["get", "default-web-browser"])
|
||||
.output()
|
||||
{
|
||||
Ok(output) => output,
|
||||
Err(err) => {
|
||||
debug!("Unable to query the default browser: {err}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
if !output.status.success() {
|
||||
debug!("xdg-settings could not determine the default browser");
|
||||
return None;
|
||||
}
|
||||
|
||||
let desktop_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
(!desktop_id.is_empty()).then_some(desktop_id)
|
||||
}
|
||||
|
||||
fn launcher_spec_for_desktop_id(desktop_id: &str) -> Option<LauncherSpec> {
|
||||
match desktop_id {
|
||||
"google-chrome.desktop" | "google-chrome-stable.desktop" => Some(LauncherSpec::Programs(GOOGLE_CHROME_BROWSERS)),
|
||||
"chromium.desktop" | "chromium-browser.desktop" | "chromium_chromium.desktop" => {
|
||||
Some(LauncherSpec::Programs(CHROMIUM_BROWSERS))
|
||||
}
|
||||
"microsoft-edge.desktop" | "microsoft-edge-stable.desktop" => Some(LauncherSpec::Programs(EDGE_BROWSERS)),
|
||||
"microsoft-edge-beta.desktop" => Some(LauncherSpec::Programs(EDGE_BETA_BROWSERS)),
|
||||
"microsoft-edge-dev.desktop" => Some(LauncherSpec::Programs(EDGE_DEV_BROWSERS)),
|
||||
"firefox.desktop" | "firefox_firefox.desktop" => Some(LauncherSpec::Programs(FIREFOX_BROWSERS)),
|
||||
"firefox-esr.desktop" => Some(LauncherSpec::Programs(FIREFOX_ESR_BROWSERS)),
|
||||
"com.google.Chrome.desktop" => Some(LauncherSpec::Flatpak("com.google.Chrome")),
|
||||
"org.chromium.Chromium.desktop" => Some(LauncherSpec::Flatpak("org.chromium.Chromium")),
|
||||
"com.microsoft.Edge.desktop" => Some(LauncherSpec::Flatpak("com.microsoft.Edge")),
|
||||
"org.mozilla.firefox.desktop" => Some(LauncherSpec::Flatpak("org.mozilla.firefox")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_launcher(spec: LauncherSpec) -> Option<BrowserLauncher> {
|
||||
match spec {
|
||||
LauncherSpec::Programs(programs) => find_programs(programs).map(BrowserLauncher::Executable),
|
||||
LauncherSpec::Flatpak(app_id) => {
|
||||
find_program("flatpak").map(|executable| BrowserLauncher::Flatpak { executable, app_id })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_auto_browser_launcher() -> Option<BrowserLauncher> {
|
||||
find_auto_browser().map(BrowserLauncher::Executable)
|
||||
}
|
||||
|
||||
fn find_auto_browser() -> Option<String> {
|
||||
find_chrome_browser()
|
||||
.or_else(find_edge_browser)
|
||||
.or_else(find_firefox_browser)
|
||||
}
|
||||
|
||||
fn find_chrome_browser() -> Option<String> {
|
||||
find_programs(GOOGLE_CHROME_BROWSERS).or_else(|| find_programs(CHROMIUM_BROWSERS))
|
||||
}
|
||||
|
||||
fn find_edge_browser() -> Option<String> {
|
||||
find_programs(EDGE_BROWSERS)
|
||||
.or_else(|| find_programs(EDGE_BETA_BROWSERS))
|
||||
.or_else(|| find_programs(EDGE_DEV_BROWSERS))
|
||||
}
|
||||
|
||||
fn find_firefox_browser() -> Option<String> {
|
||||
find_programs(FIREFOX_BROWSERS).or_else(|| find_programs(FIREFOX_ESR_BROWSERS))
|
||||
}
|
||||
|
||||
fn find_programs(programs: &[&str]) -> Option<String> {
|
||||
programs.iter().find_map(|program| find_program(program))
|
||||
}
|
||||
|
||||
fn find_program(name: &str) -> Option<String> {
|
||||
which::which(name).ok().map(|path| path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auto_candidates_try_chrome_then_edge_then_firefox() {
|
||||
let candidates = GOOGLE_CHROME_BROWSERS
|
||||
.iter()
|
||||
.chain(CHROMIUM_BROWSERS)
|
||||
.chain(EDGE_BROWSERS)
|
||||
.chain(EDGE_BETA_BROWSERS)
|
||||
.chain(EDGE_DEV_BROWSERS)
|
||||
.chain(FIREFOX_BROWSERS)
|
||||
.chain(FIREFOX_ESR_BROWSERS)
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
candidates,
|
||||
vec![
|
||||
"google-chrome-stable",
|
||||
"google-chrome",
|
||||
"chromium",
|
||||
"chromium-browser",
|
||||
"microsoft-edge-stable",
|
||||
"microsoft-edge",
|
||||
"microsoft-edge-beta",
|
||||
"microsoft-edge-dev",
|
||||
"firefox",
|
||||
"firefox-esr",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_desktop_ids_map_to_expected_launchers() {
|
||||
let cases = [
|
||||
("google-chrome.desktop", LauncherSpec::Programs(GOOGLE_CHROME_BROWSERS)),
|
||||
("chromium.desktop", LauncherSpec::Programs(CHROMIUM_BROWSERS)),
|
||||
("chromium-browser.desktop", LauncherSpec::Programs(CHROMIUM_BROWSERS)),
|
||||
("chromium_chromium.desktop", LauncherSpec::Programs(CHROMIUM_BROWSERS)),
|
||||
("microsoft-edge.desktop", LauncherSpec::Programs(EDGE_BROWSERS)),
|
||||
(
|
||||
"microsoft-edge-beta.desktop",
|
||||
LauncherSpec::Programs(EDGE_BETA_BROWSERS),
|
||||
),
|
||||
("microsoft-edge-dev.desktop", LauncherSpec::Programs(EDGE_DEV_BROWSERS)),
|
||||
("firefox.desktop", LauncherSpec::Programs(FIREFOX_BROWSERS)),
|
||||
("firefox-esr.desktop", LauncherSpec::Programs(FIREFOX_ESR_BROWSERS)),
|
||||
("firefox_firefox.desktop", LauncherSpec::Programs(FIREFOX_BROWSERS)),
|
||||
("com.google.Chrome.desktop", LauncherSpec::Flatpak("com.google.Chrome")),
|
||||
(
|
||||
"org.chromium.Chromium.desktop",
|
||||
LauncherSpec::Flatpak("org.chromium.Chromium"),
|
||||
),
|
||||
(
|
||||
"com.microsoft.Edge.desktop",
|
||||
LauncherSpec::Flatpak("com.microsoft.Edge"),
|
||||
),
|
||||
(
|
||||
"org.mozilla.firefox.desktop",
|
||||
LauncherSpec::Flatpak("org.mozilla.firefox"),
|
||||
),
|
||||
];
|
||||
|
||||
for (desktop_id, expected) in cases {
|
||||
assert_eq!(launcher_spec_for_desktop_id(desktop_id), Some(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_desktop_id_is_not_used() {
|
||||
assert_eq!(launcher_spec_for_desktop_id("code.desktop"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use log::info;
|
||||
|
||||
use crate::Browser;
|
||||
|
||||
const SAFARI_BUNDLE_ID: &str = "com.apple.Safari";
|
||||
const CHROME_BUNDLE_ID: &str = "com.google.Chrome";
|
||||
const EDGE_BUNDLE_ID: &str = "com.microsoft.edgemac";
|
||||
const FIREFOX_BUNDLE_ID: &str = "org.mozilla.firefox";
|
||||
|
||||
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
|
||||
match browser {
|
||||
Browser::Auto | Browser::Default => open_default_browser(url),
|
||||
Browser::Safari => open_browser_bundle(url, SAFARI_BUNDLE_ID),
|
||||
Browser::Chrome => open_browser_bundle(url, CHROME_BUNDLE_ID),
|
||||
Browser::Edge => open_browser_bundle(url, EDGE_BUNDLE_ID),
|
||||
Browser::Firefox => open_browser_bundle(url, FIREFOX_BUNDLE_ID),
|
||||
Browser::Other(application) => open_browser_application(url, application),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_default_browser(url: &str) -> anyhow::Result<()> {
|
||||
if webbrowser::open(url).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
open::that_detached(url).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn open_browser_bundle(url: &str, bundle_id: &str) -> anyhow::Result<()> {
|
||||
info!("Launching browser bundle: {}", bundle_id);
|
||||
let status = std::process::Command::new("/usr/bin/open")
|
||||
.args(["-b", bundle_id, url])
|
||||
.status()?;
|
||||
|
||||
if !status.success() {
|
||||
anyhow::bail!("Failed to launch browser bundle {bundle_id}: {status}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_browser_application(url: &str, application: &str) -> anyhow::Result<()> {
|
||||
info!("Launching browser application: {}", application);
|
||||
open::with_detached(url, application).map_err(Into::into)
|
||||
}
|
||||
@@ -5,4 +5,4 @@ version.workspace = true
|
||||
authors.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
license = "MIT"
|
||||
@@ -1,674 +1,21 @@
|
||||
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>.
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Kevin Yue
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -3,6 +3,8 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use crate::constants::GP_VPNC_SCRIPT_INSTALLER_BINARY;
|
||||
use crate::constants::{GP_AUTH_BINARY, GP_CLIENT_BINARY, GP_GUI_BINARY, GP_GUI_HELPER_BINARY, GP_SERVICE_BINARY};
|
||||
|
||||
pub fn gpclient() -> PathBuf {
|
||||
@@ -13,6 +15,15 @@ pub fn gpservice() -> PathBuf {
|
||||
resolve("GP_SERVICE_BINARY", "gpservice", GP_SERVICE_BINARY)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn gp_vpnc_script_installer() -> PathBuf {
|
||||
resolve(
|
||||
"GP_VPNC_SCRIPT_INSTALLER_BINARY",
|
||||
"gp-vpnc-script-installer",
|
||||
GP_VPNC_SCRIPT_INSTALLER_BINARY,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gpauth() -> PathBuf {
|
||||
resolve("GP_AUTH_BINARY", "gpauth", GP_AUTH_BINARY)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,19 @@ 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";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const INSTALLED_VPNC_SCRIPT: &str = "/var/lib/gpclient/scripts/vpnc-script";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/lib/gpclient/scripts/vpnc-script.metadata";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/local/libexec/gpclient/gp-vpnc-script-installer";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const INSTALLED_VPNC_SCRIPT: &str = "/var/db/gpclient/scripts/vpnc-script";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/db/gpclient/scripts/vpnc-script.metadata";
|
||||
pub const MAX_VPNC_SCRIPT_SIZE: usize = 1024 * 1024;
|
||||
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
|
||||
|
||||
// Release binaries - macOS (Apple Silicon Homebrew)
|
||||
|
||||
@@ -32,11 +32,14 @@ uzers.workspace = true
|
||||
serde_urlencoded.workspace = true
|
||||
md5.workspace = true
|
||||
sha256.workspace = true
|
||||
uuid = { workspace = true, features = ["v5"] }
|
||||
uuid = { workspace = true, features = ["v4", "v5", "serde"] }
|
||||
chrono.workspace = true
|
||||
humantime.workspace = true
|
||||
netdev.workspace = true
|
||||
os_info = { version = "3", default-features = false }
|
||||
snow.workspace = true
|
||||
zeroize = { workspace = true, features = ["serde"] }
|
||||
getrandom = "0.4"
|
||||
|
||||
# Optional dependencies for features
|
||||
tauri = { workspace = true, optional = true }
|
||||
@@ -46,6 +49,9 @@ clap-verbosity-flag = { workspace = true, optional = true }
|
||||
env_logger = { workspace = true, optional = true }
|
||||
log-reload = { version = "0.1", optional = true }
|
||||
|
||||
[target.'cfg(target_os="macos")'.dependencies]
|
||||
oslog = { version = "0.2", default-features = false, 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 }
|
||||
@@ -57,4 +63,4 @@ proptest.workspace = true
|
||||
tauri = ["dep:tauri", "dep:gtk"]
|
||||
clap = ["dep:clap", "dep:clap-verbosity-flag"]
|
||||
webview-auth = []
|
||||
logger = ["dep:env_logger", "dep:log-reload"]
|
||||
logger = ["dep:env_logger", "dep:log-reload", "dep:oslog"]
|
||||
@@ -1,4 +1,7 @@
|
||||
use std::borrow::{Borrow, Cow};
|
||||
use std::{
|
||||
borrow::{Borrow, Cow},
|
||||
fmt,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{info, warn};
|
||||
@@ -9,6 +12,25 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
|
||||
|
||||
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
|
||||
pub enum AuthWindowTheme {
|
||||
#[default]
|
||||
System,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl AuthWindowTheme {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "system",
|
||||
Self::Light => "light",
|
||||
Self::Dark => "dark",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SamlAuthData {
|
||||
@@ -25,13 +47,26 @@ pub struct SamlAuthData {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SamlAuthResult {
|
||||
Success(SamlAuthData),
|
||||
Cancelled,
|
||||
Failure(String),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthenticationCancelled;
|
||||
|
||||
impl fmt::Display for AuthenticationCancelled {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Authentication cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AuthenticationCancelled {}
|
||||
|
||||
impl SamlAuthResult {
|
||||
pub fn is_success(&self) -> bool {
|
||||
match self {
|
||||
SamlAuthResult::Success(_) => true,
|
||||
SamlAuthResult::Cancelled => false,
|
||||
SamlAuthResult::Failure(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -39,6 +74,7 @@ impl SamlAuthResult {
|
||||
pub fn host_id(&self) -> Option<&str> {
|
||||
match self {
|
||||
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
|
||||
SamlAuthResult::Cancelled => None,
|
||||
SamlAuthResult::Failure(_) => None,
|
||||
}
|
||||
}
|
||||
@@ -246,4 +282,15 @@ mod tests {
|
||||
let value = serde_json::to_value(result).unwrap();
|
||||
assert!(value["success"].get("hostId").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_result_cancelled_is_structured() {
|
||||
let value = serde_json::to_value(SamlAuthResult::Cancelled).unwrap();
|
||||
|
||||
assert_eq!(value, "cancelled");
|
||||
|
||||
let result: SamlAuthResult = serde_json::from_value(value).unwrap();
|
||||
assert!(!result.is_success());
|
||||
assert_eq!(result.host_id(), None);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use anyhow::bail;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::auth::{SamlAuthData, SamlAuthResult};
|
||||
use crate::auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -250,6 +250,7 @@ impl TryFrom<SamlAuthResult> for Credential {
|
||||
fn try_from(value: SamlAuthResult) -> anyhow::Result<Self> {
|
||||
match value {
|
||||
SamlAuthResult::Success(auth_data) => Ok(Self::from(auth_data)),
|
||||
SamlAuthResult::Cancelled => bail!(AuthenticationCancelled),
|
||||
SamlAuthResult::Failure(err) => bail!(err),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,3 @@ pub mod logger;
|
||||
|
||||
#[cfg(feature = "clap")]
|
||||
pub mod clap;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub const GP_API_KEY: &[u8; 32] = &[0; 32];
|
||||
@@ -1,21 +1,33 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::bail;
|
||||
use env_logger::Logger;
|
||||
use log::{Level, warn};
|
||||
use log::{Level, Log, warn};
|
||||
use log_reload::{ReloadHandle, ReloadLog};
|
||||
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
|
||||
pub const LOG_BACKEND_ENV: &str = "GP_LOG_BACKEND";
|
||||
pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
|
||||
|
||||
type BoxedLogger = Box<dyn Log + Send + Sync>;
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
|
||||
|
||||
pub fn init(level: Level, subsystem: &str, category: &str) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if macos_unified_log_enabled() {
|
||||
init_with_logger(level, MacosLogger::new(subsystem, category));
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = (subsystem, category);
|
||||
|
||||
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() {
|
||||
pub fn init_with_logger(level: Level, logger: impl Log + Send + Sync + 'static) {
|
||||
if LOG_HANDLE.get().is_some() {
|
||||
warn!("Logger already initialized");
|
||||
return;
|
||||
}
|
||||
@@ -23,7 +35,7 @@ pub fn init_with_logger(level: Level, logger: Logger) {
|
||||
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 level_filter_logger = log_reload::LevelFilter::new(level, Box::new(logger) as BoxedLogger);
|
||||
|
||||
let reload_log = ReloadLog::new(level_filter_logger);
|
||||
let handle = reload_log.handle();
|
||||
@@ -42,3 +54,61 @@ pub fn set_max_level(level: Level) -> anyhow::Result<()> {
|
||||
.modify(|logger| logger.set_level(level))
|
||||
.map_err(|e| anyhow::anyhow!(e))
|
||||
}
|
||||
|
||||
pub fn macos_unified_log_enabled() -> bool {
|
||||
cfg!(target_os = "macos") && std::env::var(LOG_BACKEND_ENV).as_deref() == Ok(MACOS_UNIFIED_LOG_BACKEND)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct MacosLogger {
|
||||
inner: oslog::OsLog,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl MacosLogger {
|
||||
pub fn new(subsystem: &str, category: &str) -> Self {
|
||||
Self {
|
||||
inner: oslog::OsLog::new(subsystem, category),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&self, level: Level, target: &str, message: &str) {
|
||||
self
|
||||
.inner
|
||||
.with_level(macos_log_level(level), &format!("[{target}] {message}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Log for MacosLogger {
|
||||
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
|
||||
self.inner.level_is_enabled(macos_log_level(metadata.level()))
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if self.enabled(record.metadata()) {
|
||||
self.write(record.level(), record.target(), &record.args().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_log_level(level: Level) -> oslog::Level {
|
||||
match level {
|
||||
Level::Trace | Level::Debug => oslog::Level::Debug,
|
||||
Level::Info => oslog::Level::Default,
|
||||
Level::Warn | Level::Error => oslog::Level::Error,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn info_logs_use_the_persistent_macos_level() {
|
||||
assert_eq!(macos_log_level(Level::Info) as u8, oslog::Level::Default as u8);
|
||||
}
|
||||
}
|
||||
@@ -362,6 +362,7 @@ mod platform {
|
||||
mod platform {
|
||||
use super::{
|
||||
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
|
||||
serial_number,
|
||||
};
|
||||
use log::debug;
|
||||
|
||||
@@ -429,9 +430,17 @@ mod platform {
|
||||
}
|
||||
|
||||
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))
|
||||
resolve_linux_serial_number(
|
||||
read_linux_identity_file("/sys/class/dmi/id/product_serial"),
|
||||
collect_linux_product_uuid,
|
||||
)
|
||||
}
|
||||
|
||||
fn resolve_linux_serial_number(
|
||||
product_serial: Option<String>,
|
||||
product_uuid: impl FnOnce() -> Option<String>,
|
||||
) -> Option<String> {
|
||||
product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -446,6 +455,20 @@ mod platform {
|
||||
);
|
||||
assert_eq!(normalize_uuid("not-a-uuid"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() {
|
||||
let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string());
|
||||
|
||||
assert_eq!(
|
||||
resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()),
|
||||
Some("product-serial".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_linux_serial_number(None, || uuid),
|
||||
Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use tokio::process::Command;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use crate::auth::AuthWindowTheme;
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
@@ -27,6 +29,10 @@ pub struct SamlAuthLauncher<'a> {
|
||||
clean: bool,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
default_browser: bool,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_title: Option<&'a str>,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: Option<AuthWindowTheme>,
|
||||
browser: Option<&'a str>,
|
||||
verbose: Option<&'a str>,
|
||||
}
|
||||
@@ -52,6 +58,10 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
clean: false,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
default_browser: false,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_title: None,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: None,
|
||||
browser: None,
|
||||
verbose: None,
|
||||
}
|
||||
@@ -122,6 +132,18 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
pub fn window_title(mut self, window_title: &'a str) -> Self {
|
||||
self.window_title = Some(window_title);
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
pub fn window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
|
||||
self.window_theme = Some(window_theme);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn browser(mut self, browser: Option<&'a str>) -> Self {
|
||||
self.browser = browser;
|
||||
self
|
||||
@@ -194,6 +216,14 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
if self.default_browser {
|
||||
auth_cmd.arg("--default-browser");
|
||||
}
|
||||
|
||||
if let Some(window_title) = self.window_title {
|
||||
auth_cmd.arg("--window-title").arg(window_title);
|
||||
}
|
||||
|
||||
if let Some(window_theme) = self.window_theme {
|
||||
auth_cmd.arg("--window-theme").arg(window_theme.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(browser) = self.browser {
|
||||
|
||||
@@ -5,21 +5,21 @@ use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
use crate::{process::command_traits::CommandExt, utils};
|
||||
use crate::{process::command_traits::CommandExt, service::transport::SessionCredential};
|
||||
|
||||
pub struct GuiHelperLauncher<'a> {
|
||||
program: PathBuf,
|
||||
envs: Option<&'a HashMap<String, String>>,
|
||||
api_key: &'a [u8],
|
||||
credential: &'a SessionCredential,
|
||||
gui_version: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> GuiHelperLauncher<'a> {
|
||||
pub fn new(api_key: &'a [u8]) -> Self {
|
||||
pub fn new(credential: &'a SessionCredential) -> Self {
|
||||
Self {
|
||||
program: binary_paths::gpgui_helper(),
|
||||
envs: None,
|
||||
api_key,
|
||||
credential,
|
||||
gui_version: None,
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
cmd.envs(envs);
|
||||
}
|
||||
|
||||
cmd.arg("--api-key-on-stdin");
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if let Some(gui_version) = self.gui_version {
|
||||
cmd.arg("--gui-version").arg(gui_version);
|
||||
@@ -60,13 +60,11 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let api_key = utils::base64::encode(self.api_key);
|
||||
tokio::spawn(async move {
|
||||
stdin.write_all(api_key.as_bytes()).await.unwrap();
|
||||
drop(stdin);
|
||||
});
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
info!("gpgui-helper exited with: {}", exit_status);
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::{
|
||||
collections::HashMap,
|
||||
path::PathBuf,
|
||||
process::{ExitStatus, Stdio},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
@@ -9,24 +10,24 @@ use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, utils::base64};
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
|
||||
pub struct GuiLauncher<'a> {
|
||||
version: &'a str,
|
||||
program: PathBuf,
|
||||
api_key: &'a [u8],
|
||||
credential: Arc<SessionCredential>,
|
||||
minimized: bool,
|
||||
envs: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl<'a> GuiLauncher<'a> {
|
||||
pub fn new(version: &'a str, api_key: &'a [u8]) -> Self {
|
||||
pub fn new(version: &'a str, credential: Arc<SessionCredential>) -> Self {
|
||||
Self {
|
||||
version,
|
||||
program: binary_paths::gpgui(),
|
||||
api_key,
|
||||
credential,
|
||||
minimized: false,
|
||||
envs: None,
|
||||
}
|
||||
@@ -61,7 +62,7 @@ impl<'a> GuiLauncher<'a> {
|
||||
cmd.envs(envs);
|
||||
}
|
||||
|
||||
cmd.arg("--api-key-on-stdin");
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
@@ -79,13 +80,11 @@ impl<'a> GuiLauncher<'a> {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let api_key = base64::encode(self.api_key);
|
||||
tokio::spawn(async move {
|
||||
stdin.write_all(api_key.as_bytes()).await.unwrap();
|
||||
drop(stdin);
|
||||
});
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
|
||||
Ok(exit_status)
|
||||
}
|
||||
@@ -109,7 +108,7 @@ impl<'a> GuiLauncher<'a> {
|
||||
}
|
||||
|
||||
async fn download_program(&self) -> anyhow::Result<()> {
|
||||
let gui_helper = GuiHelperLauncher::new(self.api_key);
|
||||
let gui_helper = GuiHelperLauncher::new(&self.credential);
|
||||
|
||||
gui_helper
|
||||
.envs(self.envs.as_ref())
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
pub(crate) mod command_traits;
|
||||
mod command_traits;
|
||||
mod desktop_session_env;
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub use command_traits::CommandExt;
|
||||
|
||||
pub mod auth_launcher;
|
||||
pub mod gui_launcher;
|
||||
pub mod hip_launcher;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
pub mod event;
|
||||
pub mod request;
|
||||
pub mod transport;
|
||||
pub mod vpn_env;
|
||||
pub mod vpn_state;
|
||||
pub mod vpnc_script;
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, fmt};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
@@ -10,6 +11,8 @@ use crate::{
|
||||
|
||||
use super::vpn_state::ConnectInfo;
|
||||
|
||||
pub const MAX_CLIENT_IDENTITY_DATA: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct LaunchGuiRequest {
|
||||
user: String,
|
||||
@@ -30,7 +33,7 @@ impl LaunchGuiRequest {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
#[derive(Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectArgs {
|
||||
cookie: String,
|
||||
vpnc_script: Option<String>,
|
||||
@@ -43,6 +46,8 @@ pub struct ConnectArgs {
|
||||
|
||||
certificate: Option<String>,
|
||||
sslkey: Option<String>,
|
||||
certificate_data: Option<String>,
|
||||
sslkey_data: Option<String>,
|
||||
key_password: Option<String>,
|
||||
|
||||
hip: bool,
|
||||
@@ -72,6 +77,8 @@ impl ConnectArgs {
|
||||
host_id: None,
|
||||
certificate: None,
|
||||
sslkey: None,
|
||||
certificate_data: None,
|
||||
sslkey_data: None,
|
||||
key_password: None,
|
||||
hip: false,
|
||||
csd_uid: 0,
|
||||
@@ -127,6 +134,22 @@ impl ConnectArgs {
|
||||
self.sslkey.clone()
|
||||
}
|
||||
|
||||
pub fn certificate_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
|
||||
self
|
||||
.certificate_data
|
||||
.as_deref()
|
||||
.map(crate::utils::base64::decode_to_vec)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn sslkey_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
|
||||
self
|
||||
.sslkey_data
|
||||
.as_deref()
|
||||
.map(crate::utils::base64::decode_to_vec)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn key_password(&self) -> Option<String> {
|
||||
self.key_password.clone()
|
||||
}
|
||||
@@ -176,6 +199,40 @@ impl ConnectArgs {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ConnectArgs {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ConnectArgs")
|
||||
.field("cookie", &"<redacted>")
|
||||
.field("vpnc_script", &self.vpnc_script)
|
||||
.field(
|
||||
"client_auth_path",
|
||||
&(self.certificate.is_some() || self.sslkey.is_some()),
|
||||
)
|
||||
.field(
|
||||
"client_auth_data",
|
||||
&(self.certificate_data.is_some() || self.sslkey_data.is_some()),
|
||||
)
|
||||
.field("hip", &self.hip)
|
||||
.field("csd_uid", &self.csd_uid)
|
||||
.field("csd_wrapper", &self.csd_wrapper)
|
||||
.field("reconnect_timeout", &self.reconnect_timeout)
|
||||
.field("mtu", &self.mtu)
|
||||
.field("disable_ipv6", &self.disable_ipv6)
|
||||
.field("no_dtls", &self.no_dtls)
|
||||
.field("allow_extend_session", &self.allow_extend_session)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConnectArgs {
|
||||
fn drop(&mut self) {
|
||||
self.cookie.zeroize();
|
||||
self.key_password.zeroize();
|
||||
self.certificate_data.zeroize();
|
||||
self.sslkey_data.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectRequest {
|
||||
info: ConnectInfo,
|
||||
@@ -229,6 +286,16 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_certificate_data(mut self, certificate: Option<Vec<u8>>) -> Self {
|
||||
self.args.certificate_data = certificate.map(encode_secret);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_sslkey_data(mut self, sslkey: Option<Vec<u8>>) -> Self {
|
||||
self.args.sslkey_data = sslkey.map(encode_secret);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
|
||||
self.args.key_password = key_password.into();
|
||||
self
|
||||
@@ -287,6 +354,12 @@ impl ConnectRequest {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_secret(mut data: Vec<u8>) -> String {
|
||||
let encoded = crate::utils::base64::encode(&data);
|
||||
data.zeroize();
|
||||
encoded
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
pub struct DisconnectRequest;
|
||||
|
||||
@@ -299,9 +372,12 @@ pub enum WsRequest {
|
||||
Connect(Box<ConnectRequest>),
|
||||
Disconnect(DisconnectRequest),
|
||||
UpdateLogLevel(UpdateLogLevelRequest),
|
||||
RestartGui,
|
||||
UpdateGui(UpdateGuiRequest),
|
||||
GetVpncScriptMetadata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct UpdateGuiRequest {
|
||||
pub path: String,
|
||||
pub checksum: String,
|
||||
@@ -349,4 +425,19 @@ mod tests {
|
||||
Some(profile.host_identity().host_id().to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_identity_data_round_trips_without_debug_disclosure() {
|
||||
let req = ConnectRequest::new(test_connect_info(), "secret-cookie".to_string())
|
||||
.with_certificate_data(Some(b"certificate".to_vec()))
|
||||
.with_sslkey_data(Some(b"private-key".to_vec()));
|
||||
let encoded = serde_json::to_vec(&req).unwrap();
|
||||
let decoded: ConnectRequest = serde_json::from_slice(&encoded).unwrap();
|
||||
|
||||
assert_eq!(decoded.args().certificate_data().unwrap().unwrap(), b"certificate");
|
||||
assert_eq!(decoded.args().sslkey_data().unwrap().unwrap(), b"private-key");
|
||||
let debug = format!("{decoded:?}");
|
||||
assert!(!debug.contains("secret-cookie"));
|
||||
assert!(!debug.contains("private-key"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use std::fmt;
|
||||
|
||||
use ::base64::{Engine, engine::general_purpose};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::base64;
|
||||
|
||||
use super::{MAX_CREDENTIAL_FRAME, MAX_PRODUCT_VERSION, TransportError};
|
||||
|
||||
pub struct SessionCredential {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
product_version: String,
|
||||
}
|
||||
|
||||
impl SessionCredential {
|
||||
pub fn generate(service_instance_id: Uuid, product_version: &str) -> Result<Self, TransportError> {
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let mut secret = Zeroizing::new([0_u8; 32]);
|
||||
getrandom::fill(secret.as_mut()).map_err(|_| TransportError::InvalidState)?;
|
||||
|
||||
Ok(Self {
|
||||
service_instance_id,
|
||||
session_id: Uuid::new_v4(),
|
||||
secret,
|
||||
product_version: product_version.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn service_instance_id(&self) -> Uuid {
|
||||
self.service_instance_id
|
||||
}
|
||||
|
||||
pub fn session_id(&self) -> Uuid {
|
||||
self.session_id
|
||||
}
|
||||
|
||||
pub fn secret(&self) -> &[u8; 32] {
|
||||
&self.secret
|
||||
}
|
||||
|
||||
pub fn product_version(&self) -> &str {
|
||||
&self.product_version
|
||||
}
|
||||
|
||||
pub fn encode_frame(&self) -> Result<Zeroizing<Vec<u8>>, TransportError> {
|
||||
let encoded_secret = Zeroizing::new(base64::encode(self.secret()));
|
||||
let dto = CredentialDtoRef {
|
||||
service_instance_id: self.service_instance_id,
|
||||
session_id: self.session_id,
|
||||
secret: encoded_secret.as_str(),
|
||||
product_version: &self.product_version,
|
||||
};
|
||||
let payload = Zeroizing::new(serde_json::to_vec(&dto)?);
|
||||
|
||||
if payload.len() + 2 > MAX_CREDENTIAL_FRAME || payload.len() > u16::MAX as usize {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
|
||||
let mut frame = Zeroizing::new(Vec::with_capacity(payload.len() + 2));
|
||||
frame.extend_from_slice(&(payload.len() as u16).to_be_bytes());
|
||||
frame.extend_from_slice(&payload);
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
pub fn decode_frame(frame: &[u8]) -> Result<Self, TransportError> {
|
||||
if frame.len() < 2 || frame.len() > MAX_CREDENTIAL_FRAME {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let payload_len = u16::from_be_bytes([frame[0], frame[1]]) as usize;
|
||||
if payload_len == 0 || payload_len + 2 != frame.len() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let dto: CredentialDto = serde_json::from_slice(&frame[2..]).map_err(|_| TransportError::InvalidCredential)?;
|
||||
let CredentialDto {
|
||||
service_instance_id,
|
||||
session_id,
|
||||
secret,
|
||||
product_version,
|
||||
} = dto;
|
||||
let encoded_secret = secret;
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let mut secret = Zeroizing::new([0_u8; 32]);
|
||||
let decoded_len = general_purpose::STANDARD
|
||||
.decode_slice(encoded_secret.as_bytes(), secret.as_mut())
|
||||
.map_err(|_| TransportError::InvalidCredential)?;
|
||||
if decoded_len != secret.len() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
service_instance_id,
|
||||
session_id,
|
||||
secret,
|
||||
product_version,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SessionCredential {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("SessionCredential")
|
||||
.field("service_instance_id", &self.service_instance_id)
|
||||
.field("session_id", &self.session_id)
|
||||
.field("secret", &"[REDACTED]")
|
||||
.field("product_version", &self.product_version)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CredentialDtoRef<'a> {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: &'a str,
|
||||
product_version: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CredentialDto {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: Zeroizing<String>,
|
||||
product_version: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_round_trips_without_debugging_secret() {
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.4").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let decoded = SessionCredential::decode_frame(&frame).unwrap();
|
||||
|
||||
assert_eq!(decoded.service_instance_id(), credential.service_instance_id());
|
||||
assert_eq!(decoded.session_id(), credential.session_id());
|
||||
assert_eq!(decoded.secret(), credential.secret());
|
||||
assert_eq!(decoded.product_version(), credential.product_version());
|
||||
assert!(!format!("{credential:?}").contains(&base64::encode(credential.secret())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_rejects_malformed_lengths() {
|
||||
assert!(SessionCredential::decode_frame(&[]).is_err());
|
||||
assert!(SessionCredential::decode_frame(&[0, 0]).is_err());
|
||||
assert!(SessionCredential::decode_frame(&[0, 2, b'{']).is_err());
|
||||
assert!(SessionCredential::decode_frame(&vec![0; MAX_CREDENTIAL_FRAME + 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TransportError {
|
||||
#[error("invalid credential frame")]
|
||||
InvalidCredential,
|
||||
#[error("invalid transport state")]
|
||||
InvalidState,
|
||||
#[error("message exceeds transport limit")]
|
||||
MessageTooLarge,
|
||||
#[error("malformed transport message")]
|
||||
MalformedMessage,
|
||||
#[error("Noise operation failed")]
|
||||
Noise(#[from] snow::Error),
|
||||
#[error("transport serialization failed")]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum HandshakeRejection {
|
||||
VersionMismatch { client: String, service: String },
|
||||
ServiceRestarted { service_instance_id: Uuid },
|
||||
ReconnectSuperseded,
|
||||
Unauthorized,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ServiceErrorCode {
|
||||
InvalidRequest,
|
||||
Busy,
|
||||
ChecksumFailed,
|
||||
InstallFailed,
|
||||
Internal,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CloseReason {
|
||||
VersionMismatch,
|
||||
Unauthorized,
|
||||
SessionReplaced,
|
||||
HandshakeFailed,
|
||||
MalformedMessage,
|
||||
MessageTooLarge,
|
||||
AuthenticationFailed,
|
||||
HandshakeTimeout,
|
||||
ReconnectSuperseded,
|
||||
InternalError,
|
||||
ServiceRestarted,
|
||||
HeartbeatTimeout,
|
||||
}
|
||||
|
||||
impl CloseReason {
|
||||
pub const fn code(self) -> u16 {
|
||||
match self {
|
||||
Self::VersionMismatch => 4001,
|
||||
Self::Unauthorized => 4002,
|
||||
Self::SessionReplaced => 4003,
|
||||
Self::HandshakeFailed => 4004,
|
||||
Self::MalformedMessage => 4005,
|
||||
Self::MessageTooLarge => 4006,
|
||||
Self::AuthenticationFailed => 4007,
|
||||
Self::HandshakeTimeout => 4008,
|
||||
Self::ReconnectSuperseded => 4009,
|
||||
Self::InternalError => 4010,
|
||||
Self::ServiceRestarted => 4011,
|
||||
Self::HeartbeatTimeout => 4012,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn reason(self) -> &'static str {
|
||||
match self {
|
||||
Self::VersionMismatch => "VersionMismatch",
|
||||
Self::Unauthorized => "Unauthorized",
|
||||
Self::SessionReplaced => "SessionReplaced",
|
||||
Self::HandshakeFailed => "HandshakeFailed",
|
||||
Self::MalformedMessage => "MalformedMessage",
|
||||
Self::MessageTooLarge => "MessageTooLarge",
|
||||
Self::AuthenticationFailed => "AuthenticationFailed",
|
||||
Self::HandshakeTimeout => "HandshakeTimeout",
|
||||
Self::ReconnectSuperseded => "ReconnectSuperseded",
|
||||
Self::InternalError => "InternalError",
|
||||
Self::ServiceRestarted => "ServiceRestarted",
|
||||
Self::HeartbeatTimeout => "HeartbeatTimeout",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn close_codes_are_unique_application_codes() {
|
||||
let reasons = [
|
||||
CloseReason::VersionMismatch,
|
||||
CloseReason::Unauthorized,
|
||||
CloseReason::SessionReplaced,
|
||||
CloseReason::HandshakeFailed,
|
||||
CloseReason::MalformedMessage,
|
||||
CloseReason::MessageTooLarge,
|
||||
CloseReason::AuthenticationFailed,
|
||||
CloseReason::HandshakeTimeout,
|
||||
CloseReason::ReconnectSuperseded,
|
||||
CloseReason::InternalError,
|
||||
CloseReason::ServiceRestarted,
|
||||
CloseReason::HeartbeatTimeout,
|
||||
];
|
||||
let codes: HashSet<_> = reasons.iter().map(|reason| reason.code()).collect();
|
||||
assert_eq!(codes.len(), reasons.len());
|
||||
assert!(codes.iter().all(|code| (4000..5000).contains(code)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{HandshakeRejection, MAX_PRELUDE, MAX_PRODUCT_VERSION, TransportError};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ClientPrelude {
|
||||
pub product_version: String,
|
||||
pub service_instance_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
}
|
||||
|
||||
impl ClientPrelude {
|
||||
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
|
||||
if self.product_version.is_empty() || self.product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MalformedMessage);
|
||||
}
|
||||
let encoded = serde_json::to_vec(self)?;
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let prelude: Self = serde_json::from_slice(encoded)?;
|
||||
if prelude.product_version.is_empty() || prelude.product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MalformedMessage);
|
||||
}
|
||||
Ok(prelude)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServerPrelude {
|
||||
Ready,
|
||||
Rejected(HandshakeRejection),
|
||||
}
|
||||
|
||||
impl ServerPrelude {
|
||||
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
|
||||
let encoded = serde_json::to_vec(self)?;
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(serde_json::from_slice(encoded)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preludes_reject_unknown_fields_and_invalid_versions() {
|
||||
let instance = Uuid::new_v4();
|
||||
let session = Uuid::new_v4();
|
||||
let unknown = format!(
|
||||
r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}","extra":true}}"#
|
||||
);
|
||||
assert!(ClientPrelude::decode(unknown.as_bytes()).is_err());
|
||||
assert!(
|
||||
ClientPrelude {
|
||||
product_version: String::new(),
|
||||
service_instance_id: instance,
|
||||
session_id: session,
|
||||
}
|
||||
.encode()
|
||||
.is_err()
|
||||
);
|
||||
assert!(ClientPrelude::decode(&vec![b'x'; MAX_PRELUDE + 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpnc_script::VpncScriptMetadata};
|
||||
|
||||
use super::{MAX_PLAINTEXT, MAX_SERVICE_MESSAGE, ServiceErrorCode, TransportError};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ClientMessage {
|
||||
Attach { last_event_revision: Option<u64> },
|
||||
Request { id: Uuid, request: WsRequest },
|
||||
Resync { last_event_revision: u64 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServerMessage {
|
||||
Attached {
|
||||
connection_id: Uuid,
|
||||
current_revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
},
|
||||
Reply {
|
||||
id: Uuid,
|
||||
result: ServiceResult,
|
||||
},
|
||||
Event {
|
||||
revision: u64,
|
||||
event: WsEvent,
|
||||
},
|
||||
Snapshot {
|
||||
current_revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServiceResult {
|
||||
Accepted,
|
||||
VpncScriptMetadata(Option<VpncScriptMetadata>),
|
||||
Rejected(ServiceRejection),
|
||||
}
|
||||
|
||||
impl ServiceResult {
|
||||
pub fn rejected(code: ServiceErrorCode, message: impl Into<String>) -> Self {
|
||||
Self::Rejected(ServiceRejection::new(code, message))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "ServiceRejectionDto")]
|
||||
pub struct ServiceRejection {
|
||||
code: ServiceErrorCode,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl ServiceRejection {
|
||||
fn new(code: ServiceErrorCode, message: impl Into<String>) -> Self {
|
||||
let mut message = message.into();
|
||||
if message.len() > MAX_SERVICE_MESSAGE {
|
||||
let mut boundary = MAX_SERVICE_MESSAGE;
|
||||
while !message.is_char_boundary(boundary) {
|
||||
boundary -= 1;
|
||||
}
|
||||
message.truncate(boundary);
|
||||
}
|
||||
Self { code, message }
|
||||
}
|
||||
|
||||
pub fn code(&self) -> ServiceErrorCode {
|
||||
self.code
|
||||
}
|
||||
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ServiceRejectionDto {
|
||||
code: ServiceErrorCode,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl TryFrom<ServiceRejectionDto> for ServiceRejection {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: ServiceRejectionDto) -> Result<Self, Self::Error> {
|
||||
if value.message.len() > MAX_SERVICE_MESSAGE {
|
||||
return Err("service rejection message is too long");
|
||||
}
|
||||
Ok(Self {
|
||||
code: value.code,
|
||||
message: value.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn encode<T: Serialize>(message: &T) -> Result<Vec<u8>, TransportError> {
|
||||
let encoded = serde_json::to_vec(message)?;
|
||||
if encoded.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub(crate) fn decode<T: for<'de> Deserialize<'de>>(encoded: &[u8]) -> Result<T, TransportError> {
|
||||
if encoded.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(serde_json::from_slice(encoded)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
service::{
|
||||
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA, WsRequest},
|
||||
vpn_state::ConnectInfo,
|
||||
},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_messages() {
|
||||
assert!(encode(&"x".repeat(MAX_PLAINTEXT)).is_err());
|
||||
assert!(decode::<String>(&vec![b'x'; MAX_PLAINTEXT + 1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejection_messages_are_utf8_safely_bounded() {
|
||||
let ServiceResult::Rejected(rejection) = ServiceResult::rejected(ServiceErrorCode::Internal, "界".repeat(100))
|
||||
else {
|
||||
panic!("expected rejection");
|
||||
};
|
||||
assert!(rejection.message().len() <= MAX_SERVICE_MESSAGE);
|
||||
|
||||
let oversized = format!(
|
||||
r#"{{"type":"rejected","data":{{"code":"internal","message":"{}"}}}}"#,
|
||||
"x".repeat(MAX_SERVICE_MESSAGE + 1)
|
||||
);
|
||||
assert!(serde_json::from_str::<ServiceResult>(&oversized).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_client_identity_fits_one_transport_message() {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
|
||||
let request = ConnectRequest::new(info, "cookie".to_string())
|
||||
.with_certificate_data(Some(vec![b'c'; certificate_size]))
|
||||
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
|
||||
let message = ClientMessage::Request {
|
||||
id: Uuid::new_v4(),
|
||||
request: WsRequest::Connect(Box::new(request)),
|
||||
};
|
||||
|
||||
let encoded = encode(&message).unwrap();
|
||||
assert!(encoded.len() <= MAX_PLAINTEXT);
|
||||
}
|
||||
}
|
||||