17 Commits

Author SHA1 Message Date
Hadi 031ff48696 v1.1.0
Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
2026-05-26 20:14:22 +02:00
Hadi 95d7f368e1 Add ilovetui integration
Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
2026-05-26 20:14:08 +02:00
Hadi 64b36e716c Merge branch 'main' of github.com:anotherhadi/usbguard-tui 2026-05-11 20:10:07 +02:00
Hadi 85184dafca Add FUNDING.yml
Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
2026-05-11 20:10:01 +02:00
Hadi 6db3a32758 Merge branch 'main' of github.com:anotherhadi/usbguard-tui 2026-05-06 14:42:02 +02:00
Hadi 1ac92a5ace Print nixos rules on exit
Signed-off-by: Hadi <hadi@example.com>
2026-05-06 14:41:50 +02:00
Hadi 2c54df832c Use the hash instead of ID to get the Status
Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
2026-05-05 19:47:01 +02:00
Hadi ecd12f18e0 Remove dead code
Signed-off-by: Hadi <hadi@example.com>
2026-05-05 09:50:49 +02:00
Hadi 787d4ac0f1 fmt
Signed-off-by: Hadi <hadi@example.com>
2026-05-05 09:42:34 +02:00
Hadi 8c250389b3 fix nixos readonly config
Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
2026-05-04 23:56:13 +02:00
Hadi b19739b0a6 add features section
Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
2026-05-04 22:48:45 +02:00
Hadi 20f9b7cf89 Edit mouse actions
Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
2026-05-04 22:48:38 +02:00
Hadi abe6b5dde5 Fix typo 2026-05-04 19:13:55 +02:00
Hadi c7f42c1a12 Move contributing.md
Signed-off-by: Hadi <hadi@example.com>
2026-05-04 15:01:54 +02:00
Hadi 3731160024 Add demo
Signed-off-by: Hadi <hadi@example.com>
2026-05-04 15:01:47 +02:00
Hadi 62cba43e15 add the "default" package
Signed-off-by: Hadi <hadi@example.com>
2026-05-04 14:44:39 +02:00
Hadi f1dd37cfc6 Fix version on flake.nix
Signed-off-by: Hadi <hadi@example.com>
2026-05-04 13:21:03 +02:00
15 changed files with 319 additions and 106 deletions
+1
View File
@@ -0,0 +1 @@
ko_fi: anotherhadi
Binary file not shown.

After

Width:  |  Height:  |  Size: 295 KiB

