Compare commits

..
Author SHA1 Message Date
Kevin Yue 812965f020 fix: align GUI dependency pruning across packages 2026-08-05 15:41:08 +08:00
Kevin Yue 5c3b7d118a fix: correct RPM dependencies and upgrade cleanup 2026-08-05 15:41:08 +08:00
Kevin Yue 4fdcb15629 chore: sync browser launcher lockfile version 2026-08-05 15:41:07 +08:00
Kevin Yue 88f4623f52 Merge remote-tracking branch 'origin/main' into fix/vpn-client-fixes 2026-08-05 14:26:15 +08:00
Ronald Hötschl 0c2d4830b5 Remove GUI dependencies from apk when GUI components are disabled (#638) 2026-08-05 14:23:36 +08:00
Kevin Yue 3d2dfe4be0 Merge remote-tracking branch 'origin/main' into fix/vpn-client-fixes 2026-08-05 13:53:45 +08:00
github-actions[bot] 3c49eab0c8 chore: update flake hashes for v2.6.5 (#640) 2026-08-05 12:23:53 +08:00
Kevin Yue 13ec7dfc37 Merge pull request #639 from yuezk/release/2.6.5
chore: merge 2.6.5 release
2026-08-05 12:13:22 +08:00
Kevin Yue e98fd7894a ci: build FreeBSD package on 14.4 2026-08-05 11:11:46 +08:00
Kevin Yue 6f860d3dff fix: avoid reformatting VPN progress messages 2026-08-05 10:27:19 +08:00
Kevin Yue 5902bee5ff chore: prepare 2.6.5 release 2026-08-05 10:16:07 +08:00
Kevin Yue 8c831b1fc2 fix: preserve lock files owned by another process 2026-08-05 10:08:23 +08:00
Kevin Yue 912bf3046d ci: allow explicit release repository 2026-08-01 01:00:53 +08:00
Kevin Yue 4a12de6156 ci: upload release assets with curl 2026-08-01 00:44:05 +08:00
Kevin Yue b0b8e5ec32 ci: upload release assets through the REST API 2026-08-01 00:19:54 +08:00
Kevin Yue cfe8430cae ci: delegate macOS releases to gpgui 2026-07-31 23:41:52 +08:00
Kevin Yue 7ae09aad8c fix: remove installed VPN script on uninstall 2026-07-30 22:51:40 +08:00
Kevin Yue 40b35804e7 feat: persist VPN script installation metadata 2026-07-30 22:06:18 +08:00
Kevin Yue 6999b2725e fix: launch gpgui outside Nix FHS environment 2026-07-30 21:06:43 +08:00
Kevin Yue 0a528b4aae fix: route VPN progress through log callback 2026-07-30 18:05:33 +08:00
Kevin Yue 7134d92ee8 fix: scope broker helpers to their platforms 2026-07-30 16:21:59 +08:00
Kevin Yue d21b909a0d ci: build FreeBSD package on 14.4 2026-07-30 16:01:11 +08:00
Kevin Yue e066362c92 fix: compile privileged VPN scripts on Unix 2026-07-30 15:45:13 +08:00
Kevin Yue fd9b48cd90 feat: install trusted VPN scripts 2026-07-30 15:00:24 +08:00
Kevin Yue 2c29dda2ac fix(linux): sharpen helper icon 2026-07-28 22:36:49 +08:00
Kevin Yue d3845678ab fix(linux): synchronize application icons 2026-07-28 22:03:05 +08:00
Kevin Yue 355f8d82aa fix(linux): package application icons consistently 2026-07-28 20:51:08 +08:00
Kevin Yue 2ca6b80728 feat: improve platform integration and release packaging 2026-07-26 23:22:57 +08:00
Kevin Yue c0c517806e feat(auth): refine embedded webview integration 2026-07-21 22:21:17 +08:00
Kevin Yue 537e12d706 ci: run appcast after macOS release succeeds 2026-07-20 09:53:54 +08:00
Kevin Yue 4197927f56 ci: reconcile snapshot assets individually 2026-07-20 09:23:31 +08:00
Kevin Yue 1b7380d2f2 ci: publish snapshot assets before cleanup 2026-07-20 09:03:53 +08:00
Kevin Yue 090e479e20 ci: retry snapshot release operations 2026-07-20 08:26:35 +08:00
Kevin Yue cbce8b5609 ci: build macOS app on macOS 26 2026-07-20 08:07:30 +08:00
Kevin Yue 6edd3408aa ci: sign snapshot macOS builds for development 2026-07-20 08:00:36 +08:00
Kevin Yue 5da7b45407 ci: use packaged Sparkle appcast tool path 2026-07-19 23:26:23 +08:00
Kevin Yue bd064713a8 feat(macos): improve bundled app integration 2026-07-19 22:26:19 +08:00
Kevin Yue 822d10528f ci: publish macOS release artifacts 2026-07-19 17:35:16 +08:00
Kevin Yue ce8cc5b8dd fix: quote bundled macOS VPN script path 2026-07-19 09:01:31 +08:00
Kevin Yue b407c56239 fix: use native TLS exclusively for reqwest 2026-07-17 07:52:21 +08:00
Kevin Yue 9c1428fb72 feat: add brokered macOS service mode 2026-07-16 23:16:58 +08:00
Kevin Yue ce97729984 refactor: authenticate service websocket transport 2026-07-16 20:35:46 +08:00
Kevin Yue 3817227942 update dependencies 2026-07-15 21:47:57 +08:00
Kevin Yue 88975379bf fix: enhance Linux serial number resolution and add unit tests 2026-07-15 18:48:56 +08:00
Kevin Yue 11b410f1d9 fix: update openconnect subproject to latest commit 2026-07-10 21:47:34 +08:00
Kevin Yue 917e1091a1 refactor nlp support 2026-07-10 10:55:43 +08:00
Kevin Yue 68f35cc582 fix: update openconnect subproject to latest commit 2026-07-07 19:47:28 +08:00
Kevin Yue 293cd56930 feat: add browser-launcher crate and integrate with authentication flow 2026-07-06 14:45:13 +08:00
Kevin Yue ca221e3488 feat: implement GUI restart functionality and update related routes 2026-07-04 18:37:16 +08:00
Kevin Yue 6e01164a56 fix: handle authentication cancellation in auth results 2026-07-04 18:37:16 +08:00
Kevin Yue d83bb22c58 Added diagnostic logging to collect more logs 2026-07-04 18:37:16 +08:00
Kevin Yue e808ccbdb5 fix: allow configurable gpclient lock file 2026-07-04 18:37:16 +08:00
Kevin Yue f17dd27d55 nlb improvment 2026-07-04 18:37:16 +08:00
Kevin Yue 2b7b97f0e4 fix: improve nlb handling 2026-07-04 18:37:15 +08:00
Kevin Yue 3a2398e677 fix: esp gcm algo [codex] 2026-07-04 18:37:15 +08:00
Kevin Yue 7a373813ce fix: esp gcm algo 2026-07-04 18:37:15 +08:00
Kevin Yue 8a41765c53 Bump openconnect: fix ESP-GCM nonce for GlobalProtect gateways
Use IV||seq GCM nonce matching official PanGPS instead of RFC4106
salt||IV, which caused ESP probes to be silently dropped on
aes-256-gcm gateways.
2026-07-04 18:37:15 +08:00
Kevin Yue 7a16e6bce8 Bump openconnect submodule for ESP-GCM wire header fix
Updates to a669448a: GCM packets now use the RFC4106 8-byte IV on the
wire instead of the 16-byte CBC layout, which was preventing probe
replies and ESP session establishment on GCM gateways.
2026-07-04 18:37:15 +08:00
Kevin Yue 6d23d41797 Bump openconnect submodule for RFC4106 GCM ESP fix
Updates the fork to ae767195, which builds the GCM nonce as salt||IV
per RFC4106 and uses only the cipher key bytes for AES-GCM init. This
fixes ESP session establishment on existing gateways that negotiate
aes-256-gcm after the NLB branch started advertising GCM in getconfig.
2026-07-04 18:37:15 +08:00
Kevin Yue 5263c03889 Migrate OpenConnect patches into GitHub submodule fork
Point openconnect at yuezk/openconnect globalprotect (d5c1925f) with GP
patches 0001-0019 baked in. Point libxml2 at github.com/GNOME/libxml2
keeping the v2.9.9 pin. Remove compile-time patch application from
build.rs and delete deps/patches/.
2026-07-04 18:37:14 +08:00
Kevin Yue c44be546c3 Fix malformed NLB patch 0012 for CI patch application
Regenerate patch 0012 as a proper git diff against the post-0011 tree.
The previous version used zeroed index headers and a truncated
fake-gp-server.py context line, causing patch(1) to fail in LIBXML2_STATIC
builds.
2026-07-04 18:37:14 +08:00
Kevin Yue 63c873a906 Fix NLB prepare opaque-key wipe after tunnel-opaque decrypt
gp_nlb_clear_decrypted_opaque zeroed opaque_key after enc-hs-key
decipherment, causing gpst_nlb_prepare to fail when both blobs were
present. Clear opaque_key only at prepare start and replace unused
decrypted_opaque storage with an opaque_body_ready flag.
2026-07-04 18:37:14 +08:00
Kevin Yue 3c16026acc Cleanup NLB dead auth fields and tighten error handling
Remove unused hdr_auth/opaque_auth_ready state left after hs-key-only
envelope auth, trigger ESP/SSL reconnect on opaque refresh failure,
and log outbound NLB encap failures at ERR level.
2026-07-04 18:37:14 +08:00
Kevin Yue 81fcd253d3 Harden NLB crypto and envelope authentication
Fail prepare when opaque decrypt or hs-key setup is incomplete, require
hs-key for all envelope sign/verify, reject TLS 1.3 for blob decrypt,
fix GnuTLS AES-192 CBC selection, and replace the opaque-auth test with
real HMAC-SHA1 vector checks.
2026-07-04 18:37:14 +08:00
Kevin Yue 4f94a28ad2 Add NLB troubleshooting logs for gateway testing
Log opaque crypto readiness, envelope sign/verify details with hex
dumps, and richer invalid-packet diagnostics to help debug NLB ESP
envelope auth against live gateways.
2026-07-04 18:37:14 +08:00
Kevin Yue f403f19164 Wire NLB tunnel-opaque auth into ESP envelope (Phase 6)
Extract 6-byte auth material from decrypted tunnel-opaque, populate
wire sequence and HMAC-SHA1 header tags using hs-key, and verify on
inbound NLB ESP envelopes.
2026-07-04 18:37:13 +08:00
Kevin Yue ab10af726b Implement exact PanGPS do_ssl_decrypt NLB blob decipherment
Reverse-engineer PanGPS 6.3.3.1 decrypt_data: derive TLS 1.2 server
write key/IV via key expansion, AES-CBC decrypt ciphertext after the
28-byte cleartext blob prefix, and decrypt tunnel-opaque with the
decrypted enc-hs-key using the same TLS IV.
2026-07-04 18:37:13 +08:00
Kevin Yue 52f719d192 Add ESP GCM and NLB enc-hs-key handling (Phase 7)
Implement RFC4106 AES-GCM ESP for GlobalProtect gateways (gnutls and
OpenSSL backends), recognize aes128gcm8/12/16 ICV sizes, and add NLB
enc-hs-key blob parsing with TLS 1.2 session-key decipherment to
decrypt tunnel-opaque payloads.
2026-07-04 18:37:13 +08:00
Kevin Yue 6723685385 Add GlobalProtect NLB integration (Phase 6)
Expose NLB session metadata through the Rust FFI, extend fake-gp-server
with NLB mode for integration testing, wire NLB unit tests into
Makefile.am, recognize AES-GCM algorithm strings in check_enc_algo,
and add gp-nlb-auth-and-config to verify getconfig parsing.
2026-07-04 18:37:13 +08:00
Kevin Yue aa14c67e92 Add GlobalProtect NLB lifecycle (Phase 5)
Refresh tunnel-opaque via targeted getconfig.esp when valid-period nears
expiry, without disturbing ESP keys or routes. Send periodic NLB ESP
keepalives on established sessions and reset keepalive state after refresh.
2026-07-04 18:37:13 +08:00
Kevin Yue fa14b94520 Add GlobalProtect NLB SSL failover (Phase 4)
Extend gpst_connect for NLB gateways: send install=yes with preferred IPs,
parse the 110...START_TUNNEL line protocol response, update tunnel VIP,
and install a split-include route for the inner gateway IP.
2026-07-04 18:37:13 +08:00
Kevin Yue ded66586b2 Add GlobalProtect NLB ESP envelope (Phase 3)
Implement the 16-byte NLB UDP wrapper around ESP ciphertext per PanGPS
6.3.3.1 RE: encap/decap in gpst_nlb.c, recv/send hooks in esp.c for
PROTO_GPST, 56-byte NLB probe payloads, and keepalive-before-data on the
first ESP probe exchange.
2026-07-04 18:37:12 +08:00
Kevin Yue cb1716ba9c Add GlobalProtect NLB module skeleton (Phase 2)
Introduce gpst_nlb.c with PanGPS 6.3.3.1 RE notes, base64 opaque blob
decoding, NLB SSL response parsing, and stub ESP encap/decap hooks.
Wire gpst_nlb_prepare into setup and add an SSL parse regression test.
2026-07-04 18:37:12 +08:00
Kevin Yue 25cca2831b Add GlobalProtect NLB config parsing (Phase 1)
Parse hs-key, enc-hs-key, tunnel-opaque, and related NLB fields from
getconfig.esp XML into vpninfo, align getconfig request parameters with
the official client, and expose diagnostic APIs for NLB detection.
2026-07-04 18:37:11 +08:00
Nanami Nakano 66f48b3ff6 Remove linux-only component from darwin build (#633)
* feat: remove linux-only component from darwin build

* fix: rewrite paths after copy files
2026-07-04 16:22:18 +08:00
github-actions[bot] 0f7d065628 chore: update flake hashes for v2.6.4 (#632) [no ci] 2026-06-25 16:37:20 +08:00
Kevin Yue 494e4a5331 fix: replace passwd with OTP on gateway MFA retry
Gateway login OTP retries were appending a second passwd form field
instead of replacing the credential password. That regressed in 2.6.0
when login params moved from a HashMap to a Vec and could cause MFA
submissions to fail with HTTP 512 (fix #626).

Bump version to 2.6.4.
2026-06-25 14:41:42 +08:00
Kevin Yue b5b71df6e6 doc: update OpenBSD/FreeBSD instructions 2026-06-24 12:53:05 +08:00
Kevin Yue 49f410e63b Merge branch 'fix/nixos-desktop-launch-path' 2026-06-24 12:52:20 +08:00
Kevin Yue 225acf13aa fix: use stable NixOS desktop launcher path 2026-06-24 09:26:07 +08:00
Kevin Yueandgithub-actions[bot] 61d2b702c0 chore: update flake hashes for v2.6.3 (#631)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-06-23 23:12:52 +08:00
github-actions[bot] 3276ac0f9a chore: update flake hashes for v2.6.3 (#630) [no ci] 2026-06-23 21:57:51 +08:00
Kevin Yue 0b037e158c chore: prepare 2.6.3 release
- Fix NixOS GUI authorization after package updates.

- Treat Ctrl+C initiated OpenConnect disconnect as a successful shutdown.

- Update snapshot flake hash automation for prebuilt Nix packages.

- Bump gp workspace version and changelog to 2.6.3.
2026-06-23 20:06:04 +08:00
Kevin Yue 10e94e0b81 fix: use minimal Rust PPA build deps 2026-06-22 23:46:06 +08:00
github-actions[bot] 0f76539075 chore: update flake hashes for v2.6.2 (#628)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-06-22 23:08:15 +08:00
Kevin Yue f9b8c55924 Merge branch 'release/2.6.2' 2026-06-22 22:50:48 +08:00
Kevin Yue a708ce0115 chore: release 2.6.2 2026-06-22 20:33:14 +08:00
github-actions[bot] b3f4ba0a32 chore: update flake hashes for v2.6.1 (#625) 2026-06-22 14:33:21 +08:00
Kevin Yue 02cf4a0b26 ci: parallelize gpgui release builds 2026-06-22 12:51:52 +08:00
Kevin Yue 370189cbee fix: resolve release changelog path 2026-06-22 12:42:47 +08:00
Kevin Yue 6746cf64c3 fix: complete 2.6.1 release updates 2026-06-22 11:46:26 +08:00
Kevin Yue 40739739b5 fix: correct direct gateway browser auth mode 2026-06-22 08:24:48 +08:00
Kevin Yue dc7a200b93 ci: avoid Docker Hub auth pulls in release builds 2026-06-21 22:28:49 +08:00
Kevin Yue f49b6471f3 ci: reduce release Docker pull pressure 2026-06-21 22:25:28 +08:00
Kevin Yue 4da922aa3b chore: prepare 2.6.1 release 2026-06-21 22:15:09 +08:00
Kevin Yue ecc9c9f09c feat: auto-select browser for external auth 2026-06-21 20:59:13 +08:00
Kevin Yue b32002710b fix: support NixOS prebuilt GUI package 2026-06-21 20:08:19 +08:00
Kevin Yue 7b6d20a003 fix: substitute NixOS gpservice wrapper path 2026-06-21 15:26:52 +08:00
Kevin Yue d27029fad8 fix: match NixOS polkit service path 2026-06-21 15:21:51 +08:00
Kevin Yue 1b488ba696 fix: launch NixOS GUI service outside FHS env 2026-06-21 14:32:13 +08:00
Kevin Yue f78f7c9bc8 fix: prefer NixOS host wrappers in prebuilt package 2026-06-21 14:03:42 +08:00
Kevin Yue 7e11693ce3 Merge branch 'feature/nix-prebuilt-binaries'
# Conflicts:
#	.github/workflows/build.yaml
#	flake.nix
2026-06-21 12:46:18 +08:00
Kevin Yue c601fa9aa2 feat: add prebuilt Nix package 2026-06-21 12:20:28 +08:00
Kevin Yue 536a43773f feat: add prebuilt Nix package (#622) 2026-06-21 11:57:57 +08:00
Kevin Yue ae4cbedd3b doc: update NixOS installation instructions 2026-06-20 22:11:06 +08:00
Kevin Yue fe55d11fc4 ci: use main PPA publish action 2026-06-20 19:39:26 +08:00
github-actions[bot] 34f1feaf43 chore: update flake hashes for v2.6.0 (#621) 2026-06-20 19:12:58 +08:00
Kevin Yue f640b4d325 Merge branch 'fix/settings-crash-wayland-thread-safety' 2026-06-20 19:08:23 +08:00
Kevin Yue a35b4a289e chore: release 2.6.0 2026-06-20 18:21:58 +08:00
Kevin Yue a7a5d9bf96 fix: recover desktop session env for browser auth 2026-06-19 23:25:05 +08:00
Kevin Yue 888dc93643 refactor: align GP profile and packaging flow
Main changes:

- Refactor connect/auth flows around a single OS profile and host identity model, including gateway fallback and cookie-on-stdin handling.

- Align request parameters, HIP host-id propagation, SAML webview user-agent behavior, and portal default-browser handling with observed official client behavior.

- Add opt-in cookie cache support and Microsoft Defender HIP reporting while keeping host-id validation explicit.

- Add BSD build, packaging, release artifact, and provenance support with FreeBSD/OpenBSD path and dependency cleanup.

- Update NixOS install documentation and dependency compatibility fixes.
2026-06-19 21:23:29 +08:00
Rafa FlorestaandRafa Floresta f98e0336dc fix(gpapi): send host-id so the portal issues the auth-override cookie (#616)
PAN-OS binds the portal authentication-override cookie (portal-userauthcookie)
to the client's host-id. GpParams never had a host-id, so to_params() omitted it
from prelogin, getconfig and gateway login (prelogin even lists it in
REQUIRED_PARAMS, but it was never produced and got silently dropped).

On portals configured for SAML at both the portal and the gateway, the portal
then returns portal-userauthcookie=empty. With no cookie to present, the gateway
login falls back to a second, gateway-level SAML that the server rejects with
saml-auth-status=-1.

Add a stable host_id to GpParams (defaulting to host_utils::derive_uuid, the same
per-machine UUID used for HIP reports) and emit "host-id" from to_params(), so
prelogin, getconfig and gateway login all carry a consistent host-id. The portal
then issues a real portal-userauthcookie, which the gateway accepts; the failing
gateway-SAML path is never taken.

Fixes #491

Co-authored-by: Rafa Floresta <[email protected]>
2026-06-19 14:39:56 +08:00
Guangyuan Weng 7a571f9b27 feat(gpclient): cache portal-cookie to skip SAML on reconnect (#608) 2026-06-19 14:38:17 +08:00
bstock-rpandbstock84 67de92044f feat: add Microsoft Defender anti-malware HIP reporting support for linux (#618)
Co-authored-by: bstock84 <[email protected]>
2026-06-19 14:29:54 +08:00
Kevin Yue 7d63836e35 ci: support remote auth in docker image 2026-05-09 22:43:44 +08:00
Kevin Yue 3e23fc7d22 ci: add Alpine docker runtime libraries 2026-05-09 20:53:34 +08:00
Kevin Yue 8bf05d381e ci: dynamically link Alpine docker build 2026-05-09 20:36:24 +08:00
Kevin Yue 1ab36a1137 fix: gate gtk dependency behind tauri feature 2026-05-09 20:21:37 +08:00
Kevin Yue 18b788e664 ci: align docker packaging path 2026-05-09 20:10:24 +08:00
Kevin Yue ebadab8f06 ci: publish docker images by digest 2026-05-09 20:02:59 +08:00
Kevin Yue 81d13deaab refactor: simplify SAML browser selection 2026-05-09 09:24:26 +08:00
Kevin Yue 6f91a79081 docs: add minimal Alpine gpclient image 2026-05-09 09:04:28 +08:00
Kevin Yue 4d252fa31c ci: simplify gpgui matrix names 2026-05-09 07:45:32 +08:00
Kevin Yue 398475c649 ci: preserve gpgui check names 2026-05-09 07:41:21 +08:00
Kevin Yue 13d4aa398c ci: matrix gpgui libc builds 2026-05-09 07:38:24 +08:00
Kevin Yue 9423665fe5 ci: remove unsupported release action input 2026-05-09 01:26:26 +08:00
Kevin Yue 5e8dbfa26d ci: disambiguate APK release assets 2026-05-09 01:14:23 +08:00
github-actions[bot] d96b3f9c0d chore: update flake hashes for v2.5.4 (#607)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-08 17:03:26 +00:00
Kevin Yue 7720942681 ci: keep gpgui matrices running after failures 2026-05-09 00:11:39 +08:00
Kevin Yue f129ca7ea1 chore: release 2.5.4 2026-05-08 23:56:07 +08:00
Kevin Yue 628d0febdd ci: keep build-gp matrix running after failures 2026-05-08 23:07:21 +08:00
Kevin Yue add284d3b4 ci: always build arm packages 2026-05-08 22:39:21 +08:00
Kevin Yue a3f2224952 ci: add Alpine APK packaging 2026-05-08 22:24:15 +08:00
github-actions[bot] 966bcc554b chore: update flake hashes for v2.5.3 (#605) 2026-05-08 08:32:04 +08:00
Kevin Yue d6e3a212f2 chore: release v2.5.3 2026-05-08 08:15:11 +08:00
Kevin Yue e45b4a4145 fix: restore systemd-resolved DNS routing (#604)
Fixes #604.
2026-05-08 08:13:37 +08:00
Kevin Yue 93a7f4bd10 ci: enhance workflow inputs and series resolution for PPA publishing 2026-05-07 19:17:29 +08:00
Kevin Yue d1401171d8 ci: simplify aur publish workflow 2026-05-07 09:40:30 +08:00
Kevin Yue 9591ca287e ci: fix aur ssh known hosts path 2026-05-07 09:23:05 +08:00
Kevin Yue 46c80ecc93 ci: harden aur publish workflow 2026-05-07 09:14:02 +08:00
Kevin Yue 99d2a26d45 ci: fix aur srcinfo validation 2026-05-07 09:11:57 +08:00
Kevin Yue 067037517e ci: publish aur git package 2026-05-07 08:29:58 +08:00
github-actions[bot] c04b49fe11 chore: update flake hashes for v2.5.2 (#603)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-07 07:19:51 +08:00
Kevin Yue a044cb35ad ci: automate flake hash updates 2026-05-07 07:13:54 +08:00
Kevin Yue ac4b6240ef chore: bump version 2026-05-06 23:35:38 +08:00
Kevin Yue 0c3af0d60d chore: update dependencies 2026-05-06 23:20:58 +08:00
Kevin Yue 6289e1539a build: use vendored openconnect dependencies 2026-05-06 23:20:57 +08:00
Kevin Yue 08a77f9d38 fix: vendor vpnc script in linux packages 2026-05-06 23:20:57 +08:00
Kevin Yue fb6db0dc12 fix: use portal policy for session extension 2026-05-06 23:20:57 +08:00
Kevin Yue 731a0d895c debug: log GlobalProtect getconfig response 2026-05-06 23:20:57 +08:00
Kevin Yue ab58dd6cec refactor: update session extension flow 2026-05-06 23:20:57 +08:00
Kevin Yue cdcf03ff2f feat: add gpclient session refresh support (#595)
* Add session info events for GUI warnings

* fix macOS local build

* fix session expiry parsing

* chore: remove session info debug logging

* fix: decouple session info from vpn connect

* refactor: share gpapi response helpers

* fix: restore blocking session info fetch

* refactor: remove service session info flow

* refactor: share session protocol helpers

* refactor: separate cli session runtime
2026-05-06 23:20:57 +08:00
Kevin Yue 1d715f059d fix macOS local build 2026-05-06 23:20:56 +08:00
Kevin Yue 88951d863b ci: upgrade workflow actions for node 24 2026-05-06 23:20:56 +08:00
Kevin Yue 0d5d06ead0 ci: update artifact download action 2026-05-06 23:20:56 +08:00
Kevin Yue 3171bb9fd1 docs: add user-level installation instructions for NixOS integration 2026-05-06 23:20:56 +08:00
Kevin Yue d48b29025e style: reorder use statements for consistency across multiple files 2026-05-06 23:20:56 +08:00
Kevin Yue d06ce925ac fix: preserve GP reconnect cookie fields 2026-05-06 23:20:56 +08:00
Kevin Yue 5ace087f92 feat: expose openconnect connection options 2026-05-06 23:20:55 +08:00
Kevin Yue a51f034036 fix: continue deb build when mk-build-deps fails 2026-05-06 23:20:55 +08:00
Kevin Yue 982562874a fix: update Rust version handling in PPA build scripts 2026-05-06 23:20:55 +08:00
Kevin Yue 45fe7165f3 chore: upgrade to vite 8 2026-05-06 23:20:55 +08:00
Kevin Yue d0f6a67be1 fix: add excluded series input to PPA publish workflow 2026-05-06 23:20:55 +08:00
Kevin Yue 8461c73bc3 chore: bump Rust version to 1.89 2026-05-06 23:20:54 +08:00
Kevin Yue 238a4ee1e3 fix: log empty gateway login response headers and handle accordingly 2026-05-06 23:20:54 +08:00
Kevin Yue 253f995dc6 fix: trim leading slash from auth callback data 2026-05-06 23:20:54 +08:00
Kevin Yue 0972c89ee1 fix: include SAML auth data in decode warning 2026-05-06 23:20:54 +08:00
Kevin Yue 13a4b928ed refactor: add cookie handling from standard input in ConnectHandler 2026-05-06 23:20:54 +08:00
Kevin Yue c6b47eef6a refactor: improve error handling and update deprecation warnings in ConnectHandler 2026-05-06 23:20:54 +08:00
Kevin Yue a1afe3f1e3 refactor: update ConnectArgs to replace deprecated options and add HIP support 2026-05-06 23:20:53 +08:00
Kevin Yue a3672ba764 fix: remove rust build requirement and clarify openconnect dependency 2026-05-06 23:20:53 +08:00
Kevin Yue d01ef9d394 refactor: replace BUILD_GUI with BUILD_GUI_HELPER and simplify build options 2026-05-06 23:20:53 +08:00
Nanami Nakano dad4f13f64 feat: App support for Intel homebrew builds (#594) 2026-04-26 21:04:20 +08:00
Kevin Yue 4f477901d9 docs: clarify v2.3.13 distro packages 2026-04-20 09:02:30 +08:00
Kevin Yue d3ffefa897 docs: mention v2.3.13 for older Linux distros 2026-04-20 09:00:29 +08:00
Kevin Yue 93f786452d Merge pull request #590 from setarcos/unsupported 2026-04-16 10:34:24 -04:00
Kevin YueandMark Sheppard 635fd9f8bf Make BUILD_GUI=0 avoid using GUI libraries & better errors when spawn fails (#592)
Co-authored-by: Mark Sheppard <[email protected]>
Co-authored-by: Kevin Yue <[email protected]>
2026-04-16 10:32:38 -04:00
Kevin Yue e4295a6ce8 fix: improve error handling when spawning child processes 2026-04-16 22:30:08 +08:00
Mark Sheppard e4426df6a2 fix: better error messages when spawning a child program fails 2026-04-16 00:44:38 +01:00
Mark Sheppard 65a93041aa fix: mention the BUILD_GUI option in the docs 2026-04-15 23:50:46 +01:00
Mark Sheppard 8287a669fb fix: builds with BUILD_GUI=0 now omit the webview-auth feature 2026-04-15 23:37:29 +01:00
Pluto Yang 48d96dbb9d feat: add architecture check for GUI updater
Return early if target architecture is not x86_64 or aarch64
2026-04-14 16:22:48 +08:00
Kevin Yue bd613382bc fix: remove optional preFixup for GIO_EXTRA_MODULES in runtimeDependencies 2026-03-19 23:30:25 +08:00
Kevin Yue 3eda3afba4 fix: use pkgs.lib for optionalString in preFixup for better compatibility 2026-03-19 23:26:21 +08:00
Kevin Yue d7ec1c16a2 fix: add glib-networking and openssl to runtime and build inputs 2026-03-19 23:20:07 +08:00
Fabio Di Giorgio d241d48f52 fix: autoreconf: not found in devcontainer (#585) 2026-02-26 18:12:46 +08:00
Flameopathic 67954d7c4b fix: pkgs.system use in README (#581) 2026-02-14 14:31:11 +08:00
Kevin Yue 977725868a fix: use source tarball for nix build 2025-12-23 21:53:30 +08:00
Kevin Yue e2acdd7df2 fix: update flake.lock 2025-12-23 21:26:34 +08:00
Kevin Yue ae50155fbd fix: update hash for Nix build 2025-12-23 12:46:07 +08:00
Kevin Yue 24f9bbbccb feat: add LIBXML2_STATIC environment variable to Docker build for static linking 2025-12-23 07:45:55 +08:00
Kevin Yue 1b4ea720a6 Release 2.5.1 2025-12-22 23:16:52 +08:00
Kevin Yue 7d87442f73 feat: add HIP report generation functionality and related dependencies 2025-12-22 23:16:31 +08:00
Kevin Yue f398ccadb7 Release 2.5.0 2025-12-08 22:41:42 +08:00
Kevin Yue 740c79af9b chore: update dependencies 2025-12-08 22:10:15 +08:00
Kevin Yue d0096c6cb2 feat: update application name and description to reflect GP Connect branding 2025-12-08 21:46:02 +08:00
Kevin Yue e4701c1bd8 feat: add support for client version emulation and integrate OpenConnect submodule 2025-12-08 21:46:02 +08:00
Kevin Yue a08ae655cf feat: support the --script-tun option 2025-12-02 19:54:09 +08:00
Olivier Louvignes a917e16e62 Add support for macOS builds (apple silicon) (#557) 2025-12-01 22:43:00 +08:00
Kevin Yue 8ed3304e61 Update flake.nix 2025-11-13 11:03:13 +08:00
Kevin Yue c40fd051e5 Release 2.4.7 2025-11-13 00:14:07 +08:00
Kevin Yue 09cd8ecb18 feat: upgrade Rust version to 1.85 2025-11-13 00:13:53 +08:00
Kevin Yue a4e1743691 feat: add NixOS support with flake configuration and package setup 2025-11-12 23:35:44 +08:00
Kevin Yue 801a339525 feat: update browser argument in Cli and ConnectArgs to include default value and argument count 2025-11-12 23:35:44 +08:00
Kevin Yue 49a7cbfe99 feat: add auth_executable parameter to SamlAuthLauncher and update launch logic 2025-11-12 23:35:44 +08:00
Kevin Yue 603975bfe0 feat: add hip parameter to ConnectArgs and VpnBuilder, update connection logic 2025-11-12 23:35:44 +08:00
Kevin Yue 49fe7447ff feat: add VpnEnv struct and update WsEvent to include VPN environment details 2025-11-12 23:35:43 +08:00
Kevin Yue 7048248268 feat: integrate common crate and add constants for user agent and lock files 2025-11-12 23:35:43 +08:00
Kevin Yue cad5ca3d68 fix: add vpnc script location 2025-11-12 23:35:43 +08:00
Kevin Yue 9e9ab6fb7d fix: update @mui/icons-material and @mui/material dependencies to version 7.3.4 2025-11-12 23:35:42 +08:00
Fred Eisele 8e55698271 Update the README.md to describe building with devcontainers (#521) 2025-11-04 22:27:25 +08:00
Kevin Yue 47338b21a8 fix: remove conditional check for PPA input in publish job 2025-10-15 23:41:42 +08:00
Kevin Yue 4c307e05f5 fix: update Docker volume paths in build steps 2025-10-15 23:38:08 +08:00
Kevin Yue b56659b0b4 Release 2.4.6 2025-10-15 22:49:55 +08:00
Kevin Yue e3c3b6e89e Update dependencies and improve crypto handling
- Updated macOS-specific dependencies in `Cargo.toml` to their latest versions for better compatibility and performance.
- Refactored nonce handling in `crypto.rs` to improve clarity and correctness in the decryption process.
- Modified `gh-release.sh` to streamline asset uploads for snapshot releases and ensure stability for tagged releases by limiting uploaded components.
2025-10-15 22:49:54 +08:00
Kevin Yue f1a8a3c19a feat: add support for ubuntu-rolling package in build-gp job 2025-10-15 19:46:11 +08:00
Kevin Yue 986b63391a fix: update visibility of auth window based on clean state 2025-10-12 22:04:16 +08:00
Kevin Yue 9b180ad90c feat: add Publish PPA workflow and support for disabling Rust toolchain 2025-10-12 22:04:16 +08:00
Kevin Yue 6079dc6aee fix: update Rust version and dependencies for packaging 2025-10-12 22:04:16 +08:00
Kevin Yue 2bd7371c7a feat: refactor password handling in ConnectHandler to reuse stdin input
--passwd-on-stdin reads again on gateway failure
Fixes #546
2025-10-12 22:04:15 +08:00
Dark12andKevin Yue e1eb191def Support for remote browser. Useful for headless servers (#544)
* Support for remote browser. Useful for headless servers

* feat: enhance browser authentication to support remote mode and local IP detection

---------

Co-authored-by: Kevin Yue <[email protected]>
2025-10-12 22:02:19 +08:00
Eric Work a9d2de06b5 Fix gpclient disconnect bailing with client is already running (#542)
The command `gpclient disconnect` should disconnect an already running gpclient connection, but instead bails with `client is already running`. The client is expected to be running since the desired behavior is to disconnect an existing connection. Fix the CLI run logic to not bail when the client is already running and a disconnect operation is in progress.

Fixes #533
2025-10-10 11:41:34 +08:00
Kevin Yue 2aa875a626 Release 2.4.5 2025-07-16 14:18:00 +08:00
Kevin Yue e4fa429dcc style: format code for consistency and readability 2025-07-16 10:01:28 +08:00
Kevin Yue 5ba7bf2e18 feat: add the --force-dpd option
gh-519
2025-07-15 22:03:35 +08:00
Kevin Yue 11925a372d fix: parse VPN URL to support custom port
Related: #404
2025-07-08 23:32:54 +08:00
Kevin Yue e1eb9e20f1 feat: update VPN connection to parse URL and ensure HTTPS prefix 2025-07-08 23:26:04 +08:00
Kevin Yue 1d3aa889d5 ci: use GitHub hosted arm action runner 2025-06-11 11:37:48 +08:00
Kevin Yue c1ab26aef3 feat: add the -i/--interface option (#512) 2025-06-10 22:12:14 +08:00
Kevin Yue ea9819d161 fix: correct the Gentoo package name, fix #71 2025-05-05 17:14:23 +08:00
Kevin Yue dc9480fd71 Release 2.4.4 2025-02-09 14:30:40 +00:00
Kevin Yue fa2849a080 chore: update dependencies 2025-02-09 14:25:35 +00:00
Kevin Yue c70c7ee5b9 fix: multiple tray icon related: #464 2025-02-09 08:23:40 +00:00
Kevin Yue fe3d3df662 ci: upload offline tarball 2025-01-23 21:59:59 +08:00
Kevin Yue 2f90b73683 fix: check the cli running state 2025-01-22 21:30:42 +08:00
Kevin Yue 5186e80c6f doc: update installation for Ubuntu 18.04 2025-01-21 23:00:32 +08:00
Kevin Yue 4ff1c1dc1f Release 2.4.3 2025-01-21 00:16:00 +08:00
Kevin Yue c1427040f6 fix: do not use default value for os_version 2025-01-21 00:14:13 +08:00
Kevin Yue a7ad02acb6 Release 2.4.2 2025-01-20 20:57:57 +08:00
Kevin Yue b188d61be1 fix: disconnect VPN when sleep 2025-01-20 19:29:22 +08:00
Kevin Yue ec85e857bc Release 2.4.1 2025-01-09 23:53:03 +08:00
Kevin Yue d37ccafdc2 feat: gpauth support macos 2025-01-09 21:22:41 +08:00
Kevin Yue 0c9b8e6c63 Update publish.yaml 2024-12-26 23:25:23 +08:00
251 changed files with 28076 additions and 8238 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
BasedOnStyle: LLVM
IndentWidth: 8
TabWidth: 8
UseTab: Always
ColumnLimit: 80
BreakBeforeBraces: Linux
+28 -27
View File
@@ -7,19 +7,37 @@ ARG USER_GID=$USER_UID
ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:$PATH \
RUST_VERSION=1.80.0
RUST_VERSION=1.89.0 \
DEBIAN_FRONTEND=noninteractive
# Install common dependencies
# Install all system dependencies in a single layer and clean up apt cache
RUN set -eux; \
apt-get update; \
apt-get install -y --no-install-recommends \
# Common utilities
dh-autoreconf \
sudo \
ca-certificates \
curl \
gnupg \
git \
less \
software-properties-common
wget \
file \
software-properties-common \
# libopenconnect-dev to install the related dependencies for building openconnect from source
# Otherwise, we have to install them manually one by one
libopenconnect-dev \
# Tauri dependencies
libwebkit2gtk-4.1-dev \
build-essential \
libxdo-dev \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev; \
# Clean up apt cache to reduce image size
apt-get clean; \
rm -rf /var/lib/apt/lists/*
# Create a non-root user
RUN set -eux; \
@@ -30,38 +48,21 @@ RUN set -eux; \
# Install Rust
RUN set -eux; \
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION; \
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION --profile minimal; \
chown -R $USERNAME:$USERNAME $RUSTUP_HOME $CARGO_HOME; \
rustup --version; \
cargo --version; \
rustc --version
# Install Node.js
# Install Node.js and global npm packages
RUN set -eux; \
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -; \
apt-get install -y nodejs; \
apt-get install -y --no-install-recommends nodejs; \
corepack enable; \
# Install diff-so-fancy
npm install -g diff-so-fancy
# Install openconnect
RUN set -eux; \
add-apt-repository ppa:yuezk/globalprotect-openconnect; \
apt-get update; \
apt-get install -y openconnect libopenconnect-dev
# Tauri dependencies
RUN set -eux; \
apt-get install -y \
libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libxdo-dev \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev
npm install -g diff-so-fancy; \
# Clean up apt cache
apt-get clean; \
rm -rf /var/lib/apt/lists/*
USER $USERNAME
+6
View File
@@ -0,0 +1,6 @@
.build
.git
.vendor
apps/gpgui-helper/node_modules
target
vendor.tar.xz
+4
View File
@@ -8,5 +8,9 @@ end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[{*.c,*.h}]
indent_style = tab
indent_size = 8
[{Makefile,Makefile.in}]
indent_style = tab
+697 -65
View File
@@ -1,5 +1,30 @@
name: Build
on:
workflow_dispatch:
inputs:
gp_branch:
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
required: true
default: dev
gpgui_branch:
description: 'gpgui branch to use for the snapshot release'
required: true
default: dev
build_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
default: false
type: boolean
build_bsd_arm64:
description: 'Build optional FreeBSD/OpenBSD arm64 packages for the snapshot release. Slow and disabled by default'
required: true
default: false
type: boolean
push:
paths-ignore:
- LICENSE
@@ -8,45 +33,56 @@ on:
- .devcontainer
branches:
- main
- dev
- hotfix/*
- feature/*
- release/*
tags:
- v*.*.*
jobs:
# Include arm64 if ref is a tag
setup-matrix:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- name: Set up matrix
id: set-matrix
run: |
# Set the matrix to include arm64 if the ref is a tag or is the dev branch
if [[ "${{ github.ref }}" == "refs/tags/"* || "${{ github.ref }}" == "refs/heads/dev" ]]; then
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "arm64", "arch": "arm64"}]' >> $GITHUB_OUTPUT
else
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}]' >> $GITHUB_OUTPUT
fi
tarball:
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && 'release' || github.ref }}
cancel-in-progress: ${{ github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/') }}
jobs:
test-gp:
runs-on: ubuntu-latest
needs: [setup-matrix]
steps:
- uses: pnpm/action-setup@v4
with:
version: 9
- name: Prepare workspace
run: rm -rf source && mkdir source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
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:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf source && mkdir -p source/artifacts
- 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: source/gp
submodules: recursive
- name: Create tarball
run: |
cd source/gp
@@ -55,23 +91,83 @@ jobs:
touch SNAPSHOT
fi
make tarball
mv -v .build/tarball/*.tar.gz ../artifacts/
- name: Generate RPM spec file
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
cd source/gp
make init-rpm \
REVISION='1%{?dist}' \
RPM_SOURCE=https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${RELEASE_TAG}/%{name}-%{version}.tar.gz
mv -v .build/rpm/*.spec ../artifacts/
- name: Upload tarball
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: artifact-source
if-no-files-found: error
path: |
source/gp/.build/tarball/*.tar.gz
source/artifacts/*
tarball-offline:
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
needs:
- tarball
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf source-offline && mkdir source-offline
- name: Download tarball
uses: actions/download-artifact@v8
with:
name: artifact-source
path: source-offline
- name: Create offline tarball
run: |
cd source-offline
offline_tarball=$(basename *.tar.gz .tar.gz).offline.tar.gz
# Extract the tarball
tar -xzf *.tar.gz
cd */
make tarball OFFLINE=1
# Rename the tarball to .offline.tar.gz
mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball
uses: actions/upload-artifact@v7
with:
path: source-offline/*.offline.tar.gz
name: artifact-source-offline
if-no-files-found: error
build-gp:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
needs:
- setup-matrix
- tarball
strategy:
fail-fast: false
matrix:
# Only build gp on amd64, as the arm64 package will be built in release.yaml
os: [{runner: ubuntu-latest, arch: amd64}]
package: [deb, rpm, pkg, binary]
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
package: [deb, rpm, pkg, apk, binary, ubuntu-rolling]
runs-on: ${{ matrix.os.runner }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
steps:
@@ -80,112 +176,648 @@ jobs:
rm -rf build-gp-${{ matrix.package }}
mkdir -p build-gp-${{ matrix.package }}
- name: Download tarball
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
name: artifact-source
path: build-gp-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: |
docker run --pull=always --rm \
-v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2
- name: Install ${{ matrix.package }} package in Docker
run: |
docker run --pull=always --rm \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_INSTALLED=0 \
-v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
bash install.sh
# Don't upload package for ubuntu-rolling because it's duplicate of deb package
- name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v4
if: ${{ matrix.package != 'ubuntu-rolling' }}
uses: actions/upload-artifact@v7
with:
name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
build-gp-${{ matrix.package }}/artifacts/*
build-gpgui:
needs:
- setup-matrix
build-docker-image:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
strategy:
fail-fast: false
matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.os.arch }})
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- uses: pnpm/action-setup@v4
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: .
file: packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
build-gpgui:
strategy:
fail-fast: false
matrix:
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
libc:
- name: glibc
builder: gpgui-builder-tauri2
artifact_suffix: ""
- name: musl
builder: gpgui-alpine-builder-tauri2
artifact_suffix: "-musl"
runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.libc.name }}, ${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gpgui-source/gp
- name: Checkout gpgui@${{ github.ref_name }}
uses: actions/checkout@v4
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.ref_name }}
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
tar -czf gpgui.tar.gz gpgui gp
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build gpgui in Docker
run: |
docker run --pull=always --rm -v $(pwd)/gpgui-source:/gpgui yuezk/gpdev:gpgui-builder-tauri2
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
- name: Install gpgui in Docker
run: |
cd gpgui-source
tar -xJf *.bin.tar.xz
docker run --pull=always --rm -v $(pwd):/gpgui yuezk/gpdev:gpgui-builder-tauri2 \
bash -c "cd /gpgui/gpgui_*/ && ./gpgui --version"
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: artifact-gpgui-${{ matrix.os.arch }}
name: artifact-gpgui${{ matrix.libc.artifact_suffix }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256
gh-release:
if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }}
trigger-gpgui-macos:
if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.build_macos) }}
permissions:
contents: read
runs-on: ubuntu-latest
name: trigger private macOS release
outputs:
run_id: ${{ steps.dispatch.outputs.run_id }}
run_url: ${{ steps.dispatch.outputs.run_url }}
steps:
- name: Dispatch private macOS release
id: dispatch
env:
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
PUBLIC_GH_TOKEN: ${{ github.token }}
CHANNEL: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
GP_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref_name }}
GPGUI_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
REQUEST_ID: ${{ github.run_id }}.${{ github.run_attempt }}.macos
run: |
set -euo pipefail
if [[ -z "${GH_TOKEN:-}" ]]; then
echo "GPGUI_ACTIONS_TOKEN is not configured" >&2
exit 1
fi
gp_ref_path="$(jq -rn --arg ref "$GP_REF" '$ref | @uri')"
gpgui_ref_path="$(jq -rn --arg ref "$GPGUI_REF" '$ref | @uri')"
gp_sha="$(GH_TOKEN="$PUBLIC_GH_TOKEN" gh api \
"repos/yuezk/GlobalProtect-openconnect/commits/$gp_ref_path" --jq .sha)"
gpgui_sha="$(gh api "repos/yuezk/gpgui/commits/$gpgui_ref_path" --jq .sha)"
if [[ -z "$gp_sha" || -z "$gpgui_sha" ]]; then
echo "Could not resolve release source refs" >&2
exit 1
fi
expected_title="macOS $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
jq -n \
--arg request_id "$REQUEST_ID" \
--arg channel "$CHANNEL" \
--arg release_tag "$RELEASE_TAG" \
--arg gp_ref "$gp_sha" \
--arg gpgui_ref "$gpgui_sha" \
'{
ref: "main",
inputs: {
request_id: $request_id,
channel: $channel,
release_tag: $release_tag,
gp_ref: $gp_ref,
gpgui_ref: $gpgui_ref
}
}' | gh api --method POST \
repos/yuezk/gpgui/actions/workflows/release-macos.yaml/dispatches \
--input -
run_id=""
run_url=""
for _ in {1..40}; do
runs="$(gh api \
'repos/yuezk/gpgui/actions/workflows/release-macos.yaml/runs?event=workflow_dispatch&per_page=50')"
run_id="$(jq -r --arg title "$expected_title" \
'[.workflow_runs[] | select(.display_title == $title)] | first | .id // empty' \
<<<"$runs")"
run_url="$(jq -r --arg title "$expected_title" \
'[.workflow_runs[] | select(.display_title == $title)] | first | .html_url // empty' \
<<<"$runs")"
if [[ -n "$run_id" ]]; then
{
echo "run_id=$run_id"
echo "run_url=$run_url"
} >> "$GITHUB_OUTPUT"
echo "Triggered private workflow: $run_url"
exit 0
fi
sleep 3
done
echo "Could not locate the dispatched private workflow run" >&2
exit 1
setup-bsd-matrix:
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.matrix.outputs.enabled }}
matrix: ${{ steps.matrix.outputs.matrix }}
steps:
- name: Build matrix
id: matrix
env:
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
BUILD_BSD: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd }}
BUILD_BSD_ARM64: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd_arm64 }}
run: |
python3 - <<'PY'
import json
import os
build_bsd = os.environ["IS_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
build_bsd_arm64 = os.environ["BUILD_BSD_ARM64"] == "true"
include = []
def add(os_name, arch):
include.append({
"os": os_name,
"arch": arch,
"workspace": f"{os_name}-{arch}-source",
"artifact": f"artifact-bsd-{os_name}-{arch}",
"package_target": f"package-{os_name}",
"artifact_dir": os_name,
})
if build_bsd:
add("freebsd", "x86_64")
add("openbsd", "x86_64")
if build_bsd_arm64:
add("freebsd", "arm64")
add("openbsd", "arm64")
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
output.write(f"enabled={str(bool(include)).lower()}\n")
output.write(f"matrix={json.dumps({'include': include}, separators=(',', ':'))}\n")
PY
build-gpgui-frontend:
needs: setup-bsd-matrix
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-frontend && mkdir gpgui-frontend
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gpgui-frontend/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: gpgui-frontend/gpgui
- name: Build gpgui frontend
run: |
cd gpgui-frontend/gpgui/app
pnpm install --frozen-lockfile
pnpm build
- name: Upload gpgui frontend
uses: actions/upload-artifact@v7
with:
name: bsd-gpgui-frontend
if-no-files-found: error
path: gpgui-frontend/gpgui/app/dist/**
build-bsd:
needs:
- setup-bsd-matrix
- build-gpgui-frontend
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
runs-on: ubuntu-latest
name: build-${{ matrix.os }} (${{ matrix.arch }})
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-bsd-matrix.outputs.matrix) }}
steps:
- name: Prepare workspace
run: rm -rf "${{ matrix.workspace }}" && mkdir "${{ matrix.workspace }}"
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: ${{ matrix.workspace }}/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: ${{ matrix.workspace }}/gpgui
- name: Download gpgui frontend
uses: actions/download-artifact@v8
with:
name: bsd-gpgui-frontend
path: ${{ matrix.workspace }}/gpgui/app/dist
- name: Build on FreeBSD
if: ${{ matrix.os == 'freebsd' }}
uses: vmactions/freebsd-vm@v1
with:
release: "14.4"
arch: ${{ matrix.arch }}
usesh: true
prepare: |
pkg install -y \
git \
rust \
libiconv \
gettext-tools \
autoconf \
automake \
libtool \
patch \
gmake \
pkgconf \
libxml2 \
gnutls \
p11-kit \
nettle \
gmp \
gnome-keyring \
libayatana-appindicator \
polkit \
webkit2-gtk_41
run: |
set -eu
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/app/src-tauri
cargo build --release --workspace
cd ../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Build on OpenBSD
if: ${{ matrix.os == 'openbsd' }}
uses: vmactions/openbsd-vm@v1
with:
release: "7.9"
arch: ${{ matrix.arch }}
usesh: true
prepare: |
pkg_add -z \
git \
rust \
libiconv \
gettext-tools \
autoconf-2.72 \
automake-1.17 \
libtool \
patch \
gmake \
pkgconf \
libxml \
gnutls \
p11-kit \
nettle \
gmp \
gnome-keyring \
polkit \
webkitgtk41
ln -sf /usr/local/bin/autoreconf-2.72 /usr/local/bin/autoreconf
ln -sf /usr/local/bin/autoconf-2.72 /usr/local/bin/autoconf
ln -sf /usr/local/bin/autoheader-2.72 /usr/local/bin/autoheader
ln -sf /usr/local/bin/autom4te-2.72 /usr/local/bin/autom4te
ln -sf /usr/local/bin/aclocal-1.17 /usr/local/bin/aclocal
ln -sf /usr/local/bin/automake-1.17 /usr/local/bin/automake
run: |
set -eu
export AUTOCONF_VERSION=2.72
export AUTOMAKE_VERSION=1.17
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/app/src-tauri
cargo build --release --workspace
cd ../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Upload BSD package
uses: actions/upload-artifact@v7
with:
name: ${{ matrix.artifact }}
if-no-files-found: error
path: |
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
gh-release:
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }}
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
needs:
- tarball
- tarball-offline
- build-gp
- build-docker-image
- build-gpgui
- setup-bsd-matrix
- build-gpgui-frontend
- build-bsd
steps:
- name: Check required jobs
env:
NEEDS_JSON: ${{ toJson(needs) }}
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
run: |
python3 - <<'PY'
import json
import os
import sys
needs = json.loads(os.environ["NEEDS_JSON"])
bsd_matrix_enabled = os.environ["BSD_MATRIX_ENABLED"] == "true"
is_tag = os.environ["IS_TAG"] == "true"
failed = []
for name, data in needs.items():
result = data["result"]
if result in {"failure", "cancelled"}:
failed.append(f"{name}: {result}")
elif name in {"build-gp", "build-docker-image"} and result == "skipped" and is_tag:
continue
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
continue
elif result == "skipped":
failed.append(f"{name}: {result}")
if failed:
print("Required jobs did not complete successfully:")
for item in failed:
print(f" - {item}")
sys.exit(1)
PY
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gh-release/gp
submodules: recursive
- name: Download all artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
path: gh-release/gp/.build/artifacts
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-amd64/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-ubuntu-24.04-arm/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Generate release asset checksums
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-assets.sh "$RELEASE_TAG" > .build/release-assets.txt
if [ ! -s .build/release-assets.txt ]; then
echo "No release assets found"
exit 1
fi
while IFS= read -r file; do
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
printf '%s %s\n' "$digest" "$(basename "$file")"
done < .build/release-assets.txt > .build/release-assets.sha256
- name: Attest release assets
uses: actions/attest-build-provenance@v4
with:
subject-checksums: gh-release/gp/.build/release-assets.sha256
- name: Create GH release
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
wait-gpgui-macos:
if: ${{ always() && needs.trigger-gpgui-macos.result != 'skipped' }}
needs:
- gh-release
- trigger-gpgui-macos
runs-on: ubuntu-latest
timeout-minutes: 130
steps:
- name: Wait for private macOS release
env:
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
PUBLIC_RELEASE_RESULT: ${{ needs.gh-release.result }}
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
run: |
set -euo pipefail
if [[ -z "$PRIVATE_RUN_ID" ]]; then
echo "The private macOS workflow was not started" >&2
exit 1
fi
if [[ "$PUBLIC_RELEASE_RESULT" != "success" ]]; then
gh api --method POST \
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
echo "The public release failed; cancelled $PRIVATE_RUN_URL" >&2
exit 1
fi
for _ in $(seq 1 480); do
run="$(gh api "repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID")"
status="$(jq -r '.status' <<<"$run")"
conclusion="$(jq -r '.conclusion // ""' <<<"$run")"
if [[ "$status" == "completed" ]]; then
echo "Private macOS workflow completed: $PRIVATE_RUN_URL"
if [[ "$conclusion" != "success" ]]; then
echo "Private macOS workflow concluded with: $conclusion" >&2
exit 1
fi
exit 0
fi
sleep 15
done
gh api --method POST \
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
echo "Private macOS workflow timed out: $PRIVATE_RUN_URL" >&2
exit 1
publish-docker-image:
needs:
- build-docker-image
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
docker buildx imagetools create -t "$IMAGE:$RELEASE_TAG" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$RELEASE_TAG"
+142
View File
@@ -0,0 +1,142 @@
name: Publish AUR git package
on:
workflow_dispatch:
inputs:
build-package:
type: boolean
description: "Build the package before publishing"
required: true
default: true
publish:
type: boolean
description: "Push PKGBUILD, .SRCINFO, and gp.install to AUR"
required: true
default: true
push:
branches:
- main
paths:
- packaging/aur/globalprotect-openconnect-git/**
- .github/workflows/publish-aur-git.yaml
permissions:
contents: read
jobs:
aur:
runs-on: ubuntu-latest
container: archlinux:base-devel
defaults:
run:
shell: bash
env:
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
steps:
- name: Install checkout tools
run: pacman -Syu --noconfirm --needed git openssh
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install build tools
run: |
pacman -Syu --noconfirm --needed \
appmenu-gtk-module \
cargo \
curl \
desktop-file-utils \
file \
git \
libappindicator-gtk3 \
libsecret \
libxml2 \
namcap \
openconnect \
openssl \
pkgconf \
librsvg \
shared-mime-info \
vpnc \
wget \
webkit2gtk-4.1
- name: Save committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: cp "$AUR_PACKAGE_DIR/.SRCINFO" /tmp/committed.SRCINFO
- name: Prepare build user
run: |
useradd -m builder
chown -R builder:builder "$GITHUB_WORKSPACE"
- name: Refresh VCS package version
if: ${{ github.event_name == 'workflow_dispatch' }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --nobuild --noconfirm --cleanbuild
- name: Regenerate .SRCINFO
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --printsrcinfo > .SRCINFO
- name: Check committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: |
cmp -s /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO" || {
diff -u /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO"
echo ".SRCINFO is out of date. Regenerate it with makepkg --printsrcinfo." >&2
exit 1
}
- name: Run namcap
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- namcap PKGBUILD
- name: Build package
if: ${{ github.event_name == 'workflow_dispatch' && inputs['build-package'] }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --noconfirm --clean --cleanbuild
- name: Configure SSH
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
env:
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
run: |
if [[ -z "$AUR_SSH_PRIVATE_KEY" ]]; then
echo "AUR_SSH_PRIVATE_KEY is required to publish to AUR" >&2
exit 1
fi
install -d -m 700 ~/.ssh
printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > ~/.ssh/aur
chmod 600 ~/.ssh/aur
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
- name: Publish to AUR
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
env:
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
run: |
workdir="$(mktemp -d)"
git clone "$AUR_REPO" "$workdir/aur"
cp "$AUR_PACKAGE_DIR"/PKGBUILD "$workdir/aur/PKGBUILD"
cp "$AUR_PACKAGE_DIR"/.SRCINFO "$workdir/aur/.SRCINFO"
cp "$AUR_PACKAGE_DIR"/gp.install "$workdir/aur/gp.install"
cd "$workdir/aur"
if git diff --quiet; then
echo "AUR package is already up to date"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add PKGBUILD .SRCINFO gp.install
git commit -m "Update globalprotect-openconnect-git"
git push origin master
+151
View File
@@ -0,0 +1,151 @@
name: Publish PPA
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag to publish'
required: true
revision:
description: 'Package revision'
required: false
default: "1"
series:
description: 'Space-separated Ubuntu series. Leave empty to publish all supported series.'
type: "string"
required: false
default: ""
rust:
description: 'Rust version to use'
type: "string"
required: true
default: "1.89"
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Check tag exists
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
run: |
if ! gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null 2>&1; then
echo "Tag $TAG does not exist"
exit 1
fi
resolve-series:
needs: check
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.resolve.outputs.matrix }}
steps:
- name: Resolve Ubuntu series
id: resolve
env:
INPUT_SERIES: ${{ inputs.series }}
run: |
sudo apt-get update
sudo apt-get install -y distro-info distro-info-data
if [[ "$INPUT_SERIES" == *","* ]]; then
echo "Use space-separated series, for example: jammy noble" >&2
exit 1
fi
series=()
if [[ -z "${INPUT_SERIES// }" ]]; then
while IFS= read -r item; do
[[ -n "$item" ]] && series+=("$item")
done < <(ubuntu-distro-info --supported)
else
read -r -a series <<< "$INPUT_SERIES"
fi
if [[ "${#series[@]}" -eq 0 ]]; then
echo "No Ubuntu series resolved" >&2
exit 1
fi
for item in "${series[@]}"; do
ubuntu-distro-info --series "$item" >/dev/null
done
matrix="$(printf '%s\n' "${series[@]}" | jq -R . | jq -s -c '{series: .}')"
echo "Resolved matrix: $matrix"
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
publish-ppa:
needs: [check, resolve-series]
name: publish-ppa (${{ matrix.series }})
runs-on: ubuntu-latest
container:
image: ubuntu:${{ matrix.series }}
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.resolve-series.outputs.matrix) }}
steps:
- name: Install container tools
run: |
apt-get update
apt-get install -y ca-certificates curl gpg sudo
mkdir -p /etc/apt/keyrings
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
| gpg --dearmor -o /etc/apt/keyrings/githubcli-archive-keyring.gpg
chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list
apt-get update
apt-get install -y gh
- name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} offline source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*.offline.tar.gz' \
--dir publish-ppa
- name: Patch the source code
run: |
cd publish-ppa
# Rename the source tarball without the offline suffix
mv -v *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
# Extract the source tarball
tar -xzf *.tar.gz
# Prepare the debian directory with custom files
cd globalprotect-openconnect-*/
# Prepare the debian directory with custom files
mkdir -p .build/debian
cp -v packaging/deb/control.in .build/debian/control
cp -v packaging/deb/rules.in .build/debian/rules
cp -v packaging/deb/compat .build/debian/compat
cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@BUILD_GUI_HELPER@/1/g" .build/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/1/g" .build/debian/rules
# Update the control file with the correct Rust version
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/rules
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
- name: Publish to PPA
uses: yuezk/publish-ppa-package@main
with:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: ${{ vars.DEB_EMAIL }}
deb_fullname: ${{ vars.DEB_FULLNAME }}
extra_ppa: "yuezk/globalprotect-openconnect"
series: ${{ matrix.series }}
revision: ${{ inputs.revision }}
-99
View File
@@ -1,99 +0,0 @@
name: Publish Packages
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag to publish'
required: true
revision:
description: 'Package revision'
required: true
default: "1"
ppa:
description: 'Publish to PPA'
type: boolean
required: true
default: true
obs:
description: 'Publish to OBS'
type: boolean
required: true
default: true
aur:
description: 'Publish to AUR'
type: boolean
required: true
default: true
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Check tag exists
uses: mukunku/[email protected]
id: check-tag
with:
tag: ${{ inputs.tag }}
- name: Exit if tag does not exist
run: |
if [[ "${{ steps.check-tag.outputs.exists }}" == "false" ]]; then
echo "Tag ${{ inputs.tag }} does not exist"
exit 1
fi
publish-ppa:
needs: check
if: ${{ inputs.ppa }}
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v4
with:
version: 9
- name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} source code
uses: robinraju/[email protected]
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
tarBall: false
zipBall: false
out-file-path: publish-ppa
- name: Make the offline tarball
run: |
cd publish-ppa
tar -xf globalprotect-openconnect-*.tar.gz
cd globalprotect-openconnect-*/
make tarball OFFLINE=1
# Prepare the debian directory with custom files
mkdir -p .build/debian
cp -v packaging/deb/control.in .build/debian/control
cp -v packaging/deb/rules.in .build/debian/rules
cp -v packaging/deb/compat .build/debian/compat
cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@RUST@/cargo-1.80/g" .build/debian/control
sed -i "s/@OFFLINE@/1/g" .build/debian/rules
sed -i "s/@BUILD_GUI@/1/g" .build/deb/debian/rules
sed -i "s/@RUST_VERSION@/1.80/g" .build/deb/debian/rules
- name: Publish to PPA
uses: yuezk/publish-ppa-package@gp
with:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*/.build/tarball/*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: "[email protected]"
deb_fullname: "Kevin Yue"
extra_ppa: "yuezk/globalprotect-openconnect liushuyu-011/rust-updates-1.80"
# Ubuntu 18.04 and 20.04 are excluded because tauri2 no longer supports them
excluded_series: "bionic focal"
revision: ${{ inputs.revision }}
+191 -30
View File
@@ -30,11 +30,21 @@ on:
description: 'Build PKG package'
required: true
default: true
release-apk:
type: boolean
description: 'Build APK package'
required: true
default: true
release-binary:
type: boolean
description: 'Build binary package'
required: true
default: true
release-docker:
type: boolean
description: 'Publish Docker image'
required: true
default: true
gh-release:
type: boolean
description: 'Update GitHub release'
@@ -73,13 +83,13 @@ jobs:
const inputs = ${{ toJson(inputs) }}
const { arch } = inputs
const osMap = {
"all": ["ubuntu-latest", "arm64"],
"all": ["ubuntu-latest", "ubuntu-24.04-arm"],
"x86_64": ["ubuntu-latest"],
"arm64": ["arm64"]
"arm64": ["ubuntu-24.04-arm"]
}
const package = Object.entries(inputs)
.filter(([key, value]) => key.startsWith('release-') && value)
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value)
.map(([key, value]) => key.replace('release-', ''))
return JSON.stringify({
@@ -96,58 +106,209 @@ jobs:
steps:
- name: Prepare workspace
run: rm -rf build-${{ matrix.package }} && mkdir -p build-${{ matrix.package }}
- name: Download ${{ inputs.tag }} source code
uses: robinraju/[email protected]
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
tarBall: false
zipBall: false
out-file-path: build-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
docker run --pull=always --rm \
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir build-${{ matrix.package }}
- name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: |
docker run --rm \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
-e INCLUDE_GUI=1 \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2
- name: Install ${{ matrix.package }} package in Docker
run: |
docker run --pull=always --rm \
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
bash install.sh
- name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: artifact-${{ matrix.os }}-${{ matrix.package }}
if-no-files-found: error
path: |
build-${{ matrix.package }}/artifacts/*
build-docker-image:
needs:
- check
if: ${{ inputs.release-docker }}
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Prepare workspace
run: rm -rf docker-image && mkdir -p docker-image/source
- name: Download ${{ inputs.tag }} source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir docker-image
tar -xzf docker-image/*.tar.gz -C docker-image/source --strip-components=1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: docker-image/source
file: docker-image/source/packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
publish-docker-image:
needs:
- build-docker-image
if: ${{ inputs.release-docker }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
TAG: ${{ inputs.tag }}
run: |
VERSION="${TAG#v}"
tags=(-t "$IMAGE:$TAG")
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
tags+=(-t "$IMAGE:$VERSION" -t "$IMAGE:latest")
fi
docker buildx imagetools create "${tags[@]}" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$TAG"
gh-release:
needs:
- build
runs-on: ubuntu-latest
if: ${{ inputs.gh-release }}
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
steps:
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Download artifact
uses: actions/download-artifact@v4
with:
path: gh-release
- name: Update release
uses: softprops/action-gh-release@v1
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
prerelease: ${{ contains(github.ref, 'snapshot') }}
fail_on_unmatched_files: true
tag_name: ${{ inputs.tag }}
files: |
gh-release/artifact-*/*
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
path: gh-release/gp
submodules: recursive
- name: Download artifact
uses: actions/download-artifact@v8
with:
path: gh-release
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/artifact-ubuntu-latest-apk/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Generate release asset checksums
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-assets.sh all "$GITHUB_WORKSPACE/gh-release" > .build/release-assets.txt
if [ ! -s .build/release-assets.txt ]; then
echo "No release assets found"
exit 1
fi
while IFS= read -r file; do
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
printf '%s %s\n' "$digest" "$(basename "$file")"
done < .build/release-assets.txt > .build/release-assets.sha256
- name: Attest release assets
uses: actions/attest-build-provenance@v4
with:
subject-checksums: gh-release/gp/.build/release-assets.sha256
- name: Upload release assets
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
mapfile -t files < gh-release/gp/.build/release-assets.txt
if [[ "${{ inputs.tag }}" == "snapshot" ]]; then
for file in "${files[@]}"; do
gh release upload snapshot "$file" --clobber \
--repo yuezk/GlobalProtect-openconnect
done
else
gh-release/gp/scripts/upload-release-assets.sh "${{ inputs.tag }}" "${files[@]}"
fi
+120
View File
@@ -0,0 +1,120 @@
name: Update flake hashes
on:
workflow_dispatch:
inputs:
version:
description: "Release version. Defaults to Cargo.toml workspace version."
required: false
release_tag:
description: "GitHub release tag to fetch assets from. Defaults to v<version>; use snapshot for snapshot assets."
required: false
permissions:
contents: write
pull-requests: write
jobs:
update-flake-hashes:
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Update flake hashes
env:
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: |
if [[ -n "$RELEASE_VERSION" ]]; then
scripts/update-flake-hashes.sh "$RELEASE_VERSION" "$RELEASE_TAG"
else
scripts/update-flake-hashes.sh "" "$RELEASE_TAG"
fi
- name: Upload updated flake
uses: actions/upload-artifact@v7
with:
name: updated-flake
path: flake.nix
if-no-files-found: error
validate-nix-prebuilt:
needs:
- update-flake-hashes
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
nixpkgs: nixos-25.11
- runner: ubuntu-latest
nixpkgs: nixos-26.05
- runner: ubuntu-24.04-arm
nixpkgs: nixos-25.11
- runner: ubuntu-24.04-arm
nixpkgs: nixos-26.05
name: validate-nix-prebuilt (${{ matrix.nixpkgs }}, ${{ matrix.runner }})
runs-on: ${{ matrix.runner }}
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
submodules: recursive
- name: Download updated flake
uses: actions/download-artifact@v8
with:
name: updated-flake
path: .
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Build prebuilt Nix package
run: |
nix build .#prebuilt \
--override-input nixpkgs "github:NixOS/nixpkgs/${{ matrix.nixpkgs }}" \
--extra-experimental-features "nix-command flakes" \
--print-build-logs
- name: Inspect prebuilt Nix package
run: |
test -x result/bin/gpclient
test -x result/bin/gpauth
test -x result/bin/gpservice
test -x result/bin/gpgui-helper
test -x result/bin/gpgui
test ! -L result/bin/gpservice
head -n1 result/bin/gpclient | grep '^#!'
head -n1 result/bin/gpservice | grep '^#!'
grep -q '/run/wrappers/bin/pkexec' result/bin/gpclient
grep -q 'gpservice_public=.*/bin/gpservice' result/bin/gpclient
grep -q 'exec .*/bin/gpservice' result/bin/gpservice
! grep -q '@gpservice_public@\|@gpservice_fhs@\|\$out/bin/gpservice' result/bin/gpclient result/bin/gpservice
! grep -R '/usr/bin/gp' result/share
open-pull-request:
needs:
- validate-nix-prebuilt
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Download updated flake
uses: actions/download-artifact@v8
with:
name: updated-flake
path: .
- name: Open pull request
env:
GH_TOKEN: ${{ github.token }}
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: scripts/open-flake-hashes-pr.sh "$RELEASE_VERSION" "$RELEASE_TAG"
+6
View File
@@ -8,6 +8,12 @@
.cargo
.build
SNAPSHOT
SOURCE_COMMIT
# Tauri generated files
gen
# Nix files
result
.DS_Store
+7
View File
@@ -0,0 +1,7 @@
[submodule "crates/openconnect/deps/openconnect"]
path = crates/openconnect/deps/openconnect
url = https://github.com/yuezk/openconnect.git
branch = globalprotect
[submodule "crates/openconnect/deps/libxml2"]
path = crates/openconnect/deps/libxml2
url = https://github.com/GNOME/libxml2.git
+14
View File
@@ -0,0 +1,14 @@
{
"configurations": [
{
"name": "Mac",
"includePath": ["crates/openconnect/deps/openconnect"],
"macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"],
"intelliSenseMode": "macos-clang-x64",
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++17"
}
],
"version": 4
}
+11
View File
@@ -23,8 +23,12 @@
"gpgui",
"gpservice",
"hidpi",
"Ivars",
"jnlp",
"LOGNAME",
"NSHTTPURL",
"NSURL",
"objc",
"oneshot",
"openconnect",
"pkcs",
@@ -55,9 +59,16 @@
"Vite",
"vpnc",
"vpninfo",
"webbrowser",
"wmctrl",
"XAUTHORITY",
"yuezk"
],
"rust-analyzer.cargo.features": "all",
"files.associations": {
"unistd.h": "c",
"utsname.h": "c",
"vpn.h": "c",
"openconnect.h": "c"
},
}
Generated
+2290 -1612
View File
File diff suppressed because it is too large. Load diff
+31 -15
View File
@@ -1,55 +1,71 @@
[workspace]
resolver = "2"
members = ["crates/*", "apps/gpclient", "apps/gpservice", "apps/gpauth", "apps/gpgui-helper/src-tauri"]
members = [
"crates/*",
"apps/gpclient",
"apps/gpservice",
"apps/gpauth",
"apps/gpgui-helper/src-tauri",
]
[workspace.package]
rust-version = "1.80"
version = "2.4.0"
rust-version = "1.89"
version = "2.6.5"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2021"
edition = "2024"
license = "GPL-3.0"
[workspace.dependencies]
anyhow = "1.0"
askama = "0.16"
base64 = "0.22"
chrono = "0.4"
clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3"
ctrlc = "3.4"
directories = "5.0"
dns-lookup = "2.0.4"
directories = "6.0"
dns-lookup = "3"
env_logger = "0.11"
is_executable = "1.0"
log = "0.4"
regex = "1"
reqwest = { version = "0.12", features = ["native-tls", "json"] }
reqwest = { version = "0.13", default-features = false, features = ["native-tls", "charset", "http2", "system-proxy", "json", "form", "query"] }
openssl = "0.10"
pem = "3"
roxmltree = "0.20"
xmltree = { version = "0.12", features = ["attribute-order"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sysinfo = "0.33"
# Use 0.36 as newer versions requires Rust 1.88+
sysinfo = "0.36"
tempfile = "3.8"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1" }
tokio-util = "0.7"
url = "2.4"
urlencoding = "2.1.3"
axum = "0.7"
axum = "0.8"
futures = "0.3"
futures-util = "0.3"
uzers = "0.12"
whoami = "1"
whoami = "2"
thiserror = "2"
redact-engine = "0.1"
compile-time = "0.2"
serde_urlencoded = "0.7"
md5="0.7"
sha256="1"
which="7"
md5 = "0.8"
sha256 = "1"
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" }
specta = "=2.0.0-rc.20"
proptest = "1"
[profile.release]
opt-level = 'z' # Optimize for size
+238 -53
View File
@@ -1,13 +1,27 @@
.SHELLFLAGS += -e
SHELL := /bin/sh
.SHELLFLAGS := -ec
OFFLINE ?= 0
BUILD_FE ?= 1
INCLUDE_GUI ?= 0
CARGO ?= cargo
RUST_VERSION = 1.80
DISABLE_RUST_TOOLCHAIN ?= 0
RUST_VERSION ?= 1.89
IGNORE_RUST_VERSION ?= 0
VERSION = $(shell $(CARGO) metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
SOURCE_COMMIT_VALUE := $(shell \
if [ -n "$$SOURCE_GIT_COMMIT" ]; then \
printf '%s' "$$SOURCE_GIT_COMMIT" | cut -c1-9; \
elif [ -n "$$GITHUB_SHA" ]; then \
printf '%s' "$$GITHUB_SHA" | cut -c1-9; \
elif [ -f SOURCE_COMMIT ]; then \
head -n1 SOURCE_COMMIT | tr -d '[:space:]' | cut -c1-9; \
else \
git rev-parse --short=9 HEAD 2>/dev/null || printf unknown; \
fi)
GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true)
REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz
PPA_REVISION ?= 1
PKG_NAME = globalprotect-openconnect
PKG = $(PKG_NAME)-$(VERSION)
@@ -15,11 +29,22 @@ SERIES ?= $(shell lsb_release -cs)
PUBLISH ?= 0
# Indicates whether to build the GUI components
BUILD_GUI ?= 1
BUILD_GUI_HELPER ?= 1
# Indicates whether to build embedded webview auth support into gpauth
BUILD_WEBVIEW_AUTH ?= 1
PREFIX ?= /usr/local
BSD_FLAVOR ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
GPGUI_BINARY ?= ../gpgui/target/release/gpgui
export DEBEMAIL = [email protected]
export DEBFULLNAME = Kevin Yue
export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false")
export OFFLINE_BUILD = $(shell test -f OFFLINE_BUILD && echo "1" || echo "0")
# If OFFLINE is not set, use OFFLINE_BUILD
ifndef OFFLINE
OFFLINE = $(OFFLINE_BUILD)
endif
ifeq ($(SNAPSHOT), true)
RELEASE_TAG = snapshot
@@ -33,8 +58,15 @@ ifeq ($(OFFLINE), 1)
CARGO_BUILD_ARGS += --frozen
endif
ifeq ($(IGNORE_RUST_VERSION), 1)
CARGO_BUILD_ARGS += --ignore-rust-version
endif
default: build
dev-service:
./scripts/dev-service.sh
version:
@echo $(VERSION)
@@ -43,24 +75,20 @@ clean-tarball:
rm -rf .vendor
rm -rf vendor.tar.xz
rm -rf .cargo
rm -f SOURCE_COMMIT
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball
if [ $(BUILD_GUI) -eq 1 ] && [ $(BUILD_FE) -eq 1 ]; then \
echo "Building frontend..."; \
cd apps/gpgui-helper && pnpm install && pnpm build; \
fi
# Remove node_modules to reduce the tarball size
rm -rf apps/gpgui-helper/node_modules
mkdir -p .cargo
mkdir -p .build/tarball
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
# If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build
if [ $(OFFLINE) -eq 1 ]; then \
$(CARGO) vendor .vendor > .cargo/config.toml; \
tar -cJf vendor.tar.xz .vendor; \
touch OFFLINE_BUILD; \
fi
@echo "Creating tarball..."
@@ -72,40 +100,37 @@ download-gui:
if [ $(INCLUDE_GUI) -eq 1 ]; then \
echo "Downloading GlobalProtect GUI..."; \
mkdir -p .build/gpgui; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m).bin.tar.xz; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz; \
tar -xJf .build/gpgui/*.tar.xz -C .build/gpgui; \
else \
echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \
fi
build: download-gui build-fe build-rs
# Install and build the frontend
# If OFFLINE is set to 1, skip it
build-fe:
if [ $(BUILD_GUI) -eq 0 ] || [ $(OFFLINE) -eq 1 ] || [ $(BUILD_FE) -eq 0 ]; then \
echo "Skipping frontend build (BUILD_GUI=0 or OFFLINE=1 or BUILD_FE=0)"; \
else \
cd apps/gpgui-helper && pnpm install && pnpm build; \
fi
if [ $(BUILD_GUI) -eq 1 ] && [ ! -d apps/gpgui-helper/dist ]; then \
echo "Error: frontend build failed"; \
exit 1; \
fi
build: download-gui build-rs
build-rs:
if [ $(OFFLINE) -eq 1 ]; then \
tar -xJf vendor.tar.xz; \
fi
# Only build the GUI components if BUILD_GUI is set to 1
if [ $(BUILD_GUI) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth; \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper --features "tauri/custom-protocol"; \
# Remove the rust-toolchain.toml if DISABLE_RUST_TOOLCHAIN is set to 1
if [ $(DISABLE_RUST_TOOLCHAIN) -eq 1 ]; then \
rm -vf rust-toolchain.toml; \
fi
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice
# Build gpauth with or without embedded webview auth support
if [ $(BUILD_WEBVIEW_AUTH) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth; \
else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth --no-default-features; \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth --no-default-features; \
fi
# Only build the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper; \
fi
clean:
@@ -120,9 +145,10 @@ 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 is set to 1
if [ $(BUILD_GUI) -eq 1 ]; then \
# Install the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper; \
fi
@@ -130,13 +156,122 @@ install:
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
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
install-bsd:
@echo "Installing $(PKG_NAME) for BSD under $(PREFIX)..."
install -d $(DESTDIR)$(PREFIX)/bin
install -m 755 target/release/gpclient $(DESTDIR)$(PREFIX)/bin/gpclient
install -m 755 target/release/gpauth $(DESTDIR)$(PREFIX)/bin/gpauth
install -m 755 target/release/gpservice $(DESTDIR)$(PREFIX)/bin/gpservice
if [ "$(BUILD_GUI_HELPER)" = "1" ]; then \
install -m 755 target/release/gpgui-helper $(DESTDIR)$(PREFIX)/bin/gpgui-helper; \
fi
if [ -x "$(GPGUI_BINARY)" ]; then \
install -m 755 "$(GPGUI_BINARY)" $(DESTDIR)$(PREFIX)/bin/gpgui; \
fi
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
install -m 755 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
install -d $(DESTDIR)$(PREFIX)/share/applications
install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/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
clean-bsd-package:
rm -rf .build/$(BSD_FLAVOR)
bsd-gpgui-tarball:
test -x "$(GPGUI_BINARY)"
rm -rf .build/$(BSD_FLAVOR)/gpgui
mkdir -p .build/$(BSD_FLAVOR)/artifacts .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)
cp "$(GPGUI_BINARY)" .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)/
tar -cf - -C .build/$(BSD_FLAVOR)/gpgui gpgui_$(VERSION) | xz -c > .build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz
file=.build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz; \
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$$file" | cut -d ' ' -f 1; \
elif command -v sha256 >/dev/null 2>&1; then sha256 -q "$$file"; \
else cksum -a sha256 "$$file" | awk '{print $$1}'; fi > "$$file.sha256"
package-freebsd: BSD_FLAVOR=freebsd
package-freebsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts .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/\..*//'); \
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
sed \
-e 's/@PKG_NAME@/$(PKG_NAME)/g' \
-e 's/@VERSION@/$(VERSION)/g' \
-e "s/@ABI@/FreeBSD:$$freebsd_major:$$freebsd_arch/g" \
-e "s/@ARCH@/freebsd:$$freebsd_major:$$freebsd_arch/g" \
-e 's|@PREFIX@|$(PREFIX)|g' \
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/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)"
package-openbsd: BSD_FLAVOR=openbsd
package-openbsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/openbsd/pkgroot .build/openbsd/artifacts
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/openbsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
{ \
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); \
polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | sed 's/^inst://' | head -n 1); \
pkg_create \
-B .build/openbsd/pkgroot \
-D COMMENT="$$comment" \
-d .build/openbsd/+DESC \
-f .build/openbsd/PLIST \
-p $(PREFIX) \
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
-P sysutils/polkit:polkit-*:$$polkit_pkg \
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_pkg \
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
uninstall:
@echo "Uninstalling $(PKG_NAME)..."
@@ -146,13 +281,27 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
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
@@ -169,28 +318,34 @@ init-debian: clean-debian tarball
cp -f packaging/deb/postrm .build/deb/$(PKG)/debian/postrm
cp -f packaging/deb/compat .build/deb/$(PKG)/debian/compat
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_GUI@/$(BUILD_GUI)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/control
# Remove the GUI dependencies if BUILD_GUI is set to 0
if [ $(BUILD_GUI) -eq 0 ]; then \
sed -i "/libxml2/d" .build/deb/$(PKG)/debian/control; \
# Remove the GUI dependencies if neither GUI component is included
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \
sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \
fi
# Remove WebKitGTK only if no included component needs it
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
fi
sed -i "s/@INCLUDE_GUI@/$(INCLUDE_GUI)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/$(BUILD_WEBVIEW_AUTH)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
rm -f .build/deb/$(PKG)/debian/changelog
deb: init-debian
# Remove the rust build dependency from the control file
sed -i "s/@RUST@//g" .build/deb/$(PKG)/debian/control
cd .build/deb/$(PKG) && dch --create --distribution unstable --package $(PKG_NAME) --newversion $(VERSION)-$(REVISION) "Bugfix and improvements."
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b
# Install build dependencies
cd .build/deb/$(PKG) && sudo mk-build-deps --install --remove debian/control || echo "mk-build-deps failed, continuing"
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b -d
check-ppa:
if [ $(OFFLINE) -eq 0 ]; then \
@@ -199,8 +354,6 @@ check-ppa:
# Usage: make ppa SERIES=focal OFFLINE=1 PUBLISH=1
ppa: check-ppa init-debian
sed -i "s/@RUST@/cargo-1.80/g" .build/deb/$(PKG)/debian/control
$(eval SERIES_VER = $(shell distro-info --series $(SERIES) -r | cut -d' ' -f1))
@echo "Building for $(SERIES) $(SERIES_VER)"
@@ -227,7 +380,7 @@ init-rpm: clean-rpm
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@REVISION@/$(REVISION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s|@SOURCE@|$(RPM_SOURCE)|g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@DATE@/$(shell LC_ALL=en.US date "+%a %b %d %Y")/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.changes
@@ -256,15 +409,47 @@ 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
sed -i "s/@REVISION@/$(REVISION)/g" .build/pkgbuild/PKGBUILD
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/pkgbuild/PKGBUILD
pkgbuild: init-pkgbuild
cd .build/pkgbuild && makepkg -s --noconfirm
clean-apk:
rm -rf .build/apk
init-apk: clean-apk tarball
mkdir -p .build/apk
cp .build/tarball/${PKG}.tar.gz .build/apk
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
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
sed -i "s/@REVISION@/$(REVISION)/g" .build/apk/APKBUILD
checksum=$$(sha512sum .build/apk/${PKG}.tar.gz | cut -d' ' -f1); \
sed -i "s/@SHA512@/$$checksum/g" .build/apk/APKBUILD
# Remove the GUI dependencies if neither GUI component is included
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
sed -i "/^\tlibayatana-appindicator$$/d" .build/apk/APKBUILD; \
sed -i "/^\tlibsecret$$/d" .build/apk/APKBUILD; \
fi
# Remove WebKitGTK only if no included component needs it
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
sed -i "/^\twebkit2gtk-4.1$$/d" .build/apk/APKBUILD; \
fi
apk: init-apk
cd .build/apk && abuild -r -P "$(CURDIR)/.build/apk/packages"
find .build/apk/packages -type f -name "$(PKG_NAME)-*.apk" -exec cp {} .build/apk \;
clean-binary:
rm -rf .build/binary
@@ -276,7 +461,7 @@ binary: clean-binary tarball
mkdir -p .build/binary/$(PKG_NAME)_$(VERSION)/artifacts
make -C .build/binary/${PKG} build OFFLINE=$(OFFLINE) BUILD_FE=0 INCLUDE_GUI=$(INCLUDE_GUI)
make -C .build/binary/${PKG} build INCLUDE_GUI=$(INCLUDE_GUI)
make -C .build/binary/${PKG} install DESTDIR=$(PWD)/.build/binary/$(PKG_NAME)_$(VERSION)/artifacts
cp packaging/binary/Makefile.in .build/binary/$(PKG_NAME)_$(VERSION)/Makefile
+394 -97
View File
@@ -1,32 +1,55 @@
# GlobalProtect-openconnect
A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method. Inspired by [gp-saml-gui](https://github.com/dlenski/gp-saml-gui).
A modern GlobalProtect VPN client for Linux, built on OpenConnect with full support for SSO authentication. This project provides both command-line and graphical interfaces for seamless VPN connectivity.
<p align="center">
<img width="300" src="https://github.com/yuezk/GlobalProtect-openconnect/assets/3297602/9242df9c-217d-42ab-8c21-8f9f69cd4eb5">
<img width="300" src="https://github.com/user-attachments/assets/2fb6116c-dc57-43f2-af75-9c3d97ab7122">
</p>
> **Inspired by** [gp-saml-gui](https://github.com/dlenski/gp-saml-gui)
## Table of Contents
- [Features](#features)
- [Usage](#usage)
- [Command-Line Interface](#command-line-interface)
- [Graphical User Interface](#graphical-user-interface)
- [Installation](#installation)
- [Debian / Ubuntu](#debian--ubuntu)
- [Arch Linux / Manjaro](#arch-linux--manjaro)
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
- [Other RPM-based Distributions](#other-rpm-based-distributions)
- [Alpine Linux](#alpine-linux)
- [Gentoo](#gentoo)
- [NixOS](#nixos)
- [Official Docker Image](#official-docker-image)
- [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions)
- [NetworkManager Integration](#networkmanager-integration)
- [License](#license)
## Features
- [x] Better Linux support
- [x] Support both CLI and GUI
- [x] Support both SSO and non-SSO authentication
- [x] Support the FIDO2 authentication (e.g., YubiKey)
- [x] Support authentication using default browser
- [x] Support client certificate authentication
- [x] Support multiple portals
- [x] Support gateway selection
- [x] Support connect gateway directly
- [x] Support auto-connect on startup
- [x] Support system tray icon
- **Cross-Platform Linux Support** – Optimized for various Linux distributions
- **Dual Interface** – Available as both CLI and GUI applications
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication
- **Browser Integration** – Authenticate using your default browser or any specified browser
- **Multi-Portal Support** – Connect to multiple portals and gateways
- **Direct Gateway Connection** – Bypass portal selection when needed
- **Auto-Connect** – Automatically connect on system startup
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME)
## Usage
### CLI
### Command-Line Interface
The CLI version is always free and open source in this repo. It has almost the same features as the GUI version.
The CLI version is fully open source and feature-rich, providing nearly identical functionality to the GUI version.
```
#### Basic Commands
```bash
Usage: gpclient [OPTIONS] <COMMAND>
Commands:
@@ -36,58 +59,72 @@ Commands:
help Print this message or the help of the given subcommand(s)
Options:
--fix-openssl Get around the OpenSSL `unsafe legacy renegotiation` error
--ignore-tls-errors Ignore the TLS errors
--fix-openssl Get around the OpenSSL 'unsafe legacy renegotiation' error
--ignore-tls-errors Ignore TLS errors
-h, --help Print help
-V, --version Print version
See 'gpclient help <command>' for more information on a specific command.
```
To use the external browser for authentication with the CLI version, you need to use the following command:
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
#### External Browser Authentication
For browser-based authentication with the CLI:
**Method 1:** Using sudo with environment preservation:
```bash
sudo gpclient connect --browser <portal>
```
**Method 2:** Using authentication piping:
```bash
gpauth <portal> --browser 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
```
**Browser Options:**
- Use `--browser` to auto-select Chrome, Firefox, then the system default browser
- Use `--browser default` to use the system default browser
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
- Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
### Graphical User Interface
The GUI application provides an intuitive interface for managing VPN connections. Launch it from your application menu or via the terminal:
```bash
sudo -E gpclient connect --browser default <portal>
gpclient launch-gui
```
Or you can try the following command if the above command does not work:
```bash
gpauth <portal> --browser default 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
```
You can specify the browser with the `--browser <browser>` option, e.g., `--browser firefox`, `--browser chrome`, etc.
### GUI
The GUI version is also available after you installed it. You can launch it from the application menu or run `gpclient launch-gui` in the terminal.
> [!Note]
>
> The GUI version is partially open source. Its background service is open sourced in this repo as [gpservice](./apps/gpservice/). The GUI part is a wrapper of the background service, which is not open sourced.
> The GUI version is partially open source. The background service ([gpservice](./apps/gpservice/)) is open source, while the GUI wrapper is proprietary.
## Installation
### Debian/Ubuntu based distributions
> [!Note]
>
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
#### Install from PPA (Ubuntu > 18.04)
### Debian / Ubuntu
```
#### Option 1: Install from PPA (Recommended)
```bash
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
sudo apt-get update
sudo apt-get install globalprotect-openconnect
```
> [!Note]
>
> For Linux Mint, you might need to import the GPG key with: `sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761` if you encountered an error `gpg: keyserver receive failed: General error`.
> **For Linux Mint users:** If you encounter a GPG key error, import the key manually:
> ```bash
> sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761
> ```
#### **Ubuntu 18.04**
#### Option 2: Install from DEB Package
The latest package is not available in the PPA, but you still needs to add the `ppa:yuezk/globalprotect-openconnect` repo beforehand to use the required `openconnect` package. Then you can follow the [Install from deb package](#install-from-deb-package) section to install the latest package.
#### Install from deb package
Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `apt`:
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo apt install --fix-broken globalprotect-openconnect_*.deb
@@ -95,112 +132,372 @@ sudo apt install --fix-broken globalprotect-openconnect_*.deb
### Arch Linux / Manjaro
#### Install from AUR
#### Option 1: Install from AUR
Install from AUR: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
Package: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
You can install it using an AUR helper like [`yay`](https://github.com/Jguer/yay):
```bash
yay -S globalprotect-openconnect-git
```
#### Install from package
#### Option 2: Install from the Official Extra Repository
Download the latest package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `pacman`:
The package is also available in the official Arch Linux Extra repository.
Package: [globalprotect-openconnect](https://archlinux.org/packages/extra/x86_64/globalprotect-openconnect/)
> [!Note]
>
> Since the official package does not include the system tray support dependency, you need to install `libappindicator` manually:
```bash
sudo pacman -S libappindicator globalprotect-openconnect
```
#### Option 3: Install from Package
Download the latest package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
```
### Fedora 38 and later / Fedora Rawhide
### Fedora 38+ / Rawhide
#### Install from COPR
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for various RPM-based distributions. You can install it with the following commands:
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for RPM-based distributions:
```bash
sudo dnf copr enable yuezk/globalprotect-openconnect
sudo dnf install globalprotect-openconnect
```
### openSUSE Leap 15.6 / openSUSE Tumbleweed
### openSUSE Leap 15.6+ / Tumbleweed
#### Install from OBS (openSUSE Build Service)
The package is also available on [OBS](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect) for various RPM-based distributions. You can follow the instructions [on this page](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) to install it.
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [installation instructions](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
### Other RPM-based distributions
### Other RPM-based Distributions
#### Install from RPM package
#### Install from RPM Package
Download the latest RPM package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
Download the latest RPM package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
```bash
sudo rpm -i globalprotect-openconnect-*.rpm
```
### Alpine Linux
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
```
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
### FreeBSD
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
```
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
### OpenBSD
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
```
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
### Gentoo
It is available via `guru` and `lamdness` overlays.
Available via the `guru` and `lamdness` overlays:
```bash
sudo eselect repository enable guru
sudo emerge -r guru sync
sudo emerge -av net-vpn/globalprotect-openconnect
sudo emerge --sync guru
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
```
### Other distributions
### NixOS
- Install `openconnect >= 8.20`, `webkit2gtk`, `libsecret`, `libayatana-appindicator` or `libappindicator-gtk3`.
- Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
- Extract the tarball with `tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz`.
- Run `sudo make install` to install the client.
This repository includes a flake for NixOS integration.
## Build from source
#### Installation Steps
You can also build the client from source, steps are as follows:
Add the flake input and package to your `flake.nix`:
### Prerequisites
```nix
{
inputs = {
# ... other inputs
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
};
- [Install Rust 1.80 or later](https://www.rust-lang.org/tools/install)
- Install Tauri dependencies: https://tauri.app/start/prerequisites/
- Install `perl` and `jq`
- Install `openconnect >= 8.20` and `libopenconnect-dev` (or `openconnect-devel` on RPM-based distributions)
- Install `pkexec`, `gnome-keyring` (or `pam_kwallet` on KDE)
- Install `nodejs` and `pnpm` (optional only if you downloaded the source tarball from the release page and run with the `BUILD_FE=0` flag, see below)
outputs = { self, nixpkgs, globalprotect-openconnect, ... }:
let
system = "x86_64-linux"; # or "aarch64-linux" for ARM64
hostname = "<your-host>";
in {
nixosConfigurations.${hostname} = nixpkgs.lib.nixosSystem {
inherit system;
### Build
modules = [
./configuration.nix
{
services.ayatana-indicators.enable = true;
1. Download the source code tarball from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Choose `globalprotect-openconnect-${version}.tar.gz`.
2. Extract the tarball with `tar -xzf globalprotect-openconnect-${version}.tar.gz`.
3. Enter the source directory and run `make build BUILD_FE=0` to build the client.
3. Run `sudo make install` to install the client. (Note, `DESTDIR` is not supported)
environment.systemPackages = [
globalprotect-openconnect.packages.${system}.default
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
];
}
];
};
};
}
```
## FAQ
Apply:
1. How to deal with error `Secure Storage not ready`
```bash
sudo nixos-rebuild switch
loginctl terminate-user "$USER"
```
Try upgrade the client to `2.2.0` or later, which will use a file-based storage as a fallback.
After logging back in to GNOME, enable AppIndicator support if needed:
You need to install the `gnome-keyring` package, and restart the system (See [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
```bash
gnome-extensions enable [email protected]
```
2. How to deal with error `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`
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.
If you encounter this error when using the CLI version, try to run the command with `sudo -E` (See [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
### Official Docker Image
## About Trial
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
The CLI version is always free, while the GUI version is paid. There are two trial modes for the GUI version:
```bash
docker pull yuezk/globalprotect-openconnect:<version>
```
1. 10-day trial: You can use the GUI stable release for 10 days after the installation.
2. 14-day trial: Each beta release has a fresh trial period (at most 14 days) after released.
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
## License
Run it with access to the TUN device:
- crate [gpapi](./crates/gpapi): [MIT](./crates/gpapi/LICENSE)
- crate [openconnect](./crates/openconnect): [GPL-3.0](./crates/openconnect/LICENSE)
- crate [common](./crates/common): [GPL-3.0](./crates/common/LICENSE)
- crate [auth](./crates/auth): [GPL-3.0](./crates/auth/LICENSE)
- app [gpservice](./apps/gpservice): [GPL-3.0](./apps/gpservice/LICENSE)
- app [gpclient](./apps/gpclient): [GPL-3.0](./apps/gpclient/LICENSE)
- app [gpauth](./apps/gpauth): [GPL-3.0](./apps/gpauth/LICENSE)
- app [gpgui-helper](./apps/gpgui-helper): [GPL-3.0](./apps/gpgui-helper/LICENSE)
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
For browser authentication in a headless environment, use remote browser authentication:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
```bash
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
Alternatively, pipe `gpauth` remote-browser output into `gpclient`:
```bash
docker run --rm -it --entrypoint gpauth yuezk/globalprotect-openconnect:<version> \
<portal> --browser remote 2>/dev/null \
| docker run --rm -i --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
### Other Distributions
#### Manual Installation
1. **Install dependencies:**
- `webkit2gtk`
- `libsecret`
- `libayatana-appindicator` or `libappindicator-gtk3`
2. **Download and extract:**
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
```bash
tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz
```
3. **Install:**
```bash
sudo make install
```
## Building from Source
You can build the application from source using either a DevContainer (recommended) or a local development environment.
### Method 1: Using DevContainer (Recommended)
This project includes a DevContainer configuration that provides a consistent, reproducible build environment with all dependencies pre-installed.
#### Prerequisites
- [Docker](https://docs.docker.com/get-docker/)
- [Visual Studio Code](https://code.visualstudio.com/) (optional, for IDE support)
- [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (if using VS Code)
#### Build Steps
1. **Clone the repository:**
```bash
git clone https://github.com/yuezk/GlobalProtect-openconnect.git
cd GlobalProtect-openconnect
git submodule update --init --recursive
```
2. **Build the DevContainer image:**
```bash
docker build -t gpoc-devcontainer .devcontainer/
```
3. **Build the project:**
To build everything including the GUI helper run this command:
```bash
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
```
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
5. **Locate build artifacts:**
The compiled binaries will be available in `target/release/`:
- `gpclient` – CLI client
- `gpservice` – Background service
- `gpauth` – Authentication helper
- `gpgui-helper` – GUI helper
#### Alternative: Using VS Code
1. Open the project in VS Code
2. When prompted, click "Reopen in Container" (or run **Dev Containers: Reopen in Container**)
3. Once the container is ready, open a terminal and run:
```bash
make build
```
### Method 2: Local Development Build
#### Prerequisites
- [Rust 1.89 or later](https://www.rust-lang.org/tools/install)
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
- `nodejs` and `pnpm` (optional)
#### Build Steps
1. **Download source code:**
Download `globalprotect-openconnect-${version}.tar.gz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
2. **Extract and build:**
```bash
tar -xzf globalprotect-openconnect-${version}.tar.gz
cd globalprotect-openconnect-${version}
make build
```
3. **Install:**
```bash
sudo make install
```
> **Note:** `DESTDIR` is not currently supported.
### Testing Your Build
Verify the CLI client is working correctly:
```bash
./target/release/gpclient --help
```
### Build Options
- `BUILD_GUI_HELPER=0` – Build CLI components only (excludes GUI)
- `OFFLINE=1` – Build in offline mode using vendored dependencies
## Frequently Asked Questions
### Q: How do I resolve the "Secure Storage not ready" error?
**Solution 1:** Update to version 2.2.0 or later, which includes a file-based storage fallback.
**Solution 2:** Install the `gnome-keyring` package and restart your system.
See related issues: [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
### Q: How do I fix the "cannot open display" error when using CLI?
If you encounter `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`, try running the command with `sudo -E`:
```bash
sudo -E gpclient connect <portal>
```
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
## 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
The **CLI version** is completely free and open source.
The **GUI version** is a paid application with a **7-day trial period** after installation.
### Open Source Licenses
This project consists of multiple components, each with its own license:
| Component | Type | License |
|-----------|------|---------|
| [gpapi](./crates/gpapi) | Crate | [MIT](./crates/gpapi/LICENSE) |
| [openconnect](./crates/openconnect) | 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) |
| [gpauth](./apps/gpauth) | Application | [GPL-3.0](./apps/gpauth/LICENSE) |
| [gpgui-helper](./apps/gpgui-helper) | Application | [GPL-3.0](./apps/gpgui-helper/LICENSE) |
+7 -3
View File
@@ -10,23 +10,27 @@ license.workspace = true
tauri-build = { version = "2", features = [], optional = true }
[dependencies]
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
common = { path = "../../crates/common" }
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
tokio = { workspace = true, features = ["rt-multi-thread"] }
tempfile.workspace = true
compile-time.workspace = true
# Pin to specific version due to MSRV
home = "=0.5.11"
# webview auth dependencies
tauri = { workspace = true, optional = true }
[features]
default = ["webview-auth"]
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
release-devtools = ["auth/release-devtools"]
+59
View File
@@ -1,4 +1,63 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPAUTH_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPAUTH_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
#[cfg(feature = "webview-auth")]
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPAUTH_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 57 KiB

+210 -41
View File
@@ -1,21 +1,28 @@
use std::borrow::Cow;
use auth::{auth_prelogin, Authenticator, BrowserAuthenticator};
use auth::{BrowserAuthenticator, auth_prelogin};
use clap::Parser;
#[cfg(feature = "webview-auth")]
use gpapi::auth::AuthWindowTheme;
use gpapi::{
auth::{SamlAuthData, SamlAuthResult},
clap::{args::Os, handle_error, Args},
gp_params::{ClientOs, GpParams},
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
utils::{normalize_server, openssl},
GP_USER_AGENT,
};
use log::{info, LevelFilter};
use log::info;
use serde_json::json;
use tempfile::NamedTempFile;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPAUTH_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser, Clone)]
#[derive(Parser)]
#[command(
version = VERSION,
author,
@@ -33,7 +40,7 @@ const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::dat
See 'gpauth -h' for more information.
"
)]
pub(crate) struct Cli {
struct Cli {
#[arg(help = "The portal server to authenticate")]
server: String,
@@ -43,14 +50,27 @@ pub(crate) struct Cli {
#[arg(long, help = "The SAML authentication request")]
saml_request: Option<String>,
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
#[arg(long, value_enum, default_value_t = Os::default())]
os: Os,
#[arg(long)]
os_version: Option<String>,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long, help = "Override the GlobalProtect client version reported to the server")]
client_version: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>,
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
fix_openssl: bool,
@@ -64,7 +84,9 @@ pub(crate) struct Cli {
#[arg(
long,
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser.",
default_missing_value = "auto",
num_args=0..=1
)]
browser: Option<String>,
@@ -75,6 +97,17 @@ pub(crate) struct Cli {
#[cfg(feature = "webview-auth")]
#[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,
}
impl Args for Cli {
@@ -110,29 +143,32 @@ impl Cli {
let openssl_conf = self.prepare_env()?;
let server = normalize_server(&self.server)?;
let server: &'static str = Box::leak(server.into_boxed_str());
let gp_params: &'static GpParams = Box::leak(Box::new(self.build_gp_params()));
let gp_params = self.build_gp_params();
info!(
"gpauth auth host-id: {}",
gp_params.os_profile().host_identity().host_id()
);
let auth_request = match self.saml_request.as_deref() {
Some(auth_request) => Cow::Borrowed(auth_request),
None => Cow::Owned(auth_prelogin(server, gp_params).await?),
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await?,
};
let auth_request: &'static str = Box::leak(auth_request.into_owned().into_boxed_str());
let authenticator = Authenticator::new(&server, gp_params).with_auth_request(&auth_request);
#[cfg(feature = "webview-auth")]
let browser = self
.browser
.as_deref()
.or_else(|| self.default_browser.then_some("default"));
.or_else(|| self.default_browser.then(|| "default"));
#[cfg(not(feature = "webview-auth"))]
let browser = self.browser.as_deref().or(Some("default"));
if browser.is_some() {
let auth_result = authenticator.browser_authenticate(browser).await;
print_auth_result(auth_result);
if let Some(browser) = browser {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
let authenticator = BrowserAuthenticator::new(&auth_request, browser);
let auth_result = authenticator.authenticate().await;
print_auth_result(auth_result, Some(&auth_host_id));
// explicitly drop openssl_conf to avoid the unused variable warning
drop(openssl_conf);
@@ -140,32 +176,66 @@ impl Cli {
}
#[cfg(feature = "webview-auth")]
crate::webview_auth::authenticate(&self, authenticator, openssl_conf)?;
crate::webview_auth::authenticate(
server,
gp_params,
auth_request,
self.clean,
self.window_title.clone(),
self.window_theme,
openssl_conf,
)
.await?;
Ok(())
}
fn build_gp_params(&self) -> GpParams {
let gp_params = GpParams::builder()
.user_agent(&self.user_agent)
.client_os(ClientOs::from(&self.os))
.os_version(self.os_version.clone())
GpParams::builder(self.build_os_profile())
.ignore_tls_errors(self.ignore_tls_errors)
.certificate(self.certificate.clone())
.sslkey(self.sslkey.clone())
.key_password(self.key_password.clone())
.is_gateway(self.gateway)
.build();
.build()
}
gp_params
fn build_os_profile(&self) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(self.os));
if let Some(host_id) = self.host_id.as_deref() {
builder = builder.host_id_override(host_id);
}
if let Some(client_version) = self.client_version.as_deref() {
builder = builder.client_version(client_version);
}
builder.build()
}
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.default_browser || self.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
true
}
}
}
fn init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
fn init_logger(cli: &Cli) {
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() {
let cli = Cli::parse();
init_logger();
init_logger(&cli);
info!("gpauth started: {}", VERSION);
if let Err(err) = cli.run().await {
@@ -174,11 +244,110 @@ pub async fn run() {
}
}
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>) {
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) {
let auth_result = match auth_result {
Ok(auth_data) => SamlAuthResult::Success(auth_data),
Ok(auth_data) => {
let auth_data = match host_id {
Some(host_id) => auth_data.with_host_id(host_id),
None => auth_data,
};
SamlAuthResult::Success(auth_data)
}
Err(err) if err.downcast_ref::<AuthenticationCancelled>().is_some() => SamlAuthResult::Cancelled,
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
println!("{}", json!(auth_result));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn os_defaults_to_runtime_os() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
assert_eq!(cli.os, Os::default());
}
#[test]
fn host_id_arg_sets_profile_host_id_seed() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.host_identity().host_id(), "host-seed");
}
#[test]
fn browser_arg_requests_external_browser() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "firefox"]).expect("gpauth args should parse");
assert!(cli.external_browser_requested());
}
#[test]
fn browser_without_value_uses_auto_mode() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--browser"]).expect("gpauth args should parse");
assert_eq!(cli.browser.as_deref(), Some("auto"));
assert!(cli.external_browser_requested());
}
#[test]
fn browser_default_keeps_system_default_mode() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "default"]).expect("gpauth args should parse");
assert_eq!(cli.browser.as_deref(), Some("default"));
assert!(cli.external_browser_requested());
}
#[test]
fn client_version_arg_sets_profile_client_version() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
#[test]
fn client_certificate_args_parse() {
let cli = Cli::try_parse_from([
"gpauth",
"portal.example.com",
"--certificate",
"/tmp/client.pem",
"--sslkey",
"/tmp/client.key",
"--key-password",
"secret",
])
.expect("gpauth args should parse");
assert_eq!(cli.certificate.as_deref(), Some("/tmp/client.pem"));
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
View File
@@ -1,6 +1,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod cli;
#[cfg(feature = "webview-auth")]
mod webview_auth;
+21 -8
View File
@@ -1,24 +1,37 @@
use auth::{Authenticator, WebviewAuthenticator};
use auth::{WebviewAuthenticator, apply_auth_theme};
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
use log::info;
use tauri::RunEvent;
use tempfile::NamedTempFile;
use crate::cli::{print_auth_result, Cli};
use crate::cli::print_auth_result;
pub fn authenticate(
cli: &Cli,
authenticator: Authenticator<'static>,
pub async fn authenticate(
server: String,
gp_params: GpParams,
auth_request: String,
clean: bool,
window_title: Option<String>,
window_theme: AuthWindowTheme,
mut openssl_conf: Option<NamedTempFile>,
) -> anyhow::Result<()> {
let authenticator = authenticator.with_clean(cli.clean);
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 auth_result = authenticator.webview_authenticate(&app_handle).await;
print_auth_result(auth_result);
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_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));
// Ensure the app exits after the authentication process
app_handle.exit(0);
+4 -1
View File
@@ -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"]
}
}
+10 -3
View File
@@ -12,18 +12,25 @@ gpapi = { path = "../../crates/gpapi", features = ["clap"] }
openconnect = { path = "../../crates/openconnect" }
anyhow.workspace = true
askama.workspace = true
chrono.workspace = true
clap.workspace = true
env_logger.workspace = true
inquire = "0.7"
inquire = "0.9"
log.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_urlencoded.workspace = true
whoami.workspace = true
tempfile.workspace = true
reqwest.workspace = true
directories = "5.0"
directories.workspace = true
compile-time.workspace = true
netdev.workspace = true
xmltree.workspace = true
uuid = { workspace = true, features = ["v5"] }
[features]
default = ["webview-auth"]
+56
View File
@@ -0,0 +1,56 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
let commit = env_commit("GPCLIENT_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(&source_commit))
.or_else(|| git_commit(&repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string());
println!("cargo:rustc-env=GPCLIENT_GIT_COMMIT={commit}");
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=12", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+101 -17
View File
@@ -1,24 +1,43 @@
use std::{env::temp_dir, fs::File};
use std::{
env::temp_dir,
fs::File,
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::bail;
use clap::{Parser, Subcommand};
use gpapi::{
clap::{handle_error, Args},
clap::{Args, InfoLevelVerbosity, handle_error},
utils::openssl,
};
use log::{info, LevelFilter};
use log::info;
use sysinfo::{Pid, System};
use tempfile::NamedTempFile;
use tokio::fs;
use crate::{
GP_CLIENT_LOCK_FILE,
connect::{ConnectArgs, ConnectHandler},
disconnect::DisconnectHandler,
disconnect::{DisconnectArgs, DisconnectHandler},
hip::{HipArgs, HipHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPCLIENT_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
pub(crate) struct SharedArgs {
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,
}
#[derive(Subcommand)]
@@ -26,9 +45,11 @@ enum CliCommand {
#[command(about = "Connect to a portal server")]
Connect(Box<ConnectArgs>),
#[command(about = "Disconnect from the server")]
Disconnect,
Disconnect(DisconnectArgs),
#[command(about = "Launch the GUI")]
LaunchGui(LaunchGuiArgs),
#[command(about = "Generate HIP report")]
Hip(HipArgs),
}
#[derive(Parser)]
@@ -60,6 +81,16 @@ 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,
}
impl Args for Cli {
@@ -73,6 +104,25 @@ impl Args for Cli {
}
impl Cli {
async fn is_running(&self) -> bool {
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
return false;
};
let Ok(pid) = Pid::from_str(c.trim()) else {
return false;
};
let s = System::new_all();
let Some(p) = s.process(pid) else {
return false;
};
p.exe()
.map(|exe| exe.to_string_lossy().contains("gpclient"))
.unwrap_or(false)
}
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
if self.fix_openssl {
let file = openssl::fix_openssl_env()?;
@@ -83,12 +133,19 @@ impl Cli {
}
async fn run(&self) -> anyhow::Result<()> {
// check if an instance is running
if !matches!(self.command, CliCommand::Disconnect(_)) && self.is_running().await {
bail!("Another instance of the client is already running");
}
// The temp file will be dropped automatically when the file handle is dropped
// So, declare it here to ensure it's not dropped
let _file = self.fix_openssl()?;
let shared_args = SharedArgs {
fix_openssl: self.fix_openssl,
ignore_tls_errors: self.ignore_tls_errors,
lock_file: &self.lock_file,
verbose: &self.verbose,
};
if self.ignore_tls_errors {
@@ -97,24 +154,25 @@ impl Cli {
match &self.command {
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
CliCommand::Disconnect => DisconnectHandler::new().handle(),
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,
}
}
}
fn init_logger(command: &CliCommand) {
fn init_logger(cli: &Cli) {
let mut builder = env_logger::builder();
builder.filter_level(LevelFilter::Info);
builder.filter_level(cli.verbose.log_level_filter());
// Output the log messages to a file if the command is the auth callback
if let CliCommand::LaunchGui(args) = command {
if let CliCommand::LaunchGui(args) = &cli.command {
let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() {
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
if !auth_data.is_empty()
&& let Ok(log_file) = File::create(temp_dir().join("gpcallback.log"))
{
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
}
@@ -124,7 +182,7 @@ fn init_logger(command: &CliCommand) {
pub(crate) async fn run() {
let cli = Cli::parse();
init_logger(&cli.command);
init_logger(&cli);
info!("gpclient started: {}", VERSION);
@@ -133,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"));
}
}
-436
View File
@@ -1,436 +0,0 @@
use std::{cell::RefCell, fs, sync::Arc};
use anyhow::bail;
use clap::Args;
use common::vpn_utils::find_csd_wrapper;
use gpapi::{
auth::SamlAuthResult,
clap::args::Os,
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{gateway_login, GatewayLogin},
gp_params::{ClientOs, GpParams},
portal::{prelogin, retrieve_config, Prelogin},
process::{
auth_launcher::SamlAuthLauncher,
users::{get_non_root_user, get_user_by_name},
},
utils::{request::RequestIdentityError, shutdown_signal},
GP_USER_AGENT,
};
use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::info;
use openconnect::Vpn;
use crate::{cli::SharedArgs, GP_CLIENT_LOCK_FILE};
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
gateway: Option<String>,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
passwd_on_stdin: bool,
#[arg(long, help = "Read the cookie from standard input")]
cookie_on_stdin: bool,
#[arg(long, short, help = "The VPNC script to use")]
script: Option<String>,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
as_gateway: bool,
#[arg(
long,
help = "Use the default CSD wrapper to generate the HIP report and send it to the server"
)]
hip: bool,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>,
#[arg(long, help = "Same as the '--csd-user' option in the openconnect command")]
csd_user: Option<String>,
#[arg(long, help = "Same as the '--csd-wrapper' option in the openconnect command")]
csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
disable_ipv6: bool,
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
os: Os,
#[arg(long)]
os_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")]
no_dtls: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Use the default browser to authenticate")]
default_browser: bool,
#[arg(
long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
)]
browser: Option<String>,
}
impl ConnectArgs {
fn os_version(&self) -> String {
if let Some(os_version) = &self.os_version {
return os_version.to_owned();
}
match self.os {
Os::Linux => format!("Linux {}", whoami::distro()),
Os::Windows => String::from("Microsoft Windows 11 Pro , 64-bit"),
Os::Mac => String::from("Apple Mac OS X 13.4.0"),
}
}
}
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs,
latest_key_password: RefCell<Option<String>>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
Self {
args,
shared_args,
latest_key_password: Default::default(),
}
}
fn build_gp_params(&self) -> GpParams {
GpParams::builder()
.user_agent(&self.args.user_agent)
.client_os(ClientOs::from(&self.args.os))
.os_version(self.args.os_version())
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.build()
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
#[cfg(feature = "webview-auth")]
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
let Err(err) = self.handle_impl().await else {
return Ok(());
};
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
eprintln!("ERROR: No private key found in the certificate file");
eprintln!("ERROR: Please provide the private key file using the `-k` option");
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
// Decrypt the private key error, ask for the key password
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
if as_gateway {
info!("Treating the server as a gateway");
return self.connect_gateway_with_prelogin(server).await;
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
info!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server).await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = prelogin(portal, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, portal).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
portal_config.sort_gateways(prelogin.region());
let gateways = portal_config.gateways();
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into();
let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(cookie) => cookie,
Err(err) => {
info!("Gateway login failed: {}", err);
return self.connect_gateway_with_prelogin(gateway).await;
}
};
self.connect_gateway(gateway, &cookie).await
}
async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
self.connect_gateway(gateway, &cookie).await
}
async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
let mut gp_params = gp_params.clone();
loop {
match gateway_login(gateway, cred, &gp_params).await? {
GatewayLogin::Cookie(cookie) => return Ok(cookie),
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
gp_params.set_otp(&otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
async fn connect_gateway(&self, gateway: &str, cookie: &str) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0);
let csd_uid = get_csd_uid(&self.args.csd_user)?;
let csd_wrapper = if self.args.csd_wrapper.is_some() {
self.args.csd_wrapper.clone()
} else if self.args.hip {
find_csd_wrapper()
} else {
None
};
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_string();
let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.user_agent(self.args.user_agent.clone())
.os(Some(os))
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.build()?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
// Listen for the interrupt signal in the background
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
vpn_clone.disconnect();
});
vpn.connect(write_pid_file);
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
fs::remove_file(GP_CLIENT_LOCK_FILE)?;
}
Ok(())
}
async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
if self.args.cookie_on_stdin {
return read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let browser = if prelogin.support_default_browser() {
self.args.browser.as_deref()
} else if !cfg!(feature = "webview-auth") {
bail!("The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature");
} else {
None
};
let os_version = self.args.os_version();
let auth_launcher = SamlAuthLauncher::new(&self.args.server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.user_agent(&self.args.user_agent)
.os(self.args.os.as_str())
.os_version(Some(&os_version))
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.browser(browser);
#[cfg(feature = "webview-auth")]
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
#[cfg(feature = "webview-auth")]
let auth_launcher = auth_launcher
.hidpi(self.args.hidpi)
.clean(self.args.clean)
.default_browser(use_default_browser);
let cred = auth_launcher.launch().await?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
let password = if self.args.passwd_on_stdin {
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
input.trim_end().to_owned()
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into())
}
}
}
}
fn read_cookie_from_stdin() -> anyhow::Result<Credential> {
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
let Ok(auth_result) = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()) else {
bail!("Failed to parse auth data")
};
Credential::try_from(auth_result)
}
fn write_pid_file() {
let pid = std::process::id();
fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()).unwrap();
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
}
fn get_csd_uid(csd_user: &Option<String>) -> anyhow::Result<u32> {
if let Some(csd_user) = csd_user {
get_user_by_name(csd_user).map(|user| user.uid())
} else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
+401
View File
@@ -0,0 +1,401 @@
use clap::Args;
use gpapi::{
clap::args::Os,
cookie_store,
gp_params::CscMode,
os_profile::{ClientOs, OsProfile},
};
use log::warn;
use std::path::PathBuf;
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
pub(super) server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
pub(super) gateway: Option<String>,
#[arg(
long,
conflicts_with = "gateway",
help = "Automatically try gateways in priority order until gateway auth/config succeeds, without prompting"
)]
pub(super) auto_gateway: bool,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
pub(super) user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
pub(super) passwd_on_stdin: bool,
#[arg(long, help = "Read the gpauth authentication result from standard input")]
pub(super) cookie_on_stdin: bool,
#[arg(
long,
help = "Read and write the portal cookie cache, optionally specify the cache file path",
default_missing_value = "",
num_args=0..=1
)]
pub(super) cookie_cache: Option<String>,
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
pub(super) script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
pub(super) interface: Option<String>,
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
pub(super) script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
pub(super) as_gateway: bool,
#[arg(
long,
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
default_missing_value = "",
num_args=0..=1
)]
pub(super) hip: Option<String>,
#[arg(long, help = "The user used to run the HIP script")]
pub(super) hip_user: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
pub(super) certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
pub(super) sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
pub(super) key_password: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_user: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
pub(super) reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
pub(super) mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
pub(super) disable_ipv6: bool,
#[arg(long = "user-agent", hide = true)]
pub(super) deprecated_user_agent: Option<String>,
#[arg(long = "os-version", hide = true)]
pub(super) deprecated_os_version: Option<String>,
#[arg(long, help = "Override the client version reported to the server, e.g., '6.2.4-49'")]
pub(super) client_version: Option<String>,
#[arg(long, value_enum, default_value_t = Os::default())]
pub(super) os: Os,
#[arg(long, value_enum, default_value_t = CscMode::Auto, help = "CSC support mode: auto, yes, or no")]
pub(super) csc: CscMode,
#[arg(long, help = "Disable DTLS and ESP")]
pub(super) no_dtls: bool,
#[arg(
long = "local-hostname",
help = "Same as the '--local-hostname' option in the openconnect command"
)]
pub(super) local_hostname: Option<String>,
#[arg(
long = "force-dpd",
help = "Same as the '--force-dpd' option in the openconnect command"
)]
pub(super) dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
pub(super) no_xmlpost: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
pub(super) hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
pub(super) clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
pub(super) default_browser: bool,
#[arg(
long,
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.",
default_missing_value = "auto",
num_args=0..=1
)]
pub(super) browser: Option<String>,
}
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
build_os_profile_with_host_id(args, None)
}
pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option<&str>) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(args.os));
if let Some(client_version) = args.client_version.as_deref() {
builder = builder.client_version(client_version.to_string());
}
if let Some(local_hostname) = args.local_hostname.as_deref() {
builder = builder.computer_name_override(local_hostname.to_string());
}
if let Some(host_id) = host_id {
builder = builder.host_id_override(host_id);
}
builder.build()
}
pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option<PathBuf> {
args.cookie_cache.as_deref().map(|path| {
let custom = (!path.is_empty()).then_some(path);
cookie_store::cookie_path(custom)
})
}
pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
if args.csd_user.is_some() {
warn!("Deprecated option --csd-user will be removed; use --hip-user instead");
}
if args.csd_wrapper.is_some() {
warn!("Deprecated option --csd-wrapper will be removed; use --hip instead");
}
if args.deprecated_user_agent.is_some() {
warn!("Deprecated option --user-agent is ignored; user agent is derived from --os");
}
if args.deprecated_os_version.is_some() {
warn!("Deprecated option --os-version is ignored; OS version is derived from --os");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(clap::Parser)]
struct ConnectArgsTestCli {
#[command(flatten)]
args: ConnectArgs,
}
#[test]
fn parses_csc_mode_values() {
use clap::ValueEnum;
assert_eq!(CscMode::from_str("auto", false), Ok(CscMode::Auto));
assert_eq!(CscMode::from_str("yes", false), Ok(CscMode::Yes));
assert_eq!(CscMode::from_str("no", false), Ok(CscMode::No));
assert!(CscMode::from_str("maybe", false).is_err());
}
#[test]
fn auto_gateway_flag_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--auto-gateway"])
.expect("--auto-gateway alone should parse");
assert!(cli.args.auto_gateway);
assert!(cli.args.gateway.is_none());
}
#[test]
fn auto_gateway_help_describes_auth_config_retry() {
use clap::CommandFactory;
let help = ConnectArgsTestCli::command().render_long_help().to_string();
assert!(help.contains("--auto-gateway"));
assert!(help.contains("Automatically try gateways in priority order until gateway auth/config succeeds"));
}
#[test]
fn gateway_flag_alone_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1"])
.expect("--gateway alone should parse");
assert!(!cli.args.auto_gateway);
assert_eq!(cli.args.gateway.as_deref(), Some("gw1"));
}
#[test]
fn browser_without_value_uses_auto_mode() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser"])
.expect("--browser without value should parse");
assert_eq!(cli.args.browser.as_deref(), Some("auto"));
}
#[test]
fn browser_default_keeps_system_default_mode() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser", "default"])
.expect("--browser default should parse");
assert_eq!(cli.args.browser.as_deref(), Some("default"));
}
#[test]
fn os_defaults_to_runtime_os() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert_eq!(cli.args.os, Os::default());
}
#[test]
fn deprecated_profile_override_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
assert_eq!(cli.args.deprecated_user_agent.as_deref(), Some("legacy-agent"));
assert_eq!(cli.args.deprecated_os_version.as_deref(), Some("legacy-os"));
assert_eq!(cli.args.client_version.as_deref(), Some("legacy-client"));
}
#[test]
fn deprecated_profile_override_flags_do_not_affect_os_profile() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--os",
"Linux",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
let profile = build_os_profile(&cli.args);
assert_ne!(profile.user_agent(), "legacy-agent");
assert_ne!(profile.os_version(), "legacy-os");
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
#[test]
fn stdin_host_id_sets_profile_runtime_identity_seed() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--os", "Linux"])
.expect("connect args should parse");
let profile = build_os_profile_with_host_id(&cli.args, Some("auth-host-id"));
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
}
#[test]
fn cookie_cache_is_disabled_by_default() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert!(cli.args.cookie_cache.is_none());
assert!(cookie_cache_path(&cli.args).is_none());
}
#[test]
fn cookie_cache_accepts_default_path_without_value() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache"])
.expect("--cookie-cache without value should parse");
assert_eq!(cli.args.cookie_cache.as_deref(), Some(""));
assert!(cookie_cache_path(&cli.args).is_some());
}
#[test]
fn cookie_cache_accepts_custom_path() {
use clap::Parser;
let cli =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache", "/tmp/gp-cookie.json"])
.expect("--cookie-cache with value should parse");
assert_eq!(
cookie_cache_path(&cli.args).as_deref(),
Some(std::path::Path::new("/tmp/gp-cookie.json"))
);
}
#[test]
fn deprecated_hip_alias_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--csd-user",
"legacy-user",
"--csd-wrapper",
"/tmp/legacy-hip.sh",
])
.expect("deprecated HIP alias flags should remain parse-compatible");
assert_eq!(cli.args.csd_user.as_deref(), Some("legacy-user"));
assert_eq!(cli.args.csd_wrapper.as_deref(), Some("/tmp/legacy-hip.sh"));
}
#[test]
fn auto_gateway_and_gateway_are_mutually_exclusive() {
use clap::Parser;
use clap::error::ErrorKind;
let result =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1", "--auto-gateway"]);
let err = match result {
Ok(_) => panic!("--gateway and --auto-gateway must conflict"),
Err(err) => err,
};
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
}
+271
View File
@@ -0,0 +1,271 @@
use anyhow::{Context, bail};
use gpapi::{
auth::SamlAuthResult,
clap::ToVerboseArg,
credential::{Credential, PasswordCredential},
portal::{Prelogin, StandardPrelogin},
process::auth_launcher::SamlAuthLauncher,
};
use inquire::{Password, PasswordDisplayMode, Text};
use log::info;
use super::ConnectHandler;
#[derive(Default)]
pub(super) struct CleanAuthState {
requested: bool,
}
impl CleanAuthState {
pub(super) fn new(requested: bool) -> Self {
Self { requested }
}
fn consume_for_webview(&mut self, webview_auth: bool) -> bool {
if !webview_auth || !self.requested {
return false;
}
self.requested = false;
true
}
}
impl ConnectHandler<'_> {
pub(super) fn prepare_cookie_from_stdin(&self) -> anyhow::Result<()> {
if !self.args.cookie_on_stdin || self.cookie_from_stdin.borrow().is_some() {
return Ok(());
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Ok(())
}
pub(super) async fn obtain_credential(
&self,
prelogin: &Prelogin,
server: &str,
gateway_browser_auth_allowed: bool,
) -> anyhow::Result<Credential> {
if should_read_stdin_credential(self.args.cookie_on_stdin, self.args.as_gateway, prelogin.is_gateway()) {
return self.read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let external_browser_supported = can_use_external_browser_auth(
prelogin.support_default_browser(),
is_gateway,
gateway_browser_auth_allowed,
);
let browser = if external_browser_supported {
self.args.browser.as_deref()
} else if !cfg!(feature = "webview-auth") {
bail!(
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
);
} else {
None
};
let verbose = self.shared_args.verbose.to_verbose_arg();
let os_profile = self.os_profile.borrow().clone();
let key_password = self.latest_key_password.borrow().clone();
let auth_launcher = SamlAuthLauncher::new(server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.os_profile(&os_profile)
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.as_deref())
.sslkey(self.args.sslkey.as_deref())
.key_password(key_password.as_deref())
.browser(browser)
.verbose(verbose);
#[cfg(feature = "webview-auth")]
let use_default_browser = external_browser_supported && self.args.default_browser;
#[cfg(feature = "webview-auth")]
let browser_kind = if browser.is_some() || use_default_browser {
"external"
} else {
"embedded"
};
#[cfg(not(feature = "webview-auth"))]
let browser_kind = "external";
let clean_auth = self
.clean_auth_state
.borrow_mut()
.consume_for_webview(browser_kind == "embedded");
info!(
"SAML auth launch: gateway={}, clean={}, browser={}",
is_gateway, clean_auth, browser_kind
);
#[cfg(feature = "webview-auth")]
let auth_launcher = auth_launcher
.hidpi(self.args.hidpi)
.clean(clean_auth)
.default_browser(use_default_browser);
let cred = auth_launcher.launch().await?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
let password = self.obtain_password(prelogin)?;
let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into())
}
}
}
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> {
if let Some(cookie) = self.cookie_from_stdin.borrow().as_ref() {
info!("Reusing the cookie read from standard input");
return Credential::try_from(serde_json::from_str::<SamlAuthResult>(cookie)?);
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Credential::try_from(auth_result)
}
fn read_auth_result_from_stdin(&self) -> anyhow::Result<SamlAuthResult> {
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
self.cookie_from_stdin.replace(Some(cookie.trim_end().to_owned()));
let auth_result = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()).context("Failed to parse auth data")?;
Ok(auth_result)
}
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
let password = if self.args.passwd_on_stdin {
if let Some(password) = self.password_from_stdin.borrow().as_ref() {
info!("Reusing the password read from standard input");
return Ok(password.clone());
}
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let password = input.trim_end().to_owned();
self.password_from_stdin.replace(Some(password.clone()));
password
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
Ok(password)
}
}
fn should_read_stdin_credential(cookie_on_stdin: bool, as_gateway: bool, prelogin_is_gateway: bool) -> bool {
cookie_on_stdin && (!prelogin_is_gateway || as_gateway)
}
fn can_use_external_browser_auth(
saml_support_default_browser: bool,
is_gateway: bool,
gateway_browser_auth_allowed: bool,
) -> bool {
saml_support_default_browser && (!is_gateway || gateway_browser_auth_allowed)
}
fn log_stdin_host_id(host_id: Option<&str>) {
match host_id {
Some(host_id) => info!("stdin auth result host-id: {}", host_id),
None => info!("stdin auth result host-id: <none>"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_auth_state_is_consumed_once_for_webview() {
let mut state = CleanAuthState::new(true);
assert!(state.consume_for_webview(true));
assert!(!state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_is_not_consumed_by_external_browser() {
let mut state = CleanAuthState::new(true);
assert!(!state.consume_for_webview(false));
assert!(state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_remains_false_when_not_requested() {
let mut state = CleanAuthState::new(false);
assert!(!state.consume_for_webview(true));
assert!(!state.consume_for_webview(false));
}
#[test]
fn stdin_credential_is_allowed_for_portal_auth() {
assert!(should_read_stdin_credential(true, false, false));
}
#[test]
fn stdin_credential_is_allowed_for_direct_gateway_auth() {
assert!(should_read_stdin_credential(true, true, true));
}
#[test]
fn stdin_credential_is_not_reused_for_gateway_fallback_auth() {
assert!(!should_read_stdin_credential(true, false, true));
}
#[test]
fn stdin_credential_is_not_used_when_flag_is_disabled() {
assert!(!should_read_stdin_credential(false, false, false));
assert!(!should_read_stdin_credential(false, true, true));
}
#[test]
fn portal_saml_can_use_default_browser_when_supported() {
assert!(can_use_external_browser_auth(true, false, false));
}
#[test]
fn gateway_saml_requires_gateway_browser_auth_allowance() {
assert!(!can_use_external_browser_auth(true, true, false));
assert!(can_use_external_browser_auth(true, true, true));
}
#[test]
fn default_browser_auth_requires_saml_support() {
assert!(!can_use_external_browser_auth(false, false, true));
assert!(!can_use_external_browser_auth(false, true, true));
}
}
+535
View File
@@ -0,0 +1,535 @@
use std::{
fs,
path::Path,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
};
use gpapi::{
cookie_store,
credential::{AuthCookieCredential, Credential},
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
gp_params::GpParams,
os_profile::OsProfile,
portal::prelogin,
process::users::{get_non_root_user, get_user_by_name},
utils::shutdown_signal,
};
use inquire::Text;
use log::{info, warn};
use openconnect::{Vpn, VpnBuilder};
use tokio::{runtime::Handle, task::JoinHandle};
use crate::session::{
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
};
use super::{ConnectHandler, args::cookie_cache_path};
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GatewayConnectFailureStage {
BeforeTunnel,
AfterTunnel,
}
#[derive(Debug)]
pub(super) struct GatewayConnectError {
stage: GatewayConnectFailureStage,
error: anyhow::Error,
}
impl GatewayConnectError {
fn before_tunnel(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::BeforeTunnel,
error,
}
}
fn after_tunnel(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::AfterTunnel,
error,
}
}
pub(super) fn is_before_tunnel(&self) -> bool {
self.stage == GatewayConnectFailureStage::BeforeTunnel
}
pub(super) fn as_error(&self) -> &anyhow::Error {
&self.error
}
pub(super) fn into_error(self) -> anyhow::Error {
self.error
}
}
impl ConnectHandler<'_> {
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<()> {
let path = cookie_cache_path(self.args)?;
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
let stored = cookie_store::load(&path, server, &host_id)?;
if !stored.auth_cookie.can_authenticate_gateway() {
warn!(
"Cached portal cookie for {} is not usable for gateway authentication. Clearing cache.",
stored.server
);
cookie_store::clear(&path);
return None;
}
info!(
"Using cached portal cookie for {} (saved_at={}, gateway={})",
stored.server, stored.saved_at, stored.last_gateway
);
let cred: Credential = (&stored.auth_cookie).into();
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params, None).await {
Ok(session) => session,
Err(err) => {
warn!(
"Cached portal cookie rejected by gateway {}: {}. Clearing cache and falling back to portal auth.",
stored.last_gateway, err
);
cookie_store::clear(&path);
return None;
}
};
match self
.connect_gateway(
server,
&stored.last_gateway,
&login_session.cookie,
false,
login_session.extension_auth,
)
.await
{
Ok(()) => Some(()),
Err(err) => {
warn!("Gateway connect failed after cached-cookie login: {}", err.as_error());
None
}
}
}
pub(super) async fn connect_gateway_with_prelogin(
&self,
portal: &str,
gateway: &str,
allow_extend_session: bool,
gateway_context: Option<GatewayLoginContext>,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let gateway_browser_auth_allowed = true;
let prelogin = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()).await?;
let cred = self
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
.await?;
let login_session = self
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
.await?;
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await
.map_err(GatewayConnectError::into_error)
}
/// Connect to a gateway using the official client's auth flow:
///
/// 1. Call gateway prelogin and retain the response (SAML data is held as a fallback).
/// 2. If the portal provided auth cookies, attempt gateway login using them.
/// 3. If that login succeeds, proceed directly to the VPN connection.
/// 4. If no portal auth cookies exist or portal-cookie login fails, use the retained gateway prelogin response to authenticate
/// against the gateway (SAML or username/password) and obtain a gateway-issued
/// credential.
/// 5. Retry gateway login with the gateway credential (now carrying the gateway's
/// `prelogin-cookie`) and connect on success.
pub(super) async fn connect_gateway_with_fallback(
&self,
portal: &str,
gateway: &str,
portal_cred: &AuthCookieCredential,
allow_extend_session: bool,
portal_config_default_browser: bool,
gateway_context: GatewayLoginContext,
) -> Result<(), GatewayConnectError> {
info!("Connecting to gateway with portal-cookie first, gateway prelogin fallback...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let gateway_browser_auth_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
let gateway_prelogin = prelogin(gateway, &gp_params, self.prelogin_options(gateway_browser_auth_allowed))
.await
.map_err(GatewayConnectError::before_tunnel)?;
if portal_cred.can_authenticate_gateway() {
let portal_cred_for_login: Credential = portal_cred.into();
match self
.login_gateway(gateway, &portal_cred_for_login, &gp_params, Some(&gateway_context))
.await
{
Ok(login_session) => {
info!("Gateway login with portal auth cookies succeeded");
self.save_cookie_cache(portal, gateway, portal_cred);
return self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await;
}
Err(err) => {
info!("Gateway login with portal auth cookies failed: {}", err);
info!("Falling back to gateway prelogin authentication...");
}
}
} else {
info!("Portal config did not provide gateway auth cookies; using gateway prelogin flow");
}
let gateway_cred = match self
.obtain_credential(&gateway_prelogin, gateway, gateway_browser_auth_allowed)
.await
{
Ok(cred) => cred,
Err(err) => {
self.print_direct_gateway_recommendation(gateway);
return Err(GatewayConnectError::before_tunnel(err));
}
};
let login_session = match self
.login_gateway(gateway, &gateway_cred, &gp_params, Some(&gateway_context))
.await
{
Ok(login_session) => login_session,
Err(err) => {
self.print_direct_gateway_recommendation(gateway);
return Err(GatewayConnectError::before_tunnel(err));
}
};
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await
}
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
let Some(path) = cookie_cache_path(self.args) else {
return;
};
if !auth_cookie.can_authenticate_gateway() {
return;
}
let stored = cookie_store::StoredCookie::new(
portal.to_string(),
auth_cookie.username().to_string(),
self.os_profile.borrow().host_identity().host_id().to_string(),
gateway.to_string(),
auth_cookie.clone(),
);
match cookie_store::save(&path, &stored) {
Ok(()) => info!("Saved portal cookie cache to {}", path.display()),
Err(err) => warn!("Failed to save portal cookie cache to {}: {}", path.display(), err),
}
}
fn print_direct_gateway_recommendation(&self, gateway: &str) {
if !self.args.cookie_on_stdin {
return;
}
eprintln!("\nNOTE: Gateway authentication failed after portal login.");
eprintln!("NOTE: If this server also accepts direct gateway login, try:");
eprintln!("NOTE: {}", direct_gateway_command(gateway));
}
async fn login_gateway(
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
gateway_context: Option<&GatewayLoginContext>,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone();
loop {
let login = match gateway_context {
Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?,
None => gateway_login(gateway, cred, &gp_params).await?,
};
match login {
GatewayLogin::Cookie(cookie) => {
return Ok(GatewayLoginSession {
cookie,
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
});
}
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
gp_params.set_otp(&otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
async fn connect_gateway(
&self,
portal: &str,
gateway: &str,
cookie: &str,
allow_extend_session: bool,
extension_auth: SessionExtensionAuth,
) -> Result<(), GatewayConnectError> {
let mtu = self.args.mtu.unwrap_or(0);
let (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user();
let csd_uid = get_uid(&hip_user).map_err(GatewayConnectError::before_tunnel)?;
let os_profile = self.os_profile.borrow().clone();
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
os_profile: os_profile.clone(),
certificate: self.args.certificate.clone(),
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn_builder = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.interface(self.args.interface.clone())
.script_tun(self.args.script_tun)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.hip(hip)
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
.no_xmlpost(self.args.no_xmlpost);
let vpn = apply_os_profile(vpn_builder, &os_profile)
.build()
.map_err(|err| GatewayConnectError::before_tunnel(err.into()))?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
let tunnel_established = Arc::new(AtomicBool::new(false));
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
let disconnect_requested = Arc::new(AtomicBool::new(false));
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
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(&lock_file_on_connect);
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
info!("VPN session info: {}", session_info.log_summary());
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
session_task_on_connect.lock().unwrap().replace(task);
});
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
if fs::metadata(&lock_file).is_ok() {
info!("Removing PID file");
fs::remove_file(&lock_file).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
}
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
}
fn determine_hip_script(&self) -> (bool, Option<String>) {
if let Some(hip) = &self.args.hip {
return if hip.is_empty() {
(true, None)
} else {
(true, Some(hip.clone()))
};
}
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
}
fn determine_hip_user(&self) -> Option<String> {
if let Some(hip_user) = &self.args.hip_user {
return Some(hip_user.clone());
}
self.args.csd_user.clone()
}
}
fn classify_openconnect_result(
exit_code: i32,
tunnel_established: bool,
disconnect_requested: bool,
) -> Result<(), GatewayConnectError> {
if exit_code == 0 {
return Ok(());
}
if disconnect_requested && exit_code == OPENCONNECT_INTERRUPTED_EXIT_CODE {
return Ok(());
}
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
if tunnel_established {
Err(GatewayConnectError::after_tunnel(error))
} else {
Err(GatewayConnectError::before_tunnel(error))
}
}
fn direct_gateway_command(gateway: &str) -> String {
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
}
fn write_pid_file(lock_file: &Path) {
let pid = std::process::id();
if let Err(err) = fs::write(lock_file, pid.to_string()) {
warn!("Failed to write PID file: {}", err);
} else {
info!("Wrote PID {} to {}", pid, lock_file.display());
}
}
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
if let Some(user) = user {
get_user_by_name(user).map(|user| user.uid())
} else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
builder
.os(Some(profile.client_os().to_openconnect_os().to_string()))
.os_version(Some(profile.os_version().to_string()))
.client_version(Some(profile.client_version().to_string()))
.host_id(Some(profile.host_identity().host_id().to_string()))
.user_agent(Some(profile.user_agent().to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn openconnect_success_is_not_a_gateway_failure() {
assert!(classify_openconnect_result(0, false, false).is_ok());
assert!(classify_openconnect_result(0, true, false).is_ok());
}
#[test]
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
let err = classify_openconnect_result(1, false, false).expect_err("nonzero exit should fail");
assert!(err.is_before_tunnel());
}
#[test]
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
let err = classify_openconnect_result(1, true, false).expect_err("nonzero exit should fail");
assert!(!err.is_before_tunnel());
}
#[test]
fn interrupted_exit_after_requested_disconnect_is_success() {
assert!(classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, true).is_ok());
}
#[test]
fn interrupted_exit_without_requested_disconnect_is_failure() {
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
.expect_err("unexpected interrupt should fail");
assert!(!err.is_before_tunnel());
}
#[test]
fn direct_gateway_recommendation_uses_gateway_server() {
assert_eq!(
direct_gateway_command("gateway.example.test"),
"gpauth --gateway gateway.example.test | sudo gpclient connect gateway.example.test --as-gateway --cookie-on-stdin"
);
}
}
+314
View File
@@ -0,0 +1,314 @@
mod args;
mod credential;
mod gateway;
use std::cell::RefCell;
use anyhow::bail;
use gpapi::{
error::PortalError,
gateway::{GatewayLoginContext, GatewaySelection},
gp_params::GpParams,
os_profile::OsProfile,
portal::{PreloginOptions, prelogin, retrieve_config},
utils::request::RequestIdentityError,
};
use inquire::{Password, PasswordDisplayMode, Select};
use log::{info, warn};
use crate::cli::SharedArgs;
pub(crate) use args::ConnectArgs;
use args::{build_os_profile, build_os_profile_with_host_id, warn_deprecated_connect_args};
use credential::CleanAuthState;
use gateway::GatewayConnectError;
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs<'a>,
os_profile: RefCell<OsProfile>,
latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>,
clean_auth_state: RefCell<CleanAuthState>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
warn_deprecated_connect_args(args);
#[cfg(feature = "webview-auth")]
let clean_auth = args.clean;
#[cfg(not(feature = "webview-auth"))]
let clean_auth = false;
Self {
args,
shared_args,
os_profile: RefCell::new(build_os_profile(args)),
latest_key_password: Default::default(),
password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(),
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
}
}
fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder(self.os_profile.borrow().clone());
builder
.csc_mode(self.args.csc)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone());
builder.build()
}
pub(super) fn prelogin_options(&self, gateway_browser_auth_allowed: bool) -> PreloginOptions {
PreloginOptions::default()
.external_browser_requested(self.external_browser_requested())
.gateway_external_browser_allowed(gateway_browser_auth_allowed)
}
pub(super) fn direct_gateway_prelogin_options(&self) -> PreloginOptions {
self.prelogin_options(true)
}
pub(super) fn gateway_browser_auth_allowed(&self, portal_config_default_browser: bool) -> bool {
gateway_browser_auth_allowed(portal_config_default_browser, self.external_browser_requested())
}
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.args.default_browser || self.args.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
self.args.browser.is_some()
}
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
#[cfg(feature = "webview-auth")]
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
let Err(err) = self.handle_impl().await else {
return Ok(());
};
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
eprintln!("ERROR: No private key found in the certificate file");
eprintln!("ERROR: Please provide the private key file using the `-k` option");
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
self.prepare_cookie_from_stdin()?;
if as_gateway {
info!("Treating the server as a gateway");
return self.connect_gateway_with_prelogin(server, server, false, None).await;
}
if !self.args.cookie_on_stdin {
if let Some(()) = self.try_cached_cookie(server).await {
return Ok(());
}
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server, server, false, None).await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = prelogin(portal, &gp_params, self.prelogin_options(false)).await?;
let cred = self.obtain_credential(&prelogin, portal, false).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
portal_config.sort_gateways(prelogin.region());
let auth_cookie = match cred.password() {
Some(password) => portal_config.auth_cookie().clone().with_password(password),
None => portal_config.auth_cookie().clone(),
};
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
info!("Portal config default-browser: {}", portal_config_default_browser);
if self.args.auto_gateway {
let gateways = portal_config.gateways();
if gateways.is_empty() {
bail!("No gateways available in portal config for auto-gateway selection");
}
info!(
"Auto-gateway mode: trying {} gateway(s) in priority order",
gateways.len()
);
let mut last_err: Option<anyhow::Error> = None;
for gateway in &gateways {
info!("Auto-gateway: attempting gateway {}", gateway);
let gateway_context =
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(portal_config.connect_method());
match self
.connect_gateway_with_fallback(
portal,
gateway.server(),
&auth_cookie,
allow_extend_session,
portal_config_default_browser,
gateway_context,
)
.await
{
Ok(()) => return Ok(()),
Err(err) => {
if !err.is_before_tunnel() {
return Err(err.into_error());
}
warn!(
"Auto-gateway: gateway {} failed before tunnel setup: {}",
gateway,
err.as_error()
);
last_err = Some(err.into_error());
}
}
}
let detail = last_err
.map(|e| e.to_string())
.unwrap_or_else(|| "unknown error".to_string());
bail!(
"Auto-gateway: all {} gateway(s) failed to connect; last error: {}",
gateways.len(),
detail
);
}
let gateway_selection = if self.args.gateway.is_some() {
GatewaySelection::Manual
} else {
GatewaySelection::Auto
};
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
let gateways = portal_config.gateways();
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
let gateway = selected_gateway.server();
let gateway_context =
GatewayLoginContext::new(selected_gateway, gateway_selection).with_connect_method(portal_config.connect_method());
self
.connect_gateway_with_fallback(
portal,
gateway,
&auth_cookie,
allow_extend_session,
portal_config_default_browser,
gateway_context,
)
.await
.map_err(GatewayConnectError::into_error)
}
fn apply_stdin_host_id(&self, host_id: Option<&str>) {
let Some(host_id) = host_id else {
return;
};
self
.os_profile
.replace(build_os_profile_with_host_id(self.args, Some(host_id)));
info!(
"connect profile host-id: {}",
self.os_profile.borrow().host_identity().host_id()
);
}
}
fn gateway_browser_auth_allowed(portal_config_default_browser: bool, external_browser_requested: bool) -> bool {
portal_config_default_browser || external_browser_requested
}
#[cfg(test)]
mod tests {
use super::gateway_browser_auth_allowed;
#[test]
fn gateway_browser_auth_is_allowed_by_portal_config() {
assert!(gateway_browser_auth_allowed(true, false));
}
#[test]
fn gateway_browser_auth_is_allowed_by_explicit_browser_request() {
assert!(gateway_browser_auth_allowed(false, true));
}
#[test]
fn gateway_browser_auth_is_disabled_without_portal_config_or_user_request() {
assert!(!gateway_browser_auth_allowed(false, false));
}
}
+52 -20
View File
@@ -1,31 +1,63 @@
use crate::GP_CLIENT_LOCK_FILE;
use clap::Args;
use gpapi::utils::lock_file::gpservice_lock_info;
use log::{info, warn};
use std::fs;
use std::{fs, path::Path, str::FromStr, thread, time::Duration};
use sysinfo::{Pid, Signal, System};
pub(crate) struct DisconnectHandler;
#[derive(Args)]
pub struct DisconnectArgs {
#[arg(
long,
required = false,
help = "The time in seconds to wait for the VPN connection to disconnect"
)]
wait: Option<u64>,
}
impl DisconnectHandler {
pub(crate) fn new() -> Self {
Self
pub struct DisconnectHandler<'a> {
args: &'a DisconnectArgs,
lock_file: &'a Path,
}
impl<'a> DisconnectHandler<'a> {
pub fn new(args: &'a DisconnectArgs, lock_file: &'a Path) -> Self {
Self { args, lock_file }
}
pub(crate) fn handle(&self) -> anyhow::Result<()> {
if fs::metadata(GP_CLIENT_LOCK_FILE).is_err() {
warn!("PID file not found, maybe the client is not running");
return Ok(());
pub async fn handle(&self) -> anyhow::Result<()> {
// Try to disconnect the CLI client
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);
});
};
// Try to disconnect the GUI service
if let Ok(c) = gpservice_lock_info().await {
send_signal(&c.pid.to_string(), Signal::User1).unwrap_or_else(|err| {
warn!("Failed to send signal to service: {}", err);
});
};
// sleep, to give the client and service time to disconnect
if let Some(wait) = self.args.wait {
thread::sleep(Duration::from_secs(wait));
}
let pid = fs::read_to_string(GP_CLIENT_LOCK_FILE)?;
let pid = pid.trim().parse::<usize>()?;
let s = System::new_all();
if let Some(process) = s.process(Pid::from(pid)) {
info!("Found process {}, killing...", pid);
if process.kill_with(Signal::Interrupt).is_none() {
warn!("Failed to kill process {}", pid);
}
}
Ok(())
}
}
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<()> {
let s = System::new_all();
let pid = Pid::from_str(pid)?;
if let Some(process) = s.process(pid) {
info!("Found process {}, sending signal...", pid);
if process.kill_with(signal).is_none() {
warn!("Failed to kill process {}", pid);
}
}
Ok(())
}
+580
View File
@@ -0,0 +1,580 @@
use askama::Template;
use clap::Args;
use gpapi::{
clap::args::Os,
os_profile::{ClientOs, OsProfile, OsProfileBuilder},
};
use log::debug;
use serde::Deserialize;
use std::collections::HashMap;
use std::process::Command;
use xmltree::Element;
#[derive(Template)]
#[template(path = "hip_report.xml")]
struct HipReportTemplate<'a> {
client_version: &'a str,
generate_time: String,
day: String,
month: String,
year: String,
user_name: &'a str,
host_info: HostInfo,
md5: &'a str,
}
#[derive(Debug, Clone, Deserialize)]
struct DefenderInfo {
#[serde(rename = "appVersion")]
app_version: String,
#[serde(rename = "engineVersion")]
engine_version: String,
#[serde(rename = "definitionsVersion")]
definitions_version: String,
#[serde(rename = "realTimeProtectionEnabled")]
real_time_protection_enabled: RealTimeProtection,
}
#[derive(Debug, Clone, Deserialize)]
struct RealTimeProtection {
value: bool,
}
/// Host information for HIP reporting
struct HostInfo {
/// Common for all OSes, e.g., "Apple", "Microsoft", "Linux"
os_vendor: String,
/// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc.
os_version: String,
/// Per-OS machine identifier (UUID for Linux/Windows, MAC for macOS)
host_id: String,
/// Common for all OSes
host_name: String,
/// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130"
software_version: String,
domain: String,
network_interfaces: Vec<NetworkInterface>,
defender: Option<DefenderInfo>,
}
impl HostInfo {
/// Get the first available IPv4 address from network interfaces
pub fn default_ipv4(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv4.as_deref())
.unwrap_or_default()
}
/// Get the first available IPv6 address from network interfaces
pub fn default_ipv6(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv6.as_deref())
.unwrap_or_default()
}
}
/// Network interface information
#[derive(Clone)]
struct NetworkInterface {
name: String,
description: String,
mac_address: Option<String>,
ipv4: Option<String>,
ipv6: Option<String>,
}
impl NetworkInterface {
/// Create a new network interface with basic information
fn new(name: String, description: String) -> Self {
Self {
name,
description,
mac_address: None,
ipv4: None,
ipv6: None,
}
}
/// Set MAC address
fn with_mac(mut self, mac: Option<String>) -> Self {
self.mac_address = mac;
self
}
/// Set IPv4 address
fn with_ipv4(mut self, ipv4: Option<String>) -> Self {
self.ipv4 = ipv4;
self
}
/// Set IPv6 address
fn with_ipv6(mut self, ipv6: Option<String>) -> Self {
self.ipv6 = ipv6;
self
}
}
#[derive(Args)]
pub(crate) struct HipArgs {
#[arg(long, help = "The GP client version, e.g., 6.2.4-49")]
client_version: String,
#[arg(long, value_enum, help = "The client OS")]
client_os: Os,
#[arg(long, hide = true)]
os_version: Option<String>,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long, help = "The authentication cookie")]
cookie: String,
#[arg(long, help = "The client IPv4 address")]
client_ip: Option<String>,
#[arg(long, help = "The client IPv6 address")]
client_ipv6: Option<String>,
#[arg(long, help = "The MD5 digest to encode into the HIP report")]
md5: String,
}
pub(crate) struct HipHandler<'a> {
args: &'a HipArgs,
profile: OsProfile,
}
impl<'a> HipHandler<'a> {
pub(crate) fn new(args: &'a HipArgs) -> Self {
let profile = build_os_profile(args);
Self { args, profile }
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
let cookie_params = self.parse_cookie();
let report = self.generate_hip_report(&cookie_params)?;
debug!("Generated HIP report:\n{}", report);
println!("{}", report);
Ok(())
}
fn parse_cookie(&self) -> HashMap<String, String> {
// Parse URL-encoded cookie string using serde_urlencoded
serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default()
}
/// Generate the complete HIP report XML
fn generate_hip_report(&self, cookie_params: &HashMap<String, String>) -> anyhow::Result<String> {
let (generate_time, day, month, year) = get_current_time_components();
let user_name = cookie_params.get("user").map(|s| s.as_str()).unwrap_or("");
let host_info = self.collect_host_info(cookie_params);
let template = HipReportTemplate {
client_version: &self.args.client_version,
generate_time,
day,
month,
year,
user_name,
host_info,
md5: &self.args.md5,
};
let report = template.render()?;
format_xml(&report)
}
/// Collect host information using the configured OsProfile.
fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo {
HostInfoCollector::new(&self.profile, self.args, cookie_params).collect()
}
}
/// Construct an `OsProfile` from CLI args, falling back to per-OS defaults
/// for any value not supplied on the command line.
fn build_os_profile(args: &HipArgs) -> OsProfile {
let client_os = ClientOs::from(args.client_os);
let mut builder = OsProfileBuilder::new(client_os).client_version(args.client_version.clone());
if let Some(host_id) = args.host_id.as_deref() {
debug!("HIP host-id override supplied: {}", host_id);
builder = builder.host_id_override(host_id);
}
let profile = builder.build();
debug!(
"HIP OS profile host-id: runtime={}, projected={}, client_os={}",
profile.host_identity().host_id(),
profile.host_id(),
client_os.as_str()
);
profile
}
// ============================================================================
// Host Information Collector
// ============================================================================
/// Helper struct for collecting host information.
///
/// Identity values (vendor, host_id, computer name, software version) come
/// from the configured `OsProfile`, while runtime state (network interfaces,
/// IP addresses) is enumerated here from the underlying machine.
struct HostInfoCollector<'p, 'a> {
profile: &'p OsProfile,
args: &'a HipArgs,
cookie_params: &'a HashMap<String, String>,
}
impl<'p, 'a> HostInfoCollector<'p, 'a> {
fn new(profile: &'p OsProfile, args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self {
Self {
profile,
args,
cookie_params,
}
}
/// Domain belongs to the runtime user/session, not the simulated OS, so
/// it is sourced from the auth cookie when available.
fn get_domain(&self) -> String {
self
.cookie_params
.get("domain")
.map(|s| s.to_string())
.unwrap_or_default()
}
/// Collect network interface information with fallback
fn collect_network_interface(&self) -> NetworkInterface {
match netdev::get_default_interface() {
Ok(iface) => NetworkInterface::new(
iface.name.clone(),
iface.description.unwrap_or_else(|| iface.name.clone()),
)
.with_mac(iface.mac_addr.map(|mac| mac.address()))
.with_ipv4(iface.ipv4.first().map(|ip| ip.addr().to_string()))
.with_ipv6(iface.ipv6.first().map(|ip| ip.addr().to_string())),
Err(_) => NetworkInterface::new("unknown".to_string(), "unknown".to_string())
.with_ipv4(self.args.client_ip.clone())
.with_ipv6(self.args.client_ipv6.clone()),
}
}
/// Single entry point for collecting host info — dispatches per-OS
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
fn collect(&self) -> HostInfo {
let runtime_iface = self.collect_network_interface();
let primary = self.adapt_primary_interface(&runtime_iface);
let mut interfaces = vec![primary.clone()];
interfaces.extend(self.extra_interfaces(&primary));
HostInfo {
os_vendor: self.profile.os_vendor().to_string(),
os_version: self.profile.os_version().to_string(),
host_id: self.profile.host_id().to_string(),
host_name: self.profile.computer().to_string(),
software_version: self.profile.software_version().to_string(),
domain: self.domain_for_profile(),
network_interfaces: interfaces,
defender: self.defender_for_profile(),
}
}
/// Build the primary network interface with OS-appropriate naming and
/// MAC formatting. When emulating a different OS, the runtime interface
/// name/description are replaced with the canonical placeholder for the
/// target OS.
fn adapt_primary_interface(&self, runtime: &NetworkInterface) -> NetworkInterface {
let (name, description) = if self.profile.is_native() {
(runtime.name.clone(), runtime.description.clone())
} else {
placeholder_interface_for(self.profile, runtime)
};
NetworkInterface {
name,
description,
mac_address: format_mac_for(self.profile, runtime.mac_address.clone()),
ipv4: runtime.ipv4.clone(),
ipv6: runtime.ipv6.clone(),
}
}
/// Additional interfaces appended after the primary. Only Windows
/// emits the software loopback interface in HIP reports.
fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec<NetworkInterface> {
match self.profile.client_os() {
ClientOs::Windows => vec![NetworkInterface {
name: derive_windows_network_name(self.profile.host_id(), primary),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
}],
ClientOs::Linux | ClientOs::Mac => vec![],
}
}
/// Linux HIP reports omit the domain field; macOS/Windows include it
/// from the auth cookie.
fn domain_for_profile(&self) -> String {
match self.profile.client_os() {
ClientOs::Linux => String::new(),
ClientOs::Mac | ClientOs::Windows => self.get_domain(),
}
}
fn defender_for_profile(&self) -> Option<DefenderInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_microsoft_defender_blocking(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
}
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
let output = Command::new("mdatp")
.arg("health")
.arg("--output")
.arg("json")
.output()
.ok()?;
if !output.status.success() {
debug!("mdatp health command failed");
return None;
}
let json = String::from_utf8(output.stdout).ok()?;
let defender = parse_defender_info(&json)?;
debug!("Detected Microsoft Defender: {:?}", defender);
Some(defender)
}
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
serde_json::from_str(json).ok()
}
// ============================================================================
// Per-OS interface helpers (selected via OsProfile, not cfg)
// ============================================================================
/// Canonical interface name/description for the target OS when the runtime
/// is a different OS (i.e. emulation).
fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> (String, String) {
match profile.client_os() {
ClientOs::Linux => ("enp1s0f0".to_string(), "enp1s0f0".to_string()),
ClientOs::Mac => ("en0".to_string(), "en0".to_string()),
ClientOs::Windows => (
derive_windows_network_name(profile.host_id(), runtime),
"PANGP Virtual Ethernet Adapter Secure".to_string(),
),
}
}
/// MAC address formatting per target OS. Windows uses hyphen separators;
/// Linux and macOS preserve the colon-separated form returned by the
/// platform.
fn format_mac_for(profile: &OsProfile, mac: Option<String>) -> Option<String> {
match profile.client_os() {
ClientOs::Windows => mac.map(|m| m.replace(':', "-")),
ClientOs::Linux | ClientOs::Mac => mac,
}
}
// ============================================================================
// Utility Functions
// ============================================================================
/// Get current time components for HIP report
fn get_current_time_components() -> (String, String, String, String) {
let now = chrono::Local::now();
(
now.format("%m/%d/%Y %H:%M:%S").to_string(),
now.format("%d").to_string(),
now.format("%m").to_string(),
now.format("%Y").to_string(),
)
}
/// Format XML string with proper indentation
fn format_xml(xml_str: &str) -> anyhow::Result<String> {
let xml = Element::parse(xml_str.as_bytes())?;
let config = xmltree::EmitterConfig::new().perform_indent(true);
let mut xml_buf = Vec::new();
xml.write_with_config(&mut xml_buf, config)?;
Ok(String::from_utf8(xml_buf)?)
}
fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> String {
let seed = format!(
"{}-{}-{}",
host_id,
iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"),
iface.name
);
format!(
"{{{}}}",
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_DNS, seed.as_bytes())
.to_string()
.to_uppercase()
)
}
#[cfg(test)]
mod tests {
use super::*;
use gpapi::os_profile::runtime_client_os;
fn make_hip_args(client_os: Os) -> HipArgs {
HipArgs {
client_version: "6.2.4-49".to_string(),
client_os,
os_version: Some("test-os-version".to_string()),
host_id: None,
cookie: String::new(),
client_ip: None,
client_ipv6: None,
md5: "deadbeef".to_string(),
}
}
fn make_profile(client_os: ClientOs) -> OsProfile {
OsProfileBuilder::new(client_os).build()
}
#[test]
fn host_info_os_vendor_is_linux_for_linux_profile() {
let args = make_hip_args(Os::Linux);
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Linux");
}
#[test]
fn host_info_os_vendor_is_apple_for_mac_profile() {
let args = make_hip_args(Os::Mac);
let profile = make_profile(ClientOs::Mac);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Apple");
}
#[test]
fn host_info_os_vendor_is_microsoft_for_windows_profile() {
let args = make_hip_args(Os::Windows);
let profile = make_profile(ClientOs::Windows);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Microsoft");
}
#[test]
fn host_info_host_id_comes_from_os_profile() {
let args = make_hip_args(Os::Linux);
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.host_id, profile.host_id());
}
#[test]
fn host_info_host_id_independent_of_runtime_for_each_os() {
// host_id should reflect the OsProfile's machine identity for every
// simulated OS, regardless of the runtime platform.
for (client_os, os_arg) in [
(ClientOs::Linux, Os::Linux),
(ClientOs::Mac, Os::Mac),
(ClientOs::Windows, Os::Windows),
] {
let args = make_hip_args(os_arg);
let profile = make_profile(client_os);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.host_id, profile.host_id());
}
}
#[test]
fn hip_os_version_argument_is_ignored() {
let args = make_hip_args(Os::Linux);
let profile = build_os_profile(&args);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_version, profile.os_version());
assert_ne!(info.os_version, "test-os-version");
}
#[test]
fn host_id_argument_sets_profile_runtime_identity() {
let mut args = make_hip_args(Os::default());
args.host_id = Some("auth-host-id".to_string());
let profile = build_os_profile(&args);
assert_eq!(profile.client_os(), runtime_client_os());
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
}
#[test]
fn host_info_uses_host_id_argument_for_native_profile() {
let mut args = make_hip_args(Os::default());
args.host_id = Some("auth-host-id".to_string());
let profile = build_os_profile(&args);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
assert_eq!(info.host_id, profile.host_id());
}
#[test]
fn parses_microsoft_defender_health_json() {
let defender = parse_defender_info(
r#"{
"appVersion": "101.25042.0000",
"engineVersion": "1.1.25040.2",
"definitionsVersion": "1.429.201.0",
"realTimeProtectionEnabled": { "value": true }
}"#,
)
.expect("defender health json should parse");
assert_eq!(defender.app_version, "101.25042.0000");
assert_eq!(defender.engine_version, "1.1.25040.2");
assert_eq!(defender.definitions_version, "1.429.201.0");
assert!(defender.real_time_protection_enabled.value);
}
#[test]
fn rejects_invalid_microsoft_defender_health_json() {
assert!(parse_defender_info("{}").is_none());
}
}
+2 -2
View File
@@ -1,11 +1,11 @@
use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf};
use clap::Args;
use common::constants::GP_CALLBACK_PORT_FILENAME;
use directories::ProjectDirs;
use gpapi::{
process::service_launcher::ServiceLauncher,
utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
GP_CALLBACK_PORT_FILENAME,
};
use log::info;
use tokio::io::AsyncWriteExt;
@@ -32,7 +32,7 @@ impl<'a> LaunchGuiHandler<'a> {
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
// `launch-gui`cannot be run as root
let user = whoami::username();
let user = whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))?;
if user == "root" {
anyhow::bail!("`launch-gui` cannot be run as root");
}
+2
View File
@@ -1,7 +1,9 @@
mod cli;
mod connect;
mod disconnect;
mod hip;
mod launch_gui;
mod session;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
+247
View File
@@ -0,0 +1,247 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use gpapi::{
gateway::{SessionContext, SessionExtensionAuth, extend_session},
os_profile::OsProfile,
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{info, warn};
use openconnect::VpnSessionInfo;
use tokio::{runtime::Handle, task::JoinHandle};
#[derive(Debug, PartialEq, Eq)]
struct SessionWarningSchedule {
delay: Duration,
message: String,
should_auto_extend: bool,
}
pub(crate) struct SessionContextInput {
pub(crate) portal: String,
pub(crate) gateway: String,
pub(crate) cookie: String,
pub(crate) os_profile: OsProfile,
pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
pub(crate) disable_ipv6: bool,
pub(crate) extension_auth: Option<SessionExtensionAuth>,
}
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
let session_args = SessionRequestArgs::new(input.cookie)
.with_user_agent(input.os_profile.user_agent().to_string())
.with_certificate(input.certificate)
.with_sslkey(input.sslkey)
.with_key_password(input.key_password)
.with_disable_ipv6(input.disable_ipv6);
let ctx = SessionContext::new(input.gateway, input.portal, session_args);
match input.extension_auth {
Some(extension_auth) => ctx.with_extension_auth(extension_auth),
None => ctx,
}
}
pub(crate) fn session_info_from_vpn(vpn_session_info: VpnSessionInfo, allow_extend_session: bool) -> SessionInfo {
SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
)
}
pub(crate) fn spawn_session_runtime_with_info(
handle: &Handle,
session_ctx: SessionContext,
session_info: SessionInfo,
) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx, session_info))
}
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo) {
loop {
let Some(schedule) = build_session_warning_schedule(&session_info) else {
info!("No session warning schedule provided by the gateway");
return;
};
tokio::time::sleep(schedule.delay).await;
eprintln!("\nWARNING: {}", schedule.message);
if !schedule.should_auto_extend {
info!("Session extension is not allowed by the gateway");
return;
}
info!("Attempting to extend the session");
match extend_session(&session_ctx).await {
Ok(()) => {
let Some(next_session_info) = session_info.rescheduled_after_extension() else {
info!("Session extended, but no lifetime is available to schedule another warning");
return;
};
eprintln!("Session extended.");
session_info = next_session_info;
}
Err(err) => {
warn!("Failed to extend session: {}", err);
eprintln!("WARNING: Failed to extend session: {}", err);
return;
}
}
}
}
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
let warning = session_info.lifetime_warning.as_ref()?;
let warning_secs = if let Some(user_expires) = session_info.user_expires {
let now = unix_timestamp();
user_expires.saturating_sub(warning.prior_secs).saturating_sub(now)
} else if let Some(lifetime_secs) = session_info.lifetime_secs {
lifetime_secs.saturating_sub(warning.prior_secs)
} else {
return None;
};
Some(SessionWarningSchedule {
delay: Duration::from_secs(warning_secs as u64),
message: warning.message.clone(),
should_auto_extend: session_info.allow_extend_session,
})
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
SessionInfo {
user_expires,
lifetime_warning: Some(SessionWarning {
prior_secs: 1800,
message: "Session expires soon".to_string(),
}),
allow_extend_session,
..Default::default()
}
}
#[test]
fn builds_warning_schedule_for_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert_eq!(schedule.message, "Session expires soon");
assert!(schedule.delay <= Duration::from_secs(30));
assert!(schedule.should_auto_extend);
}
#[test]
fn builds_warning_schedule_without_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), false);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert!(!schedule.should_auto_extend);
}
#[test]
fn schedules_next_warning_after_extension_from_lifetime() {
let mut session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
session_info.lifetime_secs = Some(7200);
let next_session_info = session_info.rescheduled_after_extension().unwrap();
let schedule = build_session_warning_schedule(&next_session_info).unwrap();
assert!(schedule.delay <= Duration::from_secs(5400));
}
#[test]
fn builds_session_context_from_os_profile() {
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Mac)
.client_version("6.3.1-12".to_string())
.build();
let expected_user_agent = profile.user_agent().to_string();
let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(),
os_profile: profile,
certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
disable_ipv6: true,
extension_auth: None,
});
assert_eq!(ctx.portal(), "portal.example.com");
assert_eq!(ctx.server(), "vpn.example.com");
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
assert_eq!(
ctx.session_args().user_agent().as_deref(),
Some(expected_user_agent.as_str())
);
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
assert!(ctx.session_args().disable_ipv6());
}
#[test]
fn maps_openconnect_session_metadata_to_runtime_session_info() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
..Default::default()
},
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_gateway_session_info_does_not_allow_extension_without_portal_policy() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
..Default::default()
},
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(!info.allow_extend_session);
}
}
+290
View File
@@ -0,0 +1,290 @@
<?xml version="1.0" encoding="UTF-8"?>
<hip-report name="hip-report">
<md5-sum>{{ md5 }}</md5-sum>
<user-name>{{ user_name }}</user-name>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<ip-address>{{ host_info.default_ipv4() }}</ip-address>
<ipv6-address>{{ host_info.default_ipv6() }}</ipv6-address>
<generate-time>{{ generate_time }}</generate-time>
<hip-report-version>4</hip-report-version>
<categories>
<entry name="host-info">
<client-version>{{ client_version }}</client-version>
<os>{{ host_info.os_version }}</os>
<os-vendor>{{ host_info.os_vendor }}</os-vendor>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<network-interface>
{% for iface in host_info.network_interfaces.iter() -%}
<entry name="{{ iface.name }}">
<description>{{ iface.description }}</description>
{% if let Some(mac) = iface.mac_address -%}
<mac-address>{{ mac }}</mac-address>
{% endif -%}
{% if let Some(ipv4) = iface.ipv4 -%}
<ip-address>
<entry name="{{ ipv4 }}"/>
</ip-address>
{% endif -%}
{% if let Some(ipv6) = iface.ipv6 -%}
<ipv6-address>
<entry name="{{ ipv6 }}"/>
</ipv6-address>
{% endif -%}
</entry>
{% endfor -%}
</network-interface>
</entry>
{% if host_info.os_vendor == "Microsoft" -%}
<entry name="antivirus">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="1" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="1" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="anti-spyware">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="2" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="2" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<drives>
<entry>
<drive-name>C:\\</drive-name>
<enc-state>full</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% elif host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Gatekeeper" version="{{ host_info.software_version }}" defver="" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Time Machine" version="1.3"/>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="FileVault" version="{{ host_info.software_version }}"/>
<drives>
<entry>
<drive-name>Macintosh HD</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>Data</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>All</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="OpenBSD" name="Packet Filter" version="{{ host_info.software_version }}"/>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Software Update" version="3.0"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches>
</missing-patches>
</entry>
{% elif host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
{% if let Some(defender) = &host_info.defender -%}
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Defender ATP" version="{{ defender.app_version }}" defver="{{ defender.definitions_version }}" prodType="3" engver="{{ defender.engine_version }}" osType="1" vendor="Microsoft Corporation" dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>{% if defender.real_time_protection_enabled.value %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
{% else -%}
<list/>
{% endif -%}
</entry>
<entry name="disk-backup">
<list/>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="cryptsetup" version="2.3.3" vendor="GitLab Inc.">
</Prod>
<drives>
<entry>
<drive-name>/</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
</Prod>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="nftables" version="0.9.3" vendor="The Netfilter Project">
</Prod>
<is-enabled>n/a</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="Dandified Yum" version="4.2.23" vendor="Red Hat, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% endif -%}
<entry name="data-loss-prevention">
<list/>
</entry>
</categories>
</hip-report>
-99
View File
@@ -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

+43
View File
@@ -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
View File
@@ -1 +0,0 @@
html,body,#root{height:100%;margin:0;padding:0;-webkit-user-select:none;user-select:none;cursor:default}
+1
View File
@@ -0,0 +1 @@
html,body,#root{-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0}
-193
View File
@@ -1,193 +0,0 @@
var zg=Object.defineProperty;var wg=(l,i,c)=>i in l?zg(l,i,{enumerable:!0,configurable:!0,writable:!0,value:c}):l[i]=c;var Ni=(l,i,c)=>wg(l,typeof i!="symbol"?i+"":i,c);function Rg(l,i){for(var c=0;c<i.length;c++){const o=i[c];if(typeof o!="string"&&!Array.isArray(o)){for(const s in o)if(s!=="default"&&!(s in l)){const d=Object.getOwnPropertyDescriptor(o,s);d&&Object.defineProperty(l,s,d.get?d:{enumerable:!0,get:()=>o[s]})}}}return Object.freeze(Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}))}(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const d of s)if(d.type==="childList")for(const m of d.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&o(m)}).observe(document,{childList:!0,subtree:!0});function c(s){const d={};return s.integrity&&(d.integrity=s.integrity),s.referrerPolicy&&(d.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?d.credentials="include":s.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function o(s){if(s.ep)return;s.ep=!0;const d=c(s);fetch(s.href,d)}})();function Mg(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var Jo={exports:{}},Ui={};/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var wh;function Dg(){if(wh)return Ui;wh=1;var l=Symbol.for("react.transitional.element"),i=Symbol.for("react.fragment");function c(o,s,d){var m=null;if(d!==void 0&&(m=""+d),s.key!==void 0&&(m=""+s.key),"key"in s){d={};for(var b in s)b!=="key"&&(d[b]=s[b])}else d=s;return s=d.ref,{$$typeof:l,type:o,key:m,ref:s!==void 0?s:null,props:d}}return Ui.Fragment=i,Ui.jsx=c,Ui.jsxs=c,Ui}var Rh;function Bg(){return Rh||(Rh=1,Jo.exports=Dg()),Jo.exports}var rt=Bg(),Fo={exports:{}},Hi={},Po={exports:{}},Io={};/**
* @license React
* scheduler.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Mh;function Ng(){return Mh||(Mh=1,function(l){function i(G,it){var tt=G.length;G.push(it);t:for(;0<tt;){var ot=tt-1>>>1,S=G[ot];if(0<s(S,it))G[ot]=it,G[tt]=S,tt=ot;else break t}}function c(G){return G.length===0?null:G[0]}function o(G){if(G.length===0)return null;var it=G[0],tt=G.pop();if(tt!==it){G[0]=tt;t:for(var ot=0,S=G.length,q=S>>>1;ot<q;){var at=2*(ot+1)-1,lt=G[at],J=at+1,bt=G[J];if(0>s(lt,tt))J<S&&0>s(bt,lt)?(G[ot]=bt,G[J]=tt,ot=J):(G[ot]=lt,G[at]=tt,ot=at);else if(J<S&&0>s(bt,tt))G[ot]=bt,G[J]=tt,ot=J;else break t}}return it}function s(G,it){var tt=G.sortIndex-it.sortIndex;return tt!==0?tt:G.id-it.id}if(l.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;l.unstable_now=function(){return d.now()}}else{var m=Date,b=m.now();l.unstable_now=function(){return m.now()-b}}var v=[],p=[],C=1,_=null,w=3,j=!1,B=!1,U=!1,X=typeof setTimeout=="function"?setTimeout:null,Q=typeof clearTimeout=="function"?clearTimeout:null,F=typeof setImmediate<"u"?setImmediate:null;function V(G){for(var it=c(p);it!==null;){if(it.callback===null)o(p);else if(it.startTime<=G)o(p),it.sortIndex=it.expirationTime,i(v,it);else break;it=c(p)}}function L(G){if(U=!1,V(G),!B)if(c(v)!==null)B=!0,St();else{var it=c(p);it!==null&&_t(L,it.startTime-G)}}var O=!1,$=-1,W=5,gt=-1;function K(){return!(l.unstable_now()-gt<W)}function y(){if(O){var G=l.unstable_now();gt=G;var it=!0;try{t:{B=!1,U&&(U=!1,Q($),$=-1),j=!0;var tt=w;try{e:{for(V(G),_=c(v);_!==null&&!(_.expirationTime>G&&K());){var ot=_.callback;if(typeof ot=="function"){_.callback=null,w=_.priorityLevel;var S=ot(_.expirationTime<=G);if(G=l.unstable_now(),typeof S=="function"){_.callback=S,V(G),it=!0;break e}_===c(v)&&o(v),V(G)}else o(v);_=c(v)}if(_!==null)it=!0;else{var q=c(p);q!==null&&_t(L,q.startTime-G),it=!1}}break t}finally{_=null,w=tt,j=!1}it=void 0}}finally{it?Y():O=!1}}}var Y;if(typeof F=="function")Y=function(){F(y)};else if(typeof MessageChannel<"u"){var et=new MessageChannel,ct=et.port2;et.port1.onmessage=y,Y=function(){ct.postMessage(null)}}else Y=function(){X(y,0)};function St(){O||(O=!0,Y())}function _t(G,it){$=X(function(){G(l.unstable_now())},it)}l.unstable_IdlePriority=5,l.unstable_ImmediatePriority=1,l.unstable_LowPriority=4,l.unstable_NormalPriority=3,l.unstable_Profiling=null,l.unstable_UserBlockingPriority=2,l.unstable_cancelCallback=function(G){G.callback=null},l.unstable_continueExecution=function(){B||j||(B=!0,St())},l.unstable_forceFrameRate=function(G){0>G||125<G?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):W=0<G?Math.floor(1e3/G):5},l.unstable_getCurrentPriorityLevel=function(){return w},l.unstable_getFirstCallbackNode=function(){return c(v)},l.unstable_next=function(G){switch(w){case 1:case 2:case 3:var it=3;break;default:it=w}var tt=w;w=it;try{return G()}finally{w=tt}},l.unstable_pauseExecution=function(){},l.unstable_requestPaint=function(){},l.unstable_runWithPriority=function(G,it){switch(G){case 1:case 2:case 3:case 4:case 5:break;default:G=3}var tt=w;w=G;try{return it()}finally{w=tt}},l.unstable_scheduleCallback=function(G,it,tt){var ot=l.unstable_now();switch(typeof tt=="object"&&tt!==null?(tt=tt.delay,tt=typeof tt=="number"&&0<tt?ot+tt:ot):tt=ot,G){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=tt+S,G={id:C++,callback:it,priorityLevel:G,startTime:tt,expirationTime:S,sortIndex:-1},tt>ot?(G.sortIndex=tt,i(p,G),c(v)===null&&G===c(p)&&(U?(Q($),$=-1):U=!0,_t(L,tt-ot))):(G.sortIndex=S,i(v,G),B||j||(B=!0,St())),G},l.unstable_shouldYield=K,l.unstable_wrapCallback=function(G){var it=w;return function(){var tt=w;w=it;try{return G.apply(this,arguments)}finally{w=tt}}}}(Io)),Io}var Dh;function Ug(){return Dh||(Dh=1,Po.exports=Ng()),Po.exports}var ts={exports:{}},ht={};/**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Bh;function Hg(){if(Bh)return ht;Bh=1;var l=Symbol.for("react.transitional.element"),i=Symbol.for("react.portal"),c=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),d=Symbol.for("react.consumer"),m=Symbol.for("react.context"),b=Symbol.for("react.forward_ref"),v=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),C=Symbol.for("react.lazy"),_=Symbol.iterator;function w(S){return S===null||typeof S!="object"?null:(S=_&&S[_]||S["@@iterator"],typeof S=="function"?S:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B=Object.assign,U={};function X(S,q,at){this.props=S,this.context=q,this.refs=U,this.updater=at||j}X.prototype.isReactComponent={},X.prototype.setState=function(S,q){if(typeof S!="object"&&typeof S!="function"&&S!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,S,q,"setState")},X.prototype.forceUpdate=function(S){this.updater.enqueueForceUpdate(this,S,"forceUpdate")};function Q(){}Q.prototype=X.prototype;function F(S,q,at){this.props=S,this.context=q,this.refs=U,this.updater=at||j}var V=F.prototype=new Q;V.constructor=F,B(V,X.prototype),V.isPureReactComponent=!0;var L=Array.isArray,O={H:null,A:null,T:null,S:null},$=Object.prototype.hasOwnProperty;function W(S,q,at,lt,J,bt){return at=bt.ref,{$$typeof:l,type:S,key:q,ref:at!==void 0?at:null,props:bt}}function gt(S,q){return W(S.type,q,void 0,void 0,void 0,S.props)}function K(S){return typeof S=="object"&&S!==null&&S.$$typeof===l}function y(S){var q={"=":"=0",":":"=2"};return"$"+S.replace(/[=:]/g,function(at){return q[at]})}var Y=/\/+/g;function et(S,q){return typeof S=="object"&&S!==null&&S.key!=null?y(""+S.key):q.toString(36)}function ct(){}function St(S){switch(S.status){case"fulfilled":return S.value;case"rejected":throw S.reason;default:switch(typeof S.status=="string"?S.then(ct,ct):(S.status="pending",S.then(function(q){S.status==="pending"&&(S.status="fulfilled",S.value=q)},function(q){S.status==="pending"&&(S.status="rejected",S.reason=q)})),S.status){case"fulfilled":return S.value;case"rejected":throw S.reason}}throw S}function _t(S,q,at,lt,J){var bt=typeof S;(bt==="undefined"||bt==="boolean")&&(S=null);var ft=!1;if(S===null)ft=!0;else switch(bt){case"bigint":case"string":case"number":ft=!0;break;case"object":switch(S.$$typeof){case l:case i:ft=!0;break;case C:return ft=S._init,_t(ft(S._payload),q,at,lt,J)}}if(ft)return J=J(S),ft=lt===""?"."+et(S,0):lt,L(J)?(at="",ft!=null&&(at=ft.replace(Y,"$&/")+"/"),_t(J,q,at,"",function(Yt){return Yt})):J!=null&&(K(J)&&(J=gt(J,at+(J.key==null||S&&S.key===J.key?"":(""+J.key).replace(Y,"$&/")+"/")+ft)),q.push(J)),1;ft=0;var ie=lt===""?".":lt+":";if(L(S))for(var At=0;At<S.length;At++)lt=S[At],bt=ie+et(lt,At),ft+=_t(lt,q,at,bt,J);else if(At=w(S),typeof At=="function")for(S=At.call(S),At=0;!(lt=S.next()).done;)lt=lt.value,bt=ie+et(lt,At++),ft+=_t(lt,q,at,bt,J);else if(bt==="object"){if(typeof S.then=="function")return _t(St(S),q,at,lt,J);throw q=String(S),Error("Objects are not valid as a React child (found: "+(q==="[object Object]"?"object with keys {"+Object.keys(S).join(", ")+"}":q)+"). If you meant to render a collection of children, use an array instead.")}return ft}function G(S,q,at){if(S==null)return S;var lt=[],J=0;return _t(S,lt,"","",function(bt){return q.call(at,bt,J++)}),lt}function it(S){if(S._status===-1){var q=S._result;q=q(),q.then(function(at){(S._status===0||S._status===-1)&&(S._status=1,S._result=at)},function(at){(S._status===0||S._status===-1)&&(S._status=2,S._result=at)}),S._status===-1&&(S._status=0,S._result=q)}if(S._status===1)return S._result.default;throw S._result}var tt=typeof reportError=="function"?reportError:function(S){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var q=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof S=="object"&&S!==null&&typeof S.message=="string"?String(S.message):String(S),error:S});if(!window.dispatchEvent(q))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",S);return}console.error(S)};function ot(){}return ht.Children={map:G,forEach:function(S,q,at){G(S,function(){q.apply(this,arguments)},at)},count:function(S){var q=0;return G(S,function(){q++}),q},toArray:function(S){return G(S,function(q){return q})||[]},only:function(S){if(!K(S))throw Error("React.Children.only expected to receive a single React element child.");return S}},ht.Component=X,ht.Fragment=c,ht.Profiler=s,ht.PureComponent=F,ht.StrictMode=o,ht.Suspense=v,ht.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=O,ht.act=function(){throw Error("act(...) is not supported in production builds of React.")},ht.cache=function(S){return function(){return S.apply(null,arguments)}},ht.cloneElement=function(S,q,at){if(S==null)throw Error("The argumeLine truncated
* @license React
* react-dom.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Uh;function jg(){if(Uh)return de;Uh=1;var l=_s();function i(v){var p="https://react.dev/errors/"+v;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var C=2;C<arguments.length;C++)p+="&args[]="+encodeURIComponent(arguments[C])}return"Minified React error #"+v+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function c(){}var o={d:{f:c,r:function(){throw Error(i(522))},D:c,C:c,L:c,m:c,X:c,S:c,M:c},p:0,findDOMNode:null},s=Symbol.for("react.portal");function d(v,p,C){var _=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:_==null?null:""+_,children:v,containerInfo:p,implementation:C}}var m=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function b(v,p){if(v==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return de.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=o,de.createPortal=function(v,p){var C=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(i(299));return d(v,p,null,C)},de.flushSync=function(v){var p=m.T,C=o.p;try{if(m.T=null,o.p=2,v)return v()}finally{m.T=p,o.p=C,o.d.f()}},de.preconnect=function(v,p){typeof v=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,o.d.C(v,p))},de.prefetchDNS=function(v){typeof v=="string"&&o.d.D(v)},de.preinit=function(v,p){if(typeof v=="string"&&p&&typeof p.as=="string"){var C=p.as,_=b(C,p.crossOrigin),w=typeof p.integrity=="string"?p.integrity:void 0,j=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;C==="style"?o.d.S(v,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:_,integrity:w,fetchPriority:j}):C==="script"&&o.d.X(v,{crossOrigin:_,integrity:w,fetchPriority:j,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},de.preinitModule=function(v,p){if(typeof v=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var C=b(p.as,p.crossOrigin);o.d.M(v,{crossOrigin:C,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&o.d.M(v)},de.preload=function(v,p){if(typeof v=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var C=p.as,_=b(C,p.crossOrigin);o.d.L(v,C,{crossOrigin:_,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},de.preloadModule=function(v,p){if(typeof v=="string")if(p){var C=b(p.as,p.crossOrigin);o.d.m(v,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:C,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else o.d.m(v)},de.requestFormReset=function(v){o.d.r(v)},de.unstable_batchedUpdates=function(v,p){return v(p)},de.useFormState=function(v,p,C){return m.H.useFormState(v,p,C)},de.useFormStatus=function(){return m.H.useHostTransitionStatus()},de.version="19.0.0",de}var Hh;function qg(){if(Hh)return es.exports;Hh=1;function l(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(l)}catch(i){console.error(i)}}return l(),es.exports=jg(),es.exports}/**
* @license React
* react-dom-client.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var jh;function Lg(){if(jh)return Hi;jh=1;var l=Ug(),i=_s(),c=qg();function o(t){var e="https://react.dev/errors/"+t;if(1<arguments.length){e+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)e+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}var d=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),b=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),p=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),_=Symbol.for("react.provider"),w=Symbol.for("react.consumer"),j=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),U=Symbol.for("react.suspense"),X=Symbol.for("react.suspense_list"),Q=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),V=Symbol.for("react.offscreen"),L=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function $(t){return t===null||typeof t!="object"?null:(t=O&&t[O]||t["@@iterator"],typeof t=="function"?t:null)}var W=Symbol.for("react.client.reference");function gt(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===W?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case v:return"Fragment";case b:return"Portal";case C:return"Profiler";case p:return"StrictMode";case U:return"Suspense";case X:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case j:return(t.displayName||"Context")+".Provider";case w:return(t._context.displayName||"Context")+".Consumer";case B:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Q:return e=t.displayName||null,e!==null?e:gt(t.type)||"Memo";case F:e=t._payload,t=t._init;try{return gt(t(e))}catch{}}return null}var K=i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,y=Object.assign,Y,et;function ct(t){if(Y===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);Y=e&&e[1]||"",et=-1<n.stack.indexOf(`
at`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return`
`+Y+t+et}var St=!1;function _t(t,e){if(!t||St)return"";St=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(e){var H=function(){throw Error()};if(Object.defineProperty(H.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(H,[])}catch(M){var z=M}Reflect.construct(t,[],H)}else{try{H.call()}catch(M){z=M}t.call(H.prototype)}}else{try{throw Error()}catch(M){z=M}(H=t())&&typeof H.catch=="function"&&H.catch(function(){})}}catch(M){if(M&&z&&typeof M.stack=="string")return[M.stack,z.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var u=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");u&&u.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var r=a.DetermineComponentFrameRoot(),f=r[0],h=r[1];if(f&&h){var g=f.split(`
`),A=h.split(`
`);for(u=a=0;a<g.length&&!g[a].includes("DetermineComponentFrameRoot");)a++;for(;u<A.length&&!A[u].includes("DetermineComponentFrameRoot");)u++;if(a===g.length||u===A.length)for(a=g.length-1,u=A.length-1;1<=a&&0<=u&&g[a]!==A[u];)u--;for(;1<=a&&0<=u;a--,u--)if(g[a]!==A[u]){if(a!==1||u!==1)do if(a--,u--,0>u||g[a]!==A[u]){var D=`
`+g[a].replace(" at new "," at ");return t.displayName&&D.includes("<anonymous>")&&(D=D.replace("<anonymous>",t.displayName)),D}while(1<=a&&0<=u);break}}}finally{St=!1,Error.prepareStackTrace=n}return(n=t?t.displayName||t.name:"")?ct(n):""}function G(t){switch(t.tag){case 26:case 27:case 5:return ct(t.type);case 16:return ct("Lazy");case 13:return ct("Suspense");case 19:return ct("SuspenseList");case 0:case 15:return t=_t(t.type,!1),t;case 11:return t=_t(t.type.render,!1),t;case 1:return t=_t(t.type,!0),t;default:return""}}function it(t){try{var e="";do e+=G(t),t=t.return;while(t);return e}catch(n){return`
Error generating stack: `+n.message+`
`+n.stack}}function tt(t){var e=t,n=t;if(t.alternate)for(;e.return;)e=e.return;else{t=e;do e=t,e.flags&4098&&(n=e.return),t=e.return;while(t)}return e.tag===3?n:null}function ot(t){if(t.tag===13){var e=t.memoizedState;if(e===null&&(t=t.alternate,t!==null&&(e=t.memoizedState)),e!==null)return e.dehydrated}return null}function S(t){if(tt(t)!==t)throw Error(o(188))}function q(t){var e=t.alternate;if(!e){if(e=tt(t),e===null)throw Error(o(188));return e!==t?null:t}for(var n=t,a=e;;){var u=n.return;if(u===null)break;var r=u.alternate;if(r===null){if(a=u.return,a!==null){n=a;continue}break}if(u.child===r.child){for(r=u.child;r;){if(r===n)return S(u),t;if(r===a)return S(u),e;r=r.sibling}throw Error(o(188))}if(n.return!==a.return)n=u,a=r;else{for(var f=!1,h=u.child;h;){if(h===n){f=!0,n=u,a=r;break}if(h===a){f=!0,a=u,n=r;break}h=h.sibling}if(!f){for(h=r.child;h;){if(h===n){f=!0,n=r,a=u;break}if(h===a){f=!0,a=r,n=u;break}h=h.sibling}if(!f)throw Error(o(189))}}if(n.alternate!==a)throw Error(o(190))}if(n.tag!==3)throw Error(o(188));return n.stateNode.current===n?t:e}function at(t){var e=t.tag;if(e===5||e===26||e===27||e===6)return t;for(t=t.child;t!==null;){if(e=at(t),e!==null)return e;t=t.sibling}return null}var lt=Array.isArray,J=c.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,bt={pending:!1,data:null,method:null,action:null},ft=[],ie=-1;function At(t){return{current:t}}function Yt(t){0>ie||(t.current=ft[ie],ft[ie]=null,ie--)}function Nt(t,e){ie++,ft[ie]=t.current,t.current=e}var De=At(null),oa=At(null),tn=At(null),Un=At(null);function Ha(t,e){switch(Nt(tn,e),Nt(oa,t),Nt(De,null),t=e.nodeType,t){case 9:case 11:e=(e=e.documentElement)&&(e=e.namespaceURI)?lh(e):0;break;default:if(t=t===8?e.parentNode:e,e=t.tagName,t=t.namespaceURI)t=lh(t),e=ih(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Yt(De),Nt(De,e)}function Hn(){Yt(De),Yt(oa),Yt(tn)}function jn(t){t.memoizedState!==null&&Nt(Un,t);var e=De.current,n=ih(e,t.type);e!==n&&(Nt(oa,t),Nt(De,n))}function en(t){oa.current===t&&(Yt(De),Yt(oa)),Un.current===t&&(Yt(Un),wi._currentValue=bt)}var Hl=Object.prototype.hasOwnProperty,ja=l.unstable_scheduleCallback,jl=l.unstable_cancelCallback,dt=l.unstable_shouldYield,ry=l.unstable_requestPaint,nn=l.unstable_now,cy=l.unstable_getCurrentPriorityLevel,Qs=l.unstable_ImmediatePriority,Zs=l.unstable_UserBlockingPriority,tu=l.unstable_NormalPriority,oy=l.unstable_LowPriority,Ks=l.unstable_IdlePriority,sy=l.log,fy=l.unstable_setDisableYieldValue,ql=null,Te=null;function dy(t){if(Te&&typeof Te.onCommitFiberRoot=="function")try{Te.onCommitFiberRoot(ql,t,void 0,(t.current.flags&128)===128)}catch{}}function qn(t){if(typeof sy=="function"&&fy(t),Te&&typeof Te.setStrictMode=="function")try{Te.setStrictMode(ql,t)}catch{}}var Ae=Math.clz32?Math.clz32:yy,hy=Math.log,my=Math.LN2;function yy(t){return t>>>=0,t===0?32:31-(hy(t)/my|0)|0}var eu=128,nu=4194304;function sa(t){var e=t&42;if(e!==0)return e;switch(t&-t){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: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&4194176;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function au(t,e){var n=t.pendingLanes;if(n===0)return 0;var a=0,u=t.suspendedLanes,r=t.pingedLanes,f=t.warmLanes;t=t.finishedLanes!==0;var h=n&134217727;return h!==0?(n=h&~u,n!==0?a=sa(n):(r&=h,r!==0?a=sa(r):t||(f=h&~f,f!==0&&(a=sa(f))))):(h=n&~u,h!==0?a=sa(h):r!==0?a=sa(r):t||(f=n&~f,f!==0&&(a=sa(f)))),a===0?0:e!==0&&e!==a&&!(e&u)&&(u=a&-a,f=e&-e,u>=f||u===32&&(f&4194176)!==0)?e:a}function Ll(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function py(t,e){switch(t){case 1:case 2:case 4:case 8:return e+250;case 16:case 32:case 64: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 e+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 Ws(){var t=eu;return eu<<=1,!(eu&4194176)&&(eu=128),t}function Js(){var t=nu;return nu<<=1,!(nu&62914560)&&(nu=4194304),t}function $r(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function Gl(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function gy(t,e,n,a,u,r){var f=t.pendingLanes;t.pendingLanes=n,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=n,t.entangledLanes&=n,t.errorRecoveryDisabledLanes&=n,t.shellSuspendCounter=0;var h=t.entanglements,g=t.expirationTimes,A=t.hiddenUpdates;for(n=f&~n;0<n;){var D=31-Ae(n),H=1<<D; Line truncated
`).replace(Fp,"")}function ah(t,e){return e=nh(e),nh(t)===e}function Fu(){}function Rt(t,e,n,a,u,r){switch(n){case"children":typeof a=="string"?e==="body"||e==="textarea"&&a===""||Xa(t,a):(typeof a=="number"||typeof a=="bigint")&&e!=="body"&&Xa(t,""+a);break;case"className":iu(t,"class",a);break;case"tabIndex":iu(t,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":iu(t,n,a);break;case"style":hf(t,a,r);break;case"data":if(e!=="object"){iu(t,"data",a);break}case"src":case"href":if(a===""&&(e!=="a"||n!=="href")){t.removeAttribute(n);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(n);break}a=cu(""+a),t.setAttribute(n,a);break;case"action":case"formAction":if(typeof a=="function"){t.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 r=="function"&&(n==="formAction"?(e!=="input"&&Rt(t,e,"name",u.name,u,null),Rt(t,e,"formEncType",u.formEncType,u,null),Rt(t,e,"formMethod",u.formMethod,u,null),Rt(t,e,"formTarget",u.formTarget,u,null)):(Rt(t,e,"encType",u.encType,u,null),Rt(t,e,"method",u.method,u,null),Rt(t,e,"target",u.target,u,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(n);break}a=cu(""+a),t.setAttribute(n,a);break;case"onClick":a!=null&&(t.onclick=Fu);break;case"onScroll":a!=null&&vt("scroll",t);break;case"onScrollEnd":a!=null&&vt("scrollend",t);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(n=a.__html,n!=null){if(u.children!=null)throw Error(o(60));t.innerHTML=n}}break;case"multiple":t.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":t.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){t.removeAttribute("xlink:href");break}n=cu(""+a),t.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":a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(n,""+a):t.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":a&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(n,""):t.removeAttribute(n);break;case"capture":case"download":a===!0?t.setAttribute(n,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(n,a):t.removeAttribute(n);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?t.setAttribute(n,a):t.removeAttribute(n);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?t.removeAttribute(n):t.setAttribute(n,a);break;case"popover":vt("beforetoggle",t),vt("toggle",t),lu(t,"popover",a);break;case"xlinkActuate":yn(t,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":yn(t,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":yn(t,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":yn(t,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":yn(t,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":yn(t,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":yn(t,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":yn(t,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":yn(t,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":lu(t,"is",a);break;case"innerText":case"textContent":break;default:(!(2<n.length)||n[0]!=="o"&&n[0]!=="O"||n[1]!=="n"&&n[1]!=="N")&&(n=Oy.get(n)||n,lu(t,n,a))}}function No(t,e,n,a,u,r){switch(n){case"style":hf(t,a,r);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(n=a.__html,n!=null){if(u.children!=null)throw Error(o(60));t.innerHTML=n}}break;case"children":typeof a=="string"?Xa(t,a):(typeof a=="number"||typeof a=="bigint")&&Xa(t,""+a);break;case"onScroll":a!=null&&vt("scroll",t);break;case"onScrollEnd":a!=null&&vt("scrollend",t);break;case"onClick":a!=null&&(t.onclick=Fu);break;case"suppressContentEditableWarning":case"suppressHydrationWar Line truncated
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Xh;function v1(){if(Xh)return zt;Xh=1;var l=typeof Symbol=="function"&&Symbol.for,i=l?Symbol.for("react.element"):60103,c=l?Symbol.for("react.portal"):60106,o=l?Symbol.for("react.fragment"):60107,s=l?Symbol.for("react.strict_mode"):60108,d=l?Symbol.for("react.profiler"):60114,m=l?Symbol.for("react.provider"):60109,b=l?Symbol.for("react.context"):60110,v=l?Symbol.for("react.async_mode"):60111,p=l?Symbol.for("react.concurrent_mode"):60111,C=l?Symbol.for("react.forward_ref"):60112,_=l?Symbol.for("react.suspense"):60113,w=l?Symbol.for("react.suspense_list"):60120,j=l?Symbol.for("react.memo"):60115,B=l?Symbol.for("react.lazy"):60116,U=l?Symbol.for("react.block"):60121,X=l?Symbol.for("react.fundamental"):60117,Q=l?Symbol.for("react.responder"):60118,F=l?Symbol.for("react.scope"):60119;function V(O){if(typeof O=="object"&&O!==null){var $=O.$$typeof;switch($){case i:switch(O=O.type,O){case v:case p:case o:case d:case s:case _:return O;default:switch(O=O&&O.$$typeof,O){case b:case C:case B:case j:case m:return O;default:return $}}case c:return $}}}function L(O){return V(O)===p}return zt.AsyncMode=v,zt.ConcurrentMode=p,zt.ContextConsumer=b,zt.ContextProvider=m,zt.Element=i,zt.ForwardRef=C,zt.Fragment=o,zt.Lazy=B,zt.Memo=j,zt.Portal=c,zt.Profiler=d,zt.StrictMode=s,zt.Suspense=_,zt.isAsyncMode=function(O){return L(O)||V(O)===v},zt.isConcurrentMode=L,zt.isContextConsumer=function(O){return V(O)===b},zt.isContextProvider=function(O){return V(O)===m},zt.isElement=function(O){return typeof O=="object"&&O!==null&&O.$$typeof===i},zt.isForwardRef=function(O){return V(O)===C},zt.isFragment=function(O){return V(O)===o},zt.isLazy=function(O){return V(O)===B},zt.isMemo=function(O){return V(O)===j},zt.isPortal=function(O){return V(O)===c},zt.isProfiler=function(O){return V(O)===d},zt.isStrictMode=function(O){return V(O)===s},zt.isSuspense=function(O){return V(O)===_},zt.isValidElementType=function(O){return typeof O=="string"||typeof O=="function"||O===o||O===p||O===d||O===s||O===_||O===w||typeof O=="object"&&O!==null&&(O.$$typeof===B||O.$$typeof===j||O.$$typeof===m||O.$$typeof===b||O.$$typeof===C||O.$$typeof===X||O.$$typeof===Q||O.$$typeof===F||O.$$typeof===U)},zt.typeOf=V,zt}var $h;function S1(){return $h||($h=1,ns.exports=v1()),ns.exports}var as,kh;function T1(){if(kh)return as;kh=1;var l=S1(),i={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},c={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},o={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},s={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},d={};d[l.ForwardRef]=o,d[l.Memo]=s;function m(B){return l.isMemo(B)?s:d[B.$$typeof]||i}var b=Object.defineProperty,v=Object.getOwnPropertyNames,p=Object.getOwnPropertySymbols,C=Object.getOwnPropertyDescriptor,_=Object.getPrototypeOf,w=Object.prototype;function j(B,U,X){if(typeof U!="string"){if(w){var Q=_(U);Q&&Q!==w&&j(B,Q,X)}var F=v(U);p&&(F=F.concat(p(U)));for(var V=m(B),L=m(U),O=0;O<F.length;++O){var $=F[O];if(!c[$]&&!(X&&X[$])&&!(L&&L[$])&&!(V&&V[$])){var W=C(U,$);try{b(B,$,W)}catch{}}}}return B}return as=j,as}T1();var A1=!0;function Cm(l,i,c){var o="";return c.split(" ").forEach(function(s){l[s]!==void 0?i.push(l[s]+";"):s&&(o+=s+" ")}),o}var Rs=function(i,c,o){var s=i.key+"-"+c.name;(o===!1||A1===!1)&&i.registered[s]===void 0&&(i.registered[s]=c.styles)},Ms=function(i,c,o){Rs(i,c,o);var s=i.key+"-"+c.name;if(i.inserted[c.name]===void 0){var d=c;do i.insert(c===d?"."+s:"",d,i.sheet,!0),d=d.next;while(d!==void 0)}};function E1(l){for(var i=0,c,o=0,s=l.length;s>=4;++o,s-=4)c=l.charCodeAt(o)&255|(l.charCodeAt(++o)&255)<<8|(l.charCodeAt(++o)&255)<<16|(l.charCodeAt(++o)&255)<<24,c=(c&65535)*1540483477+((c>>>16)*59797<<16),c^=c>>>24,i=(c&65535)*1540483477+((c>>>16)*59797<<16)^(i&65535)*1540483477+((i>>>16)*59797<<16);switch(s){case 3:i^=(l.charCodeAt(o+2)&255)<<16;case 2:i^=(l.charCodeAt(o+1)&255)<<8;case 1:i^=l.charCodeAt(o)&255,i=(i&65535)*1540483477+((i>>>16)*59797<<16)}return i^=i>>>13,i=(i&65535)*1540483477+((i>>>16)*59797<<16),((i^i>>>15)>>>0).toString(36)}var x1={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},_1=/[A-Z]|^ms/g,O1=/_EMO_([^_]+?)_([^]*?)_EMO_/g,zm=function(i){return i.charCodeAt(1)===45},Qh=functioLine truncated
* @mui/styled-engine v6.3.0
*
* @license MIT
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/function Dm(l,i){return hs(l,i)}function k1(l,i){Array.isArray(l.__emotion_styles)&&(l.__emotion_styles=i(l.__emotion_styles))}const Ph=[];function Ih(l){return Ph[0]=l,Wi(Ph)}function dn(l){if(typeof l!="object"||l===null)return!1;const i=Object.getPrototypeOf(l);return(i===null||i===Object.prototype||Object.getPrototypeOf(i)===null)&&!(Symbol.toStringTag in l)&&!(Symbol.iterator in l)}function Bm(l){if(k.isValidElement(l)||!dn(l))return l;const i={};return Object.keys(l).forEach(c=>{i[c]=Bm(l[c])}),i}function Me(l,i,c={clone:!0}){const o=c.clone?{...l}:l;return dn(l)&&dn(i)&&Object.keys(i).forEach(s=>{k.isValidElement(i[s])?o[s]=i[s]:dn(i[s])&&Object.prototype.hasOwnProperty.call(l,s)&&dn(l[s])?o[s]=Me(l[s],i[s],c):c.clone?o[s]=dn(i[s])?Bm(i[s]):i[s]:o[s]=i[s]}),o}const Q1=l=>{const i=Object.keys(l).map(c=>({key:c,val:l[c]}))||[];return i.sort((c,o)=>c.val-o.val),i.reduce((c,o)=>({...c,[o.key]:o.val}),{})};function Z1(l){const{values:i={xs:0,sm:600,md:900,lg:1200,xl:1536},unit:c="px",step:o=5,...s}=l,d=Q1(i),m=Object.keys(d);function b(w){return`@media (min-width:${typeof i[w]=="number"?i[w]:w}${c})`}function v(w){return`@media (max-width:${(typeof i[w]=="number"?i[w]:w)-o/100}${c})`}function p(w,j){const B=m.indexOf(j);return`@media (min-width:${typeof i[w]=="number"?i[w]:w}${c}) and (max-width:${(B!==-1&&typeof i[m[B]]=="number"?i[m[B]]:j)-o/100}${c})`}function C(w){return m.indexOf(w)+1<m.length?p(w,m[m.indexOf(w)+1]):b(w)}function _(w){const j=m.indexOf(w);return j===0?b(m[1]):j===m.length-1?v(m[j]):p(w,m[m.indexOf(w)+1]).replace("@media","@media not all and")}return{keys:m,values:d,up:b,down:v,between:p,only:C,not:_,unit:c,...s}}function K1(l,i){if(!l.containerQueries)return i;const c=Object.keys(i).filter(o=>o.startsWith("@container")).sort((o,s)=>{var m,b;const d=/min-width:\s*([0-9.]+)/;return+(((m=o.match(d))==null?void 0:m[1])||0)-+(((b=s.match(d))==null?void 0:b[1])||0)});return c.length?c.reduce((o,s)=>{const d=i[s];return delete o[s],o[s]=d,o},{...i}):i}function W1(l,i){return i==="@"||i.startsWith("@")&&(l.some(c=>i.startsWith(`@${c}`))||!!i.match(/^@\d/))}function J1(l,i){const c=i.match(/^@([^/]+)?\/?(.+)?$/);if(!c)return null;const[,o,s]=c,d=Number.isNaN(+o)?o||0:+o;return l.containerQueries(s).up(d)}function F1(l){const i=(d,m)=>d.replace("@media",m?`@container ${m}`:"@container");function c(d,m){d.up=(...b)=>i(l.breakpoints.up(...b),m),d.down=(...b)=>i(l.breakpoints.down(...b),m),d.between=(...b)=>i(l.breakpoints.between(...b),m),d.only=(...b)=>i(l.breakpoints.only(...b),m),d.not=(...b)=>{const v=i(l.breakpoints.not(...b),m);return v.includes("not all and")?v.replace("not all and ","").replace("min-width:","width<").replace("max-width:","width>").replace("and","or"):v}}const o={},s=d=>(c(o,d),o);return c(s),{...l,containerQueries:s}}const P1={borderRadius:4};function Yi(l,i){return i?Me(l,i,{clone:!1}):l}const Br={xs:0,sm:600,md:900,lg:1200,xl:1536},tm={keys:["xs","sm","md","lg","xl"],up:l=>`@media (min-width:${Br[l]}px)`},I1={containerQueries:l=>({up:i=>{let c=typeof i=="number"?i:Br[i]||i;return typeof c=="number"&&(c=`${c}px`),l?`@container ${l} (min-width:${c})`:`@container (min-width:${c})`}})};function Nn(l,i,c){const o=l.theme||{};if(Array.isArray(i)){const d=o.breakpoints||tm;return i.reduce((m,b,v)=>(m[d.up(d.keys[v])]=c(i[v]),m),{})}if(typeof i=="object"){const d=o.breakpoints||tm;return Object.keys(i).reduce((m,b)=>{if(W1(d.keys,b)){const v=J1(o.containerQueries?o:I1,b);v&&(m[v]=c(i[b],b))}else if(Object.keys(d.values||Br).includes(b)){const v=d.up(b);m[v]=c(i[b],b)}else{const v=b;m[v]=i[v]}return m},{})}return c(i)}function tb(l={}){var c;return((c=l.keys)==null?void 0:c.reduce((o,s)=>{const d=l.up(s);return o[d]={},o},{}))||{}}function eb(l,i){return l.reduce((c,o)=>{const s=c[o];return(!s||Object.keys(s).length===0)&&delete c[o],c},i)}function jt(l){if(typeof l!="string")throw new Error(Ba(7));return l.charAt(0).toUpperCase()+l.slice(1)}function Nr(l,i,c=!0){if(!i||typeof i!="string")return null;if(l&&l.vars&&c){const o=`vars.${i}`.split(".").reduce((s,d)=>s&&s[d]?s[d]:null,l);if(o!=null)return o}return i.split(".").reduce((o,s)=>o&&o[s]!=null?o[s]:null,l)}function _r(l,i,c,o=c){let s;return typeof l=="function"?s=l(c):Array.isArray(l)?s=l[c]||o:s=Nr(l,c)||o,i&&(s=i(s,o,l)),s}function Kt(l){const{prop:i,cssProperty:c=l.prop,themeKey:o,transform:s}=l,d=m=>{if(m[i]==null)return null;const b=m[i],v=m.theme,p=Nr(v,o)||{};return Nn(m,b,_=>{let w=_r(p,s,_);return _===w&&typeof _=="string"&&(w=_r(p,s,`${i}${_==="default"?"":jt(_)}`,_)),c===!1?w:{[c]:w}})};return d.propTypes={},d.filterProps=[i],d}function nb(l){const i={};return c=>(i[c]===void 0&&(i[c]=l(c)),i[c])}const ab={m:"margin",p:"padding"},lb={t:"Top",r:"Right",b:"Bottom",l:"Left",x:["Left","Right"],y:["Top","Bottom"]},em={marginX:"mx",marginY:"my",paddingX:"px",paddingY:"py"},ib=nb(l=>{if(l.length>2)if(em[l])l=em[l];else return[l];const[i,c]=l.split(""),o=ab[i],s=lb[c]||"";return Array.isArray(s)?s.map(d=>o+d):[o+s]Line truncated
const theme = ${JSON.stringify(i,null,2)};
theme.breakpoints = createBreakpoints(theme.breakpoints || {});
theme.transitions = createTransitions(theme.transitions || {});
export default theme;`}function ys(l={},...i){const{breakpoints:c,mixins:o={},spacing:s,palette:d={},transitions:m={},typography:b={},shape:v,...p}=l;if(l.vars)throw new Error(Ba(20));const C=Ys(d),_=qs(l);let w=Me(_,{mixins:Bv(_.breakpoints,o),palette:C,shadows:Lv.slice(),typography:Uv(C,b),transitions:Xv(m),zIndex:{...$v}});return w=Me(w,p),w=i.reduce((j,B)=>Me(j,B),w),w.unstable_sxConfig={...Pi,...p==null?void 0:p.unstable_sxConfig},w.unstable_sx=function(B){return Na({sx:B,theme:this})},w.toRuntimeSource=Qm,w}function Qv(l){let i;return l<1?i=5.11916*l**2:i=4.5*Math.log(l+1)+2,Math.round(i*10)/1e3}const Zv=[...Array(25)].map((l,i)=>{if(i===0)return"none";const c=Qv(i);return`linear-gradient(rgba(255 255 255 / ${c}), rgba(255 255 255 / ${c}))`});function Zm(l){return{inputPlaceholder:l==="dark"?.5:.42,inputUnderline:l==="dark"?.7:.42,switchTrackDisabled:l==="dark"?.2:.12,switchTrack:l==="dark"?.3:.38}}function Km(l){return l==="dark"?Zv:[]}function Kv(l){const{palette:i={mode:"light"},opacity:c,overlays:o,...s}=l,d=Ys(i);return{palette:d,opacity:{...Zm(d.mode),...c},overlays:o||Km(d.mode),...s}}function Wv(l){var i;return!!l[0].match(/(cssVarPrefix|colorSchemeSelector|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!l[0].match(/sxConfig$/)||l[0]==="palette"&&!!((i=l[1])!=null&&i.match(/(mode|contrastThreshold|tonalOffset)/))}const Jv=l=>[...[...Array(25)].map((i,c)=>`--${l?`${l}-`:""}overlays-${c}`),`--${l?`${l}-`:""}palette-AppBar-darkBg`,`--${l?`${l}-`:""}palette-AppBar-darkColor`],Fv=l=>(i,c)=>{const o=l.rootSelector||":root",s=l.colorSchemeSelector;let d=s;if(s==="class"&&(d=".%s"),s==="data"&&(d="[data-%s]"),s!=null&&s.startsWith("data-")&&!s.includes("%s")&&(d=`[${s}="%s"]`),l.defaultColorScheme===i){if(i==="dark"){const m={};return Jv(l.cssVarPrefix).forEach(b=>{m[b]=c[b],delete c[b]}),d==="media"?{[o]:c,"@media (prefers-color-scheme: dark)":{[o]:m}}:d?{[d.replace("%s",i)]:m,[`${o}, ${d.replace("%s",i)}`]:c}:{[o]:{...c,...m}}}if(d&&d!=="media")return`${o}, ${d.replace("%s",String(i))}`}else if(i){if(d==="media")return{[`@media (prefers-color-scheme: ${String(i)})`]:{[o]:c}};if(d)return d.replace("%s",String(i))}return o};function Pv(l,i){i.forEach(c=>{l[c]||(l[c]={})})}function R(l,i,c){!l[i]&&c&&(l[i]=c)}function Gi(l){return typeof l!="string"||!l.startsWith("hsl")?l:Vm(l)}function Mn(l,i){`${i}Channel`in l||(l[`${i}Channel`]=Li(Gi(l[i])))}function Iv(l){return typeof l=="number"?`${l}px`:typeof l=="string"||typeof l=="function"||Array.isArray(l)?l:"8px"}const on=l=>{try{return l()}catch{}},tS=(l="mui")=>Sv(l);function rs(l,i,c,o){if(!i)return;i=i===!0?{}:i;const s=o==="dark"?"dark":"light";if(!c){l[o]=Kv({...i,palette:{mode:s,...i==null?void 0:i.palette}});return}const{palette:d,...m}=ys({...c,palette:{mode:s,...i==null?void 0:i.palette}});return l[o]={...i,palette:d,opacity:{...Zm(s),...i==null?void 0:i.opacity},overlays:(i==null?void 0:i.overlays)||Km(s)},m}function eS(l={},...i){const{colorSchemes:c={light:!0},defaultColorScheme:o,disableCssColorScheme:s=!1,cssVarPrefix:d="mui",shouldSkipGeneratingVar:m=Wv,colorSchemeSelector:b=c.light&&c.dark?"media":void 0,rootSelector:v=":root",...p}=l,C=Object.keys(c)[0],_=o||(c.light&&C!=="light"?"light":C),w=tS(d),{[_]:j,light:B,dark:U,...X}=c,Q={...X};let F=j;if((_==="dark"&&!("dark"in c)||_==="light"&&!("light"in c))&&(F=!0),!F)throw new Error(Ba(21,_));const V=rs(Q,F,p,_);B&&!Q.light&&rs(Q,B,void 0,"light"),U&&!Q.dark&&rs(Q,U,void 0,"dark");let L={defaultColorScheme:_,...V,cssVarPrefix:d,colorSchemeSelector:b,rootSelector:v,getCssVar:w,colorSchemes:Q,font:{...Dv(V.typography),...V.font},spacing:Iv(p.spacing)};Object.keys(L.colorSchemes).forEach(K=>{const y=L.colorSchemes[K].palette,Y=et=>{const ct=et.split("-"),St=ct[1],_t=ct[2];return w(et,y[St][_t])};if(y.mode==="light"&&(R(y.common,"background","#fff"),R(y.common,"onBackground","#000")),y.mode==="dark"&&(R(y.common,"background","#000"),R(y.common,"onBackground","#fff")),Pv(y,["Alert","AppBar","Avatar","Button","Chip","FilledInput","LinearProgress","Skeleton","Slider","SnackbarContent","SpeedDialAction","StepConnector","StepContent","Switch","TableCell","Tooltip"]),y.mode==="light"){R(y.Alert,"errorColor",Dt(y.error.light,.6)),R(y.Alert,"infoColor",Dt(y.info.light,.6)),R(y.Alert,"successColor",Dt(y.success.light,.6)),R(y.Alert,"warningColor",Dt(y.warning.light,.6)),R(y.Alert,"errorFilledBg",Y("palette-error-main")),R(y.Alert,"infoFilledBg",Y("palette-info-main")),R(y.Alert,"successFilledBg",Y("palette-success-main")),R(y.Alert,"warningFilledBg",Y("palette-warning-main")),R(y.Alert,"errorFilledColor",on(()=>y.getContrastText(y.error.main))),R(y.Alert,"infoFilledColor",on(()=>y.getContrastText(y.info.main))),R(y.Alert,"successFilledColor",on(()=>y.getContrastText(y.success.main))),R(y.Alert,"warningFilledColor",on(()=>y.getContrastText(y.warning.main))),R(y.Alert,"errorStandardBg",Bt(y.error.light,.9)),R(y.Alert,"infoStandardBg",Bt(y.info.light,.9)),R(y.Alert,"successStandardB Line truncated
0% {
transform: scale(0);
opacity: 0.1;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`,bS=Dl`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`,vS=Dl`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`,SS=Ie("span",{name:"MuiTouchRipple",slot:"Root"})({overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:"inherit"}),TS=Ie(yS,{name:"MuiTouchRipple",slot:"Ripple"})`
opacity: 0;
position: absolute;
&.${ke.rippleVisible} {
opacity: 0.3;
transform: scale(1);
animation-name: ${gS};
animation-duration: ${gs}ms;
animation-timing-function: ${({theme:l})=>l.transitions.easing.easeInOut};
}
&.${ke.ripplePulsate} {
animation-duration: ${({theme:l})=>l.transitions.duration.shorter}ms;
}
& .${ke.child} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${ke.childLeaving} {
opacity: 0;
animation-name: ${bS};
animation-duration: ${gs}ms;
animation-timing-function: ${({theme:l})=>l.transitions.easing.easeInOut};
}
& .${ke.childPulsate} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${vS};
animation-duration: 2500ms;
animation-timing-function: ${({theme:l})=>l.transitions.easing.easeInOut};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`,AS=k.forwardRef(function(i,c){const o=Ul({props:i,name:"MuiTouchRipple"}),{center:s=!1,classes:d={},className:m,...b}=o,[v,p]=k.useState([]),C=k.useRef(0),_=k.useRef(null);k.useEffect(()=>{_.current&&(_.current(),_.current=null)},[v]);const w=k.useRef(!1),j=hv(),B=k.useRef(null),U=k.useRef(null),X=k.useCallback(L=>{const{pulsate:O,rippleX:$,rippleY:W,rippleSize:gt,cb:K}=L;p(y=>[...y,rt.jsx(TS,{classes:{ripple:pe(d.ripple,ke.ripple),rippleVisible:pe(d.rippleVisible,ke.rippleVisible),ripplePulsate:pe(d.ripplePulsate,ke.ripplePulsate),child:pe(d.child,ke.child),childLeaving:pe(d.childLeaving,ke.childLeaving),childPulsate:pe(d.childPulsate,ke.childPulsate)},timeout:gs,pulsate:O,rippleX:$,rippleY:W,rippleSize:gt},C.current)]),C.current+=1,_.current=K},[d]),Q=k.useCallback((L={},O={},$=()=>{})=>{const{pulsate:W=!1,center:gt=s||O.pulsate,fakeElement:K=!1}=O;if((L==null?void 0:L.type)==="mousedown"&&w.current){w.current=!1;return}(L==null?void 0:L.type)==="touchstart"&&(w.current=!0);const y=K?null:U.current,Y=y?y.getBoundingClientRect():{width:0,height:0,left:0,top:0};let et,ct,St;if(gt||L===void 0||L.clientX===0&&L.clientY===0||!L.clientX&&!L.touches)et=Math.round(Y.width/2),ct=Math.round(Y.height/2);else{const{clientX:_t,clientY:G}=L.touches&&L.touches.length>0?L.touches[0]:L;et=Math.round(_t-Y.left),ct=Math.round(G-Y.top)}if(gt)St=Math.sqrt((2*Y.width**2+Y.height**2)/3),St%2===0&&(St+=1);else{const _t=Math.max(Math.abs((y?y.clientWidth:0)-et),et)*2+2,G=Math.max(Math.abs((y?y.clientHeight:0)-ct),ct)*2+2;St=Math.sqrt(_t**2+G**2)}L!=null&&L.touches?B.current===null&&(B.current=()=>{X({pulsate:W,rippleX:et,rippleY:ct,rippleSize:St,cb:$})},j.start(pS,()=>{B.current&&(B.current(),B.current=null)})):X({pulsate:W,rippleX:et,rippleY:ct,rippleSize:St,cb:$})},[s,X,j]),F=k.useCallback(()=>{Q({},{pulsate:!0})},[Q]),V=k.useCallback((L,O)=>{if(j.clear(),(L==null?void 0:L.type)==="touchend"&&B.current){B.current(),B.current=null,j.start(0,()=>{V(L,O)});return}B.current=null,p($=>$.length>0?$.slice(1):$),_.current=O},[j]);return k.useImperativeHandle(c,()=>({pulsate:F,start:Q,stop:V}),[F,Q,V]),rt.jsx(SS,{className:pe(ke.root,d.root,m),ref:U,...b,children:rt.jsx(Xs,{component:null,exit:!0,children:v})})});function ES(l){return Ii("MuiButtonBase",l)}const xS=Bl("MuiButtonBase",["root","disabled","focusVisible"]),_S=l=>{const{disabled:i,focusVisible:c,focusVisibleClassName:o,classes:s}=l,m=Xr({root:["root",i&&"disabled",c&&"focusVisible"]},ES,s);return c&&o&&(m.root+=` ${o}`),m},OS=Ie("button",{name:"MuiButtonBase",slot:"Root",overridesResolver:(l,i)=>i.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"},[`&.${xS.disabled}`]:{pointerEvents:"none",cursor:"default"},"@media print":{colorAdjust:"exact"}}),CS=k.forwardRef(function(i,c){const o=Ul({props:i,name:"MuiButtonBase"}),{action:s,centerRipple:d=!1,children:m,className:b,component:v="button",disabled:p=!1,disableRipple:C=!1,disableTouchRipple:_=!1,focusRipple:w=!1,focusVisibleClassName:j,LinkComponent:B="a",onBlur:U,onClick:X,onContextMenu:Q,onDragLeave:F,onFocus:V,onFocusVisible:L,onKeyDown:O,onKeyUp:$,onMouseDown:W,onMouseLeave:gt,onMouseUp:K,onTouchEnd:y,onTouchMove:Y,onTouchStart:et,tabIndex:ct=0,TouchRippleProps:St,touchRippleRef:_t,type:G,...it}=o,tt=k.useRef(null),ot=hS(),S=am(ot.ref,_t),[q,at]=k.useState(!1);p&&q&&at(!1),k.useImperativeHandle(s,()=>({focusVisible:()=>{at(!0),tt.current.focus()}}),[]);const lt=ot.shouldMount&&!C&&!p;k.useEffect(()=>{q&&w&&!C&&ot.pulsate()},[C,w,q,ot]);const J=Dn(ot,"start",W,_),bt=Dn(ot,"stop",Q,_),ft=Dn(ot,"stop",F,_),ie=Dn(ot,"stop",K,_),At=Dn(ot,"stop",dt=>{q&&dt.preventDefault(),gt&&gt(dt)},_),Yt=Dn(ot,"start",et,_),Nt=Dn(ot,"stop",y,_),De=Dn(ot,"stop",Y,_),oa=Dn(ot,"stop",dt=>{im(dt.target)||at(!1),U&&U(dt)},!1),tn=vr(dt=>{tt.current||(tt.current=dt.currentTarget),im(dt.target)&&(at(!0),L&&L(dt)),V&&V(dt)}),Un=()=>{const dt=tt.current;return v&&v!=="button"&&!(dt.tagName==="A"&&dt.href)},Ha=vr(dt=>{w&&!dt.repeat&&q&&dt.key===" "&&ot.stop(dt,()=>{ot.start(dt)}),dt.target===dt.currentTarget&&Un()&&dt.key===" "&&dt.preventDefault(),O&&O(dt),dt.target===dt.currentTarget&&Un()&&dt.key==="Enter"&&!p&&(dt.preventDefault(),X&&X(dt))}),Hn=vr(dt=>{w&&dt.key===" "&&q&&!dt.defaultPrevented&&ot.stop(dt,()=>{ot.pulsate(dt)}),$&&$(dt),X&&dt.target===dt.currentTarget&&Un()&&dt.key===" "&&!dt.defaultPrevented&&X(dt)});let jn=v;jn==="button"&&(it.href||it.to)&&(jn=B);const en={};jn==="button"?(en.type=G===void 0?"button":G,en.disabled=p):(!it.href&&!it.to&&(en.role="button"),p&&(en["aria-disabled"]=p));const Hl=am(c,tt),ja={...o,centerRipple:d,component:v,disabled:p,disableRipple:C,di Line truncated
0% {
left: -35%;
right: 100%;
}
60% {
left: 100%;
right: -90%;
}
100% {
left: 100%;
right: -90%;
}
`,FS=typeof Ss!="string"?Dr`
animation: ${Ss} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
`:null,Ts=Dl`
0% {
left: -200%;
right: 100%;
}
60% {
left: 107%;
right: -8%;
}
100% {
left: 107%;
right: -8%;
}
`,PS=typeof Ts!="string"?Dr`
animation: ${Ts} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
`:null,As=Dl`
0% {
opacity: 1;
background-position: 0 -23px;
}
60% {
opacity: 0;
background-position: 0 -23px;
}
100% {
opacity: 1;
background-position: -200px -23px;
}
`,IS=typeof As!="string"?Dr`
animation: ${As} 3s infinite linear;
`:null,t2=l=>{const{classes:i,variant:c,color:o}=l,s={root:["root",`color${jt(o)}`,c],dashed:["dashed",`dashedColor${jt(o)}`],bar1:["bar",`barColor${jt(o)}`,(c==="indeterminate"||c==="query")&&"bar1Indeterminate",c==="determinate"&&"bar1Determinate",c==="buffer"&&"bar1Buffer"],bar2:["bar",c!=="buffer"&&`barColor${jt(o)}`,c==="buffer"&&`color${jt(o)}`,(c==="indeterminate"||c==="query")&&"bar2Indeterminate",c==="buffer"&&"bar2Buffer"]};return Xr(s,JS,i)},ks=(l,i)=>l.vars?l.vars.palette.LinearProgress[`${i}Bg`]:l.palette.mode==="light"?Vr(l.palette[i].main,.62):Yr(l.palette[i].main,.5),e2=Ie("span",{name:"MuiLinearProgress",slot:"Root",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.root,i[`color${jt(c.color)}`],i[c.variant]]}})(Nl(({theme:l})=>({position:"relative",overflow:"hidden",display:"block",height:4,zIndex:0,"@media print":{colorAdjust:"exact"},variants:[...Object.entries(l.palette).filter(Ua()).map(([i])=>({props:{color:i},style:{backgroundColor:ks(l,i)}})),{props:({ownerState:i})=>i.color==="inherit"&&i.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)"}}]}))),n2=Ie("span",{name:"MuiLinearProgress",slot:"Dashed",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.dashed,i[`dashedColor${jt(c.color)}`]]}})(Nl(({theme:l})=>({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(l.palette).filter(Ua()).map(([i])=>{const c=ks(l,i);return{props:{color:i},style:{backgroundImage:`radial-gradient(${c} 0%, ${c} 16%, transparent 42%)`}}})]})),IS||{animation:`${As} 3s infinite linear`}),a2=Ie("span",{name:"MuiLinearProgress",slot:"Bar1",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.bar,i[`barColor${jt(c.color)}`],(c.variant==="indeterminate"||c.variant==="query")&&i.bar1Indeterminate,c.variant==="determinate"&&i.bar1Determinate,c.variant==="buffer"&&i.bar1Buffer]}})(Nl(({theme:l})=>({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(l.palette).filter(Ua()).map(([i])=>({props:{color:i},style:{backgroundColor:(l.vars||l).palette[i].main}})),{props:{variant:"determinate"},style:{transition:`transform .${vs}s linear`}},{props:{variant:"buffer"},style:{zIndex:1,transition:`transform .${vs}s linear`}},{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:{width:"auto"}},{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:FS||{animation:`${Ss} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}}]}))),l2=Ie("span",{name:"MuiLinearProgress",slot:"Bar2",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.bar,i[`barColor${jt(c.color)}`],(c.variant==="indeterminate"||c.variant==="query")&&i.bar2Indeterminate,c.variant==="buffer"&&i.bar2Buffer]}})(Nl(({theme:l})=>({width:"100%",position:"absolute",left:0,bottom:0,top:0,transition:"transform 0.2s linear",transformOrigin:"left",variants:[...Object.entries(l.palette).filter(Ua()).map(([i])=>({props:{color:i},style:{"--LinearProgressBar2-barColor":(l.vars||l).palette[i].main}})),{props:({ownerState:i})=>i.variant!=="buffer"&&i.color!=="inherit",style:{backgroundColor:"var(--LinearProgressBar2-barColor, currentColor)"}},{props:({ownerState:i})=>i.variant!=="buffer"&&i.color==="inherit",style:{backgroundColor:"currentColor"}},{props:{color:"inherit"},style:{opacity:.3}},...Object.entries(l.palette).filter(Ua()).map(([i])=>({props:{color:i,variant:"buffer"},style:{backgroundColor:ks(l,i),transition:`transform .${vs}s linear`}})),{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:{width:"auto"}},{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:PS||{animation:`${Ts} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}}]}))),i2=k.forwardRef(function(i,c){const o=Ul({props:i,name:"MuiLinearProgress"}),{className:s,color:d="primary",value:m,valueBuffer:b,variant:v="indeterminate",...p}=o,C={...o,color:d,variant:v},_=t2(C),w=yv(),j={},B={bar1:{},bar2:{}};if((v==="determinate"||v==="buffer")&&m!==void 0){j["aria-valuenow"]=Math.round(m),j["aria-valuemin"]=0,j["aria-valuemax"]=100;let U=m-100;w&&(U=-U),B.bar1.transform=`translateX(${U}%)`}if(v==="buffer"&&b!==void 0){let U=(b||0)-100;w&&(U=-U),B.bar2.transform=`translateX(${U}%)`}return rt.jsxs(e2,{className:pe(_.root,s),ownerState:C,role:"progressbar",...j,ref:c,...p,children:[v==="buffer"?rt.jsx(n2,{className:_.dashed,ownerState:C}):null,rt.jsx(a2,{className:_.bar1,ownerState:C,style:B.bar1}),v== Line truncated
+168
View File
@@ -0,0 +1,168 @@
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(`
`),l=s.split(`
`);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Ce=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Se(n):``}function Te(e,t){switch(e.tag){case 26:case 27:case 5:return Se(e.type);case 16:return Se(`Lazy`);case 13:return e.child!==t&&t!==null?Se(`Suspense Fallback`):Se(`Suspense`);case 19:return Se(`SuspenseList`);case 0:case 15:return we(e.type,!1);case 11:return we(e.type.render,!1);case 1:return we(e.type,!0);case 31:return Se(`Activity`);default:return``}}function Ee(e){try{var t=``,n=null;do t+=Te(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
Error generating stack: `+e.message+`
`+e.stack}}var De=Object.prototype.hasOwnProperty,Oe=t.unstable_scheduleCallback,ke=t.unstable_cancelCallback,Ae=t.unstable_shouldYield,je=t.unstable_requestPaint,Me=t.unstable_now,Ne=t.unstable_getCurrentPriorityLevel,Pe=t.unstable_ImmediatePriority,Fe=t.unstable_UserBlockingPriority,Ie=t.unstable_NormalPriority,Le=t.unstable_LowPriority,Re=t.unstable_IdlePriority,ze=t.log,Be=t.unstable_setDisableYieldValue,Ve=null,He=null;function Ue(e){if(typeof ze==`function`&&Be(e),He&&typeof He.setStrictMode==`function`)try{He.setStrictMode(Ve,e)}catch{}}var We=Math.clz32?Math.clz32:qe,Ge=Math.log,Ke=Math.LN2;function qe(e){return e>>>=0,e===0?32:31-(Ge(e)/Ke|0)|0}var Je=256,Ye=262144,Xe=4194304;function Ze(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Qe(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Ze(n))):i=Ze(o):i=Ze(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ze(n))):i=Ze(o)):i=Ze(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function $e(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function et(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function tt(){var e=Xe;return Xe<<=1,!(Xe&62914560)&&(Xe=4194304),e}function nt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function rt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function it(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-We(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&at(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function at(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-We(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function ot(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-We(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function st(e,t){var n=t&-t;return n=n&42?1:ct(n),(n&(e.suspendedLanes|t))===0?n:0}function ct(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function lt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function ut(){var e=O.p;return e===0?(e=window.event,e===void 0?32:mp(e.type)):e}function dt(e,t){var n=O.p;try{return O.p=e,t()}finally{O.p=n}}var ft=Math.random().toString(36).slice(2),pt=`__reactFiber$`+ft,mt=`__reactProps$`+ft,ht=`__reactContainer$`+ft,gt=`__reactEvents$`+ft,_t=`__reactListeners$`+ft,vt=`__reactHandles$`+ft,yt=`__reactResources$`+ft,bt=`__reactMarker$`+ft;function xt(e){delete e[pt],delete e[mt],delete e[gt],delete e[_t],delete e[vt]}function St(e){var t=e[pt];if(t)return t;for(var n=e.parentNode;n;){if(t=n[ht]||n[pt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=df(e);e!==null;){if(n=e[pt])return n;e=df(e)}return t}e=n,n=e.parentNode}return null}function Ct(e){if(e=e[pt]||e[ht]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function wt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(i(33))}function Tt(e){var t=e[yt];return t||=e[yt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function Et(e){e[bt]=!0}var Dt=new Set,Ot={};function kt(e,t){At(e,t),At(e+`Capture`,t)}function At(e,t){for(Ot[e]=t,e=0;e<t.length;e++)Dt.add(t[e])}var jt=RegExp(`^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001Line truncated
`).replace(Ad,``)}function Md(e,t){return t=jd(t),jd(e)===t}function $(e,t,n,r,a,o){switch(n){case`children`:typeof r==`string`?t===`body`||t===`textarea`&&r===``||Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&t!==`body`&&Zt(e,``+r);break;case`className`:Ft(e,`class`,r);break;case`tabIndex`:Ft(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:Ft(e,n,r);break;case`style`:en(e,r,o);break;case`data`:if(t!==`object`){Ft(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)){e.removeAttribute(n);break}if(r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=an(``+r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}else typeof o==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,a.name,a,null),$(e,t,`formEncType`,a.formEncType,a,null),$(e,t,`formMethod`,a.formMethod,a,null),$(e,t,`formTarget`,a.formTarget,a,null)):($(e,t,`encType`,a.encType,a,null),$(e,t,`method`,a.method,a,null),$(e,t,`target`,a.target,a,null)));if(r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=an(``+r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=on);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=an(``+r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``+r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),Pt(e,`popover`,r);break;case`xlinkActuate`:It(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:It(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:It(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:It(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:Pt(e,`is`,r);break;case`innerText`:case`textContent`:break;default:(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)&&(n=nn.get(n)||n,Pt(e,n,r))}}function Nd(e,t,n,r,a,o){switch(n){case`style`:en(e,r,o);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`children`:typeof r==`string`?Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&Zt(e,``+r);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;case`onClick`:r!=null&&(e.onclick=on);break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`innerHTML`:case`re Line truncated
const theme = ${JSON.stringify(t,null,2)};
theme.breakpoints = createBreakpoints(theme.breakpoints || {});
theme.transitions = createTransitions(theme.transitions || {});
export default theme;`}function xa(e){return typeof e==`number`?`${(e*100).toFixed(0)}%`:`calc((${e}) * 100%)`}var Sa=e=>{if(!Number.isNaN(+e))return+e;let t=e.match(/\d*\.?\d+/g);if(!t)return 0;let n=0;for(let e=0;e<t.length;e+=1)n+=+t[e];return n};function Ca(e){Object.assign(e,{alpha(t,n){let r=this||e;return r.colorSpace?`oklch(from ${t} l c h / ${typeof n==`string`?`calc(${n})`:n})`:r.vars?`rgba(${t.replace(/var\(--([^,\s)]+)(?:,[^)]+)?\)+/g,`var(--$1Channel)`)} / ${typeof n==`string`?`calc(${n})`:n})`:bi(t,Sa(n))},lighten(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #fff ${xa(n)})`:Ci(t,n)},darken(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #000 ${xa(n)})`:Si(t,n)}})}function wa(e={},...t){let{breakpoints:n,mixins:r={},spacing:i,palette:a={},transitions:o={},typography:s={},shape:c,colorSpace:l,...u}=e;if(e.vars&&e.generateThemeVars===void 0)throw Error(ee(20));let d=na({...a,colorSpace:l}),f=Nr(e),p=vn(f,{mixins:ia(f.breakpoints,r),palette:d,shadows:fa.slice(),typography:ca(d,s),transitions:_a(o),zIndex:{...va}});return p=vn(p,u),p=t.reduce((e,t)=>vn(e,t),p),p.unstable_sxConfig={...Dr,...u?.unstable_sxConfig},p.unstable_sx=function(e){return jr({sx:e,theme:this})},p.toRuntimeSource=ba,Ca(p),p}function Ta(e){let t;return t=e<1?5.11916*e**2:4.5*Math.log(e+1)+2,Math.round(t*10)/1e3}var Ea=[...Array(25)].map((e,t)=>{if(t===0)return`none`;let n=Ta(t);return`linear-gradient(rgba(255 255 255 / ${n}), rgba(255 255 255 / ${n}))`});function Da(e){return{inputPlaceholder:e===`dark`?.5:.42,inputUnderline:e===`dark`?.7:.42,switchTrackDisabled:e===`dark`?.2:.12,switchTrack:e===`dark`?.3:.38}}function Oa(e){return e===`dark`?Ea:[]}function ka(e){let{palette:t={mode:`light`},opacity:n,overlays:r,colorSpace:i,...a}=e,o=na({...t,colorSpace:i});return{palette:o,opacity:{...Da(o.mode),...n},overlays:r||Oa(o.mode),...a}}function Aa(e){return!!e[0].match(/(cssVarPrefix|colorSchemeSelector|modularCssLayers|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!e[0].match(/sxConfig$/)||e[0]===`palette`&&!!e[1]?.match(/(mode|contrastThreshold|tonalOffset)/)}var ja=e=>[...[...Array(25)].map((t,n)=>`--${e?`${e}-`:``}overlays-${n}`),`--${e?`${e}-`:``}palette-AppBar-darkBg`,`--${e?`${e}-`:``}palette-AppBar-darkColor`],Ma=e=>(t,n)=>{let r=e.rootSelector||`:root`,i=e.colorSchemeSelector,a=i;if(i===`class`&&(a=`.%s`),i===`data`&&(a=`[data-%s]`),i?.startsWith(`data-`)&&!i.includes(`%s`)&&(a=`[${i}="%s"]`),e.defaultColorScheme===t){if(t===`dark`){let i={};return ja(e.cssVarPrefix).forEach(e=>{i[e]=n[e],delete n[e]}),a===`media`?{[r]:n,"@media (prefers-color-scheme: dark)":{[r]:i}}:a?{[a.replace(`%s`,t)]:i,[`${r}, ${a.replace(`%s`,t)}`]:n}:{[r]:{...n,...i}}}if(a&&a!==`media`)return`${r}, ${a.replace(`%s`,String(t))}`}else if(t){if(a===`media`)return{[`@media (prefers-color-scheme: ${String(t)})`]:{[r]:n}};if(a)return a.replace(`%s`,String(t))}return r};function Na(e,t){t.forEach(t=>{e[t]||(e[t]={})})}function B(e,t,n){!e[t]&&n&&(e[t]=n)}function Pa(e){return typeof e!=`string`||!e.startsWith(`hsl`)?e:_i(e)}function Fa(e,t){`${t}Channel`in e||(e[`${t}Channel`]=hi(Pa(e[t]),`MUI: Can't create \`palette.${t}Channel\` because \`palette.${t}\` is not one of these formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().
To suppress this warning, you need to explicitly provide the \`palette.${t}Channel\` as a string (in rgb format, for example "12 12 12") or undefined if you want to remove the channel token.`))}function Ia(e){return typeof e==`number`?`${e}px`:typeof e==`string`||typeof e==`function`||Array.isArray(e)?e:`8px`}var La=e=>{try{return e()}catch{}},Ra=(e=`mui`)=>R(e);function za(e,t,n,r,i){if(!n)return;n=n===!0?{}:n;let a=i===`dark`?`dark`:`light`;if(!r){t[i]=ka({...n,palette:{mode:a,...n?.palette},colorSpace:e});return}let{palette:o,...s}=wa({...r,palette:{mode:a,...n?.palette},colorSpace:e});return t[i]={...n,palette:o,opacity:{...Da(a),...n?.opacity},overlays:n?.overlays||Oa(a)},s}function Ba(e={},...t){let{colorSchemes:n={light:!0},defaultColorScheme:r,disableCssColorScheme:i=!1,cssVarPrefix:a=`mui`,nativeColor:o=!1,shouldSkipGeneratingVar:s=Aa,colorSchemeSelector:c=n.light&&n.dark?`media`:void 0,rootSelector:l=`:root`,...u}=e,d=Object.keys(n)[0],f=r||(n.light&&d!==`light`?`light`:d),p=Ra(a),{[f]:m,light:h,dark:g,..._}=n,v={..._},y=m;if((f===`dark`&&!(`dark`in n)||f===`light`&&!(`light`in n))&&(y=!0),!y)throw Error(ee(21,f));let b;o&&(b=`oklch`);let x=za(b,v,y,u,f);h&&!v.light&&za(b,v,h,void 0,`light`),g&&!v.dark&&za(b,v,g,void 0,`dark`);let S={defaultColorScheme:f,...x,cssVarPrefix:a,colorSchemeSelector:c,rootSelector:l,getCssVar:p,colorSchemes:v,font:{...ra(x.typography),...x.font},spacing:Ia(u.spacing)};Object.keys(S.colorSchemes).forEach(e=>{let t=S.colorSchemes[e].palette,n=e=>{let n=e.split(`-`),r=n[1],i=n[2];return p(e,t[r][i])};t.mode===`light`&&(B(t.common,`background`,`#fff`),B(t.common,`onBackground`,`#000`)),t.mode===`dark`&&(B(t.common,`background`,`#000`),B(t.common,`onBackground`,`#fff`));function r(e,t,n){if(b){let r;return e===xi&&(r=`transparent ${((1-n)*100).toFixed(0)}%`),e===F&&(r=`#000 ${(n*100).toFixed(0)}%`),e===I&&(r=`#fff ${(n*100).toFixed(0)}%`),`color-mix(in ${b}, ${t}, ${r})`}return e(t,n)}if(Na(t,[`Alert`,`AppBar`,`Avatar`,`Button`,`Chip`,`FilledInput`,`LinearProgress`,`Skeleton`,`Slider`,`SnackbarContent`,`SpeedDialAction`,`StepConnector`,`StepContent`,`Switch`,`TableCell`,`Tooltip`]),t.mode===`light`){B(t.Alert,`errorColor`,r(F,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;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`,ko=Jt`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`,Ao=Jt`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`,jo=Ka(`span`,{name:`MuiTouchRipple`,slot:`Root`})({overflow:`hidden`,pointerEvents:`none`,position:`absolute`,zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:`inherit`}),Mo=Ka(To,{name:`MuiTouchRipple`,slot:`Ripple`})`
opacity: 0;
position: absolute;
&.${Eo.rippleVisible} {
opacity: 0.3;
transform: scale(1);
animation-name: ${Oo};
animation-duration: ${Do}ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
}
&.${Eo.ripplePulsate} {
animation-duration: ${({theme:e})=>e.transitions.duration.shorter}ms;
}
& .${Eo.child} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${Eo.childLeaving} {
opacity: 0;
animation-name: ${ko};
animation-duration: ${Do}ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
}
& .${Eo.childPulsate} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${Ao};
animation-duration: 2500ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`,No=M.forwardRef(function(e,t){let{center:n=!1,classes:r={},className:i,...a}=Za({props:e,name:`MuiTouchRipple`}),[o,s]=M.useState([]),c=M.useRef(0),l=M.useRef(null);M.useEffect(()=>{l.current&&=(l.current(),null)},[o]);let u=M.useRef(!1),d=bo(),f=M.useRef(null),p=M.useRef(null),m=M.useCallback(e=>{let{pulsate:t,rippleX:n,rippleY:i,rippleSize:a,cb:o}=e;s(e=>[...e,(0,N.jsx)(Mo,{classes:{ripple:Gr(r.ripple,Eo.ripple),rippleVisible:Gr(r.rippleVisible,Eo.rippleVisible),ripplePulsate:Gr(r.ripplePulsate,Eo.ripplePulsate),child:Gr(r.child,Eo.child),childLeaving:Gr(r.childLeaving,Eo.childLeaving),childPulsate:Gr(r.childPulsate,Eo.childPulsate)},timeout:Do,pulsate:t,rippleX:n,rippleY:i,rippleSize:a},c.current)]),c.current+=1,l.current=o},[r]),h=M.useCallback((e={},t={},r=()=>{})=>{let{pulsate:i=!1,center:a=n||t.pulsate,fakeElement:o=!1}=t;if(e?.type===`mousedown`&&u.current){u.current=!1;return}e?.type===`touchstart`&&(u.current=!0);let s=o?null:p.current,c=s?s.getBoundingClientRect():{width:0,height:0,left:0,top:0},l,h,g;if(a||e===void 0||e.clientX===0&&e.clientY===0||!e.clientX&&!e.touches)l=Math.round(c.width/2),h=Math.round(c.height/2);else{let{clientX:t,clientY:n}=e.touches&&e.touches.length>0?e.touches[0]:e;l=Math.round(t-c.left),h=Math.round(n-c.top)}if(a)g=Math.sqrt((2*c.width**2+c.height**2)/3),g%2==0&&(g+=1);else{let e=Math.max(Math.abs((s?s.clientWidth:0)-l),l)*2+2,t=Math.max(Math.abs((s?s.clientHeight:0)-h),h)*2+2;g=Math.sqrt(e**2+t**2)}e?.touches?f.current===null&&(f.current=()=>{m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},d.start(80,()=>{f.current&&=(f.current(),null)})):m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},[n,m,d]),g=M.useCallback(()=>{h({},{pulsate:!0})},[h]),_=M.useCallback((e,t)=>{if(d.clear(),e?.type===`touchend`&&f.current){f.current(),f.current=null,d.start(0,()=>{_(e,t)});return}f.current=null,s(e=>e.length>0?e.slice(1):e),l.current=t},[d]);return M.useImperativeHandle(t,()=>({pulsate:g,start:h,stop:_}),[g,h,_]),(0,N.jsx)(jo,{className:Gr(Eo.root,r.root,i),ref:p,...a,children:(0,N.jsx)(mo,{component:null,exit:!0,children:o})})});function Po(e){return Jr(`MuiButtonBase`,e)}var Fo=Yr(`MuiButtonBase`,[`root`,`disabled`,`focusVisible`]),Io=e=>{let{disabled:t,focusVisible:n,focusVisibleClassName:r,classes:i}=e,a=Hi({root:[`root`,t&&`disabled`,n&&`focusVisible`]},Po,i);return n&&r&&(a.root+=` ${r}`),a},Lo=Ka(`button`,{name:`MuiButtonBase`,slot:`Root`})({display:`inline-flex`,alignItems:`center`,justifyContent:`center`,position:`relative`,boxSizing:`border-box`,WebkitTapHighlightColor:`transparent`,backgroundColor:`transparent`,outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:`pointer`,userSelect:`none`,verticalAlign:`middle`,MozAppearance:`none`,WebkitAppearance:`none`,textDecoration:`none`,color:`inherit`,"&::-moz-focus-inner":{borderStyle:`none`},[`&.${Fo.disabled}`]:{pointerEvents:`none`,cursor:`default`},"@media print":{colorAdjust:`exact`}}),Ro=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiButtonBase`}),{action:r,centerRipple:i=!1,children:a,className:o,component:s=`button`,disabled:c=!1,disableRipple:l=!1,disableTouchRipple:u=!1,focusRipple:d=!1,focusVisibleClassName:f,LinkComponent:p=`a`,onBlur:m,onClick:h,onContextMenu:g,onDragLeave:_,onFocus:v,onFocusVisible:y,onKeyDown:b,onKeyUp:x,onMouseDown:S,onMouseLeave:C,onMouseUp:w,onTouchEnd:ee,onTouchMove:te,onTouchStart:ne,tabIndex:re=0,TouchRippleProps:ie,touchRippleRef:ae,type:oe,...T}=n,se=M.useRef(null),E=Co(),ce=no(E.ref,ae),[D,O]=M.useState(!1);c&&D&&O(!1),M.useImperativeHandle(r,()=>({focusVisible:()=>{O(!0),se.current.focus()}}),[]);let le=E.shouldMount&&!l&&!c;M.useEffect(()=>{D&&d&&!l&&E.pulsate()},[l,d,D,E]);let ue=zo(E,`start`,S,u),de=zo(E,`stop`,g,u),fe=zo(E,`stop`,_,u),pe=zo(E,`stop`,w,u),k=zo(E,`stop`,e=>{D&&e.preventDefault(),C&&C(e)},u),me=zo(E,`start`,ne,u),he=zo(E,`stop`,ee,u),ge=zo(E,`stop`,te,u),A=zo(E,`stop`,e=>{xo(e.target)||O(!1),m&&m(e)},!1),_e=eo(e=>{se.current||=e.currentTarget,xo(e.target)&&(O(!0),y&&y(e)),v&&v(e)}),j=()=>{let e=se.current;return 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);
}
100% {
transform: rotate(360deg);
}
`,Ko=Jt`
0% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 100px, 200px;
stroke-dashoffset: -15px;
}
100% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: -126px;
}
`,qo=typeof Go==`string`?null:qt`
animation: ${Go} 1.4s linear infinite;
`,Jo=typeof Ko==`string`?null:qt`
animation: ${Ko} 1.4s ease-in-out infinite;
`,Yo=e=>{let{classes:t,variant:n,color:r,disableShrink:i}=e;return Hi({root:[`root`,n,`color${V(r)}`],svg:[`svg`],track:[`track`],circle:[`circle`,`circle${V(n)}`,i&&`circleDisableShrink`]},Uo,t)},Xo=Ka(`span`,{name:`MuiCircularProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.variant],t[`color${V(n.color)}`]]}})(Xa(({theme:e})=>({display:`inline-block`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`transform`)}},{props:{variant:`indeterminate`},style:qo||{animation:`${Go} 1.4s linear infinite`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}}))]}))),Zo=Ka(`svg`,{name:`MuiCircularProgress`,slot:`Svg`})({display:`block`}),Qo=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Circle`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.circle,t[`circle${V(n.variant)}`],n.disableShrink&&t.circleDisableShrink]}})(Xa(({theme:e})=>({stroke:`currentColor`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`stroke-dashoffset`)}},{props:{variant:`indeterminate`},style:{strokeDasharray:`80px, 200px`,strokeDashoffset:0}},{props:({ownerState:e})=>e.variant===`indeterminate`&&!e.disableShrink,style:Jo||{animation:`${Ko} 1.4s ease-in-out infinite`}}]}))),$o=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Track`})(Xa(({theme:e})=>({stroke:`currentColor`,opacity:(e.vars||e).palette.action.activatedOpacity}))),es=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiCircularProgress`}),{className:r,color:i=`primary`,disableShrink:a=!1,enableTrackSlot:o=!1,size:s=40,style:c,thickness:l=3.6,value:u=0,variant:d=`indeterminate`,...f}=n,p={...n,color:i,disableShrink:a,size:s,thickness:l,value:u,variant:d,enableTrackSlot:o},m=Yo(p),h={},g={},_={};if(d===`determinate`){let e=2*Math.PI*((Wo-l)/2);h.strokeDasharray=e.toFixed(3),_[`aria-valuenow`]=Math.round(u),h.strokeDashoffset=`${((100-u)/100*e).toFixed(3)}px`,g.transform=`rotate(-90deg)`}return(0,N.jsx)(Xo,{className:Gr(m.root,r),style:{width:s,height:s,...g,...c},ownerState:p,ref:t,role:`progressbar`,..._,...f,children:(0,N.jsxs)(Zo,{className:m.svg,ownerState:p,viewBox:`${Wo/2} ${Wo/2} ${Wo} ${Wo}`,children:[o?(0,N.jsx)($o,{className:m.track,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l,"aria-hidden":`true`}):null,(0,N.jsx)(Qo,{className:m.circle,style:h,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l})]})})});function ts(e){return Jr(`MuiTypography`,e)}Yr(`MuiTypography`,[`root`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`subtitle1`,`subtitle2`,`body1`,`body2`,`inherit`,`button`,`caption`,`overline`,`alignLeft`,`alignRight`,`alignCenter`,`alignJustify`,`noWrap`,`gutterBottom`,`paragraph`]);var ns={primary:!0,secondary:!0,error:!0,info:!0,success:!0,warning:!0,textPrimary:!0,textSecondary:!0,textDisabled:!0},rs=Ya(),is=e=>{let{align:t,gutterBottom:n,noWrap:r,paragraph:i,variant:a,classes:o}=e;return Hi({root:[`root`,a,e.align!==`inherit`&&`align${V(t)}`,n&&`gutterBottom`,r&&`noWrap`,i&&`paragraph`]},ts,o)},as=Ka(`span`,{name:`MuiTypography`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,n.variant&&t[n.variant],n.align!==`inherit`&&t[`align${V(n.align)}`],n.noWrap&&t.noWrap,n.gutterBottom&&t.gutterBottom,n.paragraph&&t.paragraph]}})(Xa(({theme:e})=>({margin:0,variants:[{props:{variant:`inherit`},style:{font:`inherit`,lineHeight:`inherit`,letterSpacing:`inherit`}},...Object.entries(e.typography).filter(([e,t])=>e!==`inherit`&&t&&typeof t==`object`).map(([e,t])=>({props:{variant:e},style:t})),...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}})),...Object.entries(e.palette?.text||{}).filter(([,e])=>typeof e==`string`).map(([t])=>({props:{color:`text${V(t)}`},style:{color:(e.vars||e).palette.text[t]}})),{props:({ownerState:e})=>e.align!==`inherit`,style:{textAlign:`var(--Typography-textAlign)`}},{props:({ownerState:e})=>e.noWrap,style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`}},{props:({ownerState:e})=>e.gutterBottom,style:{marginBottom:`0.35em`}},{props:({ownerState:e})=>e.paragraph,style:{marginBottom:16}}]}))),os={h1:`h1`,h2:`h2`,h3:`h3`,h4:`h4`,h5:`h5`,h6:`h6`,subtitle1:`h6`,subtitle2:`h6`,body1:`p`,body2:`p`,inherit:`p`},ss=M.forwardRef(function(e,t){let{color:n,...r}=Za({props:e,name:`MuiTypography`}),i=!ns[n],a=rs({...r,...i&&{color:n}}),{align:o=`inherit`,className:s,component:c,gutterBottom:l=!1,noWrap:u=!1,paragraph:d=!1,variant:f=`body1`,variantMapping:p=os,...m}=a,h={...a,align:o,color:n,className:s,component:c,gutterBottom:l,noWrap:u,paragraph:d,variant:f,variantMapping:p};return(0,N.jsx)(as,{as:c||(d?`p`:p[f]||os[f])||`span`,ref:t,className:Gr(is(h).root,s),...m,ownerState:h,style:{...o!==`inherit`&&{"--Typography-textAlign":o},...m.style}})}),cs=Yr(`MuiBox`,[`root`]),ls=Kr({themeId:te,defaultTheme:Ha(),defaultClassName:cs.root,generateClassName:Ur.generate});function us(e){return Line truncated
0% {
left: -35%;
right: 100%;
}
60% {
left: 100%;
right: -90%;
}
100% {
left: 100%;
right: -90%;
}
`,Ns=typeof Ms==`string`?null:qt`
animation: ${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
`,Ps=Jt`
0% {
left: -200%;
right: 100%;
}
60% {
left: 107%;
right: -8%;
}
100% {
left: 107%;
right: -8%;
}
`,Fs=typeof Ps==`string`?null:qt`
animation: ${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
`,Is=Jt`
0% {
opacity: 1;
background-position: 0 -23px;
}
60% {
opacity: 0;
background-position: 0 -23px;
}
100% {
opacity: 1;
background-position: -200px -23px;
}
`,Ls=typeof Is==`string`?null:qt`
animation: ${Is} 3s infinite linear;
`,Rs=e=>{let{classes:t,variant:n,color:r}=e;return Hi({root:[`root`,`color${V(r)}`,n],dashed:[`dashed`,`dashedColor${V(r)}`],bar1:[`bar`,`bar1`,`barColor${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar1Indeterminate`,n===`determinate`&&`bar1Determinate`,n===`buffer`&&`bar1Buffer`],bar2:[`bar`,`bar2`,n!==`buffer`&&`barColor${V(r)}`,n===`buffer`&&`color${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar2Indeterminate`,n===`buffer`&&`bar2Buffer`]},As,t)},zs=(e,t)=>e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode===`light`?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.5),Bs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[`color${V(n.color)}`],t[n.variant]]}})(Xa(({theme:e})=>({position:`relative`,overflow:`hidden`,display:`block`,height:4,zIndex:0,"@media print":{colorAdjust:`exact`},variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:zs(e,t)}})),{props:({ownerState:e})=>e.color===`inherit`&&e.variant!==`buffer`,style:{"&::before":{content:`""`,position:`absolute`,left:0,top:0,right:0,bottom:0,backgroundColor:`currentColor`,opacity:.3}}},{props:{variant:`buffer`},style:{backgroundColor:`transparent`}},{props:{variant:`query`},style:{transform:`rotate(180deg)`}}]}))),Vs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Dashed`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.dashed,t[`dashedColor${V(n.color)}`]]}})(Xa(({theme:e})=>({position:`absolute`,marginTop:0,height:`100%`,width:`100%`,backgroundSize:`10px 10px`,backgroundPosition:`0 -23px`,variants:[{props:{color:`inherit`},style:{opacity:.3,backgroundImage:`radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>{let n=zs(e,t);return{props:{color:t},style:{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`}}})]})),Ls||{animation:`${Is} 3s infinite linear`}),Hs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar1`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar1,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar1Indeterminate,n.variant===`determinate`&&t.bar1Determinate,n.variant===`buffer`&&t.bar1Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[{props:{color:`inherit`},style:{backgroundColor:`currentColor`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:(e.vars||e).palette[t].main}})),{props:{variant:`determinate`},style:{transition:`transform .${js}s linear`}},{props:{variant:`buffer`},style:{zIndex:1,transition:`transform .${js}s linear`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Ns||{animation:`${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}}]}))),Us=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar2`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar2,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar2Indeterminate,n.variant===`buffer`&&t.bar2Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{"--LinearProgressBar2-barColor":(e.vars||e).palette[t].main}})),{props:({ownerState:e})=>e.variant!==`buffer`&&e.color!==`inherit`,style:{backgroundColor:`var(--LinearProgressBar2-barColor, currentColor)`}},{props:({ownerState:e})=>e.variant!==`buffer`&&e.color===`inherit`,style:{backgroundColor:`currentColor`}},{props:{color:`inherit`},style:{opacity:.3}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t,variant:`buffer`},style:{backgroundColor:zs(e,t),transition:`transform .${js}s linear`}})),{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Fs||{animation:`${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}}]}))),Ws=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiLinearProgress`}),{className:r,color:i=`primary`,value:a,valueBuffer:o,variant:s=`indeterminate`,...c}=n,l={...n,color:i,variant:s},u=Rs(l),d=Di(),f={},p={bar1:{},bar2:{}};if((s===`determinate`||s===`buffer`)&&a!==void 0){f[`aria-valuenow`]=Math.round(a),f[`aria-valuemin`]=0,f[`aria-valuemax`]=100;let e=a-100;d&&(e=-e),p.bar1.transform=`translateX(${e}%)`}if(s===`buffer`&&o!==void 0){let e=(o||0)-100;d&&(e=-e),p.bar2.transform=`translateX(${e}%)`}return(0,N.jsxs)(Bs,{className:Gr(u.root,r),ownerState:l,role:`progressbar`,...f,ref:t,...c,children:[s===`buffer`?(0,N.jsx)(Vs,{className:u.dashed,ownerState:l}):null,(0,N.jsx)(Hs,{className:u.bar1,ownerState:l,s Line truncated
+4 -4
View File
@@ -2,11 +2,11 @@
<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>GlobalProtect</title>
<script type="module" crossorigin src="/assets/main-CQPVXkdn.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-B3YRsHQ2.css">
<title>GP Connect Helper</title>
<script type="module" crossorigin src="/assets/main-yAo_rN_V.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-C5muOSVO.css">
</head>
<body>
<script>
-6
View File
@@ -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
View File
@@ -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 -2
View File
@@ -2,9 +2,9 @@
<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>GlobalProtect</title>
<title>GP Connect Helper</title>
</head>
<body>
<script>
+20 -20
View File
@@ -10,28 +10,28 @@
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@mui/icons-material": "^6.3.0",
"@mui/material": "^6.3.0",
"@tauri-apps/api": "^2.1.1",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.11",
"@mui/material": "^7.3.11",
"@tauri-apps/api": "^2.11.1",
"react": "^19.2.7",
"react-dom": "^19.2.7"
},
"devDependencies": {
"@tauri-apps/cli": "^2.1.0",
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
"@typescript-eslint/eslint-plugin": "^8.18.2",
"@typescript-eslint/parser": "^8.18.2",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-react": "^7.37.3",
"eslint-plugin-react-hooks": "^5.1.0",
"prettier": "3.4.2",
"typescript": "^5.7.2",
"vite": "^6.0.5"
"@tauri-apps/cli": "^2.11.2",
"@types/node": "^25.9.4",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@typescript-eslint/eslint-plugin": "^8.61.1",
"@typescript-eslint/parser": "^8.61.1",
"@vitejs/plugin-react": "^6.0.2",
"eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "3.8.3",
"typescript": "^6.0.3",
"vite": "^8.0.16"
},
"packageManager": "[email protected]"
}
+1575 -1316
View File
File diff suppressed because it is too large. Load diff
-6
View File
@@ -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
View File
@@ -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

+5 -2
View File
@@ -10,7 +10,7 @@ license.workspace = true
tauri-build = { version = "2", features = [] }
[dependencies]
gpapi = { path = "../../../crates/gpapi", features = ["tauri"] }
gpapi = { path = "../../../crates/gpapi", features = ["tauri", "clap"] }
tauri.workspace = true
tokio.workspace = true
@@ -20,8 +20,11 @@ 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"] }
[features]
custom-protocol = ["tauri/custom-protocol"]
default = ["tauri/custom-protocol"]
+59
View File
@@ -1,3 +1,62 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPGUI_HELPER_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPGUI_HELPER_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPGUI_HELPER_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 57 KiB

+49 -97
View File
@@ -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

+22 -5
View File
@@ -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");
+83 -22
View File
@@ -1,54 +1,101 @@
use clap::Parser;
use gpapi::utils::{base64, env_utils};
use log::{info, LevelFilter};
use std::{io::Read, sync::Arc};
use anyhow::{Context, bail};
use gpapi::{
clap::InfoLevelVerbosity,
service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential},
utils::env_utils,
};
use log::info;
use tokio::sync::watch;
use zeroize::Zeroizing;
use crate::app::App;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const GP_API_KEY: &[u8; 32] = &[0; 32];
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPGUI_HELPER_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[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,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
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 init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
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())
.init();
}
pub fn run() {
let cli = Cli::parse();
init_logger();
init_logger(&cli);
info!("gpgui-helper started: {}", VERSION);
if let Err(e) = cli.run() {
@@ -56,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());
}
}
+472 -24
View File
@@ -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};
@@ -15,6 +35,12 @@ const SNAPSHOT: &str = match option_env!("SNAPSHOT") {
None => "false",
};
#[cfg(target_env = "musl")]
const GUI_LIBC_SUFFIX: &str = "-musl";
#[cfg(not(target_env = "musl"))]
const GUI_LIBC_SUFFIX: &str = "";
pub struct ProgressNotifier {
win: WebviewWindow,
}
@@ -38,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"),
}
}
@@ -88,6 +366,10 @@ impl GuiUpdater {
}
pub async fn update(&self) {
if !cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
info!("GUI version is not supported on this architecture.");
return;
}
info!("Update GUI, version: {}", self.version);
#[cfg(debug_assertions)]
@@ -99,14 +381,15 @@ impl GuiUpdater {
format!("v{}", self.version)
};
#[cfg(target_arch = "x86_64")]
let arch = "x86_64";
#[cfg(target_arch = "aarch64")]
let arch = "aarch64";
let arch = if cfg!(target_arch = "x86_64") {
"x86_64"
} else {
"aarch64"
};
let file_url = format!(
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz",
release_tag, arch
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}{}.bin.tar.xz",
release_tag, arch, GUI_LIBC_SUFFIX
);
let checksum_url = format!("{}.sha256", file_url);
@@ -195,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)
}
}
+1 -1
View File
@@ -15,7 +15,7 @@
},
"windows": [
{
"title": "GlobalProtect GUI Helper",
"title": "GP Connect Helper",
"center": true,
"resizable": true,
"width": 500,
@@ -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

-99
View File
@@ -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 -1
View File
@@ -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";
+1 -1
View File
@@ -20,7 +20,7 @@ export default defineConfig(async () => {
// https://tauri.app/v1/api/config#buildconfig.beforedevcommand
envPrefix: ["VITE_", "TAURI_"],
build: {
rollupOptions: {
rolldownOptions: {
input: {
main: resolve(__dirname, "index.html"),
},
+13 -2
View File
@@ -5,11 +5,12 @@ edition.workspace = true
license.workspace = true
[dependencies]
gpapi = { path = "../../crates/gpapi" }
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
openconnect = { path = "../../crates/openconnect" }
clap.workspace = true
anyhow.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
axum = { workspace = true, features = ["ws"] }
futures.workspace = true
@@ -20,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"
+60
View File
@@ -0,0 +1,60 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPSERVICE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPSERVICE_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPSERVICE_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
@@ -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);
}
+327 -74
View File
@@ -1,20 +1,64 @@
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},
GP_SERVICE_LOCK_FILE,
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
};
use log::{info, warn, LevelFilter};
#[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"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[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)]
@@ -24,65 +68,154 @@ 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,
}
impl Cli {
async fn run(&mut self, redaction: Arc<Redaction>) -> anyhow::Result<()> {
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE));
async fn run(&mut self) -> anyhow::Result<()> {
let redaction = self.init_logger();
info!("gpservice started: {}", VERSION);
let pid = std::process::id();
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(&registry),
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_token = vpn_task.cancel_token();
let vpn_task_cancel_token = vpn_task.cancel_token();
let server_token = ws_server.cancel_token();
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 });
#[cfg(debug_assertions)]
let no_gui = self.no_gui;
#[cfg(not(debug_assertions))]
let no_gui = false;
if no_gui {
info!("GUI is disabled");
} else {
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
let minimized = self.minimized;
#[cfg(target_os = "macos")]
if externally_brokered {
let credential_server = crate::macos_broker::CredentialServer::new(Arc::clone(&registry));
let credential_token = server_token.clone();
let credential_shutdown = shutdown_tx.clone();
tokio::spawn(async move {
launch_gui(envs, api_key, minimized).await;
let _ = shutdown_tx.send(()).await;
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(&registry);
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;
});
}
tokio::select! {
_ = shutdown_signal() => {
info!("Shutdown signal received");
}
_ = shutdown_rx.recv() => {
info!("Shutdown request received, shutting down");
#[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(&registry));
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;
}
});
}
vpn_task_token.cancel();
#[cfg(unix)]
{
let vpn_ctx = vpn_task.context();
let ws_ctx = ws_server.context();
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
}
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).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 launch_managed_gui = !self.dev_standalone && !externally_brokered;
#[cfg(not(debug_assertions))]
let launch_managed_gui = !externally_brokered;
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, registry, minimized, gui_restart_requested).await;
let _ = shutdown_tx.send(()).await;
});
} else {
info!("Running with a separately started debug GUI");
}
tokio::select! {
_ = shutdown_signal() => {
info!("Shutdown signal received");
}
_ = shutdown_rx.recv() => {
info!("Shutdown request received, shutting down");
}
}
vpn_task_cancel_token.cancel();
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
lock_file.unlock()?;
@@ -92,57 +225,180 @@ impl Cli {
Ok(())
}
fn prepare_api_key(&self) -> Vec<u8> {
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.no_gui {
return gpapi::GP_API_KEY.to_vec();
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));
}
generate_key().to_vec()
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()
// Set the log level to the Trace level, the logs will be filtered
.filter_level(log::LevelFilter::Trace)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {:<5} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
.build();
logger::init_with_logger(level, inner_logger);
redaction
}
}
fn init_logger() -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let redaction_clone = Arc::clone(&redaction);
// let target = Box::new(File::create("log.txt").expect("Can't create file"));
env_logger::builder()
.filter_level(LevelFilter::Info)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
// .target(env_logger::Target::Pipe(target))
.init();
#[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);
redaction
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() => {},
}
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;
}
}
}
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
#[cfg(unix)]
mod signals {
use std::sync::Arc;
use log::{info, warn};
use crate::vpn_task::VpnTaskContext;
use crate::ws_server::WsServerContext;
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent;
use tokio::signal::unix::{Signal, SignalKind, signal};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?;
let user_sig2 = signal(SignalKind::user_defined2())?;
Ok((user_sig1, user_sig2))
}() {
Ok(signals) => signals,
Err(err) => {
warn!("Failed to create signal: {}", err);
return;
}
};
loop {
tokio::select! {
_ = user_sig1.recv() => {
info!("Received SIGUSR1 signal");
if vpn_ctx.disconnect().await {
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
let pid = std::process::id();
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
warn!("Failed to write PID to file: {}", err);
}
}
}
_ = user_sig2.recv() => {
info!("Received SIGUSR2 signal");
ws_ctx.send_event(WsEvent::ResumeConnection).await;
}
}
}
}
}
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;
}
@@ -153,10 +409,7 @@ async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut
pub async fn run() {
let mut cli = Cli::parse();
let redaction = init_logger();
info!("gpservice started: {}", VERSION);
if let Err(e) = cli.run(redaction).await {
if let Err(e) = cli.run().await {
eprintln!("Error: {}", e);
std::process::exit(1);
}
+29
View File
@@ -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
}
+219
View File
@@ -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(&registry)));
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());
}
}
+7 -155
View File
@@ -1,35 +1,12 @@
use std::{
borrow::Cow,
fs::{File, Permissions},
io::BufReader,
ops::ControlFlow,
os::unix::fs::PermissionsExt,
path::PathBuf,
sync::Arc,
};
use std::sync::Arc;
use anyhow::bail;
use axum::{
body::Bytes,
extract::{
ws::{self, CloseFrame, Message, WebSocket},
State, WebSocketUpgrade,
},
http::StatusCode,
extract::{State, WebSocketUpgrade},
response::IntoResponse,
};
use futures::{SinkExt, StreamExt};
use gpapi::{
service::{event::WsEvent, request::UpdateGuiRequest},
utils::checksum::verify_checksum,
GP_GUI_BINARY,
};
use log::{info, warn};
use tar::Archive;
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"
@@ -39,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 path = PathBuf::from(GP_GUI_BINARY);
let Some(dir) = path.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 path = entry.path()?;
if let Some(name) = path.file_name() {
let name = name.to_string_lossy();
if name == "gpgui" {
let mut file = File::create(GP_GUI_BINARY)?;
std::io::copy(&mut entry, &mut file)?;
break;
}
}
}
// Make the binary executable
fs::set_permissions(GP_GUI_BINARY, 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: Cow::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))
}
+2
View File
@@ -0,0 +1,2 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub mod vpnc_script;
+122
View File
@@ -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());
}
}
+10
View File
@@ -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;
+392
View File
@@ -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")
);
}
}
+1 -2
View File
@@ -1,8 +1,8 @@
use std::sync::Arc;
use axum::{
routing::{get, post},
Router,
routing::{get, post},
};
use crate::{handlers, ws_server::WsServerContext};
@@ -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)
}
+8
View File
@@ -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))
}
+380
View File
@@ -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()
);
}
}
+6
View File
@@ -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()))
}
+10
View File
@@ -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);
}
}
+201 -17
View File
@@ -1,26 +1,37 @@
use std::{sync::Arc, thread};
use std::{io::Write, os::unix::fs::PermissionsExt, sync::Arc, thread};
use gpapi::service::{
request::{ConnectRequest, WsRequest},
vpn_state::VpnState,
use gpapi::{
logger,
service::{
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA, UpdateLogLevelRequest, WsRequest},
vpn_state::{ConnectedInfo, VpnState},
},
session::{SessionInfo, SessionWarning},
};
use log::{info, warn};
use openconnect::Vpn;
use tokio::sync::{mpsc, oneshot, watch, RwLock};
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(),
}
}
@@ -35,19 +46,50 @@ impl VpnTaskContext {
let info = req.info().clone();
let vpn_handle = Arc::clone(&self.vpn_handle);
let args = req.args();
let vpn = match Vpn::builder(req.gateway().server(), args.cookie())
.script(args.vpnc_script())
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_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())
.certificate(args.certificate())
.sslkey(args.sslkey())
.os_version(args.os_version())
.client_version(args.client_version())
.host_id(args.host_id())
.certificate(identity.certificate.clone())
.sslkey(identity.sslkey.clone())
.key_password(args.key_password())
.csd_uid(args.csd_uid())
.hip(args.hip())
.csd_uid(csd_uid)
.csd_wrapper(args.csd_wrapper())
.reconnect_timeout(args.reconnect_timeout())
.mtu(args.mtu())
.disable_ipv6(args.disable_ipv6())
.no_dtls(args.no_dtls())
.local_hostname(args.local_hostname())
.dpd_interval(args.force_dpd())
.no_xmlpost(args.no_xmlpost())
.build()
{
Ok(vpn) => vpn,
@@ -60,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
@@ -72,9 +116,19 @@ impl VpnTaskContext {
let vpn_state_tx_clone = vpn_state_tx.clone();
vpn_handle.blocking_read().as_ref().map(|vpn| {
vpn.connect(move || {
let connect_info = Box::new(info.clone());
vpn_state_tx.send(VpnState::Connected(connect_info)).ok();
vpn.connect(move |vpn_session_info| {
let session_info = SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
);
info!("VPN session info: {}", session_info.log_summary());
let connected_info = Box::new(ConnectedInfo::new(info.clone(), Some(session_info)));
vpn_state_tx.send(VpnState::Connected(connected_info)).ok();
})
});
@@ -82,12 +136,13 @@ 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();
});
}
pub async fn disconnect(&self) {
pub async fn disconnect(&self) -> bool {
if let Some(disconnect_rx) = self.disconnect_rx.write().await.take() {
info!("Disconnecting VPN...");
if let Some(vpn) = self.vpn_handle.read().await.as_ref() {
@@ -98,9 +153,12 @@ impl VpnTaskContext {
// Wait for the VPN to be disconnected
disconnect_rx.await.ok();
info!("VPN disconnected");
true
} else {
info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok();
false
}
}
}
@@ -112,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 {
@@ -143,6 +206,10 @@ impl VpnTask {
server_cancel_token.cancel();
}
pub fn context(&self) -> Arc<VpnTaskContext> {
Arc::clone(&self.ctx)
}
async fn recv(&mut self) {
while let Some(req) = self.ws_req_rx.recv().await {
tokio::spawn(process_ws_req(req, self.ctx.clone()));
@@ -150,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) => {
@@ -158,5 +282,65 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
WsRequest::Disconnect(_) => {
ctx.disconnect().await;
}
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
let level = level.parse().unwrap_or(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");
}
}
}
#[cfg(test)]
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(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.expires_in_human.as_deref(), Some("12h"));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_request_session_metadata_keeps_extension_disabled() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert!(!info.allow_extend_session);
}
}
+336
View File
@@ -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()
);
}
}
+512 -39
View File
@@ -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);
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) {
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(&registry),
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:?}"),
}
}
}
Loaded 100 of 251 files, more files were not shown because too many files have changed in this diff. Show more