diff --git a/api/client.go b/api/client.go index 49a2b53..6e32cec 100644 --- a/api/client.go +++ b/api/client.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "strings" + "sync" "time" "github.com/fosrl/newt/logger" @@ -65,6 +66,22 @@ func (e *APIError) Unwrap() error { return e.Err } +// RequiresReauthentication reports whether the session is no longer accepted +// and logging in again would fix it: a 401, or the 403 an org's access policy +// sends once its maximum session length has passed. Other policy failures +// (two-factor required, password expired) need more than a new login, so they +// don't count. The server sends no code for the policy case, only this message. +func (e *APIError) RequiresReauthentication() bool { + if e == nil || e.Type != ErrorTypeHTTPError { + return false + } + if e.Status == 401 { + return true + } + return e.Status == 403 && + (strings.HasPrefix(e.Message, "Your session has expired") || strings.HasPrefix(e.Message, "Your session is invalid")) +} + // APIClient handles HTTP requests to the Pangolin API type APIClient struct { baseURL string @@ -73,6 +90,11 @@ type APIClient struct { csrfToken string client *http.Client onUnauthorized func() + + // launcherNoTypeFilter holds servers whose launcher rejected the + // `resourceType` filter, so it isn't sent to them again. + launcherMu sync.Mutex + launcherNoTypeFilter map[string]bool } // NewAPIClient creates a new API client instance diff --git a/api/methods.go b/api/methods.go index b27492c..f6d6e06 100644 --- a/api/methods.go +++ b/api/methods.go @@ -7,6 +7,7 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "github.com/fosrl/windows-linux/config" @@ -410,3 +411,90 @@ func (c *APIClient) ListGatewayResources(orgID string) ([]SiteResource, error) { return gateways, nil } + +// ListLauncherPrivateResources returns one page of the private resources the +// user can reach in orgID, searched and sorted by name on the server. +// +// Servers that predate the `resourceType` filter reject it as an unknown +// parameter (400). Those get the unfiltered list, with public resources dropped +// here, so a page may hold fewer than pageSize items while the pagination still +// counts every resource. +func (c *APIClient) ListLauncherPrivateResources(orgID, query string, page, pageSize int) (*ListLauncherResourcesResponse, error) { + params := url.Values{} + params.Set("groupBy", "none") + params.Set("groupKey", "__all__") + params.Set("sort_by", "name") + params.Set("order", "asc") + params.Set("page", strconv.Itoa(page)) + params.Set("pageSize", strconv.Itoa(pageSize)) + if q := strings.TrimSpace(query); q != "" { + params.Set("query", q) + } + path := fmt.Sprintf("/org/%s/launcher/resources", url.PathEscape(orgID)) + + fetch := func(p url.Values) (*ListLauncherResourcesResponse, error) { + data, resp, err := c.makeRequest("GET", path+"?"+p.Encode(), nil) + if err != nil { + return nil, err + } + var result ListLauncherResourcesResponse + if err := c.parseResponse(data, resp, &result); err != nil { + return nil, err + } + return &result, nil + } + + server := c.CurrentBaseURL() + c.launcherMu.Lock() + noFilter := c.launcherNoTypeFilter[server] + c.launcherMu.Unlock() + + var result *ListLauncherResourcesResponse + var err error + if noFilter { + result, err = fetch(params) + } else { + filtered := url.Values{} + for k, v := range params { + filtered[k] = v + } + filtered.Set("resourceType", "site") + result, err = fetch(filtered) + var apiErr *APIError + if errors.As(err, &apiErr) && apiErr.Status == 400 { + result, err = fetch(params) + if err == nil { + c.launcherMu.Lock() + if c.launcherNoTypeFilter == nil { + c.launcherNoTypeFilter = map[string]bool{} + } + c.launcherNoTypeFilter[server] = true + c.launcherMu.Unlock() + } + } + } + if err != nil { + return nil, err + } + + private := result.Resources[:0] + for _, r := range result.Resources { + if r.IsPrivate() { + private = append(private, r) + } + } + result.Resources = private + return result, nil +} + +// InvalidateLauncherCache drops the server's cached launcher results for this +// user, so the next list reflects changes made in the last minute. +func (c *APIClient) InvalidateLauncherCache(orgID string) error { + path := fmt.Sprintf("/org/%s/launcher/invalidate-cache", url.PathEscape(orgID)) + data, resp, err := c.makeRequest("POST", path, []byte("{}")) + if err != nil { + return err + } + var empty EmptyResponse + return c.parseResponse(data, resp, &empty) +} diff --git a/api/types.go b/api/types.go index e06cef9..1716949 100644 --- a/api/types.go +++ b/api/types.go @@ -200,3 +200,59 @@ type ListSiteResourcesResponse struct { type MyClientSettingsResponse struct { Settings *config.ClientSettings `json:"settings"` } + +// LauncherLabel is a label on a launcher resource. +type LauncherLabel struct { + LabelID int `json:"labelId"` + Name string `json:"name"` + Color string `json:"color"` +} + +// LauncherSite is a site serving a launcher resource. +type LauncherSite struct { + SiteID int `json:"siteId"` + Name string `json:"name"` + NiceID string `json:"niceId"` + Type string `json:"type"` + Online *bool `json:"online"` +} + +// LauncherResource is a resource from GET /org/:orgId/launcher/resources. +// ResourceType is "site" for private resources and "public" for public ones. +type LauncherResource struct { + Key string `json:"launcherResourceKey"` + ResourceType string `json:"resourceType"` + ResourceID int `json:"resourceId"` + SiteResourceID *int `json:"siteResourceId"` + NiceID string `json:"niceId"` + Name string `json:"name"` + AccessDisplay string `json:"accessDisplay"` + AccessCopyValue string `json:"accessCopyValue"` + AccessURL *string `json:"accessUrl"` + Enabled bool `json:"enabled"` + Mode string `json:"mode"` + // Alias and PamMode are private resources only, and missing from older servers. + Alias *string `json:"alias"` + PamMode *string `json:"pamMode"` + Labels []LauncherLabel `json:"labels"` + Sites []LauncherSite `json:"sites"` +} + +// IsPrivate reports whether this is a private (site) resource. +func (r LauncherResource) IsPrivate() bool { return r.ResourceType == "site" } + +// LauncherPagination is the paging info of a launcher list. +type LauncherPagination struct { + Total int `json:"total"` + Page int `json:"page"` + PageSize int `json:"pageSize"` +} + +// ListLauncherResourcesResponse is the inner `data` of GET /org/:orgId/launcher/resources. +type ListLauncherResourcesResponse struct { + Resources []LauncherResource `json:"resources"` + Pagination LauncherPagination `json:"pagination"` +} + +// HasMore reports whether pages after this one exist. +func (p LauncherPagination) HasMore() bool { return p.Page*p.PageSize < p.Total } diff --git a/config/config.go b/config/config.go index 1ad259a..d5ccae8 100644 --- a/config/config.go +++ b/config/config.go @@ -49,6 +49,10 @@ type Config struct { CheckForUpdatesButtonEnabled *bool `json:"checkForUpdatesButtonEnabled,omitempty"` UpdateCheckIntervalSeconds *int `json:"updateCheckIntervalSeconds,omitempty"` AutoDownloadUpdatesEnabled *bool `json:"autoDownloadUpdatesEnabled,omitempty"` + // ShowResourcesInMenu shows the Resources section in the tray popup (default on). + ShowResourcesInMenu *bool `json:"showResourcesInMenu,omitempty"` + // ResourcesCollapsed folds the tray popup's Resources section to its header. + ResourcesCollapsed *bool `json:"resourcesCollapsed,omitempty"` // Orgs holds per-org overrides, keyed by org ID. Precedence when connecting // to an org: server settings > its entry here > the global settings above. @@ -300,6 +304,31 @@ func (cm *ConfigManager) UserConfigExists() bool { return err == nil } +// GetShowResourcesInMenu reports whether the tray popup lists the private +// resources the user can reach. On unless turned off. +func (cm *ConfigManager) GetShowResourcesInMenu() bool { + cm.mu.RLock() + defer cm.mu.RUnlock() + return cm.config == nil || cm.config.ShowResourcesInMenu == nil || *cm.config.ShowResourcesInMenu +} + +// GetResourcesCollapsed reports whether the tray popup's Resources section is +// folded to its header. +func (cm *ConfigManager) GetResourcesCollapsed() bool { + cm.mu.RLock() + defer cm.mu.RUnlock() + return cm.config != nil && cm.config.ResourcesCollapsed != nil && *cm.config.ResourcesCollapsed +} + +// SetResourcesCollapsed folds or unfolds the tray popup's Resources section. +func (cm *ConfigManager) SetResourcesCollapsed(value bool) bool { + cm.mu.Lock() + defer cm.mu.Unlock() + cfg := cm.getConfigCopy() + cfg.ResourcesCollapsed = &value + return cm.save(cfg) +} + // GetOnboardingSeenWelcome reports whether the setup welcome page was completed. func (cm *ConfigManager) GetOnboardingSeenWelcome() bool { cm.mu.RLock() @@ -802,6 +831,14 @@ func mergeConfig(base, override *Config) *Config { v := *override.AutoDownloadUpdatesEnabled merged.AutoDownloadUpdatesEnabled = &v } + if override.ShowResourcesInMenu != nil { + v := *override.ShowResourcesInMenu + merged.ShowResourcesInMenu = &v + } + if override.ResourcesCollapsed != nil { + v := *override.ResourcesCollapsed + merged.ResourcesCollapsed = &v + } if override.OnboardingSeenWelcome != nil { v := *override.OnboardingSeenWelcome merged.OnboardingSeenWelcome = &v @@ -907,6 +944,14 @@ func copyConfig(src *Config) *Config { autoDownloadUpdatesEnabled := *src.AutoDownloadUpdatesEnabled cfg.AutoDownloadUpdatesEnabled = &autoDownloadUpdatesEnabled } + if src.ShowResourcesInMenu != nil { + showResourcesInMenu := *src.ShowResourcesInMenu + cfg.ShowResourcesInMenu = &showResourcesInMenu + } + if src.ResourcesCollapsed != nil { + resourcesCollapsed := *src.ResourcesCollapsed + cfg.ResourcesCollapsed = &resourcesCollapsed + } if src.OnboardingSeenWelcome != nil { onboardingSeenWelcome := *src.OnboardingSeenWelcome cfg.OnboardingSeenWelcome = &onboardingSeenWelcome diff --git a/docs/dev/linux.md b/docs/dev/linux.md index 6f26848..3031d85 100644 --- a/docs/dev/linux.md +++ b/docs/dev/linux.md @@ -101,9 +101,11 @@ admins install immediately; others are asked via polkit (`pkcheck `packaging/linux/net.pangolin.client.policy` must be installed (all packages and `install-linux` do). pkcheck exit codes: 1 not authorized, 2 no authentication agent in the session, 3 cancelled, 127 + "is not registered" = -policy missing. The install downloads `pangolin-cli_linux_` from the -CLI's latest GitHub release (`managers/cli_release.go`, shared with Windows), -checks it's an ELF, and renames it into `/usr/local/bin/pangolin` (same place +policy missing. The install gets the latest CLI version and asset checksums +from the Fossorial API (`api.fossorial.io/api/v1/versions/cli`, as `get-cli.sh` +does), downloads `pangolin-cli_linux_` from that version's GitHub release +(`managers/cli_release.go`, shared with Windows), checks its sha256 and that +it's an ELF, and renames it into `/usr/local/bin/pangolin` (same place `get-cli.sh` uses). Test with network: `PANGOLIN_TEST_CLI_DOWNLOAD=1 go test ./managers -run CLI`. ## Secrets (`managers/secretstore/filestore_linux.go`) diff --git a/managers/cli_installer_linux.go b/managers/cli_installer_linux.go index f0ef0cd..f2d2fa8 100644 --- a/managers/cli_installer_linux.go +++ b/managers/cli_installer_linux.go @@ -14,8 +14,8 @@ import ( "github.com/fosrl/newt/logger" ) -// The daemon installs the CLI binary from the CLI's GitHub release into the -// same place its install script (get-cli.sh) does. +// The daemon installs the CLI binary (see cli_release.go) into the same place +// its install script (get-cli.sh) does. var cliInstallDir = "/usr/local/bin" const cliBinaryName = "pangolin" @@ -77,15 +77,15 @@ func InstallCLI(userToken uintptr) error { if err != nil { return err } - release, err := getLatestCLIRelease(cliInstallerRepo) + release, err := getLatestCLIRelease() if err != nil { return err } - url, err := release.assetURL(asset) + url, digest, err := release.asset(asset) if err != nil { return err } - logger.Info("Installing Pangolin CLI %s from %s", release.TagName, url) + logger.Info("Installing Pangolin CLI %s from %s", release.Version, url) if err := os.MkdirAll(cliInstallDir, 0o755); err != nil { return err @@ -102,7 +102,7 @@ func InstallCLI(userToken uintptr) error { if err := os.Remove(tmpPath); err != nil { return err } - if err := downloadCLIAsset(url, tmpPath); err != nil { + if err := downloadCLIAsset(url, tmpPath, digest); err != nil { return err } if err := checkELF(tmpPath); err != nil { @@ -115,7 +115,7 @@ func InstallCLI(userToken uintptr) error { if err := os.Rename(tmpPath, target); err != nil { return fmt.Errorf("failed to install %s: %w", target, err) } - logger.Info("Installed Pangolin CLI %s at %s", release.TagName, target) + logger.Info("Installed Pangolin CLI %s at %s", release.Version, target) return nil } diff --git a/managers/cli_installer_windows.go b/managers/cli_installer_windows.go index 55ceb9e..5f3e5ba 100644 --- a/managers/cli_installer_windows.go +++ b/managers/cli_installer_windows.go @@ -7,6 +7,8 @@ import ( "os/exec" "path/filepath" "syscall" + + "github.com/fosrl/newt/logger" ) const cliInstallerAssetName = "pangolin-cli_windows_installer.msi" @@ -34,23 +36,25 @@ func authorizeCLIInstall(s *ManagerService) (userToken, error) { } func InstallCLI(userToken uintptr) error { - release, err := getLatestCLIRelease(cliInstallerRepo) + release, err := getLatestCLIRelease() if err != nil { return err } - installerURL, err := release.assetURL(cliInstallerAssetName) + installerURL, digest, err := release.asset(cliInstallerAssetName) if err != nil { return err } + logger.Info("Installing Pangolin CLI %s from %s", release.Version, installerURL) tempDir, err := os.MkdirTemp("", "pangolin-cli-install-*") if err != nil { return fmt.Errorf("failed to create temp dir: %w", err) } + defer os.RemoveAll(tempDir) installerPath := filepath.Join(tempDir, cliInstallerAssetName) - if err := downloadCLIAsset(installerURL, installerPath); err != nil { + if err := downloadCLIAsset(installerURL, installerPath, digest); err != nil { return err } diff --git a/managers/cli_release.go b/managers/cli_release.go index 2020fe5..176535f 100644 --- a/managers/cli_release.go +++ b/managers/cli_release.go @@ -1,77 +1,91 @@ package managers import ( + "crypto/sha256" + "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" "os" + "regexp" "strings" "time" ) -// The CLI install on each platform downloads an asset from the CLI's latest -// GitHub release. -const cliInstallerRepo = "fosrl/cli" +// The CLI install on each platform asks the Fossorial API for the latest CLI +// version and its assets' checksums, as the CLI's install script (get-cli.sh) +// does, then downloads the asset from that version's GitHub release. +const ( + cliReleaseAPIURL = "https://api.fossorial.io/api/v1/versions/cli" + cliReleaseDownloadURL = "https://github.com/fosrl/cli/releases/download" + cliInstallerUserAgent = "pangolin-client-cli-installer" +) -type githubReleaseAsset struct { - Name string `json:"name"` - URL string `json:"browser_download_url"` -} +// cliVersionPattern matches the release versions get-cli.sh accepts, so a +// version can't change the shape of the download URL. +var cliVersionPattern = regexp.MustCompile(`^[0-9A-Za-z.+-]+$`) -type githubReleaseResponse struct { - TagName string `json:"tag_name"` - HTMLURL string `json:"html_url"` - Assets []githubReleaseAsset `json:"assets"` +type cliRelease struct { + Version string + AssetDigests map[string]string } -const cliInstallerUserAgent = "pangolin-client-cli-installer" - -func getLatestCLIRelease(repo string) (*githubReleaseResponse, error) { - repoParts := strings.Split(repo, "/") - if len(repoParts) != 2 || repoParts[0] == "" || repoParts[1] == "" { - return nil, fmt.Errorf("invalid repo %q, expected owner/name", repo) - } +type cliReleaseResponse struct { + Data struct { + LatestVersion string `json:"latestVersion"` + AssetDigests map[string]string `json:"assetDigests"` + } `json:"data"` +} - url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", repoParts[0], repoParts[1]) - req, err := http.NewRequest(http.MethodGet, url, nil) +func getLatestCLIRelease() (*cliRelease, error) { + req, err := http.NewRequest(http.MethodGet, cliReleaseAPIURL, nil) if err != nil { return nil, fmt.Errorf("failed to create release request: %w", err) } - req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("Accept", "application/json") req.Header.Set("User-Agent", cliInstallerUserAgent) client := &http.Client{Timeout: 15 * time.Second} resp, err := client.Do(req) if err != nil { - return nil, fmt.Errorf("failed to query GitHub releases: %w", err) + return nil, fmt.Errorf("failed to get the latest CLI version: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - return nil, fmt.Errorf("GitHub releases API returned %d: %s", resp.StatusCode, string(body)) + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) + return nil, fmt.Errorf("CLI version API returned %d: %s", resp.StatusCode, string(body)) } - var release githubReleaseResponse - if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { - return nil, fmt.Errorf("failed to decode release response: %w", err) + var body cliReleaseResponse + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + return nil, fmt.Errorf("failed to decode the CLI version response: %w", err) + } + version := strings.TrimPrefix(body.Data.LatestVersion, "v") + if !cliVersionPattern.MatchString(version) { + return nil, fmt.Errorf("CLI version API returned an invalid version %q", body.Data.LatestVersion) } - return &release, nil + return &cliRelease{Version: version, AssetDigests: body.Data.AssetDigests}, nil } -// assetURL returns the download URL of the release asset called name. -func (r *githubReleaseResponse) assetURL(name string) (string, error) { - for _, asset := range r.Assets { - if asset.Name == name && asset.URL != "" { - return asset.URL, nil - } +// asset returns the download URL and published sha256 of the release asset +// called name. An asset without a published checksum isn't installed. +func (r *cliRelease) asset(name string) (url, digest string, err error) { + digest = strings.ToLower(r.AssetDigests[name]) + if len(digest) != sha256.Size*2 { + return "", "", fmt.Errorf("CLI %s has no published checksum for %s", r.Version, name) + } + if _, err := hex.DecodeString(digest); err != nil { + return "", "", fmt.Errorf("CLI %s has an invalid checksum for %s", r.Version, name) } - return "", fmt.Errorf("latest release does not include %s (release: %s)", name, r.HTMLURL) + return fmt.Sprintf("%s/%s/%s", cliReleaseDownloadURL, r.Version, name), digest, nil } -// downloadCLIAsset saves url to destPath, which it creates. -func downloadCLIAsset(url, destPath string) error { +// downloadCLIAsset saves url to destPath, which it creates, and checks it +// against the published sha256. A file that doesn't match is removed. +func downloadCLIAsset(url, destPath, digest string) (err error) { req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return fmt.Errorf("failed to create download request: %w", err) @@ -87,7 +101,7 @@ func downloadCLIAsset(url, destPath string) error { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) return fmt.Errorf("CLI download failed with %d: %s", resp.StatusCode, string(body)) } @@ -95,10 +109,22 @@ func downloadCLIAsset(url, destPath string) error { if err != nil { return fmt.Errorf("failed to create download file: %w", err) } - defer out.Close() + defer func() { + out.Close() + if err != nil { + os.Remove(destPath) + } + }() - if _, err := io.Copy(out, resp.Body); err != nil { + hash := sha256.New() + if _, err := io.Copy(io.MultiWriter(out, hash), resp.Body); err != nil { return fmt.Errorf("failed to write download file: %w", err) } - return out.Close() + if err := out.Close(); err != nil { + return fmt.Errorf("failed to write download file: %w", err) + } + if got := hex.EncodeToString(hash.Sum(nil)); got != digest { + return errors.New("the downloaded CLI doesn't match its published checksum; it may be corrupted or tampered with") + } + return nil } diff --git a/ui/actions.go b/ui/actions.go index 6fb5ac0..2a65af2 100644 --- a/ui/actions.go +++ b/ui/actions.go @@ -30,7 +30,7 @@ func invokeMenuItem(id string) { // account and organization switches so their progress shows, and for exit // node selection so the checkmark just moves. keepOpen := id == menuIDConnect || strings.HasPrefix(id, menuPrefixAccount) || strings.HasPrefix(id, menuPrefixOrg) || - id == menuIDExitNodeNone || strings.HasPrefix(id, menuPrefixExitNode) + id == menuIDExitNodeNone || strings.HasPrefix(id, menuPrefixExitNode) || strings.HasPrefix(id, menuPrefixResourceExitNode) if !keepOpen { hideTrayPopup() } @@ -79,6 +79,8 @@ func invokeMenuItem(id string) { switchAccount(strings.TrimPrefix(id, menuPrefixAccount)) case strings.HasPrefix(id, menuPrefixOrg): selectOrganization(strings.TrimPrefix(id, menuPrefixOrg)) + case isResourceAction(id): + invokeResourceAction(id) case id == menuIDExitNodeNone: disableExitNode() case strings.HasPrefix(id, menuPrefixExitNode): diff --git a/ui/app.go b/ui/app.go index e24e4c2..9fb8146 100644 --- a/ui/app.go +++ b/ui/app.go @@ -72,6 +72,7 @@ func Run(d Deps) error { notifier = notifications.New() opts := appOptions(assets, []application.Service{ application.NewService(&MenuService{}), + application.NewService(&ResourcesService{}), application.NewService(&SettingsService{}), application.NewService(&StatusService{}), application.NewService(&LogsService{}), diff --git a/ui/exitnode.go b/ui/exitnode.go index f83c46c..2f2e6de 100644 --- a/ui/exitnode.go +++ b/ui/exitnode.go @@ -206,17 +206,25 @@ func selectExitNode(idStr string) { return } - if exitNodeLocked(org.Id) { - logger.Warn("Ignoring exit node selection: it is locked by the organization") - return - } - gateway, ok := findExitNode(org.Id, id) if !ok { logger.Error("Exit node %d no longer exists", id) refreshExitNodes() return } + selectExitNodeGateway(org.Id, gateway) +} + +// selectExitNodeGateway routes all traffic through gateway in orgID. With the +// tunnel up it takes effect immediately; otherwise it is applied on the next connect. +func selectExitNodeGateway(orgID string, gateway api.SiteResource) { + if accountManager == nil || tunnelManager == nil { + return + } + if exitNodeLocked(orgID) { + logger.Warn("Ignoring exit node selection: it is locked by the organization") + return + } if tunnelManager.State() == tunnel.StateRunning { if err := tunnelManager.SelectGateway(gateway.SiteResourceID, gateway.SiteIDs); err != nil { @@ -229,7 +237,7 @@ func selectExitNode(idStr string) { } active, err := accountManager.ActiveAccount() - if err != nil || accountManager.SetExitNode(active.UserID, org.Id, gateway.SiteResourceID) != nil { + if err != nil || accountManager.SetExitNode(active.UserID, orgID, gateway.SiteResourceID) != nil { logger.Warn("Exit node applied but could not be saved for the next connect") } logger.Info("Exit node set to %s", gateway.Name) diff --git a/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/index.ts b/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/index.ts index 717d1af..7aa51eb 100644 --- a/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/index.ts +++ b/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/index.ts @@ -8,6 +8,7 @@ import * as LoginService from "./loginservice.js"; import * as LogsService from "./logsservice.js"; import * as MenuService from "./menuservice.js"; import * as OnboardingService from "./onboardingservice.js"; +import * as ResourcesService from "./resourcesservice.js"; import * as SettingsService from "./settingsservice.js"; import * as StatusService from "./statusservice.js"; import * as UpdateService from "./updateservice.js"; @@ -19,6 +20,7 @@ export { LogsService, MenuService, OnboardingService, + ResourcesService, SettingsService, StatusService, UpdateService @@ -34,8 +36,12 @@ export type { LoginView, LogsSnapshot, MenuItem, + MenuResources, MenuState, OnboardingState, + ResourceRow, + ResourceSite, + ResourcesPage, Settings, SettingsOpened, SettingsResult, diff --git a/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/models.ts b/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/models.ts index d939401..990deec 100644 --- a/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/models.ts +++ b/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/models.ts @@ -169,6 +169,34 @@ export interface MenuItem { */ "value": string; "items"?: MenuItem[] | null; + + /** + * Resources configures a MenuKindResources row. + */ + "resources"?: MenuResources | null; +} + +/** + * MenuResources is what the Resources section needs from the menu state. + */ +export interface MenuResources { + /** + * Scope changes with the org, user or server; the section then starts over. + */ + "scope": string; + "collapsed": boolean; + + /** + * ActiveExitNodeID is the exit node in use (0 for none), so an exit node + * resource can show whether it's the one. + */ + "activeExitNodeId": number; + + /** + * ExitNodeChangeable is false while the exit node can't be changed: the + * server locks it, or the tunnel or account is switching. + */ + "exitNodeChangeable": boolean; } /** @@ -199,6 +227,68 @@ export interface OnboardingState { "opened": number; } +/** + * ResourceRow is a private resource as the tray popup shows it. + */ +export interface ResourceRow { + "key": string; + "name": string; + "mode": string; + "modeLabel": string; + + /** + * Address is what to show for how to reach it, or "" when there's none. + */ + "address": string; + "labels": string[] | null; + + /** + * Sites are the first few, online first; SiteCount and OnlineSiteCount count all. + */ + "sites": ResourceSite[] | null; + "siteCount": number; + "onlineSiteCount": number; + "canOpen": boolean; + "canCopyAddress": boolean; + "canCopySsh": boolean; + + /** + * ExitNodeID is the site resource ID when this is an exit node, else 0. + */ + "exitNodeId": number; +} + +/** + * ResourceSite is a site serving a resource, as its details list it. + */ +export interface ResourceSite { + "name": string; + "online": boolean; +} + +/** + * ResourcesPage is the answer to one load of the Resources section. + */ +export interface ResourcesPage { + /** + * Scope is the org, user and server the page belongs to. The popup drops + * pages for a scope other than the menu's. + */ + "scope": string; + "items": ResourceRow[] | null; + + /** + * NextPage is the page to ask for to continue, when HasMore. + */ + "nextPage": number; + "hasMore": boolean; + + /** + * Error is set when the load failed for a reason worth showing. + */ + "error": string; +} + /** * Settings is the form shared by the General and Connection tabs. The tunnel * settings are what the current org actually uses, so they aren't always the @@ -226,6 +316,12 @@ export interface Settings { */ "autoDownloadUpdatesUnavailable": string; + /** + * ShowResources lists the private resources the user can reach in the tray + * popup. An application setting, so always global. + */ + "showResources": boolean; + /** * Disabled is set when an administrator has turned off user settings. */ diff --git a/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/resourcesservice.ts b/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/resourcesservice.ts new file mode 100644 index 0000000..c565e84 --- /dev/null +++ b/ui/frontend/src/bindings/github.com/fosrl/windows-linux/ui/resourcesservice.ts @@ -0,0 +1,36 @@ +// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL +// This file is automatically generated. DO NOT EDIT + +/** + * ResourcesService backs the tray popup's Resources section. + * @module + */ + +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore: Unused imports +import { Call as $Call, CancellablePromise as $CancellablePromise } from "@wailsio/runtime"; + +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore: Unused imports +import * as $models from "./models.js"; + +/** + * List loads one page of the current org's private resources matching query. + */ +export function List(query: string, page: number): $CancellablePromise<$models.ResourcesPage> { + return $Call.ByID(537901376, query, page); +} + +/** + * Refresh drops the server's cached results, before the popup reloads. + */ +export function Refresh(): $CancellablePromise { + return $Call.ByID(2099457155); +} + +/** + * SetCollapsed folds or unfolds the section, and remembers it. + */ +export function SetCollapsed(collapsed: boolean): $CancellablePromise { + return $Call.ByID(1296278545, collapsed); +} diff --git a/ui/frontend/src/mocks/bindings.ts b/ui/frontend/src/mocks/bindings.ts index a24a854..1b25f05 100644 --- a/ui/frontend/src/mocks/bindings.ts +++ b/ui/frontend/src/mocks/bindings.ts @@ -6,6 +6,8 @@ import type { LogsSnapshot, LoginView, MenuState, + ResourceRow, + ResourcesPage, Settings, SettingsOpened, StatusView, @@ -85,6 +87,13 @@ return { id: "exitnodes", kind: "submenu", label: "None", items: [hdr("Route All Traffic Through", true), check("exitnode.none", "None", true), check("exitnode:7", "Office")], }), + ...(locked || !settings.showResources ? [] : [ + sep, + row({ + id: "resources", kind: "resources", label: "Resources", + resources: { scope: "mock", collapsed: resourcesCollapsed, activeExitNodeId: activeExitNode, exitNodeChangeable: true }, + }), + ]), ]), sep, it("settings", "Settings…"), @@ -108,6 +117,10 @@ function mockInvoke(id: string) { if (id === "connect") { menuState = menuState === "connected" ? "disconnected" : "connected"; emit(); + } else if (id.startsWith("resource.exitNode:")) { + const r = mockResources.find((m) => `resource.exitNode:${m.key}` === id); + activeExitNode = r && activeExitNode !== r.exitNodeId ? r.exitNodeId : 0; + emit(); } else if (id.startsWith("account:") || id.startsWith("org:")) { const was = menuState; menuState = "loading"; @@ -123,7 +136,7 @@ function mockInvoke(id: string) { const settings: Settings = { openAtLogin: true, autoConnect: false, dnsOverride: true, dnsTunnel: false, primaryDns: "", secondaryDns: "", mtu: "1280", exitNodeTakesPrecedence: false, - autoDownloadUpdates: false, + autoDownloadUpdates: false, showResources: !params.has("noResources"), autoDownloadUpdatesUnavailable: params.has("aur") ? "Pangolin was installed from the AUR. Update the pangolin-client-bin package with your AUR helper, for example: yay -Syu pangolin-client-bin" : "", @@ -178,6 +191,48 @@ function mockLoginStart(hostname: string) { const layout: TrayLayout = { submenuSide: "right", anchor: "top", panelWidth: 310, padding: 8 }; +// Resources section: 300 fake private resources, searched and paged with a +// delay like the server. `?resources=none|error` previews the empty and error states. +let resourcesCollapsed = false; +let activeExitNode = 0; +const modes = ["host", "host", "host", "cidr", "http", "ssh", "inference", "gateway"]; +const words = ["postgres", "redis", "grafana", "gitlab", "vault", "jenkins", "nas", "printer", "office-vpn", "k8s-api"]; +const envs = ["prod", "staging", "dev"]; +const mockResources: ResourceRow[] = params.get("resources") === "none" ? [] : Array.from({ length: 300 }, (_, i) => { + const mode = modes[i % modes.length]; + const name = mode === "gateway" ? `exit-${envs[i % 3]}-${i}` : `${words[i % words.length]}-${envs[i % 3]}-${i}`; + const siteCount = i % 17 === 0 ? 1200 : (i % 5) + 1; + const sites = Array.from({ length: Math.min(siteCount, 10) }, (_, s) => ({ name: `edge-site-${String(s + 1).padStart(4, "0")}`, online: s % 3 !== 2 })); + return { + key: `site:${i}`, name, mode, + modeLabel: { host: "Host", cidr: "CIDR Range", http: "HTTP", ssh: "SSH", inference: "AI Inference", gateway: "Exit Node" }[mode] ?? mode, + address: mode === "gateway" ? "Routes all traffic" : mode === "http" ? `https://${name}.internal` : `${name}.internal`, + labels: i % 4 === 0 ? ["Production"] : [], + sites, siteCount, onlineSiteCount: Math.round(siteCount * 0.66), + canOpen: mode === "http", canCopyAddress: mode !== "gateway", canCopySsh: mode === "ssh", + exitNodeId: mode === "gateway" ? 1000 + i : 0, + }; +}); +function mockListResources(query: string, page: number): Promise { + log("resources list", query, page); + const q = query.trim().toLowerCase(); + const matches = mockResources.filter((r) => !q || r.name.includes(q) || r.address.includes(q)); + const items = matches.slice((page - 1) * 25, page * 25); + const result: ResourcesPage = params.get("resources") === "error" + ? { scope: "mock", items: [], nextPage: page, hasMore: false, error: "Cannot connect to server at https://app.pangolin.net." } + : { scope: "mock", items, nextPage: page + 1, hasMore: page * 25 < matches.length, error: "" }; + return new Promise((resolve) => setTimeout(() => resolve(result), 350)); +} +export const ResourcesService = { + List: mockListResources, + Refresh: () => new Promise((resolve) => setTimeout(resolve, 300)), + SetCollapsed: (c: boolean) => { + resourcesCollapsed = c; + Events.Emit("menu:state", buildMenu()); + return ok(undefined); + }, +}; + export const MenuService = { State: () => ok(buildMenu()), Layout: () => ok(layout), Invoke: mockInvoke, Resize: (h: number) => ok(log("resize", h)), Hide: () => ok(log("hide")), diff --git a/ui/frontend/src/settings/GeneralTab.tsx b/ui/frontend/src/settings/GeneralTab.tsx index b2542b5..95a05cd 100644 --- a/ui/frontend/src/settings/GeneralTab.tsx +++ b/ui/frontend/src/settings/GeneralTab.tsx @@ -45,6 +45,17 @@ export function GeneralTab({ +
+ + toggle({ showResources: v })} + /> + +
+
([]); + const [loading, setLoading] = useState(false); + const [loadingMore, setLoadingMore] = useState(false); + const [error, setError] = useState(""); + // The search the shown rows belong to, trimmed; null until the first load. + const [loadedQuery, setLoadedQuery] = useState(null); + // The most rows the list has shown since the menu opened. The list keeps + // that height while searching, so the menu doesn't shrink and jump around. + const [reservedRows, setReservedRows] = useState(0); + + const generation = useRef(0); + const scopeRef = useRef(scope); + const queryRef = useRef(query); + // The search the latest first-page load was started for. + const requestedQuery = useRef(null); + const nextPage = useRef(1); + const hasMore = useRef(false); + const busy = useRef(false); + const debounce = useRef(undefined); + const errorRef = useRef(""); + + const load = useCallback((replace: boolean) => { + if (!scopeRef.current) return; + const gen = ++generation.current; + const q = queryRef.current.trim(); + busy.current = true; + if (replace) { + requestedQuery.current = q; + setLoading(true); + setLoadingMore(false); + } else { + setLoadingMore(true); + } + const page = replace ? 1 : nextPage.current; + report( + ResourcesService.List(q, page) + .then((result) => { + // A newer load, or another org, has taken over. + if (gen !== generation.current || result.scope !== scopeRef.current) return; + const items = result.items ?? []; + if (result.error && (replace || items.length === 0)) { + errorRef.current = result.error; + setError(result.error); + } else { + errorRef.current = ""; + setError(""); + } + if (!result.error || items.length > 0) { + setRows((prev) => { + if (replace) return items; + // Resources added or removed between page loads shift the pages, so skip repeats. + const seen = new Set(prev.map((r) => r.key)); + return [...prev, ...items.filter((r) => !seen.has(r.key))]; + }); + nextPage.current = result.nextPage; + hasMore.current = result.hasMore; + } + if (replace) setLoadedQuery(q); + }) + .finally(() => { + if (gen !== generation.current) return; + busy.current = false; + setLoading(false); + setLoadingMore(false); + }), + ); + }, []); + + const reset = useCallback(() => { + generation.current++; + window.clearTimeout(debounce.current); + busy.current = false; + queryRef.current = ""; + requestedQuery.current = null; + nextPage.current = 1; + hasMore.current = false; + errorRef.current = ""; + setQueryState(""); + setRows([]); + setLoading(false); + setLoadingMore(false); + setError(""); + setLoadedQuery(null); + setReservedRows(0); + }, []); + + // A new org, user or server starts over with an empty search. + useEffect(() => { + if (scopeRef.current === scope) return; + scopeRef.current = scope; + reset(); + }, [scope, reset]); + + // Load when the section shows: first appearance, a new org, or unfolding it. + useEffect(() => { + if (active && scope) load(true); + }, [active, scope, load]); + + // Opening the menu reloads the current search, so it shows fresh results. + const shownRows = Math.min(rows.length + (loadingMore ? 1 : 0), maxVisibleRows); + const shownRowsRef = useRef(shownRows); + shownRowsRef.current = shownRows; + useEffect(() => { + setReservedRows((reserved) => Math.max(reserved, shownRows)); + }, [shownRows]); + + useEvent("tray:open", () => { + // A new opening sizes the list afresh, from the rows it shows now. Not from + // zero: the rows don't change on opening, so nothing would raise it again + // and the first search would shrink the list. + setReservedRows(shownRowsRef.current); + if (active && scopeRef.current) load(true); + }); + + // Folding the section starts the reserved height over too. + useEffect(() => { + if (!active) setReservedRows(shownRowsRef.current); + }, [active]); + + const setQuery = useCallback( + (value: string) => { + queryRef.current = value; + setQueryState(value); + window.clearTimeout(debounce.current); + debounce.current = window.setTimeout(() => { + if (value.trim() !== requestedQuery.current || errorRef.current) load(true); + }, searchDebounceMs); + }, + [load], + ); + + /** Drops the server's cached results first (kept up to a minute), then reloads. */ + const refresh = useCallback(() => { + if (!scopeRef.current) return; + const gen = ++generation.current; + window.clearTimeout(debounce.current); + busy.current = true; + setLoading(true); + report( + ResourcesService.Refresh().finally(() => { + if (gen === generation.current) load(true); + }), + ); + }, [load]); + + /** Fetches the next page once a row near the end comes into view. */ + const loadMoreIfNeeded = useCallback( + (lastVisibleIndex: number, count: number) => { + if (!hasMore.current || busy.current) return; + if (lastVisibleIndex >= count - loadAheadRows) load(false); + }, + [load], + ); + + // Fill the visible list. A server that can't filter by type can return pages + // of public resources only, which leave nothing on screen to scroll to. + useEffect(() => { + if (!loading && !loadingMore && !error && hasMore.current && rows.length < maxVisibleRows) load(false); + }, [loading, loadingMore, error, rows.length, load]); + + return { + query, + setQuery, + rows, + loading, + loadingMore, + error, + loadedQuery, + // Read in render, so the list never draws shorter than it has been. + reservedRows: Math.max(reservedRows, shownRows), + refresh, + loadMoreIfNeeded, + }; +} + +export type ResourcesModel = ReturnType; + +/** What the section needs from the tray popup around it. */ +export type ResourcesContextValue = { + model: ResourcesModel; + config: MenuResources; + /** The resource whose details are open, as a submenu ID. */ + openSubmenu?: string; + /** The one to show as selected: not while the pointer is leaving it. */ + selectedSubmenu?: string; + onOpenSubmenu: (item: MenuItem, el: HTMLElement, immediate: boolean) => void; + closeSubmenus: () => void; +}; + +export const ResourcesContext = createContext(null); + +const menuItem = (r: Partial): MenuItem => ({ + id: "", kind: "item", label: "", enabled: true, checked: false, checkable: false, + loading: false, dot: "", icon: "", inset: false, value: "", ...r, +}); + +/** The resource rows as menu items, each opening its details. */ +export function useResourceMenuItems(model: ResourcesModel, config: MenuResources | undefined) { + return useMemo( + () => + config + ? model.rows.map((r) => + menuItem({ id: resourceSubmenuPrefix + r.key, kind: "submenu", label: r.name, items: resourceDetail(r, config) }), + ) + : [], + [model.rows, config], + ); +} + +/** Details for one resource: its type, address, labels, sites and actions. */ +function resourceDetail(r: ResourceRow, config: MenuResources): MenuItem[] { + const detail = (label: string, value: string) => menuItem({ kind: "detail", label, value: value || "—", enabled: false }); + const items: MenuItem[] = [ + menuItem({ kind: "header", label: r.name, enabled: false }), + detail("Type", r.modeLabel), + detail("Address", r.address), + ]; + const labels = r.labels ?? []; + if (labels.length) items.push(detail("Labels", labels.join(", "))); + + items.push(menuItem({ kind: "separator", enabled: false })); + const sites = r.sites ?? []; + const summary = + r.siteCount === 0 ? "Sites" : `${r.siteCount === 1 ? "1 Site" : `${r.siteCount} Sites`} · ${r.onlineSiteCount} Online`; + items.push(menuItem({ kind: "header", label: summary, enabled: false })); + if (r.siteCount === 0) items.push(menuItem({ kind: "label", label: "No sites", enabled: false })); + sites.forEach((s, i) => + items.push(menuItem({ id: `site-${r.key}-${i}`, kind: "site", label: s.name, dot: s.online ? "green" : "gray", enabled: false })), + ); + if (r.siteCount > sites.length) + items.push(menuItem({ kind: "label", label: `and ${r.siteCount - sites.length} more`, enabled: false })); + + if (r.exitNodeId) { + const inUse = config.activeExitNodeId === r.exitNodeId; + items.push( + menuItem({ kind: "separator", enabled: false }), + menuItem({ + id: `resource.exitNode:${r.key}`, + label: inUse ? "Stop Using as Exit Node" : "Use as Exit Node", + checkable: true, + checked: inUse, + enabled: config.exitNodeChangeable, + }), + ); + } + + const actions: MenuItem[] = []; + if (r.canOpen) actions.push(menuItem({ id: `resource.open:${r.key}`, label: "Open in Browser" })); + if (r.canCopySsh) actions.push(menuItem({ id: `resource.copySSH:${r.key}`, label: "Copy SSH Command" })); + if (r.canCopyAddress) actions.push(menuItem({ id: `resource.copyAddress:${r.key}`, label: "Copy Address" })); + if (actions.length) items.push(menuItem({ kind: "separator", enabled: false }), ...actions); + return items; +} + +/** The section itself, rendered in place of the menu's "resources" row. */ +export function ResourcesSection({ onHoverRow }: { onHoverRow: () => void }) { + const ctx = useContext(ResourcesContext); + // Folding shows at once; the saved setting catches up through the menu state. + const [collapsed, setCollapsed] = useState(ctx?.config.collapsed ?? false); + const configCollapsed = ctx?.config.collapsed; + useEffect(() => { + if (configCollapsed !== undefined) setCollapsed(configCollapsed); + }, [configCollapsed]); + if (!ctx) return null; + const { model } = ctx; + + const toggle = () => { + ctx.closeSubmenus(); + setCollapsed(!collapsed); + report(ResourcesService.SetCollapsed(!collapsed)); + }; + + return ( +
+ {/* The header, the search field and the list each count as another row, so + moving between them closes a resource's details like any other row. */} +
+ Resources + {!collapsed && + (model.loading ? ( + + + + ) : ( + + ))} + {/* As wide as the rows' chevrons, so it lines up with them. */} + + + +
+ {!collapsed && ( + <> +
+ +
+ {/* Its rows open their own details, which replaces this. */} +
+ +
+ + )} +
+ ); +} + +function ResourcesList() { + const ctx = useContext(ResourcesContext)!; + const { model } = ctx; + const items = useResourceMenuItems(model, ctx.config); + const scrollRef = useRef(null); + + if (items.length === 0) { + let text = "No private resources"; + let warning = false; + if (model.loading || model.loadedQuery === null) text = "Loading…"; + else if (model.error) { + text = model.error; + warning = true; + } else if (model.loadedQuery) text = `No private resources match “${model.loadedQuery}”.`; + // Keeps the height the list had, with the message at the top. + return ( +
+ {warning && } + {text} +
+ ); + } + + const count = items.length + (model.loadingMore ? 1 : 0); + const onScroll = () => { + // A submenu opened from a row would stay put while its row scrolls away. + if (ctx.openSubmenu?.startsWith(resourceSubmenuPrefix)) ctx.closeSubmenus(); + const el = scrollRef.current; + if (!el) return; + const lastVisible = Math.floor((el.scrollTop + el.clientHeight) / rowHeight) - 1; + model.loadMoreIfNeeded(lastVisible, model.rows.length); + }; + + return ( +
+ {items.map((item, i) => { + const row = model.rows[i]; + const open = ctx.selectedSubmenu === item.id; + return ( +
ctx.onOpenSubmenu(item, e.currentTarget, false)} + onClick={(e) => ctx.onOpenSubmenu(item, e.currentTarget, true)} + className={cx( + "flex h-[26px] items-center gap-2 rounded-[6px] px-[10px] whitespace-nowrap hover:bg-mac-menu-hover", + open && "bg-mac-menu-hover", + )} + > + + + + {item.label} + +
+ ); + })} + {model.loadingMore && ( +
+ +
+ )} +
+ ); +} + +/** A rounded search field styled to sit among menu rows. */ +function SearchField({ value, onChange }: { value: string; onChange: (v: string) => void }) { + return ( +
+ + + + + onChange(e.target.value)} + placeholder="Search resources" + aria-label="Search resources" + spellCheck={false} + autoComplete="off" + className="min-w-0 flex-1 bg-transparent text-[13px] text-mac-label outline-none placeholder:text-mac-tertiary" + /> + {value && ( + + )} +
+ ); +} + +function DisclosureChevron() { + return ( + + + + ); +} + +function RefreshIcon() { + return ( + + + + + ); +} + +function WarningIcon() { + return ( + + + + ); +} + +/** A small symbol for each private resource mode, like the macOS menu's. */ +function ModeIcon({ mode }: { mode: string }) { + const common = { viewBox: "0 0 14 14", className: "size-[13px]", fill: "none", stroke: "currentColor", strokeWidth: 1.3, "aria-hidden": true } as const; + switch (mode) { + case "host": + return ( + + + + + + ); + case "cidr": + return ( + + + + + + + ); + case "http": + return ( + + + + + + ); + case "ssh": + return ( + + + + + ); + case "inference": + return ( + + + + + ); + case "gateway": + return ( + + + + + ); + default: + return ( + + + + + ); + } +} diff --git a/ui/frontend/src/tray/TrayMenu.tsx b/ui/frontend/src/tray/TrayMenu.tsx index 99f0806..4a1344c 100644 --- a/ui/frontend/src/tray/TrayMenu.tsx +++ b/ui/frontend/src/tray/TrayMenu.tsx @@ -1,12 +1,23 @@ -import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react"; import { MenuService, type MenuItem, type MenuState, type TrayLayout } from "@bindings"; import { report, useEvent } from "../lib"; import { Chevron, Spinner, StatusDot, Switch, cx } from "../components/controls"; +import { + ResourcesContext, + ResourcesSection, + resourceSubmenuPrefix, + useResourceMenuItems, + useResources, + type ResourcesContextValue, +} from "./ResourcesSection"; // Geometry and timing follow the macOS menu bar panel (MenuBarComponents.swift // and MenuSubmenuPanel.swift). const defaultLayout: TrayLayout = { submenuSide: "left", anchor: "bottom", panelWidth: 310, padding: 8 }; const submenuHoverDelay = 120; +// Passing over other rows on the way into a submenu leaves it open this long, +// so it can be reached diagonally. +const submenuCloseDelay = 300; const submenuMinWidth = 180; // The loading spinner stays up at least this long so it doesn't flash. const minLoadingMs = 700; @@ -59,6 +70,9 @@ export function TrayMenu() { const [firstSubmenuWidth, setFirstSubmenuWidth] = useState(0); const panelRef = useRef(null); const hoverTimer = useRef(undefined); + // The level whose submenu is about to close or be replaced. Its row stops + // looking selected at once, so only the row under the pointer is highlighted. + const [leavingLevel, setLeavingLevel] = useState(null); const loading = useMinimumDuration(state.loading, minLoadingMs); // Only a rendered menu's height is kept for the spinner, not the empty // panel shown before the first state arrives. @@ -130,7 +144,15 @@ export function TrayMenu() { }); const items = state.items ?? []; - const first = path[0] && !loading ? items.find((i) => i.id === path[0].id && opensSubmenu(i)) : undefined; + // The Resources section loads its own list; its rows open details like any submenu row. + const resourcesConfig = useMemo(() => items.find((i) => i.kind === "resources")?.resources ?? undefined, [items]); + const resources = useResources(resourcesConfig); + const resourceItems = useResourceMenuItems(resources, resourcesConfig); + const topLevel = (id: string) => + id.startsWith(resourceSubmenuPrefix) + ? resourceItems.find((i) => i.id === id) + : items.find((i) => i.id === id && opensSubmenu(i)); + const first = path[0] && !loading ? topLevel(path[0].id) : undefined; const second = first && path[1] ? first.items?.find((i) => i.id === path[1].id && opensSubmenu(i)) : undefined; // Close submenus whose rows went away, e.g. Sites once the tunnel disconnects. @@ -145,26 +167,53 @@ export function TrayMenu() { report(MenuService.SetSitesVisible(sitesOpen)); }, [sitesOpen]); - const schedule = (fn: () => void, immediate: boolean) => { + const schedule = (fn: () => void, immediate: boolean, delay = submenuHoverDelay, leaving: number | null = null) => { window.clearTimeout(hoverTimer.current); - if (immediate) fn(); - else hoverTimer.current = window.setTimeout(fn, submenuHoverDelay); + setLeavingLevel(immediate ? null : leaving); + const run = () => { + setLeavingLevel(null); + fn(); + }; + if (immediate) run(); + else hoverTimer.current = window.setTimeout(run, delay); }; - // Moving onto any other row closes the submenu open beside it right away. - const closeSubmenus = (level: number) => { - window.clearTimeout(hoverTimer.current); - setPath((p) => (p.length > level ? p.slice(0, level) : p)); + // Closes the submenus from `level` on. Hovering another row closes them + // after a moment, so the pointer can cross rows on its way into one; reaching + // it, or coming back to its row, keeps it open. + const closeSubmenus = (level: number, immediate = true) => { + if (path.length <= level) { + cancelPending(); + return; + } + schedule(() => setPath((p) => (p.length > level ? p.slice(0, level) : p)), immediate, submenuCloseDelay, level); }; const openSubmenu = (level: number, item: MenuItem, el: HTMLElement, immediate: boolean) => { - // Hovering a different submenu row drops the old one now; only the new one waits. - if (path[level] && path[level].id !== item.id) closeSubmenus(level); - schedule(() => { - setPath((p) => - p[level]?.id === item.id && p[level].anchor === el ? p : [...p.slice(0, level), { id: item.id, anchor: el }], - ); - }, immediate); + // Back on the open submenu's row: keep it. + if (path[level]?.id === item.id && path[level].anchor === el) { + cancelPending(); + return; + } + // Another submenu replaces the open one in a single step, so two are never + // open together. Hovering waits briefly; clicking switches at once. + schedule( + () => { + setPath((p) => + p[level]?.id === item.id && p[level].anchor === el ? p : [...p.slice(0, level), { id: item.id, anchor: el }], + ); + }, + immediate, + submenuHoverDelay, + path.length > level ? level : null, + ); }; - const cancelPending = () => window.clearTimeout(hoverTimer.current); + // The pointer reached a submenu or came back to its row: it stays, selected. + function cancelPending() { + window.clearTimeout(hoverTimer.current); + setLeavingLevel(null); + } + // The submenu row to show as selected at each level. + const selected = (level: number) => + leavingLevel !== null && leavingLevel <= level ? undefined : path[level]?.id; const invoke = useCallback((item: MenuItem) => { if (!item.enabled || !item.id) return; @@ -173,6 +222,17 @@ export function TrayMenu() { report(MenuService.Invoke(item.id)); }, []); + const resourcesContext: ResourcesContextValue | null = resourcesConfig + ? { + model: resources, + config: resourcesConfig, + openSubmenu: path[0]?.id, + selectedSubmenu: selected(0), + onOpenSubmenu: (item, el, immediate) => openSubmenu(0, item, el, immediate), + closeSubmenus: () => closeSubmenus(0), + } + : null; + const panelSide = layout.submenuSide === "left" ? { right: layout.padding } : { left: layout.padding }; const panelEdge = layout.anchor === "bottom" ? { bottom: layout.padding } : { top: layout.padding }; const firstOffset = layout.padding + layout.panelWidth - 2; @@ -210,13 +270,15 @@ export function TrayMenu() { ) : ( - openSubmenu(0, item, el, immediate)} - onHoverRow={() => closeSubmenus(0)} - /> + + openSubmenu(0, item, el, immediate)} + onHoverRow={() => closeSubmenus(0, false)} + /> + )} @@ -229,11 +291,11 @@ export function TrayMenu() { anchor={path[0].anchor} offset={firstOffset} layout={layout} - activeSubmenu={path[1]?.id} + activeSubmenu={selected(1)} onInvoke={invoke} onEnter={cancelPending} onOpenSubmenu={(item, el, immediate) => openSubmenu(1, item, el, immediate)} - onHoverRow={() => closeSubmenus(1)} + onHoverRow={() => closeSubmenus(1, false)} onWidth={setFirstSubmenuWidth} /> )} @@ -483,7 +545,7 @@ function MenuRows({ const rowPadding = "px-[10px]"; const highlight = - "rounded-[6px] transition-colors duration-100 hover:bg-mac-menu-hover hover:duration-0 active:bg-mac-menu-pressed"; + "rounded-[6px] hover:bg-mac-menu-hover active:bg-mac-menu-pressed"; function Row({ item, @@ -517,6 +579,20 @@ function Row({ ); + case "resources": + return ; + + case "site": + // A site serving a resource, in its details: a status dot and the name. + return ( +
+ + + + {item.label} +
+ ); + case "label": return (
0 { items = append(items, header("Exit Node"), exitNodeSubmenu(in)) } + if showAuth && in.showsResources() { + items = append(items, separator(), resourcesSection(in)) + } } items = append(items, separator()) @@ -541,6 +569,28 @@ func orgSubmenu(in menuInputs) MenuItem { } } +// showsResources reports whether the Resources section is shown: it is turned +// on, there is an org to list, and its server has the launcher API. +func (in menuInputs) showsResources() bool { + return in.ShowResources && in.ResourcesScope != "" && in.ResourcesSupported && + !in.SessionExpired && !in.ServerDown && in.CurrentOrgID != "" +} + +func resourcesSection(in menuInputs) MenuItem { + return MenuItem{ + ID: "resources", + Kind: MenuKindResources, + Label: "Resources", + Enabled: true, + Resources: &MenuResources{ + Scope: in.ResourcesScope, + Collapsed: in.ResourcesCollapsed, + ActiveExitNodeID: in.ActiveExitNodeID, + ExitNodeChangeable: !in.TunnelPhase.transitional() && !in.switching() && !in.ExitNodeLocked, + }, + } +} + func exitNodeSubmenu(in menuInputs) MenuItem { enabled := !in.TunnelPhase.transitional() && !in.switching() && !in.ExitNodeLocked sub := []MenuItem{ diff --git a/ui/resources.go b/ui/resources.go new file mode 100644 index 0000000..0ab230e --- /dev/null +++ b/ui/resources.go @@ -0,0 +1,404 @@ +package ui + +import ( + "errors" + "fmt" + "net/url" + "sort" + "strings" + "sync" + + "github.com/fosrl/newt/logger" + "github.com/fosrl/windows-linux/api" + "github.com/fosrl/windows-linux/tunnel" +) + +// The tray popup's Resources section lists the private resources the user can +// reach in the current org, like the macOS menu (PrivateResourcesSection.swift). +// Orgs can hold thousands of resources, each on thousands of sites, so search +// and paging run on the server through the launcher API: the popup asks for one +// page at a time (ResourcesService.List) and keeps the list itself. Resources +// listed here are remembered by key so the popup's actions (open, copy, exit +// node) can refer to them by ID, like every other menu item. + +const ( + resourcesPageSize = 25 + // resourcesMaxPagesPerLoad bounds the pages fetched for one load when a + // server that can't filter by type returns pages of public resources only. + resourcesMaxPagesPerLoad = 10 + // resourcesMaxListedSites is how many sites a resource's details list. + resourcesMaxListedSites = 10 + // resourcesCacheLimit bounds the remembered resources; past it the cache + // starts over, and actions on rows loaded before then are ignored. + resourcesCacheLimit = 5000 +) + +// Menu item ID prefixes for resource actions, each followed by the resource's key. +const ( + menuPrefixResourceOpen = "resource.open:" + menuPrefixResourceCopyAddress = "resource.copyAddress:" + menuPrefixResourceCopySSH = "resource.copySSH:" + menuPrefixResourceExitNode = "resource.exitNode:" +) + +// ResourceSite is a site serving a resource, as its details list it. +type ResourceSite struct { + Name string `json:"name"` + Online bool `json:"online"` +} + +// ResourceRow is a private resource as the tray popup shows it. +type ResourceRow struct { + Key string `json:"key"` + Name string `json:"name"` + Mode string `json:"mode"` + ModeLabel string `json:"modeLabel"` + // Address is what to show for how to reach it, or "" when there's none. + Address string `json:"address"` + Labels []string `json:"labels"` + // Sites are the first few, online first; SiteCount and OnlineSiteCount count all. + Sites []ResourceSite `json:"sites"` + SiteCount int `json:"siteCount"` + OnlineSiteCount int `json:"onlineSiteCount"` + CanOpen bool `json:"canOpen"` + CanCopyAddress bool `json:"canCopyAddress"` + CanCopySSH bool `json:"canCopySsh"` + // ExitNodeID is the site resource ID when this is an exit node, else 0. + ExitNodeID int `json:"exitNodeId"` +} + +// ResourcesPage is the answer to one load of the Resources section. +type ResourcesPage struct { + // Scope is the org, user and server the page belongs to. The popup drops + // pages for a scope other than the menu's. + Scope string `json:"scope"` + Items []ResourceRow `json:"items"` + // NextPage is the page to ask for to continue, when HasMore. + NextPage int `json:"nextPage"` + HasMore bool `json:"hasMore"` + // Error is set when the load failed for a reason worth showing. + Error string `json:"error"` +} + +var ( + resourcesMu sync.Mutex + // resourcesCacheScope is the scope resourcesCache belongs to. + resourcesCacheScope string + resourcesCache = map[string]api.LauncherResource{} + // resourcesUnsupportedScope is a scope whose server has no launcher API, + // so the section is hidden for it. + resourcesUnsupportedScope string +) + +// currentResourcesScope identifies the current org on the current server as +// seen by the active user, or "" when no resources can be listed: org IDs are +// only unique per server, and each user sees their own resources. +func currentResourcesScope() string { + if authManager == nil || apiClient == nil || accountManager == nil { + return "" + } + if !authManager.IsAuthenticated() || authManager.SessionExpired() { + return "" + } + org := authManager.CurrentOrg() + active, err := accountManager.ActiveAccount() + if org == nil || org.Id == "" || err != nil || active == nil { + return "" + } + return apiClient.CurrentBaseURL() + "|" + active.UserID + "|" + org.Id +} + +// resourcesSupported reports whether the scope's server has the launcher API, +// as far as is known. +func resourcesSupported(scope string) bool { + resourcesMu.Lock() + defer resourcesMu.Unlock() + return scope == "" || scope != resourcesUnsupportedScope +} + +// listResources loads one page of the current org's private resources matching +// query, starting at page. Servers that can't filter by type may return pages +// holding only public resources; those are skipped, within reason. +func listResources(query string, page int) ResourcesPage { + scope := currentResourcesScope() + result := ResourcesPage{Scope: scope, Items: []ResourceRow{}} + if scope == "" { + return result + } + org := authManager.CurrentOrg() + if page < 1 { + page = 1 + } + + var collected []api.LauncherResource + more := false + var failure error + for i := 0; i < resourcesMaxPagesPerLoad; i++ { + resp, err := apiClient.ListLauncherPrivateResources(org.Id, query, page, resourcesPageSize) + if err != nil { + failure = err + break + } + collected = append(collected, resp.Resources...) + more = resp.Pagination.HasMore() + page++ + if len(collected) > 0 || !more { + break + } + } + + // The org, user or server changed while loading; the popup will reload. + if currentResourcesScope() != scope { + return ResourcesPage{Scope: currentResourcesScope(), Items: []ResourceRow{}} + } + + if failure != nil && len(collected) == 0 { + var apiErr *api.APIError + switch { + case errors.As(failure, &apiErr) && apiErr.RequiresReauthentication(): + // Logging in again is the fix, so ask for that rather than showing an + // error. The section hides while the account is locked. + logger.Info("Resources: session no longer accepted; asking to log in again") + authManager.MarkSessionExpired() + publish() + return ResourcesPage{Scope: "", Items: []ResourceRow{}} + case errors.As(failure, &apiErr) && apiErr.Status == 404: + // The server has no launcher API: hide the section. + resourcesMu.Lock() + resourcesUnsupportedScope = scope + resourcesMu.Unlock() + publish() + return result + } + logger.Debug("Resources: failed to list: %v", failure) + result.Error = failure.Error() + return result + } + + rememberResources(scope, collected) + for _, r := range collected { + result.Items = append(result.Items, resourceRow(r)) + } + result.NextPage = page + result.HasMore = more + return result +} + +// refreshResources drops the server's cached launcher results (kept up to a +// minute) so the reload that follows shows recent changes. Older servers may +// lack the endpoint; the reload still helps once their cache expires. +func refreshResources() { + if currentResourcesScope() == "" { + return + } + if org := authManager.CurrentOrg(); org != nil { + if err := apiClient.InvalidateLauncherCache(org.Id); err != nil { + logger.Debug("Resources: could not drop the server's cached results: %v", err) + } + } +} + +func rememberResources(scope string, items []api.LauncherResource) { + resourcesMu.Lock() + defer resourcesMu.Unlock() + if scope != resourcesCacheScope || len(resourcesCache)+len(items) > resourcesCacheLimit { + resourcesCache = map[string]api.LauncherResource{} + resourcesCacheScope = scope + } + for _, r := range items { + resourcesCache[r.Key] = r + } +} + +// rememberedResource returns a resource listed for the current scope. +func rememberedResource(key string) (api.LauncherResource, bool) { + scope := currentResourcesScope() + resourcesMu.Lock() + defer resourcesMu.Unlock() + if scope == "" || scope != resourcesCacheScope { + return api.LauncherResource{}, false + } + r, ok := resourcesCache[key] + return r, ok +} + +func setResourcesCollapsed(collapsed bool) { + if configManager != nil && !configManager.SetResourcesCollapsed(collapsed) { + logger.Warn("Could not save whether the Resources section is collapsed") + } + publish() +} + +// invokeResourceAction runs a resource row's action from the tray popup. +func invokeResourceAction(id string) { + prefix, key := splitResourceAction(id) + r, ok := rememberedResource(key) + if !ok { + logger.Warn("Resources: %q is no longer listed", key) + return + } + switch prefix { + case menuPrefixResourceOpen: + if u := resourceBrowserURL(r); u != "" { + openURL(u) + } + case menuPrefixResourceCopyAddress: + if r.AccessCopyValue != "" { + app.Clipboard.SetText(r.AccessCopyValue) + } + case menuPrefixResourceCopySSH: + if cmd := resourceSSHCommand(r); cmd != "" { + app.Clipboard.SetText(cmd) + } + case menuPrefixResourceExitNode: + toggleResourceExitNode(r) + } +} + +func splitResourceAction(id string) (prefix, key string) { + for _, p := range []string{menuPrefixResourceOpen, menuPrefixResourceCopyAddress, menuPrefixResourceCopySSH, menuPrefixResourceExitNode} { + if strings.HasPrefix(id, p) { + return p, strings.TrimPrefix(id, p) + } + } + return "", "" +} + +// isResourceAction reports whether id is a resource row's action. +func isResourceAction(id string) bool { + p, _ := splitResourceAction(id) + return p != "" +} + +// toggleResourceExitNode routes all traffic through an exit node resource, or +// stops if it's the one in use. The org's exit node list is what the exit node +// menu connects with; the launcher's copy of the resource stands in only until +// that list has loaded. +func toggleResourceExitNode(r api.LauncherResource) { + if authManager == nil || tunnelManager == nil || r.Mode != "gateway" || r.SiteResourceID == nil { + return + } + org := authManager.CurrentOrg() + if org == nil { + return + } + id := *r.SiteResourceID + if _, active := currentExitNodes(org.Id, tunnelManager.State() == tunnel.StateRunning); active == id { + disableExitNode() + return + } + gateway, ok := findExitNode(org.Id, id) + if !ok { + gateway = api.SiteResource{SiteResourceID: id, NiceID: r.NiceID, Name: r.Name, Mode: r.Mode, Enabled: r.Enabled} + for _, s := range r.Sites { + gateway.SiteIDs = append(gateway.SiteIDs, s.SiteID) + } + } + selectExitNodeGateway(org.Id, gateway) +} + +// resourceRow turns a launcher resource into what the popup shows. +func resourceRow(r api.LauncherResource) ResourceRow { + row := ResourceRow{ + Key: r.Key, + Name: r.Name, + Mode: r.Mode, + ModeLabel: resourceModeLabel(r.Mode), + Address: resourceAddress(r), + Labels: []string{}, + Sites: []ResourceSite{}, + SiteCount: len(r.Sites), + CanOpen: resourceBrowserURL(r) != "", + CanCopyAddress: r.AccessCopyValue != "", + CanCopySSH: resourceSSHCommand(r) != "", + } + if r.Mode == "gateway" && r.SiteResourceID != nil { + row.ExitNodeID = *r.SiteResourceID + } + for _, l := range r.Labels { + row.Labels = append(row.Labels, l.Name) + } + sites := append([]api.LauncherSite(nil), r.Sites...) + sort.SliceStable(sites, func(i, j int) bool { + a, b := siteOnline(sites[i]), siteOnline(sites[j]) + if a != b { + return a + } + return strings.ToLower(sites[i].Name) < strings.ToLower(sites[j].Name) + }) + for i, s := range sites { + if siteOnline(s) { + row.OnlineSiteCount++ + } + if i < resourcesMaxListedSites { + row.Sites = append(row.Sites, ResourceSite{Name: s.Name, Online: siteOnline(s)}) + } + } + return row +} + +func siteOnline(s api.LauncherSite) bool { return s.Online != nil && *s.Online } + +// resourceAddress is the address to show. Exit nodes route all traffic, so they +// have no address of their own. +func resourceAddress(r api.LauncherResource) string { + if r.Mode == "gateway" { + return "Routes all traffic" + } + return r.AccessDisplay +} + +// resourceBrowserURL is a web link to open, or "". Other kinds of address are +// only copied. +func resourceBrowserURL(r api.LauncherResource) string { + if r.AccessURL == nil { + return "" + } + u, err := url.Parse(*r.AccessURL) + if err != nil { + return "" + } + if scheme := strings.ToLower(u.Scheme); scheme != "http" && scheme != "https" { + return "" + } + return u.String() +} + +// resourceSSHCommand is the command that opens an SSH session to the resource, +// as the web launcher shows it: `pangolin ssh [user@]`. +// "" unless it's an SSH resource. +func resourceSSHCommand(r api.LauncherResource) string { + if r.Mode != "ssh" { + return "" + } + target := r.NiceID + if r.Alias != nil { + if alias := strings.TrimSpace(*r.Alias); alias != "" { + target = alias + } + } + if r.PamMode != nil && *r.PamMode == "push" { + return "pangolin ssh " + target + } + return fmt.Sprintf("pangolin ssh user@%s", target) +} + +func resourceModeLabel(mode string) string { + switch mode { + case "host": + return "Host" + case "cidr": + return "CIDR Range" + case "http": + return "HTTP" + case "ssh": + return "SSH" + case "inference": + return "AI Inference" + case "gateway": + return "Exit Node" + case "": + return "—" + } + return strings.ToUpper(mode[:1]) + mode[1:] +} diff --git a/ui/resources_test.go b/ui/resources_test.go new file mode 100644 index 0000000..71d5afc --- /dev/null +++ b/ui/resources_test.go @@ -0,0 +1,117 @@ +package ui + +import ( + "testing" + + "github.com/fosrl/windows-linux/api" +) + +func strPtr(s string) *string { return &s } +func intPtr(i int) *int { return &i } +func boolPtr(b bool) *bool { return &b } + +func TestResourceSSHCommand(t *testing.T) { + for _, tc := range []struct { + name string + r api.LauncherResource + want string + }{ + {"not ssh", api.LauncherResource{Mode: "host", NiceID: "db"}, ""}, + {"identifier", api.LauncherResource{Mode: "ssh", NiceID: "db"}, "pangolin ssh user@db"}, + {"alias preferred", api.LauncherResource{Mode: "ssh", NiceID: "db", Alias: strPtr(" db.internal ")}, "pangolin ssh user@db.internal"}, + {"blank alias", api.LauncherResource{Mode: "ssh", NiceID: "db", Alias: strPtr(" ")}, "pangolin ssh user@db"}, + {"push mode", api.LauncherResource{Mode: "ssh", NiceID: "db", PamMode: strPtr("push")}, "pangolin ssh db"}, + } { + if got := resourceSSHCommand(tc.r); got != tc.want { + t.Errorf("%s: got %q, want %q", tc.name, got, tc.want) + } + } +} + +func TestResourceRow(t *testing.T) { + var sites []api.LauncherSite + for i, name := range []string{"b-off", "a-off", "z-on", "c-on", "unknown"} { + s := api.LauncherSite{SiteID: i, Name: name} + switch name { + case "z-on", "c-on": + s.Online = boolPtr(true) + case "b-off", "a-off": + s.Online = boolPtr(false) + } + sites = append(sites, s) + } + for i := 0; i < 20; i++ { + sites = append(sites, api.LauncherSite{SiteID: 100 + i, Name: "extra", Online: boolPtr(false)}) + } + row := resourceRow(api.LauncherResource{ + Key: "site:1", Name: "web", Mode: "http", AccessDisplay: "https://web.internal", + AccessCopyValue: "https://web.internal", AccessURL: strPtr("https://web.internal"), Sites: sites, + }) + if row.SiteCount != 25 || row.OnlineSiteCount != 2 || len(row.Sites) != resourcesMaxListedSites { + t.Fatalf("counts: %d sites, %d online, %d listed", row.SiteCount, row.OnlineSiteCount, len(row.Sites)) + } + if row.Sites[0].Name != "c-on" || row.Sites[1].Name != "z-on" || row.Sites[2].Name != "a-off" { + t.Errorf("online sites first, then by name: %+v", row.Sites[:3]) + } + if !row.CanOpen || !row.CanCopyAddress || row.CanCopySSH || row.ExitNodeID != 0 { + t.Errorf("actions: %+v", row) + } + + gateway := resourceRow(api.LauncherResource{Key: "site:2", Mode: "gateway", SiteResourceID: intPtr(7)}) + if gateway.ExitNodeID != 7 || gateway.Address != "Routes all traffic" || gateway.ModeLabel != "Exit Node" { + t.Errorf("exit node: %+v", gateway) + } + if resourceBrowserURL(api.LauncherResource{AccessURL: strPtr("rdp://host")}) != "" { + t.Error("only http(s) links are opened") + } +} + +func TestRequiresReauthentication(t *testing.T) { + for _, tc := range []struct { + err *api.APIError + want bool + }{ + {&api.APIError{Type: api.ErrorTypeHTTPError, Status: 401}, true}, + {&api.APIError{Type: api.ErrorTypeHTTPError, Status: 403, Message: "Your session has expired. This organization requires you to log in every 14 days."}, true}, + {&api.APIError{Type: api.ErrorTypeHTTPError, Status: 403, Message: "Your session is invalid. Please log in again."}, true}, + {&api.APIError{Type: api.ErrorTypeHTTPError, Status: 403, Message: "This organization requires two-factor authentication."}, false}, + {&api.APIError{Type: api.ErrorTypeHTTPError, Status: 403, Message: "User does not have access to this organization"}, false}, + {&api.APIError{Type: api.ErrorTypeNetworkError}, false}, + } { + if got := tc.err.RequiresReauthentication(); got != tc.want { + t.Errorf("%d %q: got %v", tc.err.Status, tc.err.Message, got) + } + } +} + +func TestMenuShowsResources(t *testing.T) { + base := menuInputs{ + Authenticated: true, ActiveAccountID: "u", CurrentOrgID: "o", CurrentOrgName: "Org", + ResourcesScope: "s", ShowResources: true, ResourcesSupported: true, + } + has := func(in menuInputs) bool { + for _, it := range buildMenuState(in).Items { + if it.Kind == MenuKindResources { + return it.Resources != nil && it.Resources.Scope == "s" + } + } + return false + } + if !has(base) { + t.Fatal("section missing") + } + for name, change := range map[string]func(*menuInputs){ + "turned off": func(in *menuInputs) { in.ShowResources = false }, + "unsupported": func(in *menuInputs) { in.ResourcesSupported = false }, + "session expired": func(in *menuInputs) { in.SessionExpired = true }, + "server down": func(in *menuInputs) { in.ServerDown = true }, + "no org": func(in *menuInputs) { in.CurrentOrgID = ""; in.ResourcesScope = "" }, + "onboarding": func(in *menuInputs) { in.Onboarding = true }, + } { + in := base + change(&in) + if has(in) { + t.Errorf("%s: section shown", name) + } + } +} diff --git a/ui/services.go b/ui/services.go index f204732..6486b88 100644 --- a/ui/services.go +++ b/ui/services.go @@ -30,6 +30,18 @@ func (MenuService) OpenReady(height int) { trayOpenReady(height) } // status is only polled while it is on screen. func (MenuService) SetSitesVisible(visible bool) { setMenuSitesVisible(visible) } +// ResourcesService backs the tray popup's Resources section. +type ResourcesService struct{} + +// List loads one page of the current org's private resources matching query. +func (ResourcesService) List(query string, page int) ResourcesPage { return listResources(query, page) } + +// Refresh drops the server's cached results, before the popup reloads. +func (ResourcesService) Refresh() { refreshResources() } + +// SetCollapsed folds or unfolds the section, and remembers it. +func (ResourcesService) SetCollapsed(collapsed bool) { setResourcesCollapsed(collapsed) } + // SettingsService backs the General and Connection tabs of the settings window. type SettingsService struct{} diff --git a/ui/settings.go b/ui/settings.go index e0ebb30..48946d1 100644 --- a/ui/settings.go +++ b/ui/settings.go @@ -38,6 +38,9 @@ type Settings struct { // AutoDownloadUpdatesUnavailable explains why this copy can't install updates // itself (Linux AUR and hand-installed builds); empty when it can. AutoDownloadUpdatesUnavailable string `json:"autoDownloadUpdatesUnavailable"` + // ShowResources lists the private resources the user can reach in the tray + // popup. An application setting, so always global. + ShowResources bool `json:"showResources"` // Disabled is set when an administrator has turned off user settings. Disabled bool `json:"disabled"` // OrgName is the current org, empty if there is none. @@ -229,6 +232,7 @@ func currentSettings() Settings { ExitNodeTakesPrecedence: effective.ExitNodeTakesPrecedence, AutoDownloadUpdates: cm.GetAutoDownloadUpdates(), AutoDownloadUpdatesUnavailable: autoDownloadUpdatesUnavailable(), + ShowResources: cm.GetShowResourcesInMenu(), Disabled: cm.GetUserSettingsDisabled(), OrgName: orgName, OrgMode: cm.GetOrgConfig(orgID).HasOwnSettings(), @@ -348,6 +352,9 @@ func applySettings(form Settings) SettingsResult { autoConnect := form.AutoConnect autoDownloadUpdates := form.AutoDownloadUpdates && autoDownloadUpdatesUnavailable() == "" turnedOnAutoDownloadUpdates := autoDownloadUpdates && !configManager.GetAutoDownloadUpdates() + resourcesToggled := form.ShowResources != configManager.GetShowResourcesInMenu() + showResources := form.ShowResources + cfg.ShowResourcesInMenu = &showResources cfg.AutoConnectAtLogin = &autoConnect cfg.OpenUIAtLogin = &openAtLogin cfg.AutoDownloadUpdatesEnabled = &autoDownloadUpdates @@ -362,6 +369,10 @@ func applySettings(form Settings) SettingsResult { if !saved { showError(settingsWindowOrNil(), "Save Failed", "Failed to save settings. Please try again.") } + // Show or hide the tray popup's Resources section. + if resourcesToggled { + publish() + } // Download an available update now instead of at the manager's next check. if turnedOnAutoDownloadUpdates { if err := managers.IPCClientAutoDownloadUpdatesTurnedOn(); err != nil { diff --git a/ui/state.go b/ui/state.go index 324360b..ebc43fa 100644 --- a/ui/state.go +++ b/ui/state.go @@ -242,11 +242,18 @@ func collectMenuInputs() menuInputs { } in.ExitNodes, in.ActiveExitNodeID = currentExitNodes(in.CurrentOrgID, rawPhase == phaseRunning) in.ExitNodeLocked = exitNodeLocked(in.CurrentOrgID) + in.ResourcesScope = currentResourcesScope() + in.ResourcesSupported = resourcesSupported(in.ResourcesScope) if user := authManager.CurrentUser(); user != nil { in.CurrentUserDisplay = auth.UserDisplayName(user) } } + if configManager != nil { + in.ShowResources = configManager.GetShowResourcesInMenu() + in.ResourcesCollapsed = configManager.GetResourcesCollapsed() + } + if accountManager != nil { for _, a := range accountManager.Accounts { a := a