+27
View File
@@ -0,0 +1,27 @@
Output ./assets/demo.gif
Require usbguard-tui
Set Shell "zsh"
Set FontSize 32
Set Width 1500
Set Height 1000
Type "usbguard-tui"
Sleep 500ms
Enter
Sleep 1s
Down
Sleep 200ms
Down
Sleep 200ms
Enter
Sleep 1s
Down Sleep 200ms
Down Sleep 200ms
Sleep 1s
Enter
Sleep 1s
Type "Q"
+14 -1
View File
@@ -15,7 +15,20 @@ A terminal UI for managing USB devices via [usbguard](https://usbguard.github.io
USBGuard is a software framework for implementing a USB device authorization policy (allowlisting/blocklisting). It protects your system against rogue USB devices by scanning them and checking their parameters against a set of rules.
Built with [bubbletea](https://github.com/charmbracelet/bubbletea) & Goland!
<img alt="USBGuard-tui demo" src="./.github/assets/demo.gif" width="600" />
Built with [bubbletea](https://github.com/charmbracelet/bubbletea) & Golang!
Colors and styles can be customized using [ilovetui](https://github.com/anotherhadi/ilovetui), which applies theme changes across all compatible TUI applications at once.
## Features
- List all connected USB devices with their current status (allowed, blocked, rejected)
- Allow, block, or reject devices: temporarily or permanently
- Action popup with mouse support for quick device management
- Filter devices by name with `/`
- Auto-refresh
- Keyboard shortcuts for all actions (`a`/`A`, `b`/`B`, `e`/`E`)
## Requirements
+7 -7
View File
@@ -14,18 +14,18 @@
(system: f system (import nixpkgs {inherit system;}));
pname = "usbguard-tui";
version = "1.0.0";
version = "1.1.0";
ldflags = ["-s" "-w" "-X main.version=${version}"];
in {
packages = forAllSystems (system: pkgs: {
"${pname}" = pkgs.buildGoModule {
packages = forAllSystems (system: pkgs: let
pkg = pkgs.buildGoModule {
inherit pname version ldflags;
src = ./.;
outputs = ["out"];
vendorHash = "sha256-NfmNdQaISob3ZguQnwgfXHUDUFION988ucp18q996pM=";
vendorHash = "sha256-tXMeJy9IpXTRhikYedcL+76H9X3In9mb1/KnN1XFPu4=";
meta = with pkgs.lib; {
description = "A terminal UI for managing USB devices via usbguard.";
@@ -33,9 +33,9 @@
platforms = platforms.unix;
};
};
in {
"${pname}" = pkg;
default = pkg;
});
defaultPackage =
forAllSystems (system: pkgs: self.packages.${system}.${pname});
};
}
+13
View File
@@ -10,20 +10,33 @@ require (
)
require (
charm.land/glamour/v2 v2.0.0 // indirect
github.com/alecthomas/chroma/v2 v2.14.0 // indirect
github.com/anotherhadi/ilovetui v0.1.6 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260416155717-489999b90468 // indirect
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/dlclark/regexp2 v1.11.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sahilm/fuzzy v0.1.1 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yuin/goldmark v1.7.8 // indirect
github.com/yuin/goldmark-emoji v1.0.5 // indirect
golang.org/x/net v0.39.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.43.0 // indirect
golang.org/x/text v0.24.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+28
View File
@@ -2,12 +2,20 @@ charm.land/bubbles/v2 v2.1.0 h1:YSnNh5cPYlYjPxRrzs5VEn3vwhtEn3jVGRBT3M7/I0g=
charm.land/bubbles/v2 v2.1.0/go.mod h1:l97h4hym2hvWBVfmJDtrEHHCtkIKeTEb3TTJ4ZOB3wY=
charm.land/bubbletea/v2 v2.0.6 h1:UHN/91OyuhaOFGSrBXQ/hMZD8IO1Uc4BvHlgHXL2WJo=
charm.land/bubbletea/v2 v2.0.6/go.mod h1:MH/D8ZLlN3op37vQvijKuU29g3rqTp+aQapURFonF9g=
charm.land/glamour/v2 v2.0.0 h1:IDBoqLEy7Hdpb9VOXN+khLP/XSxtJy1VsHuW/yF87+U=
charm.land/glamour/v2 v2.0.0/go.mod h1:kjq9WB0s8vuUYZNYey2jp4Lgd9f4cKdzAw88FZtpj/w=
charm.land/lipgloss/v2 v2.0.3 h1:yM2zJ4Cf5Y51b7RHIwioil4ApI/aypFXXVHSwlM6RzU=
charm.land/lipgloss/v2 v2.0.3/go.mod h1:7myLU9iG/3xluAWzpY/fSxYYHCgoKTie7laxk6ATwXA=
github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E=
github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I=
github.com/anotherhadi/ilovetui v0.1.6 h1:NKg+T1DpV08Q4r+iowFrXF+0bTd6Y2f4OFpFwhsfsyY=
github.com/anotherhadi/ilovetui v0.1.6/go.mod h1:HVai6u5NGKSMOpmioYpwrN0lSxQjc7HtISUc5hTwvOw=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/ultraviolet v0.0.0-20260416155717-489999b90468 h1:Q9fO0y1Zo5KB/5Vu8JZoLGm1N3RzF9bNj3Ao3xoR+Ac=
@@ -16,6 +24,8 @@ github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dA
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI=
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
@@ -26,12 +36,18 @@ github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSE
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
@@ -40,9 +56,21 @@ github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=
github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk=
github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+40 -3
View File
@@ -2,6 +2,7 @@ package guard
import (
"errors"
"os"
"os/exec"
"strconv"
"strings"
@@ -28,7 +29,7 @@ func ListDevices() ([]Device, error) {
}
d, err := parseLine(line)
if err == nil {
d.Permanent = rules[d.VidPid] == d.Status
d.Permanent = rules[d.Hash] == d.Status
devices = append(devices, d)
}
}
@@ -46,8 +47,8 @@ func listRules() map[string]Status {
continue
}
d, err := parseLine(line)
if err == nil {
rules[d.VidPid] = d.Status
if err == nil && d.Hash != "" {
rules[d.Hash] = d.Status
}
}
return rules
@@ -86,6 +87,42 @@ func wrapExecError(err error) error {
return err
}
func IsRulesManaged() bool {
out, err := exec.Command("systemctl", "cat", "usbguard").Output()
if err != nil {
return false
}
configPath := extractConfigPath(string(out))
if configPath == "" {
return false
}
ruleFile := parseRuleFilePath(configPath)
return strings.HasPrefix(ruleFile, "/nix/store/")
}
func extractConfigPath(s string) string {
fields := strings.Fields(s)
for i, f := range fields {
if f == "-c" && i+1 < len(fields) {
return fields[i+1]
}
}
return ""
}
func parseRuleFilePath(configPath string) string {
data, err := os.ReadFile(configPath)
if err != nil {
return ""
}
for _, line := range strings.Split(string(data), "\n") {
if after, ok := strings.CutPrefix(line, "RuleFile="); ok {
return strings.TrimSpace(after)
}
}
return ""
}
func classifyError(output string) error {
lower := strings.ToLower(output)
switch {
+6
View File
@@ -20,6 +20,7 @@ type Device struct {
Name string
Status Status
VidPid string
Hash string
Permanent bool
}
@@ -57,6 +58,7 @@ func parseLine(line string) (Device, error) {
Name: name,
Status: status,
VidPid: extractUnquoted(rest, "id"),
Hash: extractField(rest, "hash"),
}, nil
}
@@ -74,6 +76,10 @@ func extractField(rule, field string) string {
return rest[:end]
}
func NixOSRule(dev Device, status Status) string {
return fmt.Sprintf("%s id %s name \"%s\"", status, dev.VidPid, dev.Name)
}
func extractUnquoted(rule, field string) string {
prefix := field + " "
idx := strings.Index(rule, prefix)
+1 -1
View File
@@ -5,5 +5,5 @@ import "errors"
var (
ErrNotFound = errors.New("usbguard not found in PATH")
ErrPermission = errors.New("insufficient permissions to manage devices")
ErrReadOnly = errors.New("rules file is read-only")
ErrReadOnly = errors.New("rules file is not writable")
)
+11 -19
View File
@@ -2,16 +2,15 @@ package ui
import (
"fmt"
"image/color"
"io"
"charm.land/bubbles/v2/list"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/anotherhadi/ilovetui"
"github.com/anotherhadi/usbguard-tui/internal/guard"
)
// deviceDelegate renders device list items with status colors.
type deviceDelegate struct{}
func (d deviceDelegate) Height() int { return 2 }
@@ -26,37 +25,31 @@ func (d deviceDelegate) Render(w io.Writer, m list.Model, index int, item list.I
selected := index == m.Index()
var clr color.Color
colorMap := statusColors
if selected {
var ok bool
clr, ok = statusColorsSelected[dev.Status]
if !ok {
clr = colorMuted
colorMap = statusColorsSelected
}
} else {
var ok bool
clr, ok = statusColors[dev.Status]
clr, ok := colorMap[dev.Status]
if !ok {
clr = colorMuted
}
clr = ilovetui.S.Muted
}
var nameStyle, descStyle lipgloss.Style
if selected {
nameStyle = lipgloss.NewStyle().
Border(lipgloss.NormalBorder(), false, false, false, true).
BorderForeground(colorAccent).
BorderForeground(ilovetui.S.Primary).
Foreground(clr).
Bold(true).
PaddingLeft(1)
descStyle = lipgloss.NewStyle().
Border(lipgloss.NormalBorder(), false, false, false, true).
BorderForeground(colorAccent).
Foreground(colorMuted).
BorderForeground(ilovetui.S.Primary).
Foreground(ilovetui.S.Muted).
PaddingLeft(1)
} else {
nameStyle = lipgloss.NewStyle().Foreground(clr).PaddingLeft(2)
descStyle = lipgloss.NewStyle().Foreground(colorMuted).PaddingLeft(2)
descStyle = lipgloss.NewStyle().Foreground(ilovetui.S.Muted).PaddingLeft(2)
}
permIndicator := "○ tmp"
@@ -69,19 +62,18 @@ func (d deviceDelegate) Render(w io.Writer, m list.Model, index int, item list.I
)
}
// actionItem represents a device policy action in the select popup.
type actionItem struct {
label string
fn func(int, bool) error
permanent bool
status guard.Status
nixos bool
}
func (a actionItem) Title() string { return a.label }
func (a actionItem) Description() string { return "" }
func (a actionItem) FilterValue() string { return a.label }
// actionDelegate renders single-line action items.
type actionDelegate struct{}
func (d actionDelegate) Height() int { return 1 }
@@ -96,7 +88,7 @@ func (d actionDelegate) Render(w io.Writer, m list.Model, index int, item list.I
if index == m.Index() {
clr, ok := statusColorsSelected[a.status]
if !ok {
clr = colorAccent
clr = ilovetui.S.Primary
}
fmt.Fprintf(w, " %s", lipgloss.NewStyle().Bold(true).Foreground(clr).Render("> "+a.label))
} else {
+137 -40
View File
@@ -1,6 +1,7 @@
package ui
import (
"fmt"
"strings"
"time"
@@ -10,6 +11,7 @@ import (
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/anotherhadi/ilovetui"
"github.com/anotherhadi/usbguard-tui/internal/guard"
)
@@ -25,6 +27,7 @@ type (
devicesMsg []guard.Device
daemonStatusMsg string
actionMsg struct{ err error }
nixRuleMsg struct{ rule string }
)
type Model struct {
@@ -37,8 +40,12 @@ type Model struct {
height int
notice string
selectedDev *guard.Device
rulesManaged bool
pendingRules []string
}
func (m Model) PendingRules() []string { return m.pendingRules }
func New() Model {
l := list.New(nil, deviceDelegate{}, 0, 0)
l.SetShowHelp(false)
@@ -51,31 +58,53 @@ func New() Model {
l.Styles = list.DefaultStyles(true)
filterStyles := textinput.DefaultStyles(true)
filterStyles.Focused.Prompt = filterStyles.Focused.Prompt.Foreground(colorAccent)
filterStyles.Blurred.Prompt = filterStyles.Blurred.Prompt.Foreground(colorAccent)
filterStyles.Focused.Prompt = filterStyles.Focused.Prompt.Foreground(ilovetui.S.Primary)
filterStyles.Blurred.Prompt = filterStyles.Blurred.Prompt.Foreground(ilovetui.S.Primary)
l.Styles.Filter = filterStyles
h := help.New()
h.Styles = help.DefaultStyles(true)
h := ilovetui.NewHelp()
rulesManaged := guard.IsRulesManaged()
notice := ""
if rulesManaged {
notice = "Rules managed by NixOS config: permanent actions will print NixOS rules on exit."
listKeys.AllowPerm.SetEnabled(false)
listKeys.BlockPerm.SetEnabled(false)
listKeys.RejectPerm.SetEnabled(false)
}
return Model{
state: stateList,
list: l,
actionList: makeActionList(),
actionList: makeActionList(rulesManaged),
help: h,
rulesManaged: rulesManaged,
notice: notice,
}
}
func makeActionList() list.Model {
items := []list.Item{
actionItem{"allow", guard.AllowDevice, false, guard.Allowed},
actionItem{"allow (permanent)", guard.AllowDevice, true, guard.Allowed},
actionItem{"block", guard.BlockDevice, false, guard.Blocked},
actionItem{"block (permanent)", guard.BlockDevice, true, guard.Blocked},
actionItem{"reject", guard.RejectDevice, false, guard.Rejected},
actionItem{"reject (permanent)", guard.RejectDevice, true, guard.Rejected},
func makeActionList(rulesManaged bool) list.Model {
var items []list.Item
if rulesManaged {
items = []list.Item{
actionItem{"allow", guard.AllowDevice, false, guard.Allowed, false},
actionItem{"allow (perm)", nil, true, guard.Allowed, true},
actionItem{"block", guard.BlockDevice, false, guard.Blocked, false},
actionItem{"block (perm)", nil, true, guard.Blocked, true},
actionItem{"reject", guard.RejectDevice, false, guard.Rejected, false},
actionItem{"reject (perm)", nil, true, guard.Rejected, true},
}
l := list.New(items, actionDelegate{}, 24, 6)
} else {
items = []list.Item{
actionItem{"allow", guard.AllowDevice, false, guard.Allowed, false},
actionItem{"allow (permanent)", guard.AllowDevice, true, guard.Allowed, false},
actionItem{"block", guard.BlockDevice, false, guard.Blocked, false},
actionItem{"block (permanent)", guard.BlockDevice, true, guard.Blocked, false},
actionItem{"reject", guard.RejectDevice, false, guard.Rejected, false},
actionItem{"reject (permanent)", guard.RejectDevice, true, guard.Rejected, false},
}
}
l := list.New(items, actionDelegate{}, 24, len(items))
l.SetShowHelp(false)
l.SetShowTitle(false)
l.SetShowStatusBar(false)
@@ -114,20 +143,32 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.daemonStatus = string(msg)
return m, nil
case nixRuleMsg:
m.state = stateList
m.selectedDev = nil
m.pendingRules = append(m.pendingRules, msg.rule)
count := len(m.pendingRules)
if count == 1 {
m.notice = "1 NixOS rule queued (printed on exit)"
} else {
m.notice = fmt.Sprintf("%d NixOS rules queued (printed on exit)", count)
}
return m, nil
case actionMsg:
m.state = stateList
m.selectedDev = nil
if msg.err != nil {
switch msg.err {
case guard.ErrReadOnly:
m.notice = "Read-only rules: applied temporarily. Add the rule to your config for persistence."
m.notice = "Rules file is not writable: permanent changes are not supported."
case guard.ErrPermission:
m.notice = "Permission denied. Run with appropriate privileges."
default:
m.notice = msg.err.Error()
}
} else {
m.notice = ""
m.notice = m.defaultNotice()
}
return m, fetchDevices
@@ -145,11 +186,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
case tea.MouseWheelMsg:
if m.state == statePopup {
var cmd tea.Cmd
m.actionList, cmd = m.actionList.Update(msg)
return m, cmd
}
return m.updateMouseWheel(msg)
}
if m.state == stateList {
@@ -171,7 +208,7 @@ func (m Model) updateList(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
case key.Matches(msg, listKeys.Quit):
return m, tea.Quit
case key.Matches(msg, listKeys.Refresh):
m.notice = ""
m.notice = m.defaultNotice()
return m, tea.Batch(fetchDevices, fetchDaemonStatus)
case key.Matches(msg, listKeys.Help):
m.help.ShowAll = !m.help.ShowAll
@@ -186,18 +223,11 @@ func (m Model) updateList(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
m.state = statePopup
return m, nil
}
case id >= 0 && key.Matches(msg, listKeys.Allow):
return m, doAction(id, guard.AllowDevice, false)
case id >= 0 && key.Matches(msg, listKeys.AllowPerm):
return m, doAction(id, guard.AllowDevice, true)
case id >= 0 && key.Matches(msg, listKeys.Block):
return m, doAction(id, guard.BlockDevice, false)
case id >= 0 && key.Matches(msg, listKeys.BlockPerm):
return m, doAction(id, guard.BlockDevice, true)
case id >= 0 && key.Matches(msg, listKeys.Reject):
return m, doAction(id, guard.RejectDevice, false)
case id >= 0 && key.Matches(msg, listKeys.RejectPerm):
return m, doAction(id, guard.RejectDevice, true)
}
if id >= 0 {
if cmd := m.deviceActionCmd(msg, id); cmd != nil {
return m, cmd
}
}
}
var cmd tea.Cmd
@@ -214,6 +244,10 @@ func (m Model) updatePopup(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
case key.Matches(msg, listKeys.Open):
if item := m.actionList.SelectedItem(); item != nil {
a := item.(actionItem)
if a.nixos && m.selectedDev != nil {
rule := guard.NixOSRule(*m.selectedDev, a.status)
return m, func() tea.Msg { return nixRuleMsg{rule: rule} }
}
return m, doAction(m.selectedDev.ID, a.fn, a.permanent)
}
}
@@ -269,10 +303,15 @@ func (m Model) renderActionSelect() string {
innerW := m.actionListInnerWidth()
title := popupTitleStyle.Foreground(color).Width(innerW).Render(dev.Name)
hint := lipgloss.NewStyle().Foreground(colorMuted).Width(innerW).Render("↑↓ navigate enter confirm esc cancel")
hint := lipgloss.NewStyle().Foreground(ilovetui.S.Muted).Width(innerW).Render("↑↓ navigate enter confirm esc cancel")
content := strings.Join([]string{title, m.actionList.View(), "", hint}, "\n")
return popupStyle.Width(innerW).Render(content)
parts := []string{title, m.actionList.View(), ""}
if m.rulesManaged {
nixosHint := lipgloss.NewStyle().Foreground(ilovetui.S.Muted).Width(innerW).Render("[NixOS: perm rules printed on exit]")
parts = append(parts, nixosHint)
}
parts = append(parts, hint)
return popupStyle.Width(innerW).Render(strings.Join(parts, "\n"))
}
func (m Model) popupOuterWidth() int {
@@ -290,15 +329,30 @@ func (m Model) actionListInnerWidth() int {
return m.popupOuterWidth() - 8 // border(2) + padding_h(6)
}
func (m Model) defaultNotice() string {
if m.rulesManaged {
return "Rules managed by NixOS config: permanent actions will print NixOS rules on exit."
}
return ""
}
func (m Model) actionItemCount() int {
return 6
}
// updateActionListSize sizes the action list and toggles pagination based on available space.
// When there is enough room for all items: pagination is hidden and height is set exactly,
// avoiding the phantom line that bubbles/list reserves when showPagination=true.
// When space is limited: pagination is shown naturally by bubbles/list.
func (m *Model) updateActionListSize() {
const items = 6
items := m.actionItemCount()
innerW := m.actionListInnerWidth()
// popup overhead: border(2) + padding_v(2) + title(1) + blank(1) + hint(1) = 7
available := m.height - 7 - 2 // 2 lines margin
// popup overhead: border(2) + padding_v(2) + title(1) + blank(1) + hint(1) = 7; +1 for NixOS footer
overhead := 7
if m.rulesManaged {
overhead = 8
}
available := m.height - overhead - 2 // 2 lines margin
if available >= items {
m.actionList.SetShowPagination(false)
m.actionList.SetSize(innerW, items)
@@ -347,3 +401,46 @@ func doAction(id int, fn func(int, bool) error, permanent bool) tea.Cmd {
return actionMsg{err: fn(id, permanent)}
}
}
type actionBinding struct {
binding key.Binding
fn func(int, bool) error
perm bool
needsWritable bool
}
var deviceActionBindings = []actionBinding{
{listKeys.Allow, guard.AllowDevice, false, false},
{listKeys.AllowPerm, guard.AllowDevice, true, true},
{listKeys.Block, guard.BlockDevice, false, false},
{listKeys.BlockPerm, guard.BlockDevice, true, true},
{listKeys.Reject, guard.RejectDevice, false, false},
{listKeys.RejectPerm, guard.RejectDevice, true, true},
}
func (m Model) deviceActionCmd(msg tea.KeyPressMsg, id int) tea.Cmd {
for _, b := range deviceActionBindings {
if (!b.needsWritable || !m.rulesManaged) && key.Matches(msg, b.binding) {
return doAction(id, b.fn, b.perm)
}
}
return nil
}
func (m Model) updateMouseWheel(msg tea.MouseWheelMsg) (tea.Model, tea.Cmd) {
switch msg.Button {
case tea.MouseWheelUp:
if m.state == statePopup {
m.actionList.CursorUp()
} else {
m.list.CursorUp()
}
case tea.MouseWheelDown:
if m.state == statePopup {
m.actionList.CursorDown()
} else {
m.list.CursorDown()
}
}
return m, nil
}
+13 -25
View File
@@ -4,51 +4,39 @@ import (
"image/color"
"charm.land/lipgloss/v2"
"github.com/anotherhadi/ilovetui"
"github.com/anotherhadi/usbguard-tui/internal/guard"
)
var (
colorAllowed color.Color = lipgloss.Color("28")
colorAllowedSelected color.Color = lipgloss.Color("42")
colorBlocked color.Color = lipgloss.Color("124")
colorBlockedSelected color.Color = lipgloss.Color("196")
colorRejected color.Color = lipgloss.Color("130")
colorRejectedSelected color.Color = lipgloss.Color("214")
colorMuted color.Color = lipgloss.Color("240")
colorAccent color.Color = lipgloss.Color("99")
)
var statusColors = map[guard.Status]color.Color{
guard.Allowed: colorAllowed,
guard.Blocked: colorBlocked,
guard.Rejected: colorRejected,
guard.Allowed: ilovetui.S.Success,
guard.Blocked: ilovetui.S.Error,
guard.Rejected: ilovetui.S.Warning,
}
var statusColorsSelected = map[guard.Status]color.Color{
guard.Allowed: colorAllowedSelected,
guard.Blocked: colorBlockedSelected,
guard.Rejected: colorRejectedSelected,
guard.Allowed: ilovetui.S.Success,
guard.Blocked: ilovetui.S.Error,
guard.Rejected: ilovetui.S.Warning,
}
var (
headerStyle = lipgloss.NewStyle().
Bold(true).
Foreground(colorAccent).
Foreground(ilovetui.S.Primary).
PaddingLeft(1)
daemonActiveStyle = lipgloss.NewStyle().Foreground(colorAllowedSelected)
daemonOtherStyle = lipgloss.NewStyle().Foreground(colorMuted)
daemonActiveStyle = lipgloss.NewStyle().Foreground(ilovetui.S.Success)
daemonOtherStyle = lipgloss.NewStyle().Foreground(ilovetui.S.Muted)
mutedStyle = lipgloss.NewStyle().Foreground(colorMuted)
mutedStyle = lipgloss.NewStyle().Foreground(ilovetui.S.Muted)
popupStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(colorAccent).
BorderForeground(ilovetui.S.Primary).
Padding(1, 3)
popupTitleStyle = lipgloss.NewStyle().Bold(true).MarginBottom(1)
keyHintStyle = lipgloss.NewStyle().Foreground(colorAccent).Bold(true)
warnStyle = lipgloss.NewStyle().Foreground(colorRejected)
errStyle = lipgloss.NewStyle().Foreground(colorBlocked).Bold(true)
warnStyle = lipgloss.NewStyle().Foreground(ilovetui.S.Warning)
)
+12 -1
View File
@@ -23,8 +23,19 @@ func main() {
}
p := tea.NewProgram(ui.New())
if _, err := p.Run(); err != nil {
m, err := p.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if fm, ok := m.(ui.Model); ok {
if rules := fm.PendingRules(); len(rules) > 0 {
fmt.Println("# Add to your NixOS configuration:")
fmt.Println("services.usbguard.rules = lib.mkAfter ''")
for _, rule := range rules {
fmt.Println(" ", rule)
}
fmt.Println("'';")
}
}
}