Compare commits

..
58 Commits
Author SHA1 Message Date
lukaszraczylo 22f8f7a008 refactor(tui): move to Bubble Tea, Lip Gloss and Bubbles v2
Switch imports to the charm.land v2 modules. Return tea.View from Model.View,
set alt screen and window title there, use KeyPressMsg and the "space" key
name, and call SetWidth on text inputs.
2026-10-04 10:12:33 +01:00
github-actions[bot]andGitHub 750e43501c chore(deps): update module github.com/stretchr/testify to v1.12.1
Automated dependency update. All tests passed.
2026-10-04 03:59:03 +00:00
lukaszraczylo 5bc0a13c37 ci(deps): update dependencies with Renovate [skip ci] 2026-10-03 18:44:49 +01:00
lukaszraczyloandGitHub b61c42f6e2 Update go.mod and go.sum (#53) 2026-10-03 04:11:47 +01:00
lukaszraczyloandGitHub fcc7ab664f Update go.mod and go.sum (#52) 2026-09-14 04:01:22 +01:00
lukaszraczyloandGitHub 2c2ab03feb Update go.mod and go.sum (#51) 2026-09-11 04:00:59 +01:00
lukaszraczyloandGitHub cf549ae2f6 Update go.mod and go.sum (#50) 2026-09-09 04:01:22 +01:00
lukaszraczyloandGitHub c57042cfe1 Update go.mod and go.sum (#49) 2026-09-02 04:02:54 +01:00
lukaszraczyloandGitHub 3c72c04a2b Update go.mod and go.sum (#48) 2026-08-18 04:14:52 +01:00
lukaszraczyloandGitHub d4ea0ee24b Update go.mod and go.sum (#47) 2026-08-12 04:40:47 +01:00
lukaszraczyloandGitHub a9dbce18be Update go.mod and go.sum (#46) 2026-08-11 04:29:44 +01:00
lukaszraczyloandGitHub 4b3c89860b Update go.mod and go.sum (#45) 2026-08-03 07:00:09 +01:00
lukaszraczyloandGitHub 693e72b21a Update go.mod and go.sum (#44) 2026-07-24 06:37:57 +01:00
lukaszraczyloandGitHub f05feed5dd Update go.mod and go.sum (#43) 2026-07-17 06:29:48 +01:00
lukaszraczyloandGitHub 7ed6ebbd03 Update go.mod and go.sum (#42) 2026-07-09 05:17:35 +01:00
lukaszraczyloandGitHub 276437fc58 Update go.mod and go.sum (#41) 2026-07-07 05:18:55 +01:00
lukaszraczyloandGitHub 538d6daf57 Update go.mod and go.sum (#40) 2026-06-09 05:22:29 +01:00
lukaszraczyloandGitHub 1e697c527f Update go.mod and go.sum (#39) 2026-05-31 05:27:40 +01:00
lukaszraczyloandGitHub 765150d70f Update go.mod and go.sum (#38) 2026-05-30 05:19:36 +01:00
lukaszraczyloandGitHub 190a30f46f Update go.mod and go.sum (#37) 2026-05-23 05:14:26 +01:00
lukaszraczyloandGitHub 7df420f77a Update go.mod and go.sum (#36) 2026-05-22 05:25:00 +01:00
lukaszraczyloandGitHub af378eee42 Update go.mod and go.sum (#35) 2026-05-21 05:27:34 +01:00
lukaszraczylo e8f30bae2c docs: add Telemetry section linking to oss-telemetry opt-out docs
Discloses the single anonymous adoption ping sent on startup and points
users to the upstream README section for full opt-out instructions
instead of duplicating the table here.
2026-05-21 04:06:34 +01:00
lukaszraczylo a2970a58df feat: anonymous usage telemetry via oss-telemetry
Send a single fire-and-forget ping at startup to help track adoption
and version spread. No persistent identifiers are collected.

Opt out via any of:
  DO_NOT_TRACK=1
  OSS_TELEMETRY_DISABLED=1
  LOLCATHOST_DISABLE_TELEMETRY=1
2026-05-21 03:05:06 +01:00
lukaszraczyloandGitHub a791fe688d Update go.mod and go.sum (#34) 2026-05-09 05:06:48 +01:00
lukaszraczyloandGitHub 918db31fb2 Update go.mod and go.sum (#33) 2026-05-05 05:01:35 +01:00
lukaszraczyloandGitHub dfbc6d9fb3 Update go.mod and go.sum (#32) 2026-04-30 05:12:31 +01:00
lukaszraczyloandGitHub 4a592b31df Update go.mod and go.sum (#31) 2026-04-27 05:10:21 +01:00
lukaszraczyloandGitHub dae4d893e5 Update go.mod and go.sum (#30) 2026-04-14 04:59:52 +01:00
lukaszraczyloandGitHub df82bddac5 Update go.mod and go.sum (#29) 2026-04-10 04:59:04 +01:00
lukaszraczyloandGitHub 04f51fb2a9 Update go.mod and go.sum (#28) 2026-04-09 04:54:52 +01:00
lukaszraczyloandGitHub e005c0457c Update go.mod and go.sum (#27) 2026-04-03 04:53:34 +01:00
lukaszraczyloandGitHub 8f56df9a8d Update go.mod and go.sum (#26) 2026-03-29 04:57:32 +01:00
lukaszraczyloandGitHub 6a2394a598 Update go.mod and go.sum (#25) 2026-03-12 03:45:07 +00:00
lukaszraczyloandGitHub 3c18f25a82 Update go.mod and go.sum (#24) 2026-03-10 03:43:17 +00:00
lukaszraczyloandGitHub 0c97ee1a58 Update go.mod and go.sum (#23) 2026-03-09 03:45:32 +00:00
lukaszraczyloandGitHub f1d232a9a6 Update go.mod and go.sum (#22) 2026-03-08 03:44:15 +00:00
lukaszraczyloandGitHub aa414bc2b3 Update go.mod and go.sum (#21) 2026-02-23 03:48:51 +00:00
lukaszraczyloandGitHub 62c844b22c Update go.mod and go.sum (#20) 2026-02-18 03:48:14 +00:00
lukaszraczyloandGitHub c6e1207901 Update go.mod and go.sum (#19) 2026-02-17 03:46:48 +00:00
lukaszraczyloandGitHub 9551b89082 Update go.mod and go.sum (#18) 2026-02-13 03:49:15 +00:00
lukaszraczyloandGitHub 4b808599ac Update go.mod and go.sum (#17) 2026-02-11 03:55:02 +00:00
lukaszraczyloandGitHub a2ec16d3ef Update go.mod and go.sum (#16) 2026-02-10 03:56:34 +00:00
lukaszraczyloandGitHub dc3a22c7bc Update go.mod and go.sum (#15) 2026-02-09 03:51:38 +00:00
lukaszraczyloandGitHub 3643ec6a09 Update go.mod and go.sum (#14) 2026-02-05 03:45:17 +00:00
lukaszraczyloandGitHub 2f1b5c166a Update go.mod and go.sum (#13) 2026-02-04 03:44:57 +00:00
lukaszraczyloandGitHub 7ce331182e Update go.mod and go.sum (#12) 2026-02-02 03:49:39 +00:00
lukaszraczyloandGitHub 56518210b1 Update go.mod and go.sum (#11) 2026-01-26 03:35:33 +00:00
lukaszraczyloandGitHub bcf7c0a8a8 Update go.mod and go.sum (#10) 2026-01-25 03:33:28 +00:00
lukaszraczyloandGitHub 2cdd684842 Update go.mod and go.sum (#9) 2026-01-19 03:30:59 +00:00
lukaszraczyloandGitHub 189137ede8 Update go.mod and go.sum (#8) 2026-01-16 03:29:19 +00:00
lukaszraczyloandGitHub d4cff2028e Update go.mod and go.sum (#7) 2026-01-12 03:31:07 +00:00
lukaszraczyloandGitHub 42098eb1c9 Update go.mod and go.sum (#6) 2026-01-10 03:28:19 +00:00
lukaszraczyloandGitHub ad24598036 Update go.mod and go.sum (#5) 2026-01-09 03:29:40 +00:00
lukaszraczyloandGitHub 977e766ff9 Update go.mod and go.sum (#4) 2025-12-15 03:29:37 +00:00
lukaszraczylo 0a47ea7e2a fixup! Cleanup, signing and update of internals. 2025-12-15 00:35:54 +00:00
lukaszraczylo 100251b896 Cleanup, signing and update of internals. 2025-12-15 00:32:53 +00:00
lukaszraczyloandGitHub 2d9c28657b Update go.mod and go.sum (#3) 2025-12-12 03:28:24 +00:00
30 changed files with 600 additions and 445 deletions
+7 -6
View File
@@ -1,4 +1,4 @@
name: Autoupdate go.mod and go.sum
name: Update dependencies
on:
workflow_dispatch:
@@ -6,14 +6,15 @@ on:
- cron: "0 3 * * *"
permissions:
contents: write
actions: write
contents: write
issues: write
pull-requests: write
jobs:
autoupdate:
uses: lukaszraczylo/shared-actions/.github/workflows/go-autoupdate.yaml@main
update:
uses: lukaszraczylo/shared-actions/.github/workflows/renovate-autoupdate.yaml@main
with:
go-version: ">=1.24"
release-workflow: "release.yml"
secrets: inherit
node: false
release-workflow: release.yml
+2
View File
@@ -11,7 +11,9 @@ on:
workflow_dispatch:
permissions:
id-token: write
contents: write
packages: write
jobs:
release:
+2
View File
@@ -1,2 +1,4 @@
CLAUDE.md
build
coverage.out
coverage.html
+11
View File
@@ -65,3 +65,14 @@ homebrew_casks:
system_command "/usr/bin/xattr",
args: ["-dr", "com.apple.quarantine", "#{staged_path}/lolcathost"]
end
signs:
- cmd: cosign
signature: "${artifact}.sigstore.json"
args:
- sign-blob
- "--bundle=${signature}"
- "${artifact}"
- "--yes"
artifacts: checksum
output: true
+25
View File
@@ -86,6 +86,19 @@ make build
sudo ./build/lolcathost --install
```
### Verifying Release Signatures
All release checksums are signed with [cosign](https://github.com/sigstore/cosign) using keyless signing. To verify:
```bash
# Download the checksum file and its sigstore bundle from the release
cosign verify-blob \
--certificate-identity-regexp "https://github.com/lukaszraczylo/lolcathost/.*" \
--certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
--bundle "lolcathost-<version>-checksums.txt.sigstore.json" \
lolcathost-<version>-checksums.txt
```
### Post-Installation
The installer will:
@@ -324,6 +337,18 @@ internal/
version/ - Update checker
```
## Telemetry
On startup this binary sends a single anonymous adoption ping — project name,
version, timestamp; no identifiers, no command output, no payload contents.
Fire-and-forget with a 2-second timeout; cannot block startup or panic.
See **[oss-telemetry — Disabling telemetry](https://github.com/lukaszraczylo/oss-telemetry#disabling-telemetry)**
for the exact wire format, source, and full opt-out documentation.
Quick opt-out: set any of `DO_NOT_TRACK=1`, `OSS_TELEMETRY_DISABLED=1`,
or `LOLCATHOST_DISABLE_TELEMETRY=1`.
## License
MIT License - see [LICENSE](LICENSE).
+3
View File
@@ -16,6 +16,7 @@ import (
"github.com/lukaszraczylo/lolcathost/internal/protocol"
"github.com/lukaszraczylo/lolcathost/internal/tui"
"github.com/lukaszraczylo/lolcathost/internal/version"
telemetry "github.com/lukaszraczylo/oss-telemetry"
)
// version is set at compile time via ldflags
@@ -27,6 +28,8 @@ const (
)
func main() {
telemetry.Send("lolcathost", appVersion)
// Flags
daemonMode := flag.Bool("daemon", false, "Run as daemon (called by LaunchDaemon/systemd)")
installFlag := flag.Bool("install", false, "Install the daemon service (requires sudo)")
+20 -25
View File
@@ -1,38 +1,33 @@
module github.com/lukaszraczylo/lolcathost
go 1.24.2
go 1.26.0
require (
github.com/charmbracelet/bubbles v0.21.0
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/fsnotify/fsnotify v1.9.0
github.com/stretchr/testify v1.11.1
golang.org/x/sys v0.39.0
charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.0.10
charm.land/lipgloss/v2 v2.0.6
github.com/fsnotify/fsnotify v1.10.1
github.com/lukaszraczylo/oss-telemetry v0.2.5
github.com/stretchr/testify v1.12.1
golang.org/x/sys v0.48.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/colorprofile v0.3.3 // indirect
github.com/charmbracelet/x/ansi v0.11.2 // indirect
github.com/charmbracelet/x/cellbuf v0.0.14 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
github.com/charmbracelet/x/ansi v0.11.8 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.6.1 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // 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/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/mattn/go-runewidth v0.0.30 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/text v0.32.0 // indirect
github.com/xo/terminfo v1.2.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/sync v0.23.0 // indirect
)
+42 -56
View File
@@ -1,67 +1,53 @@
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
charm.land/bubbletea/v2 v2.0.10 h1:oolvo20VBpI0PfqE7iFjkZ1bx0WpmXGfnKz5Yldjq5o=
charm.land/bubbletea/v2 v2.0.10/go.mod h1:QOatcnhOjYIfxzUSTz6raF7Ex4R/rIuHa3SnBdCCpMc=
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
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-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
github.com/charmbracelet/colorprofile v0.3.3 h1:DjJzJtLP6/NZ8p7Cgjno0CKGr7wwRJGxWUwh2IyhfAI=
github.com/charmbracelet/colorprofile v0.3.3/go.mod h1:nB1FugsAbzq284eJcjfah2nhdSLppN2NqvfotkfRYP4=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/x/ansi v0.11.2 h1:XAG3FSjiVtFvgEgGrNBkCNNYrsucAt8c6bfxHyROLLs=
github.com/charmbracelet/x/ansi v0.11.2/go.mod h1:9tY2bzX5SiJCU0iWyskjBeI2BRQfvPqI+J760Mjf+Rg=
github.com/charmbracelet/x/cellbuf v0.0.14 h1:iUEMryGyFTelKW3THW4+FfPgi4fkmKnnaLOXuc+/Kj4=
github.com/charmbracelet/x/cellbuf v0.0.14/go.mod h1:P447lJl49ywBbil/KjCk2HexGh4tEY9LH0/1QrZZ9rA=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
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/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-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA=
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro=
github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ=
github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0=
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/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/clipperhouse/displaywidth v0.6.1 h1:/zMlAezfDzT2xy6acHBzwIfyu2ic0hgkT83UX5EY2gY=
github.com/clipperhouse/displaywidth v0.6.1/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
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/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lukaszraczylo/oss-telemetry v0.2.5 h1:W6Qgwp7IY4yBRO361MmnEAmM59motdQpbAFAx8v6fJM=
github.com/lukaszraczylo/oss-telemetry v0.2.5/go.mod h1:+Cn78qZo8rc3T9eZt0v3oICYRdd75wORtSidc8lNjDQ=
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
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=
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/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/xo/terminfo v1.2.0 h1:d0ZTOCpuGE0lwSAOs0zcJjwz3jWQyqcRt9XbGJpCOl4=
github.com/xo/terminfo v1.2.0/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
-19
View File
@@ -29,14 +29,6 @@ func New(socketPath string) *Client {
}
}
// NewWithTimeout creates a new client with a custom timeout.
func NewWithTimeout(socketPath string, timeout time.Duration) *Client {
return &Client{
socketPath: socketPath,
timeout: timeout,
}
}
// Connect establishes a connection to the daemon.
func (c *Client) Connect() error {
c.mu.Lock()
@@ -435,14 +427,3 @@ func (c *Client) ListPresets() ([]protocol.PresetInfo, error) {
}
return data.Presets, nil
}
// IsConnected checks if the daemon is reachable.
func IsConnected(socketPath string) bool {
client := New(socketPath)
if err := client.Connect(); err != nil {
return false
}
defer client.Close()
return client.Ping() == nil
}
-26
View File
@@ -7,7 +7,6 @@ import (
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -398,31 +397,6 @@ func TestClient_NotConnected(t *testing.T) {
assert.Contains(t, err.Error(), "not connected")
}
func TestClient_Timeout(t *testing.T) {
client := NewWithTimeout("/nonexistent.sock", 100*time.Millisecond)
assert.Equal(t, 100*time.Millisecond, client.timeout)
}
func TestIsConnected(t *testing.T) {
t.Run("connected", func(t *testing.T) {
server := newMockServer(t)
defer server.close()
server.handler = func(req *protocol.Request) *protocol.Response {
resp, _ := protocol.NewOKResponse(nil)
return resp
}
connected := IsConnected(server.path)
assert.True(t, connected)
})
t.Run("not connected", func(t *testing.T) {
connected := IsConnected("/nonexistent/socket.sock")
assert.False(t, connected)
})
}
// Matrix test for request types
func TestClient_RequestTypes_Matrix(t *testing.T) {
types := []struct {
+147 -24
View File
@@ -124,6 +124,12 @@ func (m *Manager) Get() *Config {
return m.config
}
// Reload reloads the configuration from disk.
// This is useful for rolling back after a failed operation.
func (m *Manager) Reload() error {
return m.Load()
}
// Watch starts watching the config file for changes.
func (m *Manager) Watch(onChange func(*Config)) error {
watcher, err := fsnotify.NewWatcher()
@@ -151,8 +157,15 @@ func (m *Manager) watchLoop() {
return
}
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) {
if err := m.Load(); err == nil && m.onChange != nil {
m.onChange(m.Get())
// Load and notify under lock to prevent race conditions
m.mu.Lock()
err := m.loadLocked()
cfg := m.config
onChange := m.onChange
m.mu.Unlock()
if err == nil && onChange != nil {
onChange(cfg)
}
}
case <-m.watcher.Errors:
@@ -163,6 +176,27 @@ func (m *Manager) watchLoop() {
}
}
// loadLocked reads and parses the configuration file.
// Caller must hold m.mu lock.
func (m *Manager) loadLocked() error {
data, err := os.ReadFile(m.path)
if err != nil {
return fmt.Errorf("failed to read config file: %w", err)
}
var cfg Config
if err := yaml.Unmarshal(data, &cfg); err != nil {
return fmt.Errorf("failed to parse config file: %w", err)
}
if err := ValidateConfig(&cfg); err != nil {
return fmt.Errorf("invalid config: %w", err)
}
m.config = &cfg
return nil
}
// Stop stops watching the config file.
func (m *Manager) Stop() {
close(m.stopCh)
@@ -180,16 +214,26 @@ func (c *Config) GetAllHosts() []Host {
return hosts
}
// FindHostByAlias finds a host by its alias.
func (c *Config) FindHostByAlias(alias string) (*Host, *Group) {
// findHostIndices finds the group and host indices for a given alias.
// Returns -1, -1 if not found.
func (c *Config) findHostIndices(alias string) (groupIdx, hostIdx int) {
for i := range c.Groups {
for j := range c.Groups[i].Hosts {
if c.Groups[i].Hosts[j].Alias == alias {
return &c.Groups[i].Hosts[j], &c.Groups[i]
return i, j
}
}
}
return nil, nil
return -1, -1
}
// FindHostByAlias finds a host by its alias.
func (c *Config) FindHostByAlias(alias string) (*Host, *Group) {
groupIdx, hostIdx := c.findHostIndices(alias)
if groupIdx < 0 {
return nil, nil
}
return &c.Groups[groupIdx].Hosts[hostIdx], &c.Groups[groupIdx]
}
// FindPreset finds a preset by name.
@@ -204,15 +248,12 @@ func (c *Config) FindPreset(name string) *Preset {
// SetHostEnabled sets the enabled state of a host by alias.
func (c *Config) SetHostEnabled(alias string, enabled bool) bool {
for i := range c.Groups {
for j := range c.Groups[i].Hosts {
if c.Groups[i].Hosts[j].Alias == alias {
c.Groups[i].Hosts[j].Enabled = enabled
return true
}
}
groupIdx, hostIdx := c.findHostIndices(alias)
if groupIdx < 0 {
return false
}
return false
c.Groups[groupIdx].Hosts[hostIdx].Enabled = enabled
return true
}
// GenerateAlias creates a unique alias from a domain name.
@@ -327,15 +368,68 @@ func (c *Config) GetGroups() []string {
// DeleteHost removes a host by alias.
func (c *Config) DeleteHost(alias string) bool {
for i := range c.Groups {
for j := range c.Groups[i].Hosts {
if c.Groups[i].Hosts[j].Alias == alias {
c.Groups[i].Hosts = append(c.Groups[i].Hosts[:j], c.Groups[i].Hosts[j+1:]...)
return true
}
groupIdx, hostIdx := c.findHostIndices(alias)
if groupIdx < 0 {
return false
}
c.Groups[groupIdx].Hosts = append(c.Groups[groupIdx].Hosts[:hostIdx], c.Groups[groupIdx].Hosts[hostIdx+1:]...)
return true
}
// UpdateHost updates an existing host by alias.
func (c *Config) UpdateHost(oldAlias, domain, ip, newAlias, groupName string) error {
// Find the host
foundGroup, foundHost := c.findHostIndices(oldAlias)
if foundGroup < 0 {
return fmt.Errorf("alias not found: %s", oldAlias)
}
// Check for duplicate alias if alias is changing
if oldAlias != newAlias {
if existing, _ := c.FindHostByAlias(newAlias); existing != nil {
return fmt.Errorf("alias already exists: %s", newAlias)
}
}
return false
// Get current enabled state
enabled := c.Groups[foundGroup].Hosts[foundHost].Enabled
// If group is changing, move to new group
if c.Groups[foundGroup].Name != groupName {
// Remove from old group
c.Groups[foundGroup].Hosts = append(c.Groups[foundGroup].Hosts[:foundHost], c.Groups[foundGroup].Hosts[foundHost+1:]...)
// Add to new group
host := Host{
Domain: domain,
IP: ip,
Alias: newAlias,
Enabled: enabled,
}
// Find or create target group
found := false
for i := range c.Groups {
if c.Groups[i].Name == groupName {
c.Groups[i].Hosts = append(c.Groups[i].Hosts, host)
found = true
break
}
}
if !found {
c.Groups = append(c.Groups, Group{
Name: groupName,
Hosts: []Host{host},
})
}
} else {
// Update in place
c.Groups[foundGroup].Hosts[foundHost].Domain = domain
c.Groups[foundGroup].Hosts[foundHost].IP = ip
c.Groups[foundGroup].Hosts[foundHost].Alias = newAlias
}
return nil
}
// ApplyPreset applies a preset to the configuration.
@@ -387,6 +481,35 @@ func (c *Config) GetPresets() []Preset {
return c.Presets
}
// Clone creates a deep copy of the configuration.
func (c *Config) Clone() *Config {
clone := &Config{
Settings: c.Settings,
Groups: make([]Group, len(c.Groups)),
Presets: make([]Preset, len(c.Presets)),
}
for i, g := range c.Groups {
clone.Groups[i] = Group{
Name: g.Name,
Hosts: make([]Host, len(g.Hosts)),
}
copy(clone.Groups[i].Hosts, g.Hosts)
}
for i, p := range c.Presets {
clone.Presets[i] = Preset{
Name: p.Name,
Enable: make([]string, len(p.Enable)),
Disable: make([]string, len(p.Disable)),
}
copy(clone.Presets[i].Enable, p.Enable)
copy(clone.Presets[i].Disable, p.Disable)
}
return clone
}
// EnsureDefaultGroup ensures at least one group exists, creating "default" if needed.
func (c *Config) EnsureDefaultGroup() {
if len(c.Groups) == 0 {
@@ -412,7 +535,7 @@ func (m *Manager) Save() error {
return fmt.Errorf("failed to marshal config: %w", err)
}
// #nosec G306 -- config file should be world-readable
// #nosec G306 - Config file permissions are intentionally 0644
if err := os.WriteFile(m.path, data, 0644); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
@@ -423,7 +546,7 @@ func (m *Manager) Save() error {
// CreateDefault creates a default configuration file.
func CreateDefault(path string) error {
dir := filepath.Dir(path)
// #nosec G301 -- config directory should be world-readable
// #nosec G301 - Config directory permissions are intentionally 0755
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
@@ -465,7 +588,7 @@ func CreateDefault(path string) error {
return fmt.Errorf("failed to marshal default config: %w", err)
}
// #nosec G306 -- config file should be world-readable
// #nosec G306 - Config file permissions are intentionally 0644
if err := os.WriteFile(path, data, 0644); err != nil {
return fmt.Errorf("failed to write default config: %w", err)
}
-5
View File
@@ -92,11 +92,6 @@ func (d *Daemon) Run() error {
return d.shutdown()
}
// Stop signals the daemon to stop.
func (d *Daemon) Stop() {
close(d.stopCh)
}
func (d *Daemon) shutdown() error {
close(d.cleanupCh)
d.config.Stop()
+1 -1
View File
@@ -137,6 +137,6 @@ func (f *DNSFlusher) flushLinux(method FlushMethod) error {
}
func runCommand(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd := exec.Command(name, args...) // #nosec G204 - Commands are hardcoded DNS flush utilities, not user input
return cmd.Run()
}
+14 -66
View File
@@ -2,7 +2,6 @@
package daemon
import (
"bufio"
"fmt"
"os"
"path/filepath"
@@ -25,6 +24,10 @@ const (
markerEnd = "# ========== END LOLCATHOST =========="
)
// entryRegex matches host entries in the managed section.
// Compiled once at package init for efficiency.
var entryRegex = regexp.MustCompile(`^(\S+)\s+(\S+)\s+#\s*lolcathost:(\S+)$`)
// HostEntry represents a single entry in the hosts file.
type HostEntry struct {
IP string
@@ -47,59 +50,6 @@ func NewHostsManager() *HostsManager {
}
}
// NewHostsManagerWithPaths creates a hosts manager with custom paths (for testing).
func NewHostsManagerWithPaths(hostsPath, backupDir string) *HostsManager {
return &HostsManager{
hostsPath: hostsPath,
backupDir: backupDir,
}
}
// ReadManagedEntries reads the lolcathost-managed entries from the hosts file.
func (m *HostsManager) ReadManagedEntries() ([]HostEntry, error) {
file, err := os.Open(m.hostsPath)
if err != nil {
return nil, fmt.Errorf("failed to open hosts file: %w", err)
}
defer file.Close()
var entries []HostEntry
inManagedSection := false
scanner := bufio.NewScanner(file)
entryRegex := regexp.MustCompile(`^(\S+)\s+(\S+)\s+#\s*lolcathost:(\S+)$`)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == markerStart {
inManagedSection = true
continue
}
if line == markerEnd {
inManagedSection = false
continue
}
if inManagedSection && !strings.HasPrefix(line, "#") && line != "" {
matches := entryRegex.FindStringSubmatch(line)
if len(matches) == 4 {
entries = append(entries, HostEntry{
IP: matches[1],
Domain: matches[2],
Alias: matches[3],
Enabled: true,
})
}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read hosts file: %w", err)
}
return entries, nil
}
// WriteManagedEntries writes the managed entries to the hosts file.
func (m *HostsManager) WriteManagedEntries(entries []HostEntry) error {
// Create backup first
@@ -178,7 +128,7 @@ func (m *HostsManager) buildManagedSection(entries []HostEntry) string {
func (m *HostsManager) writeAtomic(content string) error {
// Write to temp file first
tmpFile := m.hostsPath + ".tmp"
// #nosec G306 -- hosts file must be world-readable
// #nosec G306 - Hosts file permissions are intentionally 0644
if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil {
return err
}
@@ -194,12 +144,12 @@ func (m *HostsManager) writeAtomic(content string) error {
// CreateBackup creates a backup of the current hosts file.
func (m *HostsManager) CreateBackup() error {
// #nosec G301 -- backup directory should be world-readable for recovery
// #nosec G301 - Backup directory permissions are intentionally 0755
if err := os.MkdirAll(m.backupDir, 0755); err != nil {
return fmt.Errorf("failed to create backup directory: %w", err)
}
content, err := os.ReadFile(m.hostsPath)
content, err := os.ReadFile(m.hostsPath) // #nosec G304 - Path is controlled by daemon, not user input
if err != nil {
return fmt.Errorf("failed to read hosts file: %w", err)
}
@@ -207,7 +157,7 @@ func (m *HostsManager) CreateBackup() error {
timestamp := time.Now().Format("20060102-150405")
backupPath := filepath.Join(m.backupDir, fmt.Sprintf("hosts.%s.bak", timestamp))
// #nosec G306 -- backup files should be world-readable for recovery
// #nosec G306 - Backup file permissions are intentionally 0644
if err := os.WriteFile(backupPath, content, 0644); err != nil {
return fmt.Errorf("failed to write backup: %w", err)
}
@@ -297,15 +247,14 @@ type BackupInfo struct {
// GetBackupContent returns the content of a backup file.
func (m *HostsManager) GetBackupContent(name string) (string, error) {
backupPath := filepath.Join(m.backupDir, name)
// Validate backup name to prevent path traversal
if filepath.Base(name) != name || !strings.HasPrefix(name, "hosts.") || !strings.HasSuffix(name, ".bak") {
return "", fmt.Errorf("invalid backup name")
}
// #nosec G304 -- backupPath is validated above: filepath.Base(name) == name and prefix/suffix checks
content, err := os.ReadFile(backupPath)
backupPath := filepath.Join(m.backupDir, name)
content, err := os.ReadFile(backupPath) // #nosec G304 - Path is validated above to prevent traversal
if err != nil {
return "", fmt.Errorf("failed to read backup: %w", err)
}
@@ -315,15 +264,14 @@ func (m *HostsManager) GetBackupContent(name string) (string, error) {
// RestoreBackup restores a backup by name.
func (m *HostsManager) RestoreBackup(name string) error {
backupPath := filepath.Join(m.backupDir, name)
// Validate backup name to prevent path traversal
if filepath.Base(name) != name || !strings.HasPrefix(name, "hosts.") || !strings.HasSuffix(name, ".bak") {
return fmt.Errorf("invalid backup name")
}
// #nosec G304 -- backupPath is validated above: filepath.Base(name) == name and prefix/suffix checks
content, err := os.ReadFile(backupPath)
backupPath := filepath.Join(m.backupDir, name)
content, err := os.ReadFile(backupPath) // #nosec G304 - Path is validated above to prevent traversal
if err != nil {
return fmt.Errorf("failed to read backup: %w", err)
}
+68 -21
View File
@@ -1,6 +1,7 @@
package daemon
import (
"fmt"
"os"
"path/filepath"
"strings"
@@ -10,7 +11,53 @@ import (
"github.com/stretchr/testify/require"
)
func TestHostsManager_ReadManagedEntries(t *testing.T) {
// newHostsManagerWithPaths creates a hosts manager with custom paths (for testing).
func newHostsManagerWithPaths(hostsPath, backupDir string) *HostsManager {
return &HostsManager{
hostsPath: hostsPath,
backupDir: backupDir,
}
}
// readManagedEntries reads the lolcathost-managed entries from the hosts file (for testing).
func (m *HostsManager) readManagedEntries() ([]HostEntry, error) {
content, err := os.ReadFile(m.hostsPath)
if err != nil {
return nil, fmt.Errorf("failed to read hosts file: %w", err)
}
var entries []HostEntry
inManagedSection := false
for _, line := range strings.Split(string(content), "\n") {
line = strings.TrimSpace(line)
if line == markerStart {
inManagedSection = true
continue
}
if line == markerEnd {
inManagedSection = false
continue
}
if inManagedSection && !strings.HasPrefix(line, "#") && line != "" {
matches := entryRegex.FindStringSubmatch(line)
if len(matches) == 4 {
entries = append(entries, HostEntry{
IP: matches[1],
Domain: matches[2],
Alias: matches[3],
Enabled: true,
})
}
}
}
return entries, nil
}
func TestHostsManager_readManagedEntries(t *testing.T) {
tmpDir := t.TempDir()
hostsPath := filepath.Join(tmpDir, "hosts")
@@ -26,8 +73,8 @@ func TestHostsManager_ReadManagedEntries(t *testing.T) {
err := os.WriteFile(hostsPath, []byte(hostsContent), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
entries, err := manager.ReadManagedEntries()
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
entries, err := manager.readManagedEntries()
require.NoError(t, err)
assert.Len(t, entries, 2)
@@ -39,7 +86,7 @@ func TestHostsManager_ReadManagedEntries(t *testing.T) {
assert.Equal(t, "api-local", entries[1].Alias)
}
func TestHostsManager_ReadManagedEntries_NoSection(t *testing.T) {
func TestHostsManager_readManagedEntries_NoSection(t *testing.T) {
tmpDir := t.TempDir()
hostsPath := filepath.Join(tmpDir, "hosts")
@@ -49,8 +96,8 @@ func TestHostsManager_ReadManagedEntries_NoSection(t *testing.T) {
err := os.WriteFile(hostsPath, []byte(hostsContent), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
entries, err := manager.ReadManagedEntries()
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
entries, err := manager.readManagedEntries()
require.NoError(t, err)
assert.Empty(t, entries)
@@ -68,7 +115,7 @@ func TestHostsManager_WriteManagedEntries(t *testing.T) {
err := os.WriteFile(hostsPath, []byte(initialContent), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
entries := []HostEntry{
{IP: "127.0.0.1", Domain: "myapp.com", Alias: "myapp-local", Enabled: true},
@@ -107,7 +154,7 @@ func TestHostsManager_WriteManagedEntries_UpdatesExisting(t *testing.T) {
err := os.WriteFile(hostsPath, []byte(initialContent), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
entries := []HostEntry{
{IP: "127.0.0.1", Domain: "new.com", Alias: "new", Enabled: true},
@@ -134,7 +181,7 @@ func TestHostsManager_CreateBackup(t *testing.T) {
err := os.WriteFile(hostsPath, []byte(hostsContent), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
err = manager.CreateBackup()
require.NoError(t, err)
@@ -175,7 +222,7 @@ func TestHostsManager_ListBackups(t *testing.T) {
require.NoError(t, err)
}
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
backups, err := manager.ListBackups()
require.NoError(t, err)
@@ -187,7 +234,7 @@ func TestHostsManager_ListBackups_NoBackupDir(t *testing.T) {
hostsPath := filepath.Join(tmpDir, "hosts")
backupDir := filepath.Join(tmpDir, "nonexistent")
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
backups, err := manager.ListBackups()
require.NoError(t, err)
@@ -204,7 +251,7 @@ func TestHostsManager_RestoreBackup(t *testing.T) {
err := os.WriteFile(hostsPath, []byte(initialContent), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
// Create backup
err = manager.CreateBackup()
@@ -231,7 +278,7 @@ func TestHostsManager_RestoreBackup(t *testing.T) {
func TestHostsManager_RestoreBackup_InvalidName(t *testing.T) {
tmpDir := t.TempDir()
manager := NewHostsManagerWithPaths(
manager := newHostsManagerWithPaths(
filepath.Join(tmpDir, "hosts"),
filepath.Join(tmpDir, "backups"),
)
@@ -259,7 +306,7 @@ func TestHostsManager_CleanupBackups(t *testing.T) {
err := os.WriteFile(hostsPath, []byte("localhost"), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
// Create more than MaxBackups
for i := 0; i < MaxBackups+5; i++ {
@@ -338,7 +385,7 @@ func TestHostsManager_BuildManagedSection(t *testing.T) {
}
// Matrix tests for hosts file parsing
func TestHostsManager_ReadManagedEntries_Matrix(t *testing.T) {
func TestHostsManager_readManagedEntries_Matrix(t *testing.T) {
ips := []string{"127.0.0.1", "192.168.1.1", "::1"}
domains := []string{"example.com", "sub.example.com", "my-app.test"}
aliases := []string{"test", "my-alias", "app-1"}
@@ -357,8 +404,8 @@ func TestHostsManager_ReadManagedEntries_Matrix(t *testing.T) {
err := os.WriteFile(hostsPath, []byte(content), 0644)
require.NoError(t, err)
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
entries, err := manager.ReadManagedEntries()
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
entries, err := manager.readManagedEntries()
require.NoError(t, err)
require.Len(t, entries, 1)
@@ -371,7 +418,7 @@ func TestHostsManager_ReadManagedEntries_Matrix(t *testing.T) {
}
}
func BenchmarkHostsManager_ReadManagedEntries(b *testing.B) {
func BenchmarkHostsManager_readManagedEntries(b *testing.B) {
tmpDir := b.TempDir()
hostsPath := filepath.Join(tmpDir, "hosts")
@@ -387,11 +434,11 @@ func BenchmarkHostsManager_ReadManagedEntries(b *testing.B) {
err := os.WriteFile(hostsPath, []byte(content.String()), 0644)
require.NoError(b, err)
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = manager.ReadManagedEntries()
_, _ = manager.readManagedEntries()
}
}
@@ -403,7 +450,7 @@ func BenchmarkHostsManager_WriteManagedEntries(b *testing.B) {
err := os.WriteFile(hostsPath, []byte("127.0.0.1\tlocalhost\n"), 0644)
require.NoError(b, err)
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
manager := newHostsManagerWithPaths(hostsPath, backupDir)
entries := make([]HostEntry, 50)
for i := range entries {
+6 -1
View File
@@ -30,10 +30,15 @@ func (s *Server) getPeerCredentials(conn net.Conn) *PeerCredentials {
return
}
// Validate Groups array is not empty before accessing
if xucred.Ngroups == 0 {
return
}
// Get PID separately using LOCAL_PEERPID
var pid int32
pidLen := uint32(unsafe.Sizeof(pid))
// #nosec G103 -- unsafe required for low-level syscall to get peer PID
// #nosec G103 - unsafe.Pointer required for syscall to get peer PID
_, _, errno := syscall.Syscall6(
syscall.SYS_GETSOCKOPT,
fd,
+71 -35
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"os/user"
"strconv"
"sync"
"time"
)
@@ -19,20 +20,27 @@ const (
RateLimitWindow = time.Minute
)
// RateLimiter implements per-PID rate limiting.
// pidRateBucket holds rate limiting data for a single PID using a ring buffer.
type pidRateBucket struct {
timestamps []time.Time // Ring buffer of request timestamps
head int // Next write position
count int // Number of valid entries
}
// RateLimiter implements per-PID rate limiting with efficient memory usage.
type RateLimiter struct {
mu sync.Mutex
requests map[int32][]time.Time
limit int
window time.Duration
mu sync.Mutex
buckets map[int32]*pidRateBucket
limit int
window time.Duration
}
// NewRateLimiter creates a new rate limiter.
func NewRateLimiter(limit int, window time.Duration) *RateLimiter {
return &RateLimiter{
requests: make(map[int32][]time.Time),
limit: limit,
window: window,
buckets: make(map[int32]*pidRateBucket),
limit: limit,
window: window,
}
}
@@ -44,31 +52,42 @@ func (r *RateLimiter) Allow(pid int32) bool {
now := time.Now()
cutoff := now.Add(-r.window)
// Get existing requests for this PID
reqs := r.requests[pid]
bucket, exists := r.buckets[pid]
if !exists {
// Create new bucket with fixed capacity
bucket = &pidRateBucket{
timestamps: make([]time.Time, r.limit),
head: 0,
count: 0,
}
r.buckets[pid] = bucket
}
// Filter out old requests
var validReqs []time.Time
for _, t := range reqs {
if t.After(cutoff) {
validReqs = append(validReqs, t)
// Count valid (non-expired) requests in the ring buffer
validCount := 0
for i := 0; i < bucket.count; i++ {
idx := (bucket.head - bucket.count + i + r.limit) % r.limit
if bucket.timestamps[idx].After(cutoff) {
validCount++
}
}
// Check if under limit
if len(validReqs) >= r.limit {
r.requests[pid] = validReqs
if validCount >= r.limit {
return false
}
// Add new request
validReqs = append(validReqs, now)
r.requests[pid] = validReqs
// Add new request to ring buffer (overwrites oldest if full)
bucket.timestamps[bucket.head] = now
bucket.head = (bucket.head + 1) % r.limit
if bucket.count < r.limit {
bucket.count++
}
return true
}
// Cleanup removes old entries from the rate limiter.
// Cleanup removes stale PID entries from the rate limiter.
func (r *RateLimiter) Cleanup() {
r.mu.Lock()
defer r.mu.Unlock()
@@ -76,17 +95,18 @@ func (r *RateLimiter) Cleanup() {
now := time.Now()
cutoff := now.Add(-r.window)
for pid, reqs := range r.requests {
var validReqs []time.Time
for _, t := range reqs {
if t.After(cutoff) {
validReqs = append(validReqs, t)
for pid, bucket := range r.buckets {
// Check if all timestamps are expired
hasValid := false
for i := 0; i < bucket.count; i++ {
idx := (bucket.head - bucket.count + i + r.limit) % r.limit
if bucket.timestamps[idx].After(cutoff) {
hasValid = true
break
}
}
if len(validReqs) == 0 {
delete(r.requests, pid)
} else {
r.requests[pid] = validReqs
if !hasValid {
delete(r.buckets, pid)
}
}
}
@@ -114,12 +134,12 @@ type AuditEntry struct {
func NewAuditLogger(path string) (*AuditLogger, error) {
// Ensure directory exists
dir := path[:len(path)-len("/audit.log")]
// #nosec G301 -- log directory should be world-readable
// #nosec G301 - Log directory permissions are intentionally 0755
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("failed to create log directory: %w", err)
}
// #nosec G304,G302 -- path is from constant AuditLogPath; audit log should be world-readable
// #nosec G302,G304,G306 - Path is constant, permissions are intentional for audit log
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return nil, fmt.Errorf("failed to open audit log: %w", err)
@@ -187,12 +207,28 @@ func isUserInGroup(uid uint32, targetGID uint32) bool {
}
// Check if target GID is in the list
targetGIDStr := fmt.Sprintf("%d", targetGID)
for _, gid := range groupIDs {
if gid == targetGIDStr {
for _, gidStr := range groupIDs {
gid, err := strconv.ParseUint(gidStr, 10, 32)
if err != nil {
continue
}
if uint32(gid) == targetGID {
return true
}
}
return false
}
// lookupGroupGID looks up a group by name and returns its GID.
func lookupGroupGID(name string) (int, error) {
group, err := user.LookupGroup(name)
if err != nil {
return 0, fmt.Errorf("group not found: %s", name)
}
gid, err := strconv.Atoi(group.Gid)
if err != nil {
return 0, fmt.Errorf("invalid GID for group %s: %s", name, group.Gid)
}
return gid, nil
}
+2 -2
View File
@@ -68,7 +68,7 @@ func TestRateLimiter_Cleanup(t *testing.T) {
rl.Allow(pid)
}
assert.Len(t, rl.requests, 5)
assert.Len(t, rl.buckets, 5)
// Wait for expiration
time.Sleep(15 * time.Millisecond)
@@ -76,7 +76,7 @@ func TestRateLimiter_Cleanup(t *testing.T) {
// Cleanup
rl.Cleanup()
assert.Empty(t, rl.requests)
assert.Empty(t, rl.buckets)
}
func TestAuditLogger_Log(t *testing.T) {
+79 -54
View File
@@ -8,6 +8,7 @@ import (
"net"
"os"
"sync"
"syscall"
"time"
"github.com/lukaszraczylo/lolcathost/internal/config"
@@ -50,20 +51,28 @@ func (s *Server) Start() error {
// Remove existing socket
_ = os.Remove(s.socketPath)
// Set umask to create socket with restricted permissions (0660)
// This prevents TOCTOU vulnerability between socket creation and chmod
oldUmask := syscall.Umask(0117) // 0777 & ~0117 = 0660
listener, err := net.Listen("unix", s.socketPath)
// Restore original umask immediately after socket creation
syscall.Umask(oldUmask)
if err != nil {
return fmt.Errorf("failed to listen on socket: %w", err)
}
// Set socket permissions: 0660 root:lolcathost
// #nosec G302 -- socket must be group-accessible for lolcathost group members
if err := os.Chmod(s.socketPath, 0660); err != nil {
_ = listener.Close()
return fmt.Errorf("failed to set socket permissions: %w", err)
// Look up the lolcathost group GID dynamically
gid, err := lookupGroupGID("lolcathost")
if err != nil {
// Fall back to default GID if group lookup fails
gid = LolcathostGID
}
// Set socket group to lolcathost (GID 850)
if err := os.Chown(s.socketPath, 0, 850); err != nil {
// Set socket group to lolcathost
if err := os.Chown(s.socketPath, 0, gid); err != nil {
_ = listener.Close()
return fmt.Errorf("failed to set socket ownership: %w", err)
}
@@ -126,6 +135,9 @@ func (s *Server) acceptLoop() {
// LolcathostGID is the group ID for the lolcathost group.
const LolcathostGID = 850
// connectionReadTimeout is the maximum time to wait for a client to send data.
const connectionReadTimeout = 30 * time.Second
func (s *Server) handleConnection(conn net.Conn) {
defer conn.Close()
@@ -134,7 +146,7 @@ func (s *Server) handleConnection(conn net.Conn) {
// Authorization check: verify peer is authorized
if !s.isAuthorized(creds) {
s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeUnauthorized, "unauthorized: user not in lolcathost group"))
_ = s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeUnauthorized, "unauthorized: user not in lolcathost group"))
if s.auditLogger != nil {
var uid uint32
var pid int32
@@ -149,6 +161,11 @@ func (s *Server) handleConnection(conn net.Conn) {
reader := bufio.NewReader(conn)
for {
// Set read deadline to prevent clients from hanging indefinitely
if err := conn.SetReadDeadline(time.Now().Add(connectionReadTimeout)); err != nil {
return
}
line, err := reader.ReadBytes('\n')
if err != nil {
return
@@ -156,13 +173,17 @@ func (s *Server) handleConnection(conn net.Conn) {
var req protocol.Request
if err := json.Unmarshal(line, &req); err != nil {
s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "invalid JSON"))
if err := s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "invalid JSON")); err != nil {
return // Connection error, stop handling
}
continue
}
// Rate limiting
if creds != nil && !s.rateLimiter.Allow(creds.PID) {
s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeRateLimited, "rate limit exceeded"))
if err := s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeRateLimited, "rate limit exceeded")); err != nil {
return // Connection error, stop handling
}
continue
}
@@ -171,7 +192,9 @@ func (s *Server) handleConnection(conn net.Conn) {
s.mu.Unlock()
resp := s.handleRequest(&req, creds)
s.writeResponse(conn, resp)
if err := s.writeResponse(conn, resp); err != nil {
return // Connection error, stop handling
}
}
}
@@ -198,10 +221,16 @@ func (s *Server) isAuthorized(creds *PeerCredentials) bool {
return isUserInGroup(creds.UID, LolcathostGID)
}
func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) {
data, _ := json.Marshal(resp)
func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) error {
data, err := json.Marshal(resp)
if err != nil {
return fmt.Errorf("failed to marshal response: %w", err)
}
data = append(data, '\n')
_, _ = conn.Write(data)
if _, err := conn.Write(data); err != nil {
return fmt.Errorf("failed to write response: %w", err)
}
return nil
}
func (s *Server) handleRequest(req *protocol.Request, creds *PeerCredentials) *protocol.Response {
@@ -427,14 +456,9 @@ func (s *Server) handleSet(req *protocol.Request) *protocol.Response {
// Update config
cfg.SetHostEnabled(payload.Alias, payload.Enabled)
// Save config
if err := s.config.Save(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
}
// Sync to hosts file
if err := s.syncHostsFile(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
// Save and sync with rollback on failure
if err := s.saveAndSync(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
}
resp, _ := protocol.NewOKResponse(protocol.SetData{
@@ -468,14 +492,9 @@ func (s *Server) handlePreset(req *protocol.Request) *protocol.Response {
return protocol.NewErrorResponse(protocol.ErrCodeNotFound, err.Error())
}
// Save config
if err := s.config.Save(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
}
// Sync to hosts file
if err := s.syncHostsFile(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
// Save and sync with rollback on failure
if err := s.saveAndSync(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
}
resp, _ := protocol.NewOKResponse(map[string]string{"preset": payload.Name, "applied": "true"})
@@ -573,14 +592,9 @@ func (s *Server) handleAdd(req *protocol.Request) *protocol.Response {
return protocol.NewErrorResponse(protocol.ErrCodeConflict, err.Error())
}
// Save config
if err := s.config.Save(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
}
// Sync to hosts file
if err := s.syncHostsFile(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
// Save and sync with rollback on failure
if err := s.saveAndSync(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
}
resp, _ := protocol.NewOKResponse(protocol.SetData{
@@ -610,14 +624,9 @@ func (s *Server) handleDelete(req *protocol.Request) *protocol.Response {
return protocol.NewErrorResponse(protocol.ErrCodeNotFound, fmt.Sprintf("alias not found: %s", payload.Alias))
}
// Save config
if err := s.config.Save(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
}
// Sync to hosts file
if err := s.syncHostsFile(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
// Save and sync with rollback on failure
if err := s.saveAndSync(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
}
resp, _ := protocol.NewOKResponse(map[string]string{"deleted": payload.Alias})
@@ -671,14 +680,9 @@ func (s *Server) handleDeleteGroup(req *protocol.Request) *protocol.Response {
return protocol.NewErrorResponse(protocol.ErrCodeNotFound, err.Error())
}
// Save config
if err := s.config.Save(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
}
// Sync to hosts file
if err := s.syncHostsFile(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
// Save and sync with rollback on failure
if err := s.saveAndSync(); err != nil {
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
}
resp, _ := protocol.NewOKResponse(map[string]string{"deleted": payload.Name})
@@ -824,3 +828,24 @@ func (s *Server) syncHostsFile() error {
// Flush DNS cache
return s.flusher.Flush()
}
// saveAndSync saves the configuration and syncs to /etc/hosts atomically.
// If sync fails, it attempts to reload the previous config from disk.
func (s *Server) saveAndSync() error {
// Save config
if err := s.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %w", err)
}
// Sync to hosts file
if err := s.syncHostsFile(); err != nil {
// Attempt to reload previous config on sync failure
if reloadErr := s.config.Reload(); reloadErr != nil {
// Log reload failure but return original sync error
fmt.Fprintf(os.Stderr, "warning: failed to reload config after sync failure: %v\n", reloadErr)
}
return fmt.Errorf("failed to sync hosts (config rolled back): %w", err)
}
return nil
}
+2 -2
View File
@@ -36,7 +36,7 @@ func setupTestServer(t *testing.T) (*Server, string, func()) {
server := &Server{
socketPath: socketPath,
config: cfgManager,
hosts: NewHostsManagerWithPaths(hostsPath, backupDir),
hosts: newHostsManagerWithPaths(hostsPath, backupDir),
flusher: NewDNSFlusher(FlushMethodAuto),
rateLimiter: NewRateLimiter(100, time.Minute),
stopCh: make(chan struct{}),
@@ -754,7 +754,7 @@ func BenchmarkServer_HandleSet(b *testing.B) {
server := &Server{
config: cfgManager,
hosts: NewHostsManagerWithPaths(hostsPath, backupDir),
hosts: newHostsManagerWithPaths(hostsPath, backupDir),
flusher: NewDNSFlusher(FlushMethodAuto),
rateLimiter: NewRateLimiter(100000, time.Minute),
}
+21 -22
View File
@@ -210,14 +210,14 @@ func (i *Installer) createGroup() error {
func (i *Installer) createGroupDarwin() error {
// Check if group exists
if _, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName).Output(); err == nil {
if _, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName).Output(); err == nil { // #nosec G204 - Commands use hardcoded safe values
i.log(" Group '%s' already exists", GroupName)
return nil
}
i.log(" Creating group '%s' (GID %d)...", GroupName, GroupGID)
// Create group
// Create group - commands are hardcoded with constant GroupName
cmds := [][]string{
{"dscl", ".", "-create", "/Groups/" + GroupName},
{"dscl", ".", "-create", "/Groups/" + GroupName, "PrimaryGroupID", strconv.Itoa(GroupGID)},
@@ -225,7 +225,7 @@ func (i *Installer) createGroupDarwin() error {
}
for _, args := range cmds {
// #nosec G204 -- args are hardcoded dscl commands with the constant GroupName
// #nosec G204 - Commands use hardcoded safe values
if err := exec.Command(args[0], args[1:]...).Run(); err != nil {
return fmt.Errorf("command %v failed: %w", args, err)
}
@@ -236,14 +236,14 @@ func (i *Installer) createGroupDarwin() error {
func (i *Installer) createGroupLinux() error {
// Check if group exists
if _, err := exec.Command("getent", "group", GroupName).Output(); err == nil {
if _, err := exec.Command("getent", "group", GroupName).Output(); err == nil { // #nosec G204 - GroupName is a constant
i.log(" Group '%s' already exists", GroupName)
return nil
}
i.log(" Creating group '%s'...", GroupName)
if err := exec.Command("groupadd", "-r", GroupName).Run(); err != nil {
if err := exec.Command("groupadd", "-r", GroupName).Run(); err != nil { // #nosec G204 - GroupName is a constant
return fmt.Errorf("groupadd failed: %w", err)
}
@@ -279,7 +279,7 @@ func (i *Installer) addCurrentUserToGroup() error {
func (i *Installer) addUserToGroupDarwin(username string) error {
// Check if user is already in group
output, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName, "GroupMembership").Output()
output, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName, "GroupMembership").Output() // #nosec G204 - GroupName is a constant
if err == nil && strings.Contains(string(output), username) {
i.log(" User '%s' already in group '%s'", username, GroupName)
return nil
@@ -287,7 +287,7 @@ func (i *Installer) addUserToGroupDarwin(username string) error {
i.log(" Adding user '%s' to group '%s'...", username, GroupName)
if err := exec.Command("dscl", ".", "-append", "/Groups/"+GroupName, "GroupMembership", username).Run(); err != nil {
if err := exec.Command("dscl", ".", "-append", "/Groups/"+GroupName, "GroupMembership", username).Run(); err != nil { // #nosec G204 - GroupName is a constant, username from SUDO_USER env
return fmt.Errorf("failed to add user to group: %w", err)
}
@@ -296,7 +296,7 @@ func (i *Installer) addUserToGroupDarwin(username string) error {
func (i *Installer) addUserToGroupLinux(username string) error {
// Check if user is already in group
output, err := exec.Command("id", "-nG", username).Output()
output, err := exec.Command("id", "-nG", username).Output() // #nosec G204 - username from SUDO_USER env or current user
if err == nil && strings.Contains(string(output), GroupName) {
i.log(" User '%s' already in group '%s'", username, GroupName)
return nil
@@ -304,7 +304,7 @@ func (i *Installer) addUserToGroupLinux(username string) error {
i.log(" Adding user '%s' to group '%s'...", username, GroupName)
if err := exec.Command("usermod", "-aG", GroupName, username).Run(); err != nil {
if err := exec.Command("usermod", "-aG", GroupName, username).Run(); err != nil { // #nosec G204 - GroupName is a constant, username from SUDO_USER env
return fmt.Errorf("failed to add user to group: %w", err)
}
@@ -316,7 +316,7 @@ func (i *Installer) createDirectories() error {
for _, dir := range dirs {
i.log(" Creating directory '%s'...", dir)
// #nosec G301 -- system directories should be world-readable
// #nosec G301 - System directories are intentionally 0755
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create %s: %w", dir, err)
}
@@ -342,7 +342,7 @@ func (i *Installer) installLaunchDaemon() error {
// Unload if already loaded (do this before writing plist)
i.log(" Stopping existing daemon if running...")
_ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
_ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run() // #nosec G204 - Hardcoded service name
// Give launchd time to fully unload the service
time.Sleep(500 * time.Millisecond)
@@ -351,21 +351,20 @@ func (i *Installer) installLaunchDaemon() error {
_ = os.Remove(plistPath)
i.log(" Writing LaunchDaemon plist...")
// #nosec G306 -- plist files are world-readable by convention
// #nosec G306 - Plist file permissions are intentionally 0644
if err := os.WriteFile(plistPath, []byte(plistContent), 0644); err != nil {
return fmt.Errorf("failed to write plist: %w", err)
}
// Bootstrap the daemon
i.log(" Starting daemon...")
// #nosec G204 -- plistPath is constructed from constant LaunchDaemonDir
cmd := exec.Command("launchctl", "bootstrap", "system", plistPath)
cmd := exec.Command("launchctl", "bootstrap", "system", plistPath) // #nosec G204 - plistPath is constructed from constants
output, err := cmd.CombinedOutput()
if err != nil {
// Exit code 5 means "service already loaded" - try kickstart instead
if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 5 {
i.log(" Service already registered, restarting...")
if err := exec.Command("launchctl", "kickstart", "-k", "system/com.lolcathost.daemon").Run(); err != nil {
if err := exec.Command("launchctl", "kickstart", "-k", "system/com.lolcathost.daemon").Run(); err != nil { // #nosec G204 - Hardcoded service name
return fmt.Errorf("failed to restart daemon: %w", err)
}
return nil
@@ -380,7 +379,7 @@ func (i *Installer) uninstallLaunchDaemon() {
plistPath := filepath.Join(LaunchDaemonDir, "com.lolcathost.daemon.plist")
i.log(" Stopping daemon...")
_ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
_ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run() // #nosec G204 - Hardcoded service name
i.log(" Removing LaunchDaemon plist...")
_ = os.Remove(plistPath)
@@ -391,20 +390,20 @@ func (i *Installer) installSystemdService() error {
unitContent := fmt.Sprintf(SystemdUnit, i.binaryPath)
i.log(" Writing systemd unit...")
// #nosec G306 -- systemd unit files are world-readable by convention
// #nosec G306 - Unit file permissions are intentionally 0644
if err := os.WriteFile(unitPath, []byte(unitContent), 0644); err != nil {
return fmt.Errorf("failed to write unit file: %w", err)
}
// Reload systemd
i.log(" Reloading systemd...")
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil {
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil { // #nosec G204 - Hardcoded systemctl command
return fmt.Errorf("failed to reload systemd: %w", err)
}
// Enable and start the service
i.log(" Enabling and starting service...")
if err := exec.Command("systemctl", "enable", "--now", "lolcathost.service").Run(); err != nil {
if err := exec.Command("systemctl", "enable", "--now", "lolcathost.service").Run(); err != nil { // #nosec G204 - Hardcoded service name
return fmt.Errorf("failed to enable service: %w", err)
}
@@ -413,12 +412,12 @@ func (i *Installer) installSystemdService() error {
func (i *Installer) uninstallSystemdService() {
i.log(" Stopping and disabling service...")
_ = exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run()
_ = exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run() // #nosec G204 - Hardcoded service name
i.log(" Removing systemd unit...")
_ = os.Remove(filepath.Join(SystemdDir, "lolcathost.service"))
_ = exec.Command("systemctl", "daemon-reload").Run()
_ = exec.Command("systemctl", "daemon-reload").Run() // #nosec G204 - Hardcoded systemctl command
}
func (i *Installer) createDefaultConfig() error {
@@ -435,7 +434,7 @@ func (i *Installer) createDefaultConfig() error {
// Create config directory
configDir := filepath.Dir(configPath)
// #nosec G301 -- config directory should be world-readable
// #nosec G301 - Config directory permissions are intentionally 0755
if err := os.MkdirAll(configDir, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
+35 -29
View File
@@ -7,9 +7,9 @@ import (
"strings"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/lukaszraczylo/lolcathost/internal/client"
"github.com/lukaszraczylo/lolcathost/internal/config"
@@ -143,7 +143,7 @@ func NewModel(socketPath string) *Model {
searchInput := textinput.New()
searchInput.Placeholder = "Search..."
searchInput.CharLimit = 100
searchInput.Width = 50
searchInput.SetWidth(50)
return &Model{
client: client.New(socketPath),
@@ -161,7 +161,6 @@ func NewModel(socketPath string) *Model {
func (m *Model) Init() tea.Cmd {
return tea.Batch(
m.connect(),
tea.SetWindowTitle("lolcathost"),
m.tick(),
m.checkForUpdate(),
)
@@ -330,9 +329,9 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if searchWidth > 60 {
searchWidth = 60
}
m.searchInput.Width = searchWidth
m.searchInput.SetWidth(searchWidth)
case tea.KeyMsg:
case tea.KeyPressMsg:
cmd := m.handleKey(msg)
if cmd != nil {
cmds = append(cmds, cmd)
@@ -505,7 +504,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Batch(cmds...)
}
func (m *Model) handleKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleKey(msg tea.KeyPressMsg) tea.Cmd {
// Global keys
switch msg.String() {
case "ctrl+c":
@@ -535,7 +534,7 @@ func (m *Model) handleKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleListKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleListKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "q":
return tea.Quit
@@ -549,7 +548,7 @@ func (m *Model) handleListKey(msg tea.KeyMsg) tea.Cmd {
m.list.MoveUp()
case "down", "j":
m.list.MoveDown()
case " ", "enter":
case "space", "enter":
return m.toggleSelected()
case "n":
m.mode = ViewForm
@@ -587,7 +586,7 @@ func (m *Model) handleListKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleFormKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleFormKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc":
m.mode = ViewList
@@ -615,7 +614,7 @@ func (m *Model) handleFormKey(msg tea.KeyMsg) tea.Cmd {
return m.form.Update(msg)
}
func (m *Model) handlePresetKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handlePresetKey(msg tea.KeyPressMsg) tea.Cmd {
// Handle based on preset picker mode
switch m.presetPicker.Mode() {
case PresetModeSelect:
@@ -630,7 +629,7 @@ func (m *Model) handlePresetKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handlePresetSelectKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handlePresetSelectKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc", "q":
m.mode = ViewList
@@ -652,7 +651,7 @@ func (m *Model) handlePresetSelectKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handlePresetFormKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handlePresetFormKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc":
m.presetPicker.CancelForm()
@@ -690,7 +689,7 @@ func (m *Model) handlePresetFormKey(msg tea.KeyMsg) tea.Cmd {
return m.presetPicker.Update(msg)
}
func (m *Model) handlePresetPickerKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handlePresetPickerKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc":
m.presetPicker.ClosePicker()
@@ -700,13 +699,13 @@ func (m *Model) handlePresetPickerKey(msg tea.KeyMsg) tea.Cmd {
m.presetPicker.PickerMoveUp()
case "down", "j":
m.presetPicker.PickerMoveDown()
case " ":
case "space":
m.presetPicker.TogglePickerSelection()
}
return nil
}
func (m *Model) handlePresetDeleteKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handlePresetDeleteKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "y", "Y":
if preset := m.presetPicker.Selected(); preset != "" {
@@ -719,7 +718,7 @@ func (m *Model) handlePresetDeleteKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleGroupKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleGroupKey(msg tea.KeyPressMsg) tea.Cmd {
// Handle based on group picker mode
switch m.groupPicker.Mode() {
case GroupModeSelect:
@@ -732,7 +731,7 @@ func (m *Model) handleGroupKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleGroupSelectKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleGroupSelectKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc", "q":
m.mode = ViewList
@@ -750,7 +749,7 @@ func (m *Model) handleGroupSelectKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleGroupFormKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleGroupFormKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc":
m.groupPicker.CancelForm()
@@ -770,7 +769,7 @@ func (m *Model) handleGroupFormKey(msg tea.KeyMsg) tea.Cmd {
return m.groupPicker.Update(msg)
}
func (m *Model) handleGroupDeleteKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleGroupDeleteKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "y", "Y":
if group := m.groupPicker.Selected(); group != "" {
@@ -783,7 +782,7 @@ func (m *Model) handleGroupDeleteKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleBackupKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleBackupKey(msg tea.KeyPressMsg) tea.Cmd {
switch m.backupPicker.Mode() {
case BackupModeSelect:
return m.handleBackupSelectKey(msg)
@@ -793,7 +792,7 @@ func (m *Model) handleBackupKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleBackupSelectKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleBackupSelectKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc", "q":
m.mode = ViewList
@@ -821,7 +820,7 @@ func (m *Model) handleBackupSelectKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleBackupRestoreKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleBackupRestoreKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "y", "Y":
if backup := m.backupPicker.Selected(); backup != "" {
@@ -834,7 +833,7 @@ func (m *Model) handleBackupRestoreKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleHelpKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleHelpKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc", "q", "?":
m.mode = ViewList
@@ -842,7 +841,7 @@ func (m *Model) handleHelpKey(msg tea.KeyMsg) tea.Cmd {
return nil
}
func (m *Model) handleSearchKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleSearchKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "esc":
m.mode = ViewList
@@ -860,7 +859,7 @@ func (m *Model) handleSearchKey(msg tea.KeyMsg) tea.Cmd {
return cmd
}
func (m *Model) handleConfirmDeleteKey(msg tea.KeyMsg) tea.Cmd {
func (m *Model) handleConfirmDeleteKey(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "y", "Y":
alias := m.pendingDeleteAlias
@@ -900,7 +899,14 @@ func (m *Model) setSuccess(msg string) {
}
// View renders the UI.
func (m *Model) View() string {
func (m *Model) View() tea.View {
v := tea.NewView(m.render())
v.AltScreen = true
v.WindowTitle = "lolcathost"
return v
}
func (m *Model) render() string {
var sb strings.Builder
// Title with version
@@ -1142,7 +1148,7 @@ func RunWithVersion(socketPath, version, githubOwner, githubRepo string) error {
m.version = version
m.githubOwner = githubOwner
m.githubRepo = githubRepo
p := tea.NewProgram(m, tea.WithAltScreen())
p := tea.NewProgram(m)
_, err := p.Run()
return err
+25
View File
@@ -0,0 +1,25 @@
package tui
import (
"testing"
tea "charm.land/bubbletea/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestModel_View_UsesAltScreenAndTitle(t *testing.T) {
m := NewModel("/nonexistent.sock")
v := m.View()
assert.True(t, v.AltScreen)
assert.Equal(t, "lolcathost", v.WindowTitle)
assert.Contains(t, v.Content, "lolcathost - Host Management")
}
func TestModel_SpaceKeyIsNamedSpace(t *testing.T) {
msg := tea.KeyPressMsg{Code: tea.KeySpace, Text: " "}
require.Equal(t, "space", msg.String())
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"charm.land/lipgloss/v2"
"github.com/lukaszraczylo/lolcathost/internal/protocol"
)
+4 -4
View File
@@ -5,8 +5,8 @@ import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
"github.com/lukaszraczylo/lolcathost/internal/config"
)
@@ -127,14 +127,14 @@ func (f *Form) SetSize(width, height int) {
inputWidth := min(50, width-10)
for i := range f.fields {
f.fields[i].Width = inputWidth
f.fields[i].SetWidth(inputWidth)
}
}
// Update handles input events.
func (f *Form) Update(msg tea.Msg) tea.Cmd {
switch msg := msg.(type) {
case tea.KeyMsg:
case tea.KeyPressMsg:
// Handle group dropdown navigation
if f.focus == FieldGroup {
switch msg.String() {
+4 -4
View File
@@ -4,8 +4,8 @@ package tui
import (
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
)
// GroupMode represents the group view mode.
@@ -53,7 +53,7 @@ func (g *GroupPicker) SetGroups(groups []string) {
func (g *GroupPicker) SetSize(width, height int) {
g.width = width
g.height = height
g.input.Width = min(50, width-10)
g.input.SetWidth(min(50, width-10))
}
// MoveUp moves the cursor up.
@@ -126,7 +126,7 @@ func (g *GroupPicker) CancelForm() {
}
// Update handles input events for form mode.
func (g *GroupPicker) Update(msg tea.KeyMsg) tea.Cmd {
func (g *GroupPicker) Update(msg tea.KeyPressMsg) tea.Cmd {
var cmd tea.Cmd
g.input, cmd = g.input.Update(msg)
return cmd
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"fmt"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/table"
"charm.land/lipgloss/v2"
"charm.land/lipgloss/v2/table"
"github.com/lukaszraczylo/lolcathost/internal/protocol"
)
+4 -4
View File
@@ -4,8 +4,8 @@ package tui
import (
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
"github.com/lukaszraczylo/lolcathost/internal/protocol"
)
@@ -108,7 +108,7 @@ func (p *PresetPicker) SetSize(width, height int) {
inputWidth := min(60, width-10)
for i := range p.fields {
p.fields[i].Width = inputWidth
p.fields[i].SetWidth(inputWidth)
}
}
@@ -223,7 +223,7 @@ func (p *PresetPicker) CancelForm() {
}
// Update handles input events for form mode.
func (p *PresetPicker) Update(msg tea.KeyMsg) tea.Cmd {
func (p *PresetPicker) Update(msg tea.KeyPressMsg) tea.Cmd {
switch msg.String() {
case "tab", "down":
p.nextField()
+1 -35
View File
@@ -4,7 +4,7 @@ package tui
import (
"strings"
"github.com/charmbracelet/lipgloss"
"charm.land/lipgloss/v2"
)
// Colors - matching kportal style, optimized for dark terminals
@@ -37,12 +37,6 @@ var (
disabledStyle = lipgloss.NewStyle().
Foreground(colorMuted)
pendingStyle = lipgloss.NewStyle().
Foreground(colorWarning)
errorIndicatorStyle = lipgloss.NewStyle().
Foreground(colorError)
)
// Status bar and help
@@ -118,34 +112,6 @@ var (
Padding(0, 1)
)
// Indicator returns the appropriate status indicator string.
func Indicator(enabled bool, pending bool, hasError bool) string {
if hasError {
return errorIndicatorStyle.Render("✗")
}
if pending {
return pendingStyle.Render("◐")
}
if enabled {
return enabledStyle.Render("●")
}
return disabledStyle.Render("○")
}
// StatusText returns the status text with appropriate styling
func StatusText(enabled bool, pending bool, hasError bool) string {
if hasError {
return errorIndicatorStyle.Render("✗ Error")
}
if pending {
return pendingStyle.Render("◐ Pending")
}
if enabled {
return enabledStyle.Render("● Active")
}
return disabledStyle.Render("○ Disabled")
}
// WrapHelpText wraps help text to fit within maxWidth, splitting on bullet separators.
// If maxWidth is 0 or negative, returns the original text.
func WrapHelpText(text string, maxWidth int) string {
+1 -1
View File
@@ -146,7 +146,7 @@ func parseVersion(v string) []int {
for _, p := range parts {
var num int
_, _ = fmt.Sscanf(p, "%d", &num)
_, _ = fmt.Sscanf(p, "%d", &num) // Error intentionally ignored - non-numeric parts become 0
result = append(result, num)
}