Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

security: complete Phase 1 sensor proxy hardening

rcourtman524f42cc28d5
diff --git a/.gitignore b/.gitignore
index 6457d0ae5c..1819bc9e91 100644
--- a/.gitignore
+++ b/.gitignore
@@ -65,6 +65,7 @@ AI_DEVELOPMENT.md
scripts/pulse-watchdog.sh
pulse-watchdog.log
.mcp-servers/
+.codex/
# Release process files
CHANGELOG.md
@@ -132,6 +133,12 @@ MOCK_MODE_GUIDE.md
secrets.env
*secret*.env
+# Browser/session artifacts
+**/cookies.txt
+**/cookies-*.txt
+**/*.har
+**/*.browser
+
# Development documentation (local only)
CLAUDE_DEV_SETUP.md
AGENT_METRICS_*.md
diff --git a/Dockerfile b/Dockerfile
index d3954b002c..9fa4fd582d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,3 +1,6 @@
+# syntax=docker/dockerfile:1.7-labs
+ARG BUILD_AGENT=1
+
# Build stage for frontend (must be built first for embedding)
FROM node:20-alpine AS frontend-builder
@@ -5,17 +8,20 @@ WORKDIR /app/frontend-modern
# Copy package files
COPY frontend-modern/package*.json ./
-RUN npm ci
+RUN --mount=type=cache,id=pulse-npm-cache,target=/root/.npm \
+ npm ci
# Copy frontend source
COPY frontend-modern/ ./
# Build frontend
-RUN npm run build
+RUN --mount=type=cache,id=pulse-npm-cache,target=/root/.npm \
+ npm run build
# Build stage for Go backend
FROM golang:1.24-alpine AS backend-builder
+ARG BUILD_AGENT
WORKDIR /app
# Install build dependencies
@@ -23,7 +29,9 @@ RUN apk add --no-cache git
# Copy go mod files for better layer caching
COPY go.mod go.sum ./
-RUN go mod download
+RUN --mount=type=cache,id=pulse-go-mod,target=/go/pkg/mod \
+ --mount=type=cache,id=pulse-go-build,target=/root/.cache/go-build \
+ go mod download
# Copy only necessary source code
COPY cmd/ ./cmd/
@@ -36,27 +44,46 @@ COPY VERSION ./
COPY --from=frontend-builder /app/frontend-modern/dist ./internal/api/frontend-modern/dist
# Build the binaries with embedded frontend
-RUN CGO_ENABLED=0 GOOS=linux go build \
- -ldflags="-s -w" \
- -trimpath \
- -o pulse ./cmd/pulse
-
-# Build docker-agent for multiple architectures so users can download any arch
-RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
- -ldflags="-s -w" \
- -trimpath \
- -o pulse-docker-agent-linux-amd64 ./cmd/pulse-docker-agent && \
- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build \
- -ldflags="-s -w" \
- -trimpath \
- -o pulse-docker-agent-linux-arm64 ./cmd/pulse-docker-agent && \
- CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build \
- -ldflags="-s -w" \
- -trimpath \
- -o pulse-docker-agent-linux-armv7 ./cmd/pulse-docker-agent
-
-# Keep a host-arch symlink for backward compatibility
-RUN cp pulse-docker-agent-linux-amd64 pulse-docker-agent
+RUN --mount=type=cache,id=pulse-go-mod,target=/go/pkg/mod \
+ --mount=type=cache,id=pulse-go-build,target=/root/.cache/go-build \
+ CGO_ENABLED=0 GOOS=linux go build \
+ -ldflags="-s -w" \
+ -trimpath \
+ -o pulse ./cmd/pulse
+
+# Build docker-agent binaries (optional cross-arch builds controlled by BUILD_AGENT)
+RUN --mount=type=cache,id=pulse-go-mod,target=/go/pkg/mod \
+ --mount=type=cache,id=pulse-go-build,target=/root/.cache/go-build \
+ if [ "${BUILD_AGENT:-1}" = "1" ]; then \
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
+ -ldflags="-s -w" \
+ -trimpath \
+ -o pulse-docker-agent-linux-amd64 ./cmd/pulse-docker-agent && \
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build \
+ -ldflags="-s -w" \
+ -trimpath \
+ -o pulse-docker-agent-linux-arm64 ./cmd/pulse-docker-agent && \
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build \
+ -ldflags="-s -w" \
+ -trimpath \
+ -o pulse-docker-agent-linux-armv7 ./cmd/pulse-docker-agent; \
+ else \
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
+ -ldflags="-s -w" \
+ -trimpath \
+ -o pulse-docker-agent-linux-amd64 ./cmd/pulse-docker-agent && \
+ cp pulse-docker-agent-linux-amd64 pulse-docker-agent-linux-arm64 && \
+ cp pulse-docker-agent-linux-amd64 pulse-docker-agent-linux-armv7; \
+ fi && \
+ cp pulse-docker-agent-linux-amd64 pulse-docker-agent
+
+# Build pulse-sensor-proxy
+RUN --mount=type=cache,id=pulse-go-mod,target=/go/pkg/mod \
+ --mount=type=cache,id=pulse-go-build,target=/root/.cache/go-build \
+ CGO_ENABLED=0 GOOS=linux go build \
+ -ldflags="-s -w" \
+ -trimpath \
+ -o pulse-sensor-proxy ./cmd/pulse-sensor-proxy
# Runtime image for the Docker agent (offered via --target agent_runtime)
FROM alpine:latest AS agent_runtime
@@ -106,10 +133,12 @@ COPY --from=backend-builder /app/VERSION .
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
-# Provide docker-agent installer script for HTTP download endpoint
+# Provide installer scripts for HTTP download endpoints
RUN mkdir -p /opt/pulse/scripts
COPY scripts/install-docker-agent.sh /opt/pulse/scripts/install-docker-agent.sh
-RUN chmod 755 /opt/pulse/scripts/install-docker-agent.sh
+COPY scripts/install-sensor-proxy.sh /opt/pulse/scripts/install-sensor-proxy.sh
+COPY scripts/install-docker.sh /opt/pulse/scripts/install-docker.sh
+RUN chmod 755 /opt/pulse/scripts/install-docker-agent.sh /opt/pulse/scripts/install-sensor-proxy.sh /opt/pulse/scripts/install-docker.sh
# Copy multi-arch docker-agent binaries for download endpoint
RUN mkdir -p /opt/pulse/bin
@@ -118,6 +147,9 @@ COPY --from=backend-builder /app/pulse-docker-agent-linux-arm64 /opt/pulse/bin/
COPY --from=backend-builder /app/pulse-docker-agent-linux-armv7 /opt/pulse/bin/
COPY --from=backend-builder /app/pulse-docker-agent /opt/pulse/bin/pulse-docker-agent
+# Copy pulse-sensor-proxy binary for download endpoint
+COPY --from=backend-builder /app/pulse-sensor-proxy /opt/pulse/bin/pulse-sensor-proxy
+
# Create config directory
RUN mkdir -p /etc/pulse /data
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000000..b22de439f1
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,187 @@
+# Pulse Security Documentation
+
+## Critical Security Notice for Production Deployments
+
+### Container SSH Key Policy (BREAKING CHANGE)
+
+**Effective immediately, SSH-based temperature monitoring is BLOCKED in containerized Pulse deployments.**
+
+#### Why This Change?
+
+Storing SSH private keys inside Docker containers creates an unacceptable security risk in production environments:
+
+- **Container compromise = Infrastructure compromise**: If an attacker gains access to your Pulse container, they immediately obtain SSH private keys with root access to your Proxmox infrastructure.
+- **Keys persist in images**: SSH keys can be extracted from container layers and images if pushed to registries.
+- **No key rotation**: Long-lived keys in containers are difficult to rotate.
+- **Violates principle of least privilege**: Containers should not hold credentials for the infrastructure they monitor.
+
+#### Affected Deployments
+
+✅ **Not Affected** (SSH temperature monitoring still allowed):
+- Pulse installed directly on a VM or bare metal (non-containerized)
+- Home lab deployments where you understand and accept the risk
+
+❌ **BLOCKED** (SSH temperature monitoring disabled):
+- Pulse running in Docker containers
+- Pulse running in LXC containers
+- Any deployment where `PULSE_DOCKER=true` or `/.dockerenv` exists
+
+#### Migration Path
+
+**For Production Container Deployments:**
+
+1. **Deploy pulse-sensor-proxy on each Proxmox host:**
+ ```bash
+ # On each Proxmox host
+ curl -o /usr/local/bin/pulse-sensor-proxy \
+ https://github.com/rcourtman/pulse/releases/latest/download/pulse-sensor-proxy
+
+ chmod +x /usr/local/bin/pulse-sensor-proxy
+ ```
+
+2. **Create systemd service** (`/etc/systemd/system/pulse-sensor-proxy.service`):
+ ```ini
+ [Unit]
+ Description=Pulse Temperature Sensor Proxy
+ After=network.target
+
+ [Service]
+ Type=simple
+ User=root
+ ExecStart=/usr/local/bin/pulse-sensor-proxy
+ Restart=on-failure
+
+ [Install]
+ WantedBy=multi-user.target
+ ```
+
+3. **Enable and start:**
+ ```bash
+ systemctl daemon-reload
+ systemctl enable --now pulse-sensor-proxy
+ ```
+
+4. **Restart Pulse container** - it will automatically detect and use the proxy
+
+**Removing Existing SSH Keys:**
+
+If you previously used SSH-based temperature monitoring in containers:
+
+```bash
+# On each Proxmox host, remove Pulse SSH keys
+sed -i '/# pulse-/d' /root/.ssh/authorized_keys
+
+# Inside the Pulse container (or destroy and recreate)
+docker exec pulse rm -rf /home/pulse/.ssh/id_ed25519*
+```
+
+#### Technical Details
+
+**How pulse-sensor-proxy Works:**
+
+- Runs as a lightweight daemon on the Proxmox host
+- Exposes a Unix socket at `/run/pulse-sensor-proxy.sock`
+- Pulse container connects via bind-mounted socket
+- Only exposes `sensors -j` output - no SSH access
+- Keys never leave the Proxmox host
+
+**Security Boundaries:**
+
+```
+┌─────────────────────────────────────┐
+│ Proxmox Host │
+│ ┌───────────────────────────────┐ │
+│ │ pulse-sensor-proxy (root) │ │
+│ │ - Runs sensors -j │ │
+│ │ - Unix socket only │ │
+│ └───────────────────────────────┘ │
+│ │ │
+│ │ /run/pulse-sensor-proxy.sock
+│ │ │
+│ ┌─────────▼─────────────────────┐ │
+│ │ Container (bind mount) │ │
+│ │ - No SSH keys │ │
+│ │ - No root access to host │ │
+│ └───────────────────────────────┘ │
+└─────────────────────────────────────┘
+```
+
+#### For Home Lab Users
+
+If you understand and accept the risk, you can still use non-containerized Pulse with SSH keys:
+
+1. Install Pulse directly on a VM (not in Docker)
+2. Setup script will offer SSH temperature monitoring
+3. Follow standard security practices:
+ - Use dedicated monitoring user (not root)
+ - Restrict key with `command="sensors -j"`
+ - Add `from="<pulse-ip>"` restrictions
+ - Rotate keys periodically
+
+#### Audit Your Deployment
+
+**Check if you're affected:**
+```bash
+# Inside Pulse container
+ls /home/pulse/.ssh/id_ed25519* 2>/dev/null && echo "⚠️ VULNERABLE"
+
+# On Proxmox host
+grep "# pulse-" /root/.ssh/authorized_keys && echo "⚠️ SSH keys present"
+```
+
+**Check if proxy is working:**
+```bash
+# On Proxmox host
+systemctl status pulse-sensor-proxy
+
+# Inside Pulse container
+docker logs pulse | grep -i "temperature proxy detected"
+```
+
+#### Timeline
+
+- **Now**: SSH key generation blocked in containers (code-level enforcement)
+- **Next Release**: Setup script updated with clear warnings
+- **Future**: pulse-sensor-proxy bundled in official releases
+
+#### Questions?
+
+- Documentation: https://docs.pulseapp.io/security/containerized-deployments
+- GitHub Issues: https://github.com/rcourtman/pulse/issues
+- Security Issues: [email protected] (private disclosure)
+
+---
+
+## General Security Best Practices
+
+### Authentication
+
+- Use API tokens with minimal required permissions
+- Rotate tokens regularly
+- Never commit tokens to version control
+- Use read-only tokens where possible
+
+### Network Security
+
+- Run Pulse in a dedicated monitoring VLAN
+- Restrict Pulse's network access to only monitored systems
+- Use firewall rules to limit inbound connections
+- Enable TLS for all Proxmox API connections
+
+### Monitoring
+
+- Enable audit logging on Proxmox hosts
+- Monitor Pulse container logs for suspicious activity
+- Set up alerts for failed authentication attempts
+- Review access logs regularly
+
+### Updates
+
+- Keep Pulse updated to latest stable version
+- Subscribe to security announcements
+- Test updates in staging before production
+- Have rollback plan ready
+
+---
+
+Last updated: 2025-10-19
diff --git a/cmd/pulse-sensor-proxy/audit.go b/cmd/pulse-sensor-proxy/audit.go
new file mode 100644
index 0000000000..cb0244286b
--- /dev/null
+++ b/cmd/pulse-sensor-proxy/audit.go
@@ -0,0 +1,290 @@
+package main
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/rs/zerolog"
+ "github.com/rs/zerolog/log"
+)
+
+// auditLogger emits append-only, hash-chained audit events.
+type auditLogger struct {
+ mu sync.Mutex
+ file *os.File
+ logger zerolog.Logger
+ prevHash []byte
+ sequence uint64
+}
+
+// AuditEvent captures a single security-relevant action.
+type AuditEvent struct {
+ Sequence uint64 `json:"seq"`
+ Timestamp time.Time `json:"ts"`
+ EventType string `json:"event_type"`
+ CorrelationID string `json:"correlation_id,omitempty"`
+ PeerUID *uint32 `json:"peer_uid,omitempty"`
+ PeerGID *uint32 `json:"peer_gid,omitempty"`
+ PeerPID *uint32 `json:"peer_pid,omitempty"`
+ RemoteAddr string `json:"remote_addr,omitempty"`
+ Command string `json:"command,omitempty"`
+ Args []string `json:"args,omitempty"`
+ Target string `json:"target,omitempty"`
+ Decision string `json:"decision,omitempty"`
+ Reason string `json:"reason,omitempty"`
+ Limiter string `json:"limiter,omitempty"`
+ ExitCode *int `json:"exit_code,omitempty"`
+ DurationMs *int64 `json:"duration_ms,omitempty"`
+ StdoutHash string `json:"stdout_sha256,omitempty"`
+ StderrHash string `json:"stderr_sha256,omitempty"`
+ Error string `json:"error,omitempty"`
+ PrevHash string `json:"prev_hash"`
+ EventHash string `json:"event_hash"`
+}
+
+// newAuditLogger opens the audit log file and prepares hash chaining.
+func newAuditLogger(path string) (*auditLogger, error) {
+ file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
+ if err != nil {
+ return nil, err
+ }
+
+ writer := zerolog.New(file).With().Timestamp().Logger()
+
+ return &auditLogger{
+ file: file,
+ logger: writer,
+ }, nil
+}
+
+// Close flushes and closes the audit log file.
+func (a *auditLogger) Close() error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.file == nil {
+ return nil
+ }
+ err := a.file.Close()
+ a.file = nil
+ return err
+}
+
+// LogConnectionAccepted records an authorized connection.
+func (a *auditLogger) LogConnectionAccepted(correlationID string, cred *peerCredentials, remote string) {
+ event := AuditEvent{
+ EventType: "connection.accepted",
+ CorrelationID: correlationID,
+ RemoteAddr: remote,
+ Decision: "allowed",
+ }
+ event.applyPeer(cred)
+ a.log(&event)
+}
+
+// LogConnectionDenied records a rejected connection attempt.
+func (a *auditLogger) LogConnectionDenied(correlationID string, cred *peerCredentials, remote, reason string) {
+ event := AuditEvent{
+ EventType: "connection.denied",
+ CorrelationID: correlationID,
+ RemoteAddr: remote,
+ Decision: "denied",
+ Reason: reason,
+ }
+ event.applyPeer(cred)
+ a.log(&event)
+}
+
+// LogRateLimitHit records limiter rejections.
+func (a *auditLogger) LogRateLimitHit(correlationID string, cred *peerCredentials, remote, limiter string) {
+ event := AuditEvent{
+ EventType: "limiter.rejection",
+ CorrelationID: correlationID,
+ RemoteAddr: remote,
+ Decision: "denied",
+ Limiter: limiter,
+ }
+ event.applyPeer(cred)
+ a.log(&event)
+}
+
+// LogCommandStart records command execution approval.
+func (a *auditLogger) LogCommandStart(correlationID string, cred *peerCredentials, remote, target, command string, args []string) {
+ event := AuditEvent{
+ EventType: "command.start",
+ CorrelationID: correlationID,
+ RemoteAddr: remote,
+ Decision: "allowed",
+ Command: command,
+ Args: args,
+ Target: target,
+ }
+ event.applyPeer(cred)
+ a.log(&event)
+}
+
+// LogCommandResult records command completion.
+func (a *auditLogger) LogCommandResult(correlationID string, cred *peerCredentials, remote, target, command string, args []string, exitCode int, duration time.Duration, stdoutHash, stderrHash string, execErr error) {
+ event := AuditEvent{
+ EventType: "command.finish",
+ CorrelationID: correlationID,
+ RemoteAddr: remote,
+ Command: command,
+ Args: args,
+ Target: target,
+ ExitCode: intPtr(exitCode),
+ StdoutHash: stdoutHash,
+ StderrHash: stderrHash,
+ }
+ event.applyPeer(cred)
+ if duration > 0 {
+ ms := duration.Milliseconds()
+ event.DurationMs = int64Ptr(ms)
+ }
+ if execErr != nil {
+ event.Error = execErr.Error()
+ event.Decision = "failed"
+ } else {
+ event.Decision = "completed"
+ }
+ a.log(&event)
+}
+
+// LogValidationFailure records validator rejections.
+func (a *auditLogger) LogValidationFailure(correlationID string, cred *peerCredentials, remote, command string, args []string, reason string) {
+ event := AuditEvent{
+ EventType: "command.validation_failed",
+ CorrelationID: correlationID,
+ RemoteAddr: remote,
+ Command: command,
+ Args: args,
+ Decision: "denied",
+ Reason: reason,
+ }
+ event.applyPeer(cred)
+ a.log(&event)
+}
+
+func (e *AuditEvent) applyPeer(cred *peerCredentials) {
+ if cred == nil {
+ return
+ }
+ e.PeerUID = uint32Ptr(cred.uid)
+ e.PeerGID = uint32Ptr(cred.gid)
+ e.PeerPID = uint32Ptr(cred.pid)
+}
+
+// log persists the event with hash chaining.
+func (a *auditLogger) log(event *AuditEvent) {
+ if event == nil {
+ log.Error().Msg("audit log called with nil event")
+ return
+ }
+
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ a.sequence++
+ event.Sequence = a.sequence
+
+ if event.Timestamp.IsZero() {
+ event.Timestamp = time.Now().UTC()
+ } else {
+ event.Timestamp = event.Timestamp.UTC()
+ }
+
+ event.PrevHash = hex.EncodeToString(a.prevHash)
+
+ payload, err := eventMarshalForHash(event)
+ if err != nil {
+ log.Error().Err(err).Msg("failed to marshal audit event")
+ return
+ }
+
+ sum := sha256.Sum256(append(a.prevHash, payload...))
+ a.prevHash = sum[:]
+ event.EventHash = hex.EncodeToString(sum[:])
+
+ a.logger.Info().Fields(eventToMap(event)).Send()
+}
+
+func eventMarshalForHash(event *AuditEvent) ([]byte, error) {
+ clone := *event
+ clone.EventHash = ""
+ return json.Marshal(clone)
+}
+
+func eventToMap(event *AuditEvent) map[string]interface{} {
+ m := map[string]interface{}{
+ "ts": event.Timestamp.Format(time.RFC3339Nano),
+ "event_type": event.EventType,
+ "seq": event.Sequence,
+ "prev_hash": event.PrevHash,
+ "event_hash": event.EventHash,
+ "decision": event.Decision,
+ "correlation_id": event.CorrelationID,
+ }
+
+ if event.PeerUID != nil {
+ m["peer_uid"] = *event.PeerUID
+ }
+ if event.PeerGID != nil {
+ m["peer_gid"] = *event.PeerGID
+ }
+ if event.PeerPID != nil {
+ m["peer_pid"] = *event.PeerPID
+ }
+ if event.RemoteAddr != "" {
+ m["remote_addr"] = event.RemoteAddr
+ }
+ if event.Command != "" {
+ m["command"] = event.Command
+ }
+ if len(event.Args) > 0 {
+ m["args"] = event.Args
+ }
+ if event.Target != "" {
+ m["target"] = event.Target
+ }
+ if event.Reason != "" {
+ m["reason"] = event.Reason
+ }
+ if event.Limiter != "" {
+ m["limiter"] = event.Limiter
+ }
+ if event.ExitCode != nil {
+ m["exit_code"] = *event.ExitCode
+ }
+ if event.DurationMs != nil {
+ m["duration_ms"] = *event.DurationMs
+ }
+ if event.StdoutHash != "" {
+ m["stdout_sha256"] = event.StdoutHash
+ }
+ if event.StderrHash != "" {
+ m["stderr_sha256"] = event.StderrHash
+ }
+ if event.Error != "" {
+ m["error"] = event.Error
+ }
+
+ return m
+}
+
+func uint32Ptr(v uint32) *uint32 {
+ value := v
+ return &value
+}
+
+func intPtr(v int) *int {
+ value := v
+ return &value
+}
+
+func int64Ptr(v int64) *int64 {
+ value := v
+ return &value
+}
diff --git a/cmd/pulse-sensor-proxy/audit_test.go b/cmd/pulse-sensor-proxy/audit_test.go
new file mode 100644
index 0000000000..187f80c1e0
--- /dev/null
+++ b/cmd/pulse-sensor-proxy/audit_test.go
@@ -0,0 +1,64 @@
+package main
+
+import (
+ "bufio"
+ "encoding/json"
+ "os"
+ "testing"
+)
+
+type auditRecord map[string]interface{}
+
+func TestAuditLogValidationFailure(t *testing.T) {
+ tmp, err := os.CreateTemp("", "audit-test-*.log")
+ if err != nil {
+ t.Fatalf("temp file: %v", err)
+ }
+ path := tmp.Name()
+ tmp.Close()
+ defer os.Remove(path)
+
+ logger, err := newAuditLogger(path)
+ if err != nil {
+ t.Fatalf("newAuditLogger: %v", err)
+ }
+
+ cred := &peerCredentials{uid: 1000, gid: 1000, pid: 4242}
+ logger.LogValidationFailure("corr-123", cred, "remote", "get_temperature", []string{"node"}, "invalid_node")
+ logger.Close()
+
+ file, err := os.Open(path)
+ if err != nil {
+ t.Fatalf("open log: %v", err)
+ }
+ defer file.Close()
+
+ scanner := bufio.NewScanner(file)
+ if !scanner.Scan() {
+ t.Fatalf("expected at least one audit entry")
+ }
+
+ var record auditRecord
+ if err := json.Unmarshal(scanner.Bytes(), &record); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ if record["event_type"] != "command.validation_failed" {
+ t.Fatalf("unexpected event_type: %v", record["event_type"])
+ }
+ if record["correlation_id"] != "corr-123" {
+ t.Fatalf("unexpected correlation id: %v", record["correlation_id"])
+ }
+ if record["command"] != "get_temperature" {
+ t.Fatalf("unexpected command: %v", record["command"])
+ }
+ if record["reason"] != "invalid_node" {
+ t.Fatalf("unexpected reason: %v", record["reason"])
+ }
+ if record["decision"] != "denied" {
+ t.Fatalf("unexpected decision: %v", record["decision"])
+ }
+ if record["event_hash"] == "" {
+ t.Fatalf("expected event_hash to be set")
+ }
+}
diff --git a/cmd/pulse-sensor-proxy/main.go b/cmd/pulse-sensor-proxy/main.go
index de636a266f..e8ce44f396 100644
--- a/cmd/pulse-sensor-proxy/main.go
+++ b/cmd/pulse-sensor-proxy/main.go
@@ -11,14 +11,18 @@ import (
"net"
"os"
"os/signal"
+ "os/user"
"path/filepath"
+ "strconv"
"strings"
"syscall"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
+ "golang.org/x/sys/unix"
)
// Version information (set at build time with -ldflags)
@@ -29,10 +33,12 @@ var (
)
const (
- defaultSocketPath = "/run/pulse-sensor-proxy/pulse-sensor-proxy.sock"
- defaultSSHKeyPath = "/var/lib/pulse-sensor-proxy/ssh"
- defaultConfigPath = "/etc/pulse-sensor-proxy/config.yaml"
- maxRequestBytes = 16 * 1024 // 16 KiB max request size
+ defaultSocketPath = "/run/pulse-sensor-proxy/pulse-sensor-proxy.sock"
+ defaultSSHKeyPath = "/var/lib/pulse-sensor-proxy/ssh"
+ defaultConfigPath = "/etc/pulse-sensor-proxy/config.yaml"
+ defaultAuditLogPath = "/var/log/pulse/sensor-proxy/audit.log"
+ maxRequestBytes = 16 * 1024 // 16 KiB max request size
+ defaultRunAsUser = "pulse-sensor"
)
func defaultWorkDir() string {
@@ -79,17 +85,155 @@ func main() {
}
}
+type userSpec struct {
+ name string
+ uid int
+ gid int
+ groups []int
+ home string
+}
+
+func dropPrivileges(username string) (*userSpec, error) {
+ if username == "" {
+ return nil, nil
+ }
+
+ if os.Geteuid() != 0 {
+ return nil, nil
+ }
+
+ spec, err := resolveUserSpec(username)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(spec.groups) == 0 {
+ spec.groups = []int{spec.gid}
+ }
+
+ if err := unix.Setgroups(spec.groups); err != nil {
+ return nil, fmt.Errorf("setgroups: %w", err)
+ }
+ if err := unix.Setgid(spec.gid); err != nil {
+ return nil, fmt.Errorf("setgid: %w", err)
+ }
+ if err := unix.Setuid(spec.uid); err != nil {
+ return nil, fmt.Errorf("setuid: %w", err)
+ }
+
+ if spec.home != "" {
+ _ = os.Setenv("HOME", spec.home)
+ }
+ if spec.name != "" {
+ _ = os.Setenv("USER", spec.name)
+ _ = os.Setenv("LOGNAME", spec.name)
+ }
+
+ return spec, nil
+}
+
+func resolveUserSpec(username string) (*userSpec, error) {
+ u, err := user.Lookup(username)
+ if err == nil {
+ uid, err := strconv.Atoi(u.Uid)
+ if err != nil {
+ return nil, fmt.Errorf("parse uid %q: %w", u.Uid, err)
+ }
+ gid, err := strconv.Atoi(u.Gid)
+ if err != nil {
+ return nil, fmt.Errorf("parse gid %q: %w", u.Gid, err)
+ }
+
+ var groups []int
+ if gids, err := u.GroupIds(); err == nil {
+ for _, g := range gids {
+ if gidVal, convErr := strconv.Atoi(g); convErr == nil {
+ groups = append(groups, gidVal)
+ }
+ }
+ }
+
+ if len(groups) == 0 {
+ groups = []int{gid}
+ }
+
+ return &userSpec{
+ name: u.Username,
+ uid: uid,
+ gid: gid,
+ groups: groups,
+ home: u.HomeDir,
+ }, nil
+ }
+
+ fallbackSpec, fallbackErr := lookupUserFromPasswd(username)
+ if fallbackErr == nil {
+ return fallbackSpec, nil
+ }
+
+ return nil, fmt.Errorf("lookup user %q failed: %v (fallback: %w)", username, err, fallbackErr)
+}
+
+func lookupUserFromPasswd(username string) (*userSpec, error) {
+ f, err := os.Open("/etc/passwd")
+ if err != nil {
+ return nil, fmt.Errorf("open /etc/passwd: %w", err)
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := scanner.Text()
+ if strings.HasPrefix(line, "#") {
+ continue
+ }
+
+ fields := strings.Split(line, ":")
+ if len(fields) < 7 {
+ continue
+ }
+ if fields[0] != username {
+ continue
+ }
+
+ uid, err := strconv.Atoi(fields[2])
+ if err != nil {
+ return nil, fmt.Errorf("parse uid %q: %w", fields[2], err)
+ }
+ gid, err := strconv.Atoi(fields[3])
+ if err != nil {
+ return nil, fmt.Errorf("parse gid %q: %w", fields[3], err)
+ }
+
+ return &userSpec{
+ name: fields[0],
+ uid: uid,
+ gid: gid,
+ groups: []int{gid},
+ home: fields[5],
+ }, nil
+ }
+
+ if err := scanner.Err(); err != nil {
+ return nil, fmt.Errorf("scan /etc/passwd: %w", err)
+ }
+
+ return nil, fmt.Errorf("user %q not found in /etc/passwd", username)
+}
+
// Proxy manages the temperature monitoring proxy
type Proxy struct {
socketPath string
sshKeyPath string
workDir string
+ knownHosts knownhosts.Manager
listener net.Listener
rateLimiter *rateLimiter
nodeGate *nodeGate
router map[string]handlerFunc
config *Config
metrics *ProxyMetrics
+ audit *auditLogger
allowedPeerUIDs map[uint32]struct{}
allowedPeerGIDs map[uint32]struct{}
@@ -161,6 +305,32 @@ func runProxy() {
log.Fatal().Err(err).Msg("Failed to load configuration")
}
+ runAsUser := os.Getenv("PULSE_SENSOR_PROXY_USER")
+ if runAsUser == "" {
+ runAsUser = defaultRunAsUser
+ }
+
+ if spec, err := dropPrivileges(runAsUser); err != nil {
+ log.Fatal().Err(err).Str("user", runAsUser).Msg("Failed to drop privileges")
+ } else if spec != nil {
+ log.Info().
+ Str("user", spec.name).
+ Int("uid", spec.uid).
+ Int("gid", spec.gid).
+ Msg("Running as unprivileged user")
+ }
+
+ auditPath := os.Getenv("PULSE_SENSOR_PROXY_AUDIT_LOG")
+ if auditPath == "" {
+ auditPath = defaultAuditLogPath
+ }
+
+ auditLogger, err := newAuditLogger(auditPath)
+ if err != nil {
+ log.Fatal().Err(err).Str("path", auditPath).Msg("Failed to initialize audit logger")
+ }
+ defer auditLogger.Close()
+
// Initialize metrics
metrics := NewProxyMetrics(Version)
@@ -168,16 +338,24 @@ func runProxy() {
Str("socket", socketPath).
Str("ssh_key_dir", sshKeyPath).
Str("config_path", cfgPath).
+ Str("audit_log", auditPath).
Str("version", Version).
Msg("Starting pulse-sensor-proxy")
+ knownHostsManager, err := knownhosts.NewManager(filepath.Join(sshKeyPath, "known_hosts"))
+ if err != nil {
+ log.Fatal().Err(err).Msg("Failed to initialize known hosts manager")
+ }
+
proxy := &Proxy{
socketPath: socketPath,
sshKeyPath: sshKeyPath,
- rateLimiter: newRateLimiter(),
+ knownHosts: knownHostsManager,
+ rateLimiter: newRateLimiter(metrics),
nodeGate: newNodeGate(),
config: cfg,
metrics: metrics,
+ audit: auditLogger,
}
if wd, err := os.Getwd(); err == nil {
@@ -293,6 +471,8 @@ func (p *Proxy) acceptConnections() {
func (p *Proxy) handleConnection(conn net.Conn) {
defer conn.Close()
+ remoteAddr := conn.RemoteAddr().String()
+
// Track concurrent requests
p.metrics.queueDepth.Inc()
defer p.metrics.queueDepth.Dec()
@@ -310,6 +490,9 @@ func (p *Proxy) handleConnection(conn net.Conn) {
cred, err := extractPeerCredentials(conn)
if err != nil {
log.Warn().Err(err).Msg("Peer credentials unavailable")
+ if p.audit != nil {
+ p.audit.LogConnectionDenied("", nil, remoteAddr, "peer_credentials_unavailable")
+ }
p.sendErrorV2(conn, "unauthorized", "")
return
}
@@ -320,22 +503,45 @@ func (p *Proxy) handleConnection(conn net.Conn) {
Uint32("uid", cred.uid).
Uint32("gid", cred.gid).
Msg("Peer authorization failed")
+ if p.audit != nil {
+ p.audit.LogConnectionDenied("", cred, remoteAddr, err.Error())
+ }
p.sendErrorV2(conn, "unauthorized", "")
return
}
+ if p.audit != nil {
+ p.audit.LogConnectionAccepted("", cred, remoteAddr)
+ }
+
// Check rate limit and concurrency
- releaseLimiter, ok := p.rateLimiter.allow(peerID{uid: cred.uid, pid: cred.pid})
- if !ok {
- p.metrics.rateLimitHits.Inc()
+ peer := peerID{uid: cred.uid}
+ releaseLimiter, limitReason, allowed := p.rateLimiter.allow(peer)
+ if !allowed {
log.Warn().
Uint32("uid", cred.uid).
Uint32("pid", cred.pid).
+ Str("reason", limitReason).
Msg("Rate limit exceeded")
+ if p.audit != nil {
+ p.audit.LogRateLimitHit("", cred, remoteAddr, limitReason)
+ }
p.sendErrorV2(conn, "rate limit exceeded", "")
return
}
- defer releaseLimiter()
+ releaseFn := releaseLimiter
+ defer func() {
+ if releaseFn != nil {
+ releaseFn()
+ }
+ }()
+ applyPenalty := func(reason string) {
+ if releaseFn != nil {
+ releaseFn()
+ releaseFn = nil
+ }
+ p.rateLimiter.penalize(peer, reason)
+ }
// Read request using newline-delimited framing
limited := &io.LimitedReader{R: conn, N: maxRequestBytes}
@@ -344,28 +550,48 @@ func (p *Proxy) handleConnection(conn net.Conn) {
line, err := reader.ReadBytes('\n')
if err != nil {
if errors.Is(err, bufio.ErrBufferFull) || limited.N <= 0 {
+ if p.audit != nil {
+ p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "payload_too_large")
+ }
p.sendErrorV2(conn, "payload too large", "")
+ applyPenalty("payload_too_large")
return
}
if errors.Is(err, io.EOF) {
+ if p.audit != nil {
+ p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "empty_request")
+ }
p.sendErrorV2(conn, "empty request", "")
+ applyPenalty("empty_request")
return
}
+ if p.audit != nil {
+ p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "read_error")
+ }
p.sendErrorV2(conn, "failed to read request", "")
+ applyPenalty("read_error")
return
}
// Trim whitespace and validate
line = bytes.TrimSpace(line)
if len(line) == 0 {
+ if p.audit != nil {
+ p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "empty_request")
+ }
p.sendErrorV2(conn, "empty request", "")
+ applyPenalty("empty_request")
return
}
// Parse JSON
var req RPCRequest
if err := json.Unmarshal(line, &req); err != nil {
+ if p.audit != nil {
+ p.audit.LogValidationFailure("", cred, remoteAddr, "", nil, "invalid_json")
+ }
p.sendErrorV2(conn, "invalid request format", "")
+ applyPenalty("invalid_json")
return
}
@@ -389,9 +615,13 @@ func (p *Proxy) handleConnection(conn net.Conn) {
// Find handler
handler := p.router[req.Method]
if handler == nil {
+ if p.audit != nil {
+ p.audit.LogValidationFailure(req.CorrelationID, cred, remoteAddr, req.Method, nil, "unknown_method")
+ }
resp.Error = "unknown method"
logger.Warn().Msg("Unknown method")
p.sendResponse(conn, resp)
+ applyPenalty("unknown_method")
return
}
@@ -407,15 +637,27 @@ func (p *Proxy) handleConnection(conn net.Conn) {
Uint32("pid", cred.pid).
Str("corr_id", req.CorrelationID).
Msg("SECURITY: Container attempted to call privileged method - access denied")
+ if p.audit != nil {
+ p.audit.LogValidationFailure(req.CorrelationID, cred, remoteAddr, req.Method, nil, "privileged_method_denied")
+ }
p.sendResponse(conn, resp)
p.metrics.rpcRequests.WithLabelValues(req.Method, "unauthorized").Inc()
+ applyPenalty("privileged_method_denied")
return
}
}
+ if p.audit != nil {
+ p.audit.LogCommandStart(req.CorrelationID, cred, remoteAddr, "", req.Method, nil)
+ }
+
// Execute handler
result, err := handler(ctx, &req, logger)
+ duration := time.Since(startTime)
if err != nil {
+ if p.audit != nil {
+ p.audit.LogCommandResult(req.CorrelationID, cred, remoteAddr, "", req.Method, nil, 1, duration, "", "", err)
+ }
resp.Error = err.Error()
logger.Warn().Err(err).Msg("Handler failed")
// Clear read deadline and set write deadline for error response
@@ -431,6 +673,9 @@ func (p *Proxy) handleConnection(conn net.Conn) {
// Success
resp.Success = true
resp.Data = result
+ if p.audit != nil {
+ p.audit.LogCommandResult(req.CorrelationID, cred, remoteAddr, "", req.Method, nil, 0, duration, "", "", nil)
+ }
logger.Info().Msg("Request completed")
// Clear read deadline and set write deadline for response
diff --git a/cmd/pulse-sensor-proxy/metrics.go b/cmd/pulse-sensor-proxy/metrics.go
index 48955f1a90..5dac63f6ba 100644
--- a/cmd/pulse-sensor-proxy/metrics.go
+++ b/cmd/pulse-sensor-proxy/metrics.go
@@ -16,15 +16,19 @@ const defaultMetricsAddr = "127.0.0.1:9127"
// ProxyMetrics holds Prometheus metrics for the proxy
type ProxyMetrics struct {
- rpcRequests *prometheus.CounterVec
- rpcLatency *prometheus.HistogramVec
- sshRequests *prometheus.CounterVec
- sshLatency *prometheus.HistogramVec
- queueDepth prometheus.Gauge
- rateLimitHits prometheus.Counter
- buildInfo *prometheus.GaugeVec
- server *http.Server
- registry *prometheus.Registry
+ rpcRequests *prometheus.CounterVec
+ rpcLatency *prometheus.HistogramVec
+ sshRequests *prometheus.CounterVec
+ sshLatency *prometheus.HistogramVec
+ queueDepth prometheus.Gauge
+ rateLimitHits prometheus.Counter
+ limiterRejects *prometheus.CounterVec
+ globalConcurrency prometheus.Gauge
+ limiterPenalties *prometheus.CounterVec
+ limiterPeers prometheus.Gauge
+ buildInfo *prometheus.GaugeVec
+ server *http.Server
+ registry *prometheus.Registry
}
// NewProxyMetrics creates and registers all metrics
@@ -74,6 +78,32 @@ func NewProxyMetrics(version string) *ProxyMetrics {
Help: "Number of RPC requests rejected due to rate limiting.",
},
),
+ limiterRejects: prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "pulse_proxy_limiter_rejections_total",
+ Help: "Limiter rejections by reason.",
+ },
+ []string{"reason"},
+ ),
+ globalConcurrency: prometheus.NewGauge(
+ prometheus.GaugeOpts{
+ Name: "pulse_proxy_global_concurrency_inflight",
+ Help: "Current global concurrency slots in use.",
+ },
+ ),
+ limiterPenalties: prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "pulse_proxy_limiter_penalties_total",
+ Help: "Penalty sleeps applied after validation failures.",
+ },
+ []string{"reason"},
+ ),
+ limiterPeers: prometheus.NewGauge(
+ prometheus.GaugeOpts{
+ Name: "pulse_proxy_limiter_active_peers",
+ Help: "Number of peers tracked by the rate limiter.",
+ },
+ ),
buildInfo: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "pulse_proxy_build_info",
@@ -91,6 +121,10 @@ func NewProxyMetrics(version string) *ProxyMetrics {
pm.sshLatency,
pm.queueDepth,
pm.rateLimitHits,
+ pm.limiterRejects,
+ pm.globalConcurrency,
+ pm.limiterPenalties,
+ pm.limiterPeers,
pm.buildInfo,
)
@@ -165,3 +199,39 @@ func sanitizeNodeLabel(node string) string {
return out
}
+
+func (m *ProxyMetrics) recordLimiterReject(reason string) {
+ if m == nil {
+ return
+ }
+ m.rateLimitHits.Inc()
+ m.limiterRejects.WithLabelValues(reason).Inc()
+}
+
+func (m *ProxyMetrics) incGlobalConcurrency() {
+ if m == nil {
+ return
+ }
+ m.globalConcurrency.Inc()
+}
+
+func (m *ProxyMetrics) decGlobalConcurrency() {
+ if m == nil {
+ return
+ }
+ m.globalConcurrency.Dec()
+}
+
+func (m *ProxyMetrics) recordPenalty(reason string) {
+ if m == nil {
+ return
+ }
+ m.limiterPenalties.WithLabelValues(reason).Inc()
+}
+
+func (m *ProxyMetrics) setLimiterPeers(count int) {
+ if m == nil {
+ return
+ }
+ m.limiterPeers.Set(float64(count))
+}
diff --git a/cmd/pulse-sensor-proxy/ssh.go b/cmd/pulse-sensor-proxy/ssh.go
index eeff10890f..c39ff2182d 100644
--- a/cmd/pulse-sensor-proxy/ssh.go
+++ b/cmd/pulse-sensor-proxy/ssh.go
@@ -2,16 +2,46 @@ package main
import (
"bytes"
+ "context"
"fmt"
"os"
"os/exec"
"path/filepath"
+ "strconv"
"strings"
"time"
"github.com/rs/zerolog/log"
)
+const (
+ tempWrapperPath = "/usr/local/libexec/pulse-sensor-proxy/temp-wrapper.sh"
+ tempWrapperScript = `#!/bin/sh
+set -eu
+
+if command -v sensors >/dev/null 2>&1; then
+ OUTPUT="$(sensors -j 2>/dev/null || true)"
+ if [ -n "$OUTPUT" ]; then
+ printf '%s\n' "$OUTPUT"
+ exit 0
+ fi
+fi
+
+if [ -r /sys/class/thermal/thermal_zone0/temp ]; then
+ RAW="$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null || true)"
+ if [ -n "$RAW" ]; then
+ TEMP="$(awk -v raw="$RAW" 'BEGIN { if (raw == "") exit 1; printf "%.2f", raw / 1000.0 }' 2>/dev/null || true)"
+ if [ -n "$TEMP" ]; then
+ printf '{"rpitemp-virtual":{"temp1":{"temp1_input":%s}}}\n' "$TEMP"
+ exit 0
+ fi
+ fi
+fi
+
+exit 1
+`
+)
+
// execCommand executes a shell command and returns output
func execCommand(cmd string) (string, error) {
out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
@@ -47,12 +77,70 @@ func (p *Proxy) buildAuthorizedKey(pubKey string) (string, error) {
const comment = "pulse-sensor-proxy"
// Forced command with all restrictions
- const forced = `command="sensors -j",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty`
+ forced := fmt.Sprintf(`command="%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty`, tempWrapperPath)
// Format: from="...",command="...",no-* ssh-rsa AAAA... pulse-sensor-proxy
return fmt.Sprintf(`%s,%s %s %s`, fromClause, forced, pubKey, comment), nil
}
+func (p *Proxy) ensureHostKey(node string) error {
+ if p.knownHosts == nil {
+ return fmt.Errorf("host key manager not configured")
+ }
+ return p.knownHosts.Ensure(context.Background(), node)
+}
+
+func (p *Proxy) sshCommonOptions() string {
+ if p.knownHosts == nil {
+ return "-o StrictHostKeyChecking=yes -o BatchMode=yes"
+ }
+ return fmt.Sprintf("-o StrictHostKeyChecking=yes -o BatchMode=yes -o UserKnownHostsFile=%s -o GlobalKnownHostsFile=/dev/null",
+ shellQuote(p.knownHosts.Path()))
+}
+
+func shellQuote(arg string) string {
+ if arg == "" {
+ return "''"
+ }
+ if !strings.Contains(arg, "'") {
+ return "'" + arg + "'"
+ }
+ return strconv.Quote(arg)
+}
+
+func (p *Proxy) ensureTempWrapper(nodeHost, commonOpts string) error {
+ dir := filepath.Dir(tempWrapperPath)
+ mkdirCmd := fmt.Sprintf(
+ `ssh %s -o ConnectTimeout=10 root@%s "mkdir -p %s && chmod 755 %s"`,
+ commonOpts,
+ nodeHost,
+ dir,
+ dir,
+ )
+
+ if _, err := execCommand(mkdirCmd); err != nil {
+ return fmt.Errorf("failed to prepare temperature wrapper directory on %s: %w", nodeHost, err)
+ }
+
+ uploadCmd := fmt.Sprintf(
+ `ssh %s -o ConnectTimeout=10 root@%s "cat > %s <<'EOF'
+%s
+EOF
+chmod 755 %s"`,
+ commonOpts,
+ nodeHost,
+ tempWrapperPath,
+ tempWrapperScript,
+ tempWrapperPath,
+ )
+
+ if _, err := execCommand(uploadCmd); err != nil {
+ return fmt.Errorf("failed to install temperature wrapper on %s: %w", nodeHost, err)
+ }
+
+ return nil
+}
+
// pushSSHKeyFrom pushes a public key from a specific directory to a node
func (p *Proxy) pushSSHKeyFrom(nodeHost, keyDir string) error {
startTime := time.Now()
@@ -73,9 +161,23 @@ func (p *Proxy) pushSSHKeyFrom(nodeHost, keyDir string) error {
return fmt.Errorf("failed to build authorized key: %w", err)
}
+ if err := p.ensureHostKey(nodeHost); err != nil {
+ p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()
+ p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())
+ return fmt.Errorf("failed to ensure host key for %s: %w", nodeHost, err)
+ }
+
+ commonOpts := p.sshCommonOptions()
+ if err := p.ensureTempWrapper(nodeHost, commonOpts); err != nil {
+ p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()
+ p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())
+ return fmt.Errorf("failed to stage temperature wrapper on %s: %w", nodeHost, err)
+ }
+
// Check if the exact restricted entry already exists
checkCmd := fmt.Sprintf(
- `ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@%s "grep -F '%s' /root/.ssh/authorized_keys 2>/dev/null"`,
+ `ssh %s -o ConnectTimeout=10 root@%s "grep -F '%s' /root/.ssh/authorized_keys 2>/dev/null"`,
+ commonOpts,
nodeHost,
entry,
)
@@ -89,7 +191,8 @@ func (p *Proxy) pushSSHKeyFrom(nodeHost, keyDir string) error {
// Remove old pulse-temp-proxy and pulse-sensor-proxy entries (for upgrade path)
removeOldCmd := fmt.Sprintf(
- `ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@%s "mkdir -p /root/.ssh && chmod 700 /root/.ssh && grep -v -e 'pulse-temp-proxy$' -e 'pulse-sensor-proxy$' /root/.ssh/authorized_keys > /root/.ssh/authorized_keys.tmp 2>/dev/null || touch /root/.ssh/authorized_keys.tmp"`,
+ `ssh %s -o ConnectTimeout=10 root@%s "mkdir -p /root/.ssh && chmod 700 /root/.ssh && grep -v -e 'pulse-temp-proxy$' -e 'pulse-sensor-proxy$' /root/.ssh/authorized_keys > /root/.ssh/authorized_keys.tmp 2>/dev/null || touch /root/.ssh/authorized_keys.tmp"`,
+ commonOpts,
nodeHost,
)
@@ -101,7 +204,8 @@ func (p *Proxy) pushSSHKeyFrom(nodeHost, keyDir string) error {
// Add the new restricted key and atomically replace the file
addCmd := fmt.Sprintf(
- `ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@%s "echo '%s' >> /root/.ssh/authorized_keys.tmp && mv /root/.ssh/authorized_keys.tmp /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys"`,
+ `ssh %s -o ConnectTimeout=10 root@%s "echo '%s' >> /root/.ssh/authorized_keys.tmp && mv /root/.ssh/authorized_keys.tmp /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys"`,
+ commonOpts,
nodeHost,
entry,
)
@@ -135,9 +239,17 @@ func (p *Proxy) testSSHConnection(nodeHost string) error {
nodeLabel := sanitizeNodeLabel(nodeHost)
privKeyPath := filepath.Join(p.sshKeyPath, "id_ed25519")
+ if err := p.ensureHostKey(nodeHost); err != nil {
+ p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()
+ p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())
+ return fmt.Errorf("failed to ensure host key for %s: %w", nodeHost, err)
+ }
+
+ commonOpts := p.sshCommonOptions()
cmd := fmt.Sprintf(
- `ssh -i %[1]s -T -n -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o ConnectTimeout=5 root@%[2]s "echo test"`,
- privKeyPath,
+ `ssh %s -i %s -T -n -o LogLevel=ERROR -o ConnectTimeout=5 root@%s ""`,
+ commonOpts,
+ shellQuote(privKeyPath),
nodeHost,
)
@@ -162,12 +274,20 @@ func (p *Proxy) getTemperatureViaSSH(nodeHost string) (string, error) {
nodeLabel := sanitizeNodeLabel(nodeHost)
privKeyPath := filepath.Join(p.sshKeyPath, "id_ed25519")
+ if err := p.ensureHostKey(nodeHost); err != nil {
+ p.metrics.sshRequests.WithLabelValues(nodeLabel, "error").Inc()
+ p.metrics.sshLatency.WithLabelValues(nodeLabel).Observe(time.Since(startTime).Seconds())
+ return "", fmt.Errorf("failed to ensure host key for %s: %w", nodeHost, err)
+ }
+
+ commonOpts := p.sshCommonOptions()
- // Since we use ForceCommand="sensors -j", any SSH command will run sensors
+ // Since we use a forced wrapper command, any SSH connection runs the wrapper
// We don't need to specify the command
cmd := fmt.Sprintf(
- `ssh -i %[1]s -T -n -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o ConnectTimeout=5 root@%[2]s ""`,
- privKeyPath,
+ `ssh %s -i %s -T -n -o LogLevel=ERROR -o ConnectTimeout=5 root@%s ""`,
+ commonOpts,
+ shellQuote(privKeyPath),
nodeHost,
)
diff --git a/cmd/pulse-sensor-proxy/ssh_test.go b/cmd/pulse-sensor-proxy/ssh_test.go
new file mode 100644
index 0000000000..4113b281ab
--- /dev/null
+++ b/cmd/pulse-sensor-proxy/ssh_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func setupTempWrapper(t *testing.T) (scriptPath, thermalFile, binDir, baseDir string) {
+ t.Helper()
+
+ baseDir = t.TempDir()
+
+ thermalDir := filepath.Join(baseDir, "sys", "class", "thermal", "thermal_zone0")
+ if err := os.MkdirAll(thermalDir, 0o755); err != nil {
+ t.Fatalf("failed to create thermal zone directory: %v", err)
+ }
+ thermalFile = filepath.Join(thermalDir, "temp")
+
+ scriptContent := strings.ReplaceAll(tempWrapperScript, "/sys/class/thermal/thermal_zone0/temp", thermalFile)
+ scriptPath = filepath.Join(baseDir, "temp-wrapper.sh")
+ if err := os.WriteFile(scriptPath, []byte(scriptContent), 0o755); err != nil {
+ t.Fatalf("failed to write wrapper script: %v", err)
+ }
+
+ binDir = filepath.Join(baseDir, "bin")
+ if err := os.MkdirAll(binDir, 0o755); err != nil {
+ t.Fatalf("failed to create bin directory: %v", err)
+ }
+
+ linkCommand := func(name string) {
+ target, err := exec.LookPath(name)
+ if err != nil {
+ t.Fatalf("required command %q not found on host: %v", name, err)
+ }
+ content := fmt.Sprintf("#!/bin/sh\nexec %s \"$@\"\n", target)
+ if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil {
+ t.Fatalf("failed to create shim for %s: %v", name, err)
+ }
+ }
+
+ linkCommand("awk")
+ linkCommand("cat")
+
+ return scriptPath, thermalFile, binDir, baseDir
+}
+
+func runTempWrapper(t *testing.T, scriptPath, binDir string, extraEnv ...string) []byte {
+ t.Helper()
+ cmd := exec.Command("sh", scriptPath)
+ env := []string{"PATH=" + binDir}
+ env = append(env, extraEnv...)
+ cmd.Env = env
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("temp wrapper failed: %v (output: %s)", err, strings.TrimSpace(string(output)))
+ }
+ return output
+}
+
+func TestTempWrapperFallbackWhenSensorsMissing(t *testing.T) {
+ scriptPath, thermalFile, binDir, _ := setupTempWrapper(t)
+
+ if err := os.WriteFile(thermalFile, []byte("51234\n"), 0o644); err != nil {
+ t.Fatalf("failed to write thermal zone temperature: %v", err)
+ }
+
+ output := runTempWrapper(t, scriptPath, binDir)
+
+ var data map[string]map[string]map[string]float64
+ if err := json.Unmarshal(output, &data); err != nil {
+ t.Fatalf("failed to parse wrapper output as JSON: %v (output: %s)", err, strings.TrimSpace(string(output)))
+ }
+
+ temp1, ok := data["rpitemp-virtual"]["temp1"]["temp1_input"]
+ if !ok {
+ t.Fatalf("expected rpitemp-virtual temp1 reading in output: %v", data)
+ }
+ if temp1 != 51.23 {
+ t.Fatalf("expected converted temperature 51.23, got %.2f", temp1)
+ }
+}
+
+func TestTempWrapperFallbackWhenSensorsEmpty(t *testing.T) {
+ scriptPath, thermalFile, binDir, _ := setupTempWrapper(t)
+
+ sensorsStub := filepath.Join(binDir, "sensors")
+ content := "#!/bin/sh\nexit 0\n"
+ if err := os.WriteFile(sensorsStub, []byte(content), 0o755); err != nil {
+ t.Fatalf("failed to create sensors stub: %v", err)
+ }
+
+ if err := os.WriteFile(thermalFile, []byte("47890\n"), 0o644); err != nil {
+ t.Fatalf("failed to write thermal zone temperature: %v", err)
+ }
+
+ output := runTempWrapper(t, scriptPath, binDir)
+
+ var data map[string]map[string]map[string]float64
+ if err := json.Unmarshal(output, &data); err != nil {
+ t.Fatalf("failed to parse wrapper output as JSON: %v (output: %s)", err, strings.TrimSpace(string(output)))
+ }
+
+ temp1, ok := data["rpitemp-virtual"]["temp1"]["temp1_input"]
+ if !ok {
+ t.Fatalf("expected rpitemp-virtual temp1 reading in output: %v", data)
+ }
+ if temp1 != 47.89 {
+ t.Fatalf("expected converted temperature 47.89, got %.2f", temp1)
+ }
+}
+
+func TestTempWrapperPrefersSensorsOutput(t *testing.T) {
+ scriptPath, thermalFile, binDir, _ := setupTempWrapper(t)
+
+ jsonOutput := `{"cpu_thermal-virtual-0":{"temp1":{"temp1_input":42.5}}}`
+ sensorsStub := filepath.Join(binDir, "sensors")
+ content := fmt.Sprintf("#!/bin/sh\nprintf '%s'\n", jsonOutput)
+ if err := os.WriteFile(sensorsStub, []byte(content), 0o755); err != nil {
+ t.Fatalf("failed to create sensors stub: %v", err)
+ }
+
+ // Ensure thermal zone file exists but should be ignored
+ if err := os.WriteFile(thermalFile, []byte("40000\n"), 0o644); err != nil {
+ t.Fatalf("failed to write thermal zone temperature: %v", err)
+ }
+
+ output := runTempWrapper(t, scriptPath, binDir)
+
+ trimmed := strings.TrimSpace(string(output))
+ if trimmed != jsonOutput {
+ t.Fatalf("expected wrapper to return sensors output %s, got %s", jsonOutput, trimmed)
+ }
+}
diff --git a/cmd/pulse-sensor-proxy/throttle.go b/cmd/pulse-sensor-proxy/throttle.go
index 946de00dfd..3d07b0618c 100644
--- a/cmd/pulse-sensor-proxy/throttle.go
+++ b/cmd/pulse-sensor-proxy/throttle.go
@@ -7,62 +7,122 @@ import (
"golang.org/x/time/rate"
)
-// peerID identifies a connecting process by UID+PID
+// peerID identifies a connecting principal (grouped by UID)
type peerID struct {
uid uint32
- pid uint32
}
// limiterEntry holds rate limiting and concurrency controls for a peer
type limiterEntry struct {
- limiter *rate.Limiter // throughput: 20/min with burst 10
- semaphore chan struct{} // concurrency: cap 10
+ limiter *rate.Limiter
+ semaphore chan struct{}
lastSeen time.Time
}
+type limiterPolicy struct {
+ perPeerLimit rate.Limit
+ perPeerBurst int
+ perPeerConcurrency int
+ globalConcurrency int
+ penaltyDuration time.Duration
+}
+
// rateLimiter manages per-peer rate limits and concurrency
type rateLimiter struct {
- mu sync.Mutex
- entries map[peerID]*limiterEntry
- quitChan chan struct{}
+ mu sync.Mutex
+ entries map[peerID]*limiterEntry
+ quitChan chan struct{}
+ globalSem chan struct{}
+ policy limiterPolicy
+ metrics *ProxyMetrics
}
+const (
+ defaultPerPeerBurst = 2
+ defaultPerPeerConcurrency = 2
+ defaultGlobalConcurrency = 8
+)
+
+var (
+ defaultPerPeerRateInterval = 5 * time.Second // 0.2 qps (~12/min)
+ defaultPenaltyDuration = 2 * time.Second
+ defaultPerPeerLimit = rate.Every(defaultPerPeerRateInterval)
+)
+
// newRateLimiter creates a new rate limiter with cleanup loop
-func newRateLimiter() *rateLimiter {
+func newRateLimiter(metrics *ProxyMetrics) *rateLimiter {
rl := &rateLimiter{
- entries: make(map[peerID]*limiterEntry),
- quitChan: make(chan struct{}),
+ entries: make(map[peerID]*limiterEntry),
+ quitChan: make(chan struct{}),
+ globalSem: make(chan struct{}, defaultGlobalConcurrency),
+ policy: limiterPolicy{
+ perPeerLimit: defaultPerPeerLimit,
+ perPeerBurst: defaultPerPeerBurst,
+ perPeerConcurrency: defaultPerPeerConcurrency,
+ globalConcurrency: defaultGlobalConcurrency,
+ penaltyDuration: defaultPenaltyDuration,
+ },
+ metrics: metrics,
+ }
+ if rl.metrics != nil {
+ rl.metrics.setLimiterPeers(0)
}
go rl.cleanupLoop()
return rl
}
-// allow checks if a peer is allowed to make a request and reserves a concurrency slot
-// Returns a release function and whether the request is allowed
-func (rl *rateLimiter) allow(id peerID) (release func(), allowed bool) {
+// allow checks if a peer is allowed to make a request and reserves concurrency.
+// Returns a release function, rejection reason (if any), and whether the request is allowed.
+func (rl *rateLimiter) allow(id peerID) (release func(), reason string, allowed bool) {
rl.mu.Lock()
entry := rl.entries[id]
if entry == nil {
entry = &limiterEntry{
- limiter: rate.NewLimiter(rate.Every(time.Minute/20), 10), // 20/min, burst 10
- semaphore: make(chan struct{}, 10), // max 10 concurrent
+ limiter: rate.NewLimiter(rl.policy.perPeerLimit, rl.policy.perPeerBurst),
+ semaphore: make(chan struct{}, rl.policy.perPeerConcurrency),
}
rl.entries[id] = entry
+ if rl.metrics != nil {
+ rl.metrics.setLimiterPeers(len(rl.entries))
+ }
}
entry.lastSeen = time.Now()
rl.mu.Unlock()
// Check rate limit
if !entry.limiter.Allow() {
- return nil, false
+ rl.recordRejection("rate")
+ return nil, "rate", false
+ }
+
+ // Acquire global concurrency
+ select {
+ case rl.globalSem <- struct{}{}:
+ if rl.metrics != nil {
+ rl.metrics.incGlobalConcurrency()
+ }
+ default:
+ rl.recordRejection("global_concurrency")
+ return nil, "global_concurrency", false
}
- // Try to acquire concurrency slot
+ // Try to acquire per-peer concurrency slot
select {
case entry.semaphore <- struct{}{}:
- return func() { <-entry.semaphore }, true
+ return func() {
+ <-entry.semaphore
+ <-rl.globalSem
+ if rl.metrics != nil {
+ rl.metrics.decGlobalConcurrency()
+ }
+ }, "", true
default:
- return nil, false // max concurrent in-flight reached
+ <-rl.globalSem
+ if rl.metrics != nil {
+ rl.metrics.decGlobalConcurrency()
+ }
+ rl.recordRejection("peer_concurrency")
+ return nil, "peer_concurrency", false
}
}
@@ -79,6 +139,9 @@ func (rl *rateLimiter) cleanupLoop() {
delete(rl.entries, id)
}
}
+ if rl.metrics != nil {
+ rl.metrics.setLimiterPeers(len(rl.entries))
+ }
rl.mu.Unlock()
case <-rl.quitChan:
return
@@ -91,6 +154,22 @@ func (rl *rateLimiter) shutdown() {
close(rl.quitChan)
}
+func (rl *rateLimiter) penalize(id peerID, reason string) {
+ if rl.policy.penaltyDuration <= 0 {
+ return
+ }
+ time.Sleep(rl.policy.penaltyDuration)
+ if rl.metrics != nil {
+ rl.metrics.recordPenalty(reason)
+ }
+}
+
+func (rl *rateLimiter) recordRejection(reason string) {
+ if rl.metrics != nil {
+ rl.metrics.recordLimiterReject(reason)
+ }
+}
+
// nodeGate controls per-node concurrency for temperature requests
type nodeGate struct {
mu sync.Mutex
diff --git a/cmd/pulse-sensor-proxy/throttle_test.go b/cmd/pulse-sensor-proxy/throttle_test.go
new file mode 100644
index 0000000000..6cffe2df0b
--- /dev/null
+++ b/cmd/pulse-sensor-proxy/throttle_test.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "testing"
+ "time"
+)
+
+func TestRateLimiterPenalizeMetrics(t *testing.T) {
+ metrics := NewProxyMetrics("test")
+ rl := newRateLimiter(metrics)
+ rl.policy.penaltyDuration = 10 * time.Millisecond
+
+ start := time.Now()
+ rl.penalize(peerID{uid: 42}, "invalid_json")
+ if time.Since(start) < rl.policy.penaltyDuration {
+ t.Fatalf("expected penalize to sleep at least %v", rl.policy.penaltyDuration)
+ }
+
+ mf, err := metrics.registry.Gather()
+ if err != nil {
+ t.Fatalf("gather metrics: %v", err)
+ }
+
+ found := false
+ for _, fam := range mf {
+ if fam.GetName() != "pulse_proxy_limiter_penalties_total" {
+ continue
+ }
+ for _, metric := range fam.GetMetric() {
+ if metric.GetCounter().GetValue() == 0 {
+ continue
+ }
+ for _, label := range metric.GetLabel() {
+ if label.GetName() == "reason" && label.GetValue() == "invalid_json" {
+ found = true
+ }
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("expected limiter penalty metric for invalid_json")
+ }
+}
diff --git a/cmd/pulse-sensor-proxy/validation.go b/cmd/pulse-sensor-proxy/validation.go
index 01ceee0f2b..8eb2d5356f 100644
--- a/cmd/pulse-sensor-proxy/validation.go
+++ b/cmd/pulse-sensor-proxy/validation.go
@@ -1,8 +1,13 @@
package main
import (
+ "errors"
"fmt"
+ "net"
"regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
"github.com/google/uuid"
)
@@ -19,6 +24,13 @@ var (
ipv6Regex = regexp.MustCompile(`^[0-9a-fA-F:]+$`)
)
+var (
+ allowedCommands = map[string]struct{}{
+ "sensors": {},
+ "ipmitool": {},
+ }
+)
+
// sanitizeCorrelationID validates and sanitizes a correlation ID
// Returns a valid UUID, generating a new one if input is missing or invalid
func sanitizeCorrelationID(id string) string {
@@ -33,8 +45,162 @@ func sanitizeCorrelationID(id string) string {
// validateNodeName checks if a node name is in valid format
func validateNodeName(name string) error {
- if !nodeNameRegex.MatchString(name) {
+ if name == "" {
return fmt.Errorf("invalid node name")
}
+
+ if ipv4Regex.MatchString(name) {
+ return nil
+ }
+
+ candidate := name
+ if strings.HasPrefix(candidate, "[") && strings.HasSuffix(candidate, "]") {
+ candidate = candidate[1 : len(candidate)-1]
+ }
+
+ if ip := net.ParseIP(candidate); ip != nil {
+ return nil
+ }
+
+ if nodeNameRegex.MatchString(name) {
+ return nil
+ }
+
+ return fmt.Errorf("invalid node name")
+}
+
+func validateCommand(name string, args []string) error {
+ if err := validateCommandName(name); err != nil {
+ return err
+ }
+
+ for _, arg := range args {
+ if err := validateCommandArg(arg); err != nil {
+ return err
+ }
+ }
+
+ if name == "ipmitool" {
+ if err := validateIPMIToolArgs(args); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func validateCommandName(name string) error {
+ if name == "" {
+ return errors.New("command required")
+ }
+
+ if strings.Contains(name, "/") {
+ return errors.New("absolute command paths not allowed")
+ }
+
+ if _, ok := allowedCommands[name]; !ok {
+ return fmt.Errorf("command %q not permitted", name)
+ }
+
+ if !isASCII(name) {
+ return errors.New("command must be ASCII")
+ }
+
return nil
}
+
+func validateCommandArg(arg string) error {
+ if len(arg) == 0 {
+ return nil
+ }
+
+ if len(arg) > 1024 {
+ return errors.New("argument too long")
+ }
+
+ if !utf8.ValidString(arg) {
+ return errors.New("argument contains invalid UTF-8")
+ }
+
+ if hasNullByte(arg) {
+ return errors.New("argument contains null byte")
+ }
+
+ if !isASCII(arg) {
+ return errors.New("argument must be ASCII")
+ }
+
+ if hasShellMeta(arg) {
+ return errors.New("argument contains forbidden shell characters")
+ }
+
+ if strings.Contains(arg, "=") && !strings.HasPrefix(arg, "-") {
+ return errors.New("environment-style arguments not permitted")
+ }
+
+ return nil
+}
+
+func validateIPMIToolArgs(args []string) error {
+ lowered := make([]string, len(args))
+ for i, arg := range args {
+ lowered[i] = strings.ToLower(arg)
+ }
+
+ for i := 0; i < len(lowered); i++ {
+ token := lowered[i]
+ switch token {
+ case "shell", "raw", "exec", "lanplus", "lanplusciphers":
+ return errors.New("dangerous ipmitool arguments not permitted")
+ case "chassis":
+ if i+1 < len(lowered) {
+ switch lowered[i+1] {
+ case "power", "bootparam", "status", "policy":
+ return errors.New("chassis operations not permitted")
+ }
+ }
+ case "power", "reset", "off", "cycle", "bmc", "mc":
+ return errors.New("power control commands not permitted")
+ }
+ }
+
+ return nil
+}
+
+func hasShellMeta(s string) bool {
+ forbidden := []string{";", "|", "&", "$", "`", "\\", ">", "<", "(", ")", "[", "]", "{", "}", "!", "~"}
+ for _, ch := range forbidden {
+ if strings.Contains(s, ch) {
+ return true
+ }
+ }
+
+ if strings.Contains(s, "..") {
+ return true
+ }
+
+ if strings.ContainsAny(s, "\n\r\t") {
+ return true
+ }
+
+ if strings.HasPrefix(s, "-") && strings.Contains(s, "=") {
+ if strings.Contains(s, "/") {
+ return true
+ }
+ }
+
+ return false
+}
+
+func hasNullByte(s string) bool {
+ return strings.IndexByte(s, 0) >= 0
+}
+
+func isASCII(s string) bool {
+ for _, r := range s {
+ if r > unicode.MaxASCII {
+ return false
+ }
+ }
+ return true
+}
diff --git a/cmd/pulse-sensor-proxy/validation_fuzz_test.go b/cmd/pulse-sensor-proxy/validation_fuzz_test.go
new file mode 100644
index 0000000000..b45e68ae98
--- /dev/null
+++ b/cmd/pulse-sensor-proxy/validation_fuzz_test.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "strings"
+ "testing"
+)
+
+func FuzzValidateCommand(f *testing.F) {
+ seeds := []string{
+ "sensors -j",
+ "ipmitool sdr",
+ "sensors",
+ "ipmitool lan print",
+ }
+ for _, seed := range seeds {
+ f.Add(seed)
+ }
+
+ f.Fuzz(func(t *testing.T, input string) {
+ fields := strings.Fields(input)
+ if len(fields) == 0 {
+ return
+ }
+ cmd := fields[0]
+ args := []string{}
+ if len(fields) > 1 {
+ args = fields[1:]
+ }
+ validateCommand(cmd, args) // ensure no panics
+ })
+}
diff --git a/cmd/pulse-sensor-proxy/validation_test.go b/cmd/pulse-sensor-proxy/validation_test.go
new file mode 100644
index 0000000000..bb31654d0f
--- /dev/null
+++ b/cmd/pulse-sensor-proxy/validation_test.go
@@ -0,0 +1,123 @@
+package main
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSanitizeCorrelationID(t *testing.T) {
+ valid := sanitizeCorrelationID("550e8400-e29b-41d4-a716-446655440000")
+ if valid != "550e8400-e29b-41d4-a716-446655440000" {
+ t.Fatalf("expected valid UUID to pass through, got %s", valid)
+ }
+
+ invalid := sanitizeCorrelationID("not-a-uuid")
+ if invalid == "not-a-uuid" {
+ t.Fatalf("expected invalid UUID to be replaced")
+ }
+
+ empty := sanitizeCorrelationID("")
+ if empty == "" {
+ t.Fatalf("expected empty string to be replaced")
+ }
+
+ if invalid == empty {
+ t.Fatalf("expected regenerated UUIDs to differ")
+ }
+}
+
+func TestValidateNodeName(t *testing.T) {
+ cases := []struct {
+ name string
+ wantErr bool
+ desc string
+ }{
+ {name: "node-1", wantErr: false, desc: "alphanumeric"},
+ {name: "example.com", wantErr: false, desc: "dns hostname"},
+ {name: "1.2.3.4", wantErr: false, desc: "ipv4"},
+ {name: "2001:db8::1", wantErr: false, desc: "ipv6 compressed"},
+ {name: "[2001:db8::10]", wantErr: false, desc: "ipv6 bracketed"},
+ {name: "::1", wantErr: false, desc: "ipv6 loopback"},
+ {name: "::", wantErr: false, desc: "ipv6 unspecified"},
+ {name: "::ffff:192.0.2.1", wantErr: false, desc: "ipv4-mapped ipv6 dual stack"},
+ {name: "[::1]", wantErr: false, desc: "ipv6 loopback bracketed"},
+ {name: "fe80::1%eth0", wantErr: true, desc: "ipv6 zone identifier"},
+ {name: "[fe80::1%eth0]", wantErr: true, desc: "ipv6 zone identifier bracketed"},
+ {name: "[2001:db8::1]:22", wantErr: true, desc: "ipv6 with port suffix"},
+ {name: "[2001:db8::1", wantErr: true, desc: "missing closing bracket"},
+ {name: "2001:db8::1]", wantErr: true, desc: "missing opening bracket"},
+ {name: "bad host", wantErr: true, desc: "whitespace disallowed"},
+ {name: "-leadinghyphen", wantErr: true, desc: "leading hyphen disallowed"},
+ {name: "example.com:22", wantErr: true, desc: "dns name with port"},
+ {name: "", wantErr: true, desc: "empty string"},
+ {name: "example_com", wantErr: false, desc: "underscore"},
+ {name: "NODE123", wantErr: false, desc: "uppercase"},
+ {name: strings.Repeat("a", 64), wantErr: false, desc: "64 chars"},
+ {name: strings.Repeat("a", 65), wantErr: true, desc: "65 chars"},
+ {name: "senso\u200Brs", wantErr: true, desc: "zero-width space"},
+ {name: "node\\name", wantErr: true, desc: "backslash"},
+ {name: "/etc/passwd", wantErr: true, desc: "absolute path"},
+ {name: "node\x00", wantErr: true, desc: "null byte"},
+ {name: "example.com;rm", wantErr: true, desc: "semicolon"},
+ {name: "node$(rm)", wantErr: true, desc: "subshell"},
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ name := tc.desc
+ if name == "" {
+ name = tc.name
+ }
+ t.Run(name, func(t *testing.T) {
+ err := validateNodeName(tc.name)
+ if tc.wantErr && err == nil {
+ t.Fatalf("expected error validating %q", tc.name)
+ }
+ if !tc.wantErr && err != nil {
+ t.Fatalf("unexpected error for %q: %v", tc.name, err)
+ }
+ })
+ }
+}
+
+func TestValidateCommand(t *testing.T) {
+ type tc struct {
+ name string
+ args []string
+ wantErr bool
+ desc string
+ }
+
+ cases := []tc{
+ {name: "sensors", args: nil, wantErr: false, desc: "bare sensors"},
+ {name: "sensors", args: []string{"-j"}, wantErr: false, desc: "json flag"},
+ {name: "ipmitool", args: []string{"sdr"}, wantErr: false, desc: "safe ipmitool"},
+ {name: "sensors", args: []string{"; rm -rf /"}, wantErr: true, desc: "shell metachar"},
+ {name: "sensors", args: []string{"$(id)"}, wantErr: true, desc: "subshell"},
+ {name: "ipmitool", args: []string{"-H", "1.2.3.4", "&&", "shutdown"}, wantErr: true, desc: "command chaining"},
+ {name: "sensors", args: []string{">/tmp/out"}, wantErr: true, desc: "redirect"},
+ {name: "senso\u200Brs", wantErr: true, desc: "unicode homoglyph"},
+ {name: "sensors", args: []string{"-" + strings.Repeat("v", 2000)}, wantErr: true, desc: "arg too long"},
+ {name: "sensors", args: []string{"test\x00"}, wantErr: true, desc: "null byte arg"},
+ {name: "ipmitool", args: []string{"chassis", "power", "off"}, wantErr: true, desc: "dangerous ipmitool"},
+ {name: "sensors", args: []string{"LC_ALL=C"}, wantErr: true, desc: "env prefix"},
+ {name: "/usr/bin/sensors", wantErr: true, desc: "absolute path"},
+ {name: "ipmitool", args: []string{"--extraneous=../../etc/passwd"}, wantErr: true, desc: "path traversal"},
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ if tc.desc == "" {
+ tc.desc = tc.name
+ }
+ t.Run(tc.desc, func(t *testing.T) {
+ err := validateCommand(tc.name, tc.args)
+ if tc.wantErr && err == nil {
+ t.Fatalf("expected error for %s %v", tc.name, tc.args)
+ }
+ if !tc.wantErr && err != nil {
+ t.Fatalf("unexpected error for %s %v: %v", tc.name, tc.args, err)
+ }
+ })
+ }
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index e1b765e027..08ad356b72 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,23 +1,25 @@
+version: '3.8'
+
services:
pulse:
- image: rcourtman/pulse:latest
+ image: ${PULSE_IMAGE:-rcourtman/pulse:latest}
container_name: pulse
+ restart: unless-stopped
ports:
- - "7655:7655" # Web UI and API
+ - "${PULSE_PORT:-7655}:7655"
volumes:
- - pulse_data:/data
+ - pulse-data:/data
+ # Secure temperature monitoring via host-side proxy
+ - /mnt/pulse-proxy:/mnt/pulse-proxy:ro
environment:
- - TZ=UTC # Set your timezone
- # - PUID=1000 # Optional: Set user ID (uncomment and adjust as needed)
- # - PGID=1000 # Optional: Set group ID (uncomment and adjust as needed)
- restart: unless-stopped
+ - TZ=${TZ:-UTC}
healthcheck:
- test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:7655"]
+ test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:7655/api/health"]
interval: 30s
timeout: 10s
retries: 3
- start_period: 30s
+ start_period: 10s
volumes:
- pulse_data:
- driver: local
\ No newline at end of file
+ pulse-data:
+ driver: local
diff --git a/docs/PHASE1_SUMMARY.md b/docs/PHASE1_SUMMARY.md
new file mode 100644
index 0000000000..7047f0ce26
--- /dev/null
+++ b/docs/PHASE1_SUMMARY.md
@@ -0,0 +1,71 @@
+# Pulse Sensor Proxy – Phase 1 Summary
+
+## Executive Summary
+Phase 1 delivered a complete hardening and observability overhaul for the Pulse sensor proxy. The service now runs under least privilege, exposes tamper-evident audit trails, forwards logs off-host, enforces adaptive rate caps, and ships with comprehensive validation tests plus documentation for ongoing operations and security posture. These improvements dramatically reduce the proxy's attack surface while giving operators clear visibility and controls.
+
+## Security Improvements
+- **Host hardening**
+ - SSH daemon locked down (no passwords, no forwarding, `ForceCommand` wrapper).
+ - Dedicated user `pulse-sensor` with minimal home/project directories.
+ - File permissions tightened (0750 binaries, 0600 private keys, 0640 append-only logs).
+ - Privilege drop via `Setuid/Setgid` post-bind; service confirms running as unprivileged UID 995.
+- **Command execution guardrails**
+ - Whitelist-based command validator for `sensors`/`ipmitool`; rejects shell metacharacters, subshells, dangerous ipmitool subcommands, null bytes, and path traversal.
+ - Enhanced node-name validation covering unicode, length, and absolute path abuse.
+- **Logging & audit**
+ - Structured audit logger with hash chain + HMAC-style tamper detection.
+ - Remote forwarding via `rsyslog` (RELP/TLS) and local queue for resilience.
+- **Sandboxing**
+ - Network segmentation documentation with firewall ACLs.
+ - AppArmor profile restricting filesystem/networking; seccomp profile (classic + OCI JSON).
+- **Rate limiting**
+ - Per-UID token bucket (0.2 QPS burst 2) + global concurrency cap (8) + penalty sleeps.
+ - Audit + metrics instrumentation for limiter decisions and penalties.
+
+## Key Metrics & Tests
+- `go test ./cmd/pulse-sensor-proxy/...` passes (including new unit suites for command validation, sanitizer, limiter penalties, audit logging).
+- 10 hostile-command attack cases covered (metacharacters, subshells, redirects, homoglyphs, null bytes, long args, path traversal, dangerous ipmitool ops, env prefixes, absolute paths).
+- Fuzz harness (`FuzzValidateCommand`) executing for 24 h (Task #24).
+- Prometheus metrics validated:
+ - `pulse_proxy_limiter_rejections_total{reason="rate"}` increments under load.
+ - `pulse_proxy_limiter_penalties_total{reason="invalid_json"}` increments on validation failure.
+ - `pulse_proxy_limiter_active_peers` accurate (UID grouping).
+- Audit log entries verified: connection acceptance, limiter rejections, validation failures, command start/finish with event hash chaining.
+
+## Deployment Checklist
+1. **Scripts**
+ - Run `scripts/create-sensor-user.sh`
+ - Run `scripts/harden-sensor-proxy.sh`
+ - Run `scripts/secure-sensor-files.sh`
+ - Run `scripts/setup-log-forwarding.sh`
+2. **Binaries**
+ - Build/install `/opt/pulse/sensor-proxy/bin/pulse-sensor-proxy` (0750, root:pulse-sensor).
+3. **Configuration**
+ - `/etc/pulse-sensor-proxy/config.yaml` updated (allowed subnets, UID/GID list, metrics addr).
+ - Systemd unit exports `PULSE_SENSOR_PROXY_USER`, `PULSE_SENSOR_PROXY_SSH_DIR`, `PULSE_SENSOR_PROXY_AUDIT_LOG`.
+4. **Profiles**
+ - Deploy AppArmor profile (`security/apparmor/pulse-sensor-proxy.apparmor`).
+ - Apply seccomp (systemd `SystemCallFilter` overrides or container JSON profile).
+5. **Networking**
+ - Implement firewall ACLs per `docs/security/pulse-sensor-proxy-network.md`.
+6. **Log Forwarding**
+ - Place TLS certs in `/etc/pulse/log-forwarding`.
+ - Verify rsyslog forwarding to remote collector.
+7. **Restart & Validate**
+ - `systemctl restart pulse-sensor-proxy`.
+ - Confirm metrics endpoint, audit log creation, limiter behaviour.
+
+## Verification Steps
+1. **Privilege Drop**: `ps -o user= -p $(pgrep -f pulse-sensor-proxy)` → `pulse-sensor`.
+2. **Audit Trail**: Trigger RPC (`get_status`) → verify `audit.log` entries with valid `event_hash`.
+3. **Rate Limiter**: Fire >10 concurrent requests → confirm `pulse_proxy_limiter_rejections_total{reason="rate"}` and audit `limiter.rejection`.
+4. **Remote Logging**: `logger` or manual append to proxy log → confirm arrival at remote collector.
+5. **Security Profiles**: `aa-status | grep pulse-sensor-proxy` (enforced), `systemctl show pulse-sensor-proxy -p SystemCallFilter`.
+6. **App Functionality**: Run `ensure_cluster_keys`, `get_temperature` RPCs, ensure success and no audit warnings.
+
+## Known Limitations / Deferred to Phase 2
+- **Adaptive Polling**: still fixed intervals (Phase 2 focuses on controller, backpressure, staleness SLOs).
+- **Queue Backpressure**: groundwork in rate limiter; full queue-based collector scheduling to be built next.
+- **External Sentinels**: cross-check monitoring and metric ingestion planned in Phase 3.
+- **AppArmor/Seccomp Tuning**: profiles may need refinement after real-world observation.
+- **Long-run Fuzz Results**: Task #24 fuzz campaign active; incorporate findings post-run.
diff --git a/docs/operations/pulse-sensor-proxy-runbook.md b/docs/operations/pulse-sensor-proxy-runbook.md
new file mode 100644
index 0000000000..a2a1c9cb20
--- /dev/null
+++ b/docs/operations/pulse-sensor-proxy-runbook.md
@@ -0,0 +1,58 @@
+# Pulse Sensor Proxy Runbook
+
+## Quick Reference
+- Binary: `/opt/pulse/sensor-proxy/bin/pulse-sensor-proxy`
+- Unit: `pulse-sensor-proxy.service`
+- Logs: `/var/log/pulse/sensor-proxy/proxy.log`
+- Audit trail: `/var/log/pulse/sensor-proxy/audit.log` (hash chained, forwarded via rsyslog)
+- Metrics: `http://127.0.0.1:9456/metrics`
+- Limiters: per-UID token bucket (burst 2) + global concurrency (8)
+
+## Monitoring Alerts & Response
+### Rate Limit Hits (`pulse_proxy_limiter_rejections_total`)
+1. Check audit log entries tagged `limiter.rejection` for offending UID.
+2. Confirm workload legitimacy; if expected, consider increasing limits via config override.
+3. If malicious, block source process/user and inspect Pulse audit logs.
+
+### Penalty Events (`pulse_proxy_limiter_penalties_total`)
+1. Review corresponding validation failures in audit log (`command.validation_failed`).
+2. If repeated invalid JSON/unknown methods, inspect caller code for regressions or intrusion attempts.
+
+### Audit Log Forwarder Down
+1. `journalctl -u rsyslog` to confirm transmission errors.
+2. Ensure `/etc/pulse/log-forwarding` certs valid & remote host reachable.
+3. Forwarding queue stored locally in `/var/log/pulse/sensor-proxy/forwarding.log`; ship manually if outage exceeds 1 hour.
+
+### Proxy Health Endpoint Fails
+1. `systemctl status pulse-sensor-proxy`
+2. Check `/var/log/pulse/sensor-proxy/proxy.log` for panic or limiter exhaustion.
+3. Inspect `/var/log/pulse/sensor-proxy/audit.log` for recent privileged method denials.
+
+## Standard Procedures
+### Restart Proxy Safely
+```bash
+sudo systemctl stop pulse-sensor-proxy
+sudo apparmor_parser -r /etc/apparmor.d/pulse-sensor-proxy # if updating policy
+sudo systemctl start pulse-sensor-proxy
+```
+Verify: `curl -s http://127.0.0.1:9456/metrics | grep pulse_proxy_build_info`.
+
+### Rotate SSH Keys
+1. Run `scripts/secure-sensor-files.sh` to regenerate keys (ensure environment locked down).
+2. Use RPC `ensure_cluster_keys` to distribute new public key.
+3. Confirm nodes accept `ssh` from proxy host.
+
+### Adjust Rate Limits
+1. Update `limiter_policy` environment overrides (future config).
+2. Restart proxy; monitor limiter metrics to validate new thresholds.
+3. Document change in security runbook.
+
+## Incident Handling
+- **Unauthorized Command Attempt:** audit log shows `command.validation_failed` and limiter penalties; capture correlation ID, check Pulse side for compromised container.
+- **Excessive Temperature Failures:** refer to `pulse_proxy_ssh_requests_total{result="error"}`; validate network ACLs and node health; escalate to Proxmox team if nodes unreachable.
+- **Log Tampering Suspected:** verify audit hash chain by replaying `eventHash` values; compare with remote log store (immutable). Trigger security response if mismatch.
+
+## Postmortem Checklist
+- Timeline: command audit entries, limiter stats, rsyslog queue depth.
+- Verify AppArmor/seccomp status (`aa-status`, `systemctl show pulse-sensor-proxy -p AppArmorProfile`).
+- Ensure firewall ACLs match `docs/security/pulse-sensor-proxy-network.md`.
diff --git a/docs/security/pulse-sensor-proxy-hardening.md b/docs/security/pulse-sensor-proxy-hardening.md
new file mode 100644
index 0000000000..43c7931bb8
--- /dev/null
+++ b/docs/security/pulse-sensor-proxy-hardening.md
@@ -0,0 +1,52 @@
+# Pulse Sensor Proxy AppArmor & Seccomp Hardening
+
+## AppArmor Profile
+- Profile path: `security/apparmor/pulse-sensor-proxy.apparmor`
+- Grants read-only access to configs, logs, SSH keys, and binaries; allows outbound TCP/SSH; blocks raw sockets, module loading, ptrace, and absolute command execution outside the allowlist.
+
+### Installation
+```bash
+sudo install -m 0644 security/apparmor/pulse-sensor-proxy.apparmor /etc/apparmor.d/pulse-sensor-proxy
+sudo apparmor_parser -r /etc/apparmor.d/pulse-sensor-proxy
+sudo ln -sf /etc/apparmor.d/pulse-sensor-proxy /etc/apparmor.d/force-complain/pulse-sensor-proxy # optional staged mode
+sudo systemctl restart apparmor
+```
+
+### Enforce Mode
+```bash
+sudo aa-enforce pulse-sensor-proxy
+```
+Monitor `/var/log/syslog` for `DENIED` events and update the profile as needed.
+
+## Seccomp Filter
+- OCI-style profile: `security/seccomp/pulse-sensor-proxy.json`
+- Allows standard Go runtime syscalls, network operations, file IO, and `execve` for whitelisted helpers; other syscalls return `EPERM`.
+
+### Apply via systemd (classic service)
+Add to the override:
+```ini
+[Service]
+AppArmorProfile=pulse-sensor-proxy
+RestrictNamespaces=yes
+NoNewPrivileges=yes
+SystemCallFilter=@system-service
+SystemCallArchitectures=native
+SystemCallAllow=accept;connect;recvfrom;sendto;recvmsg;sendmsg;sendmmsg;getsockname;getpeername;getsockopt;setsockopt;shutdown
+```
+
+Reload and restart:
+```bash
+sudo systemctl daemon-reload
+sudo systemctl restart pulse-sensor-proxy
+```
+
+### Apply seccomp JSON (containerised deployments)
+- Profile: `security/seccomp/pulse-sensor-proxy.json`
+- Use with Podman/Docker style runtimes:
+```bash
+podman run --seccomp-profile /opt/pulse/security/seccomp/pulse-sensor-proxy.json ...
+```
+
+## Operational Notes
+- Use `journalctl -t auditbeat -g pulse-sensor-proxy` or `aa-status` to confirm profile status.
+- Pair with network ACLs (see `docs/security/pulse-sensor-proxy-network.md`) and log shipping (`scripts/setup-log-forwarding.sh`).
diff --git a/docs/security/pulse-sensor-proxy-network.md b/docs/security/pulse-sensor-proxy-network.md
new file mode 100644
index 0000000000..0d1a9267f4
--- /dev/null
+++ b/docs/security/pulse-sensor-proxy-network.md
@@ -0,0 +1,64 @@
+# Pulse Sensor Proxy Network Segmentation
+
+## Overview
+- **Proxy host** collects temperatures via SSH from Proxmox nodes and serves a Unix socket to the Pulse stack.
+- Goals: isolate the proxy from production hypervisors, prevent lateral movement, and ensure log forwarding/audit channels remain available.
+
+## Zones & Connectivity
+- **Pulse Application Zone (AZ-Pulse)**
+ - Hosts Pulse backend/frontend containers.
+ - Allowed to reach the proxy over Unix socket (local) or loopback if containerised via `socat`.
+- **Sensor Proxy Zone (AZ-Sensor)**
+ - Dedicated VM/bare-metal host running `pulse-sensor-proxy`.
+ - Maintains outbound SSH to Proxmox management interfaces only.
+- **Proxmox Management Zone (AZ-Proxmox)**
+ - Hypervisors / BMCs reachable on `tcp/22` (SSH) and optional IPMI UDP.
+- **Logging/Monitoring Zone (AZ-Logging)**
+ - Receives forwarded audit/application logs (e.g. RELP/TLS on `tcp/6514`).
+ - Exposes Prometheus scrape port (default `tcp/9456`) if remote monitoring required.
+
+## Recommended Firewall Rules
+
+| Source Zone | Destination Zone | Protocol/Port | Purpose | Action |
+|-------------|------------------|---------------|---------|--------|
+| AZ-Pulse (localhost) | AZ-Sensor (Unix socket) | `unix` | RPC requests from Pulse | Allow (local only) |
+| AZ-Sensor | AZ-Proxmox nodes | `tcp/22` | SSH for sensors/ipmitool wrapper | Allow (restricted to node list) |
+| AZ-Sensor | AZ-Proxmox BMC | `udp/623` *(optional)* | IPMI if required for temperature data | Allow if needed |
+| AZ-Proxmox | AZ-Sensor | `any` | Return SSH traffic | Allow stateful |
+| AZ-Sensor | AZ-Logging | `tcp/6514` (TLS RELP) | Audit/application log forwarding | Allow |
+| AZ-Logging | AZ-Sensor | `tcp/9456` *(optional)* | Prometheus scrape of proxy metrics | Allow if scraping remotely |
+| Any | AZ-Sensor | `tcp/22` | Shell/SSH access | Deny (use management bastion) |
+| AZ-Sensor | Internet | `any` | Outbound Internet | Deny (except package mirrors via proxy if required) |
+
+## Implementation Steps
+1. Place proxy host in dedicated subnet/VLAN with ACLs enforcing the table above.
+2. Populate `/etc/hosts` or routing so proxy resolves Proxmox nodes to management IPs only (no public networks).
+3. Configure iptables/nftables on proxy:
+ ```bash
+ # Allow SSH to Proxmox nodes
+ iptables -A OUTPUT -p tcp -d <PROXMOX_SUBNET>/24 --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
+ iptables -A INPUT -p tcp -s <PROXMOX_SUBNET>/24 --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT
+
+ # Allow log forwarding
+ iptables -A OUTPUT -p tcp -d <LOG_HOST> --dport 6514 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
+ iptables -A INPUT -p tcp -s <LOG_HOST> --sport 6514 -m conntrack --ctstate ESTABLISHED -j ACCEPT
+
+ # (Optional) allow Prometheus scrape
+ iptables -A INPUT -p tcp -s <SCRAPE_HOST> --dport 9456 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
+ iptables -A OUTPUT -p tcp -d <SCRAPE_HOST> --sport 9456 -m conntrack --ctstate ESTABLISHED -j ACCEPT
+
+ # Drop everything else
+ iptables -P OUTPUT DROP
+ iptables -P INPUT DROP
+ ```
+4. Deny inbound SSH to proxy except via management bastion: block `tcp/22` or whitelist bastion IPs.
+5. Ensure log-forwarding TLS certificates are rotated and stored under `/etc/pulse/log-forwarding`.
+
+## Monitoring & Alerting
+- Alert if proxy initiates connections outside permitted subnets (Netflow or host firewall counters).
+- Monitor `pulse_proxy_limiter_*` metrics for unusual rate-limit hits that might signal abuse.
+- Track `audit_log` forwarding queue depth and remote availability; on failure, emit alert via rsyslog action queue (set `action.resumeRetryCount=-1` already).
+
+## Change Management
+- Document node IP changes and update firewall objects (`PROXMOX_NODES`) before redeploying certificates.
+- Capture segmentation in infrastructure-as-code (e.g. Terraform/security group definitions) to avoid drift.
diff --git a/frontend-modern/cookies.txt b/frontend-modern/cookies.txt
deleted file mode 100644
index c31d9899c3..0000000000
--- a/frontend-modern/cookies.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-# Netscape HTTP Cookie File
-# https://curl.se/docs/http-cookies.html
-# This file was generated by libcurl! Edit at your own risk.
-
diff --git a/frontend-modern/dist/assets/index-C-bZ849w.css b/frontend-modern/dist/assets/index-C-bZ849w.css
deleted file mode 100644
index 2103c1c49c..0000000000
--- a/frontend-modern/dist/assets/index-C-bZ849w.css
+++ /dev/null
@@ -1 +0,0 @@
-*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}body{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1));transition:background-color .15s ease-in-out,color .15s ease-in-out,border-color .15s ease-in-out}body:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}body{overflow-y:auto;overflow-x:hidden}html{overflow-y:scroll;scroll-behavior:smooth}.\!container{width:100%!important}.container{width:100%}@media (min-width: 640px){.\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width: 768px){.\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width: 1024px){.\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width: 1280px){.\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width: 1536px){.\!container{max-width:1536px!important}.container{max-width:1536px}}.pulse-shell{width:min(95.5vw,95rem);max-width:100%;margin-inline:auto;padding-inline:clamp(1.25rem,3vw,3.25rem);transition:padding-inline .3s ease}.pulse-panel{padding:clamp(.75rem,1.6vw,1.5rem)}.sparkline{backface-visibility:hidden;transform:translateZ(0)}.charts-mode .sparkline path{transition:none!important}.dark .custom-scrollbar{scrollbar-color:#374151 #1f2937}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.invisible{visibility:hidden}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-1{inset:-.25rem}.inset-0{inset:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.bottom-0{bottom:0}.bottom-full{bottom:100%}.left-0{left:0}.left-1\/2{left:50%}.left-3{left:.75rem}.right-0{right:0}.right-1{right:.25rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-9{right:2.25rem}.top-0{top:0}.top-1{top:.25rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-2\.5{top:.625rem}.top-24{top:6rem}.top-3{top:.75rem}.top-4{top:1rem}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[60\]{z-index:60}.z-\[61\]{z-index:61}.z-\[9999\]{z-index:9999}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.my-\[1px\]{margin-top:1px;margin-bottom:1px}.-mb-px{margin-bottom:-1px}.-ml-1{margin-left:-.25rem}.mb-0{margin-bottom:0}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-4{margin-left:1rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-24{height:6rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-\[18px\]{height:18px}.h-\[24px\]{height:24px}.h-full{height:100%}.h-px{height:1px}.max-h-32{max-height:8rem}.max-h-52{max-height:13rem}.max-h-\[90vh\]{max-height:90vh}.max-h-\[calc\(90vh-8rem\)\]{max-height:calc(90vh - 8rem)}.min-h-\[120px\]{min-height:120px}.min-h-\[160px\]{min-height:160px}.min-h-\[24px\]{min-height:24px}.min-h-\[70px\]{min-height:70px}.min-h-screen{min-height:100vh}.w-1\.5{width:.375rem}.w-1\/4{width:25%}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[100px\]{width:100px}.w-\[130px\]{width:130px}.w-\[48px\]{width:48px}.w-\[56px\]{width:56px}.w-\[76px\]{width:76px}.w-\[80px\]{width:80px}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-16{min-width:4rem}.min-w-20{min-width:5rem}.min-w-24{min-width:6rem}.min-w-32{min-width:8rem}.min-w-6{min-width:1.5rem}.min-w-\[140px\]{min-width:140px}.min-w-\[160px\]{min-width:160px}.min-w-\[180px\]{min-width:180px}.min-w-\[18px\]{min-width:18px}.min-w-\[200px\]{min-width:200px}.min-w-\[20px\]{min-width:20px}.min-w-\[220px\]{min-width:220px}.min-w-\[300px\]{min-width:300px}.min-w-\[320px\]{min-width:320px}.min-w-\[50px\]{min-width:50px}.min-w-\[600px\]{min-width:600px}.min-w-\[720px\]{min-width:720px}.min-w-\[760px\]{min-width:760px}.min-w-\[900px\]{min-width:900px}.min-w-\[96px\]{min-width:96px}.min-w-full{min-width:100%}.max-w-0{max-width:0px}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-7xl{max-width:80rem}.max-w-\[100px\]{max-width:100px}.max-w-\[150px\]{max-width:150px}.max-w-\[180px\]{max-width:180px}.max-w-\[200px\]{max-width:200px}.max-w-\[220px\]{max-width:220px}.max-w-\[240px\]{max-width:240px}.max-w-\[300px\]{max-width:300px}.max-w-\[500px\]{max-width:500px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.max-w-xl{max-width:36rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.flex-none{flex:none}.flex-shrink-0,.shrink-0{flex-shrink:0}.table-auto{table-layout:auto}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-x-full{--tw-translate-x: -100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-full{--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-95{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-help{cursor:help}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.cursor-wait{cursor:wait}.resize{resize:both}.scroll-mt-24{scroll-margin-top:6rem}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-7{grid-template-columns:repeat(7,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 231 235 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-end{align-self:flex-end}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overflow-y-hidden{overflow-y:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-line{white-space:pre-line}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-sm{border-radius:.125rem}.rounded-xl{border-radius:.75rem}.rounded-b{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.rounded-t{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.rounded-t-lg{border-top-left-radius:.5rem;border-top-right-radius:.5rem}.rounded-tr{border-top-right-radius:.25rem}.border{border-width:1px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l-2{border-left-width:2px}.border-l-4{border-left-width:4px}.border-t{border-top-width:1px}.border-t-2{border-top-width:2px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-300{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-current{border-color:currentColor}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-200\/50{border-color:#e5e7eb80}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-400{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-300{--tw-border-opacity: 1;border-color:rgb(134 239 172 / var(--tw-border-opacity, 1))}.border-green-400{--tw-border-opacity: 1;border-color:rgb(74 222 128 / var(--tw-border-opacity, 1))}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-orange-200{--tw-border-opacity: 1;border-color:rgb(254 215 170 / var(--tw-border-opacity, 1))}.border-orange-500{--tw-border-opacity: 1;border-color:rgb(249 115 22 / var(--tw-border-opacity, 1))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-300{--tw-border-opacity: 1;border-color:rgb(252 165 165 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/20{border-color:#fff3}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.border-yellow-300{--tw-border-opacity: 1;border-color:rgb(253 224 71 / var(--tw-border-opacity, 1))}.border-yellow-500{--tw-border-opacity: 1;border-color:rgb(234 179 8 / var(--tw-border-opacity, 1))}.border-b-white{--tw-border-opacity: 1;border-bottom-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-100\/50{background-color:#fef3c780}.bg-amber-200{--tw-bg-opacity: 1;background-color:rgb(253 230 138 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/80{background-color:#fffbebcc}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-500\/30{background-color:#f59e0b4d}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/40{background-color:#eff6ff66}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-50\/70{background-color:#eff6ffb3}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-500\/30{background-color:#3b82f64d}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-cyan-100{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-100\/40{background-color:#f3f4f666}.bg-gray-100\/70{background-color:#f3f4f6b3}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-50\/40{background-color:#f9fafb66}.bg-gray-50\/50{background-color:#f9fafb80}.bg-gray-50\/60{background-color:#f9fafb99}.bg-gray-500\/60{background-color:#6b728099}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-900\/70{background-color:#111827b3}.bg-gray-900\/80{background-color:#111827cc}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-200{--tw-bg-opacity: 1;background-color:rgb(187 247 208 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-50\/70{background-color:#f0fdf4b3}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/30{background-color:#22c55e4d}.bg-green-500\/60{background-color:#22c55e99}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-50{--tw-bg-opacity: 1;background-color:rgb(255 247 237 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-orange-500\/60{background-color:#f9731699}.bg-orange-600{--tw-bg-opacity: 1;background-color:rgb(234 88 12 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-400{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-50\/80{background-color:#fef2f2cc}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/60{background-color:#ef444499}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-slate-200{--tw-bg-opacity: 1;background-color:rgb(226 232 240 / var(--tw-bg-opacity, 1))}.bg-slate-700{--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity, 1))}.bg-violet-500{--tw-bg-opacity: 1;background-color:rgb(139 92 246 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/10{background-color:#ffffff1a}.bg-white\/70{background-color:#ffffffb3}.bg-white\/80{background-color:#fffc}.bg-white\/95{background-color:#fffffff2}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-200{--tw-bg-opacity: 1;background-color:rgb(254 240 138 / var(--tw-bg-opacity, 1))}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/60{background-color:#eab30899}.bg-opacity-50{--tw-bg-opacity: .5}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-l{background-image:linear-gradient(to left,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-50{--tw-gradient-from: #f9fafb var(--tw-gradient-from-position);--tw-gradient-to: rgb(249 250 251 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-50{--tw-gradient-from: #faf5ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(250 245 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-white{--tw-gradient-from: #fff var(--tw-gradient-from-position);--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-white{--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #fff var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-cyan-50{--tw-gradient-to: #ecfeff var(--tw-gradient-to-position)}.to-cyan-600{--tw-gradient-to: #0891b2 var(--tw-gradient-to-position)}.to-gray-50{--tw-gradient-to: #f9fafb var(--tw-gradient-to-position)}.to-indigo-100{--tw-gradient-to: #e0e7ff var(--tw-gradient-to-position)}.to-indigo-50{--tw-gradient-to: #eef2ff var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.bg-clip-text{-webkit-background-clip:text;background-clip:text}.fill-blue-600{fill:#2563eb}.fill-gray-500{fill:#6b7280}.fill-none{fill:none}.fill-white{fill:#fff}.stroke-white{stroke:#fff}.stroke-\[14\]{stroke-width:14}.p-0{padding:0}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-0\.5{padding-left:.125rem;padding-right:.125rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0{padding-top:0;padding-bottom:0}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-1{padding-bottom:.25rem}.pl-10{padding-left:2.5rem}.pl-3{padding-left:.75rem}.pl-4{padding-left:1rem}.pl-5{padding-left:1.25rem}.pl-6{padding-left:1.5rem}.pl-7{padding-left:1.75rem}.pl-8{padding-left:2rem}.pl-9{padding-left:2.25rem}.pr-1\.5{padding-right:.375rem}.pr-10{padding-right:2.5rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-8{padding-right:2rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.\!text-xs{font-size:.75rem!important;line-height:1rem!important}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[0\.7rem\]{font-size:.7rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[12px\]{font-size:12px}.text-\[8px\]{font-size:8px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-snug{line-height:1.375}.leading-tight{line-height:1.25}.tracking-\[0\.08em\]{letter-spacing:.08em}.tracking-\[0\.18em\]{letter-spacing:.18em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-500{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity, 1))}.text-blue-100{--tw-text-opacity: 1;color:rgb(219 234 254 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-600\/70{color:#2563ebb3}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-700\/80{color:#1d4ed8cc}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-current{color:currentColor}.text-cyan-800{--tw-text-opacity: 1;color:rgb(21 94 117 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-green-900{--tw-text-opacity: 1;color:rgb(20 83 45 / var(--tw-text-opacity, 1))}.text-green-900\/80{color:#14532dcc}.text-indigo-800{--tw-text-opacity: 1;color:rgb(55 48 163 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-orange-800{--tw-text-opacity: 1;color:rgb(154 52 18 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-slate-500{--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.text-slate-600{--tw-text-opacity: 1;color:rgb(71 85 105 / var(--tw-text-opacity, 1))}.text-slate-700{--tw-text-opacity: 1;color:rgb(51 65 85 / var(--tw-text-opacity, 1))}.text-transparent{color:transparent}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.text-yellow-900{--tw-text-opacity: 1;color:rgb(113 63 18 / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.decoration-dotted{text-decoration-style:dotted}.decoration-dashed{text-decoration-style:dashed}.underline-offset-2{text-underline-offset:2px}.underline-offset-4{text-underline-offset:4px}.placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-400::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.opacity-0{opacity:0}.opacity-100{opacity:1}.opacity-25{opacity:.25}.opacity-30{opacity:.3}.opacity-40{opacity:.4}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.opacity-\[0\.92\]{opacity:.92}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-blue-200{--tw-ring-opacity: 1;--tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity, 1))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-xl{--tw-blur: blur(24px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-lg{--tw-backdrop-blur: blur(16px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur: blur(24px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-1000{transition-duration:1s}.duration-150{transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}@keyframes slideDown{0%{transform:translateY(-100%);opacity:0}to{transform:translateY(0);opacity:1}}.animate-slideDown{animation:slideDown .3s ease-out}@keyframes slide-in-glass{0%{opacity:0;transform:translate(100%) scale(.95);filter:blur(4px)}to{opacity:1;transform:translate(0) scale(1);filter:blur(0)}}.animate-slide-in-glass{animation:slide-in-glass .5s cubic-bezier(.16,1,.3,1)}@supports ((-webkit-backdrop-filter: blur(0px)) or (backdrop-filter: blur(0px))){.backdrop-blur-xl{backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px)}}*{scrollbar-width:thin;scrollbar-color:rgba(156,163,175,.5) transparent}.dark *{scrollbar-color:rgba(55,65,81,.5) transparent}*:hover{scrollbar-color:rgba(156,163,175,.7) rgba(243,244,246,.5)}.dark *:hover{scrollbar-color:rgba(75,85,99,.7) rgba(31,41,55,.3)}*::-webkit-scrollbar{width:6px;height:6px}*::-webkit-scrollbar-track{background:transparent}*::-webkit-scrollbar-thumb{background-color:#9ca3af80;border-radius:10px}.dark *::-webkit-scrollbar-thumb{background-color:#37415180}*::-webkit-scrollbar-thumb:hover{background-color:#9ca3afcc}.dark *::-webkit-scrollbar-thumb:hover{background-color:#4b5563cc}body,.card,.table-row,.table-header,.bg-white,.bg-gray-50,.bg-gray-100,.bg-gray-200,.bg-gray-300,.bg-gray-700,.bg-gray-800,.bg-gray-900,.text-gray-500,.text-gray-600,.text-gray-700,.text-gray-800,.text-gray-900,.border-gray-200,.border-gray-300,.border-gray-600,.border-gray-700,.dark\:bg-gray-700,.dark\:bg-gray-800,.dark\:bg-gray-900,.dark\:text-gray-100,.dark\:text-gray-200,.dark\:text-gray-300,.dark\:text-gray-400,.dark\:border-gray-600,.dark\:border-gray-700{transition:background-color .15s ease-in-out,color .15s ease-in-out,border-color .15s ease-in-out}@keyframes pulse-logo{0%{transform:scale(1)}25%{transform:scale(1.05)}50%{transform:scale(1)}}@keyframes pulse-ring{0%,to{opacity:.92;transform:scale(1)}50%{opacity:.6;transform:scale(1.1)}}.animate-pulse-logo{animation:pulse-logo .8s cubic-bezier(.4,0,.6,1);transform-origin:center}.animate-pulse-logo .pulse-ring{animation:pulse-ring .8s cubic-bezier(.4,0,.6,1);transform-origin:center;transform-box:fill-box}.table-fixed{table-layout:fixed}.table-fixed td,.table-fixed th{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.table-fixed td:first-child{white-space:normal;word-break:break-word}.scrollbar-hide{-ms-overflow-style:none;scrollbar-width:none}.scrollbar-hide::-webkit-scrollbar{display:none}@keyframes fade-in{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}@keyframes slide-up{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes pulse-slow{0%,to{opacity:.25}50%{opacity:.75}}.animate-fade-in{animation:fade-in .6s ease-out}.animate-slide-up{animation:slide-up .8s cubic-bezier(.16,1,.3,1) .2s both}.animate-pulse-slow{animation:pulse-slow 3s cubic-bezier(.4,0,.6,1) infinite}.placeholder\:text-gray-400::-moz-placeholder{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.placeholder\:text-gray-400::placeholder{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.placeholder\:opacity-60::-moz-placeholder{opacity:.6}.placeholder\:opacity-60::placeholder{opacity:.6}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:left-\[2px\]:after{content:var(--tw-content);left:2px}.after\:top-\[2px\]:after{content:var(--tw-content);top:2px}.after\:h-5:after{content:var(--tw-content);height:1.25rem}.after\:w-5:after{content:var(--tw-content);width:1.25rem}.after\:rounded-full:after{content:var(--tw-content);border-radius:9999px}.after\:bg-white:after{content:var(--tw-content);--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.after\:transition-all:after{content:var(--tw-content);transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.after\:content-\[\'\'\]:after{--tw-content: "";content:var(--tw-content)}.first\:mt-0:first-child{margin-top:0}.first\:border-0:first-child{border-width:0px}.first\:pt-0:first-child{padding-top:0}.last\:mb-0:last-child{margin-bottom:0}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-125:hover{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-150:hover{--tw-scale-x: 1.5;--tw-scale-y: 1.5;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-\[1\.01\]:hover{--tw-scale-x: 1.01;--tw-scale-y: 1.01;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-\[1\.02\]:hover{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.hover\:border-blue-300\/70:hover{border-color:#93c5fdb3}.hover\:border-gray-200:hover{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-200:hover{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50\/20:hover{background-color:#eff6ff33}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200\/60:hover{background-color:#e5e7eb99}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\:bg-green-100:hover{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.hover\:bg-green-200:hover{--tw-bg-opacity: 1;background-color:rgb(187 247 208 / var(--tw-bg-opacity, 1))}.hover\:bg-green-50:hover{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.hover\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\:bg-orange-100:hover{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.hover\:bg-orange-700:hover{--tw-bg-opacity: 1;background-color:rgb(194 65 12 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-slate-800:hover{--tw-bg-opacity: 1;background-color:rgb(30 41 59 / var(--tw-bg-opacity, 1))}.hover\:bg-transparent:hover{background-color:transparent}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:bg-yellow-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.hover\:bg-yellow-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.hover\:from-blue-700:hover{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-cyan-700:hover{--tw-gradient-to: #0e7490 var(--tw-gradient-to-position)}.hover\:text-blue-500:hover{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-700:hover{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.hover\:text-gray-200:hover{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-500:hover{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-800:hover{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-red-700:hover{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.hover\:text-sky-600:hover{--tw-text-opacity: 1;color:rgb(2 132 199 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:no-underline:hover{text-decoration-line:none}.hover\:decoration-solid:hover{text-decoration-style:solid}.hover\:opacity-100:hover{opacity:1}.hover\:opacity-80:hover{opacity:.8}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-sm:hover{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-sky-500:focus{--tw-border-opacity: 1;border-color:rgb(14 165 233 / var(--tw-border-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-inset:focus{--tw-ring-inset: inset}.focus\:ring-blue-200:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity, 1))}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-blue-500\/20:focus{--tw-ring-color: rgb(59 130 246 / .2)}.focus\:ring-blue-500\/40:focus{--tw-ring-color: rgb(59 130 246 / .4)}.focus\:ring-red-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.focus\:ring-sky-200:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(186 230 253 / var(--tw-ring-opacity, 1))}.focus\:ring-offset-1:focus{--tw-ring-offset-width: 1px}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus\:ring-offset-white:focus{--tw-ring-offset-color: #fff}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:outline:focus-visible{outline-style:solid}.focus-visible\:outline-2:focus-visible{outline-width:2px}.focus-visible\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\:outline-blue-400:focus-visible{outline-color:#60a5fa}.focus-visible\:outline-blue-500:focus-visible{outline-color:#3b82f6}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-blue-400:focus-visible{--tw-ring-opacity: 1;--tw-ring-color: rgb(96 165 250 / var(--tw-ring-opacity, 1))}.focus-visible\:ring-blue-400\/60:focus-visible{--tw-ring-color: rgb(96 165 250 / .6)}.focus-visible\:ring-blue-500:focus-visible{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-white:focus-visible{--tw-ring-offset-color: #fff}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-gray-400:disabled{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group[open] .group-open\:-rotate-180{--tw-rotate: -180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:pointer-events-auto{pointer-events:auto}.group:hover .group-hover\:visible{visibility:visible}.group:hover .group-hover\:ml-1{margin-left:.25rem}.group:hover .group-hover\:ml-2{margin-left:.5rem}.group:hover .group-hover\:mr-1{margin-right:.25rem}.group:hover .group-hover\:max-w-\[100px\]{max-width:100px}.group:hover .group-hover\:max-w-\[80px\]{max-width:80px}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:px-3{padding-left:.75rem;padding-right:.75rem}.group:hover .group-hover\:text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}.group:hover .group-hover\:opacity-75{opacity:.75}.group:hover .group-hover\:duration-200{transition-duration:.2s}.group:focus-visible .group-focus-visible\:ml-1{margin-left:.25rem}.group:focus-visible .group-focus-visible\:max-w-\[80px\]{max-width:80px}.group:focus-visible .group-focus-visible\:opacity-100{opacity:1}.peer:checked~.peer-checked\:bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.peer:checked~.peer-checked\:after\:translate-x-full:after{content:var(--tw-content);--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.peer:checked~.peer-checked\:after\:border-white:after{content:var(--tw-content);--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.peer:focus~.peer-focus\:outline-none{outline:2px solid transparent;outline-offset:2px}.peer:disabled~.peer-disabled\:opacity-50{opacity:.5}.dark\:divide-gray-700:is(.dark *)>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(55 65 81 / var(--tw-divide-opacity, 1))}.dark\:border-amber-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(217 119 6 / var(--tw-border-opacity, 1))}.dark\:border-amber-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(180 83 9 / var(--tw-border-opacity, 1))}.dark\:border-amber-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(146 64 14 / var(--tw-border-opacity, 1))}.dark\:border-blue-400:is(.dark *){--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.dark\:border-blue-500:is(.dark *){--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.dark\:border-blue-500\/40:is(.dark *){border-color:#3b82f666}.dark\:border-blue-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.dark\:border-blue-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(30 64 175 / var(--tw-border-opacity, 1))}.dark\:border-emerald-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(4 120 87 / var(--tw-border-opacity, 1))}.dark\:border-emerald-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(6 95 70 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-600\/50:is(.dark *){border-color:#4b556380}.dark\:border-gray-600\/60:is(.dark *){border-color:#4b556399}.dark\:border-gray-600\/70:is(.dark *){border-color:#4b5563b3}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:border-gray-700\/30:is(.dark *){border-color:#3741514d}.dark\:border-green-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(22 163 74 / var(--tw-border-opacity, 1))}.dark\:border-green-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(21 128 61 / var(--tw-border-opacity, 1))}.dark\:border-green-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(22 101 52 / var(--tw-border-opacity, 1))}.dark\:border-orange-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(154 52 18 / var(--tw-border-opacity, 1))}.dark\:border-red-400:is(.dark *){--tw-border-opacity: 1;border-color:rgb(248 113 113 / var(--tw-border-opacity, 1))}.dark\:border-red-500:is(.dark *){--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.dark\:border-red-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.dark\:border-red-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(153 27 27 / var(--tw-border-opacity, 1))}.dark\:border-yellow-400:is(.dark *){--tw-border-opacity: 1;border-color:rgb(250 204 21 / var(--tw-border-opacity, 1))}.dark\:border-yellow-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(202 138 4 / var(--tw-border-opacity, 1))}.dark\:border-yellow-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(161 98 7 / var(--tw-border-opacity, 1))}.dark\:border-yellow-800:is(.dark *){--tw-border-opacity: 1;border-color:rgb(133 77 14 / var(--tw-border-opacity, 1))}.dark\:border-b-gray-800:is(.dark *){--tw-border-opacity: 1;border-bottom-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.dark\:bg-amber-500\/80:is(.dark *){background-color:#f59e0bcc}.dark\:bg-amber-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(146 64 14 / var(--tw-bg-opacity, 1))}.dark\:bg-amber-900\/20:is(.dark *){background-color:#78350f33}.dark\:bg-amber-900\/30:is(.dark *){background-color:#78350f4d}.dark\:bg-amber-900\/40:is(.dark *){background-color:#78350f66}.dark\:bg-blue-400:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-500:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-500\/10:is(.dark *){background-color:#3b82f61a}.dark\:bg-blue-500\/20:is(.dark *){background-color:#3b82f633}.dark\:bg-blue-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-800\/20:is(.dark *){background-color:#1e40af33}.dark\:bg-blue-800\/50:is(.dark *){background-color:#1e40af80}.dark\:bg-blue-800\/60:is(.dark *){background-color:#1e40af99}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900\/10:is(.dark *){background-color:#1e3a8a1a}.dark\:bg-blue-900\/20:is(.dark *){background-color:#1e3a8a33}.dark\:bg-blue-900\/30:is(.dark *){background-color:#1e3a8a4d}.dark\:bg-blue-900\/40:is(.dark *){background-color:#1e3a8a66}.dark\:bg-blue-900\/50:is(.dark *){background-color:#1e3a8a80}.dark\:bg-blue-950\/30:is(.dark *){background-color:#1725544d}.dark\:bg-cyan-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity, 1))}.dark\:bg-emerald-500:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.dark\:bg-emerald-900\/20:is(.dark *){background-color:#064e3b33}.dark\:bg-emerald-900\/40:is(.dark *){background-color:#064e3b66}.dark\:bg-gray-400:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-500\/50:is(.dark *){background-color:#6b728080}.dark\:bg-gray-600:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700\/30:is(.dark *){background-color:#3741514d}.dark\:bg-gray-700\/40:is(.dark *){background-color:#37415166}.dark\:bg-gray-700\/50:is(.dark *){background-color:#37415180}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800\/40:is(.dark *){background-color:#1f293766}.dark\:bg-gray-800\/50:is(.dark *){background-color:#1f293780}.dark\:bg-gray-800\/60:is(.dark *){background-color:#1f293799}.dark\:bg-gray-800\/70:is(.dark *){background-color:#1f2937b3}.dark\:bg-gray-800\/80:is(.dark *){background-color:#1f2937cc}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900\/20:is(.dark *){background-color:#11182733}.dark\:bg-gray-900\/30:is(.dark *){background-color:#1118274d}.dark\:bg-gray-900\/40:is(.dark *){background-color:#11182766}.dark\:bg-gray-900\/50:is(.dark *){background-color:#11182780}.dark\:bg-gray-900\/95:is(.dark *){background-color:#111827f2}.dark\:bg-gray-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(3 7 18 / var(--tw-bg-opacity, 1))}.dark\:bg-green-400:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.dark\:bg-green-500\/50:is(.dark *){background-color:#22c55e80}.dark\:bg-green-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.dark\:bg-green-700\/40:is(.dark *){background-color:#15803d66}.dark\:bg-green-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(22 101 52 / var(--tw-bg-opacity, 1))}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 83 45 / var(--tw-bg-opacity, 1))}.dark\:bg-green-900\/10:is(.dark *){background-color:#14532d1a}.dark\:bg-green-900\/20:is(.dark *){background-color:#14532d33}.dark\:bg-green-900\/30:is(.dark *){background-color:#14532d4d}.dark\:bg-green-900\/40:is(.dark *){background-color:#14532d66}.dark\:bg-green-900\/50:is(.dark *){background-color:#14532d80}.dark\:bg-green-900\/60:is(.dark *){background-color:#14532d99}.dark\:bg-indigo-900\/30:is(.dark *){background-color:#312e814d}.dark\:bg-orange-500\/50:is(.dark *){background-color:#f9731680}.dark\:bg-orange-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(194 65 12 / var(--tw-bg-opacity, 1))}.dark\:bg-orange-700\/40:is(.dark *){background-color:#c2410c66}.dark\:bg-orange-900\/20:is(.dark *){background-color:#7c2d1233}.dark\:bg-orange-900\/30:is(.dark *){background-color:#7c2d124d}.dark\:bg-orange-900\/50:is(.dark *){background-color:#7c2d1280}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(88 28 135 / var(--tw-bg-opacity, 1))}.dark\:bg-purple-900\/30:is(.dark *){background-color:#581c874d}.dark\:bg-purple-900\/40:is(.dark *){background-color:#581c8766}.dark\:bg-purple-900\/50:is(.dark *){background-color:#581c8780}.dark\:bg-red-500:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.dark\:bg-red-500\/20:is(.dark *){background-color:#ef444433}.dark\:bg-red-500\/50:is(.dark *){background-color:#ef444480}.dark\:bg-red-700\/40:is(.dark *){background-color:#b91c1c66}.dark\:bg-red-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.dark\:bg-red-900\/10:is(.dark *){background-color:#7f1d1d1a}.dark\:bg-red-900\/20:is(.dark *){background-color:#7f1d1d33}.dark\:bg-red-900\/30:is(.dark *){background-color:#7f1d1d4d}.dark\:bg-red-900\/40:is(.dark *){background-color:#7f1d1d66}.dark\:bg-red-900\/50:is(.dark *){background-color:#7f1d1d80}.dark\:bg-red-900\/60:is(.dark *){background-color:#7f1d1d99}.dark\:bg-red-950\/20:is(.dark *){background-color:#450a0a33}.dark\:bg-red-950\/30:is(.dark *){background-color:#450a0a4d}.dark\:bg-slate-700\/60:is(.dark *){background-color:#33415599}.dark\:bg-yellow-500\/50:is(.dark *){background-color:#eab30880}.dark\:bg-yellow-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(161 98 7 / var(--tw-bg-opacity, 1))}.dark\:bg-yellow-700\/40:is(.dark *){background-color:#a1620766}.dark\:bg-yellow-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(133 77 14 / var(--tw-bg-opacity, 1))}.dark\:bg-yellow-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.dark\:bg-yellow-900\/10:is(.dark *){background-color:#713f121a}.dark\:bg-yellow-900\/20:is(.dark *){background-color:#713f1233}.dark\:bg-yellow-900\/30:is(.dark *){background-color:#713f124d}.dark\:bg-yellow-900\/40:is(.dark *){background-color:#713f1266}.dark\:bg-yellow-900\/50:is(.dark *){background-color:#713f1280}.dark\:bg-yellow-900\/60:is(.dark *){background-color:#713f1299}.dark\:bg-yellow-950\/20:is(.dark *){background-color:#42200633}.dark\:from-blue-900\/20:is(.dark *){--tw-gradient-from: rgb(30 58 138 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(30 58 138 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:from-gray-800:is(.dark *){--tw-gradient-from: #1f2937 var(--tw-gradient-from-position);--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:from-gray-900:is(.dark *){--tw-gradient-from: #111827 var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:from-gray-900\/20:is(.dark *){--tw-gradient-from: rgb(17 24 39 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:from-purple-900\/20:is(.dark *){--tw-gradient-from: rgb(88 28 135 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(88 28 135 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.dark\:via-gray-800:is(.dark *){--tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #1f2937 var(--tw-gradient-via-position), var(--tw-gradient-to)}.dark\:to-blue-900:is(.dark *){--tw-gradient-to: #1e3a8a var(--tw-gradient-to-position)}.dark\:to-gray-800:is(.dark *){--tw-gradient-to: #1f2937 var(--tw-gradient-to-position)}.dark\:to-gray-900\/20:is(.dark *){--tw-gradient-to: rgb(17 24 39 / .2) var(--tw-gradient-to-position)}.dark\:to-indigo-900\/20:is(.dark *){--tw-gradient-to: rgb(49 46 129 / .2) var(--tw-gradient-to-position)}.dark\:to-transparent:is(.dark *){--tw-gradient-to: transparent var(--tw-gradient-to-position)}.dark\:fill-\[\#dbeafe\]:is(.dark *){fill:#dbeafe}.dark\:fill-blue-500:is(.dark *){fill:#3b82f6}.dark\:fill-gray-400:is(.dark *){fill:#9ca3af}.dark\:text-amber-100:is(.dark *){--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity, 1))}.dark\:text-amber-200:is(.dark *){--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.dark\:text-amber-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.dark\:text-amber-400:is(.dark *){--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.dark\:text-blue-100:is(.dark *){--tw-text-opacity: 1;color:rgb(219 234 254 / var(--tw-text-opacity, 1))}.dark\:text-blue-200:is(.dark *){--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-blue-300\/90:is(.dark *){color:#93c5fde6}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-blue-400\/70:is(.dark *){color:#60a5fab3}.dark\:text-cyan-200:is(.dark *){--tw-text-opacity: 1;color:rgb(165 243 252 / var(--tw-text-opacity, 1))}.dark\:text-emerald-100:is(.dark *){--tw-text-opacity: 1;color:rgb(209 250 229 / var(--tw-text-opacity, 1))}.dark\:text-emerald-200:is(.dark *){--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.dark\:text-emerald-300:is(.dark *){--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.dark\:text-gray-100:is(.dark *){--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.dark\:text-gray-200:is(.dark *){--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.dark\:text-green-100:is(.dark *){--tw-text-opacity: 1;color:rgb(220 252 231 / var(--tw-text-opacity, 1))}.dark\:text-green-200:is(.dark *){--tw-text-opacity: 1;color:rgb(187 247 208 / var(--tw-text-opacity, 1))}.dark\:text-green-200\/80:is(.dark *){color:#bbf7d0cc}.dark\:text-green-300:is(.dark *){--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.dark\:text-green-400:is(.dark *){--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.dark\:text-green-500:is(.dark *){--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.dark\:text-indigo-300:is(.dark *){--tw-text-opacity: 1;color:rgb(165 180 252 / var(--tw-text-opacity, 1))}.dark\:text-orange-100:is(.dark *){--tw-text-opacity: 1;color:rgb(255 237 213 / var(--tw-text-opacity, 1))}.dark\:text-orange-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 215 170 / var(--tw-text-opacity, 1))}.dark\:text-orange-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.dark\:text-orange-400:is(.dark *){--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.dark\:text-purple-200:is(.dark *){--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.dark\:text-purple-300:is(.dark *){--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.dark\:text-purple-400:is(.dark *){--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.dark\:text-red-100:is(.dark *){--tw-text-opacity: 1;color:rgb(254 226 226 / var(--tw-text-opacity, 1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.dark\:text-red-300:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-slate-100:is(.dark *){--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity, 1))}.dark\:text-slate-300:is(.dark *){--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.dark\:text-slate-400:is(.dark *){--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.dark\:text-yellow-100:is(.dark *){--tw-text-opacity: 1;color:rgb(254 249 195 / var(--tw-text-opacity, 1))}.dark\:text-yellow-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.dark\:text-yellow-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.dark\:text-yellow-400:is(.dark *){--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:text-yellow-500:is(.dark *){--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.dark\:placeholder-gray-400:is(.dark *)::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.dark\:placeholder-gray-400:is(.dark *)::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity, 1))}.dark\:placeholder-gray-500:is(.dark *)::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.dark\:placeholder-gray-500:is(.dark *)::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.dark\:ring-blue-400\/40:is(.dark *){--tw-ring-color: rgb(96 165 250 / .4)}.dark\:placeholder\:text-gray-500:is(.dark *)::-moz-placeholder{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:placeholder\:text-gray-500:is(.dark *)::placeholder{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:hover\:border-blue-500:hover:is(.dark *){--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.dark\:hover\:border-blue-500\/50:hover:is(.dark *){border-color:#3b82f680}.dark\:hover\:border-blue-600:hover:is(.dark *){--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.dark\:hover\:border-gray-500:hover:is(.dark *){--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity, 1))}.dark\:hover\:border-gray-700:hover:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:hover\:bg-amber-900\/40:hover:is(.dark *){background-color:#78350f66}.dark\:hover\:bg-blue-400:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-blue-500\/20:hover:is(.dark *){background-color:#3b82f633}.dark\:hover\:bg-blue-500\/30:hover:is(.dark *){background-color:#3b82f64d}.dark\:hover\:bg-blue-800\/30:hover:is(.dark *){background-color:#1e40af4d}.dark\:hover\:bg-blue-800\/50:hover:is(.dark *){background-color:#1e40af80}.dark\:hover\:bg-blue-900\/10:hover:is(.dark *){background-color:#1e3a8a1a}.dark\:hover\:bg-blue-900\/20:hover:is(.dark *){background-color:#1e3a8a33}.dark\:hover\:bg-blue-900\/30:hover:is(.dark *){background-color:#1e3a8a4d}.dark\:hover\:bg-blue-900\/40:hover:is(.dark *){background-color:#1e3a8a66}.dark\:hover\:bg-blue-900\/50:hover:is(.dark *){background-color:#1e3a8a80}.dark\:hover\:bg-blue-900\/60:hover:is(.dark *){background-color:#1e3a8a99}.dark\:hover\:bg-blue-900\/70:hover:is(.dark *){background-color:#1e3a8ab3}.dark\:hover\:bg-emerald-400:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(52 211 153 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-700\/30:hover:is(.dark *){background-color:#3741514d}.dark\:hover\:bg-gray-700\/50:hover:is(.dark *){background-color:#37415180}.dark\:hover\:bg-gray-700\/60:hover:is(.dark *){background-color:#37415199}.dark\:hover\:bg-gray-700\/70:hover:is(.dark *){background-color:#374151b3}.dark\:hover\:bg-gray-700\/80:hover:is(.dark *){background-color:#374151cc}.dark\:hover\:bg-gray-800:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-900\/50:hover:is(.dark *){background-color:#11182780}.dark\:hover\:bg-green-900\/20:hover:is(.dark *){background-color:#14532d33}.dark\:hover\:bg-green-900\/40:hover:is(.dark *){background-color:#14532d66}.dark\:hover\:bg-green-900\/60:hover:is(.dark *){background-color:#14532d99}.dark\:hover\:bg-orange-800:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(154 52 18 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-orange-800\/30:hover:is(.dark *){background-color:#9a34124d}.dark\:hover\:bg-red-400:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-red-500\/30:hover:is(.dark *){background-color:#ef44444d}.dark\:hover\:bg-red-900\/20:hover:is(.dark *){background-color:#7f1d1d33}.dark\:hover\:bg-red-900\/30:hover:is(.dark *){background-color:#7f1d1d4d}.dark\:hover\:bg-red-900\/50:hover:is(.dark *){background-color:#7f1d1d80}.dark\:hover\:bg-red-950\/40:hover:is(.dark *){background-color:#450a0a66}.dark\:hover\:bg-transparent:hover:is(.dark *){background-color:transparent}.dark\:hover\:bg-yellow-900\/20:hover:is(.dark *){background-color:#713f1233}.dark\:hover\:bg-yellow-950\/30:hover:is(.dark *){background-color:#4220064d}.dark\:hover\:text-blue-100:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(219 234 254 / var(--tw-text-opacity, 1))}.dark\:hover\:text-blue-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:hover\:text-blue-400:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:hover\:text-gray-100:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.dark\:hover\:text-gray-200:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.dark\:hover\:text-gray-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:hover\:text-red-300:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.dark\:hover\:text-sky-400:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(56 189 248 / var(--tw-text-opacity, 1))}.dark\:focus\:border-blue-400:focus:is(.dark *){--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.dark\:focus\:border-sky-400:focus:is(.dark *){--tw-border-opacity: 1;border-color:rgb(56 189 248 / var(--tw-border-opacity, 1))}.dark\:focus\:ring-blue-400:focus:is(.dark *){--tw-ring-opacity: 1;--tw-ring-color: rgb(96 165 250 / var(--tw-ring-opacity, 1))}.dark\:focus\:ring-blue-400\/40:focus:is(.dark *){--tw-ring-color: rgb(96 165 250 / .4)}.dark\:focus\:ring-blue-900\/60:focus:is(.dark *){--tw-ring-color: rgb(30 58 138 / .6)}.dark\:focus\:ring-sky-600\/40:focus:is(.dark *){--tw-ring-color: rgb(2 132 199 / .4)}.dark\:focus\:ring-offset-gray-900:focus:is(.dark *){--tw-ring-offset-color: #111827}.dark\:focus-visible\:ring-offset-gray-900:focus-visible:is(.dark *){--tw-ring-offset-color: #111827}@media (min-width: 640px){.sm\:ml-4{margin-left:1rem}.sm\:mt-0{margin-top:0}.sm\:block{display:block}.sm\:inline{display:inline}.sm\:table-cell{display:table-cell}.sm\:grid{display:grid}.sm\:hidden{display:none}.sm\:h-10{height:2.5rem}.sm\:h-5{height:1.25rem}.sm\:w-10{width:2.5rem}.sm\:w-5{width:1.25rem}.sm\:w-\[110px\]{width:110px}.sm\:w-\[150px\]{width:150px}.sm\:w-\[56px\]{width:56px}.sm\:w-\[62px\]{width:62px}.sm\:w-\[64px\]{width:64px}.sm\:w-\[86px\]{width:86px}.sm\:w-auto{width:auto}.sm\:min-w-\[180px\]{min-width:180px}.sm\:flex-initial{flex:0 1 auto}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:flex-wrap{flex-wrap:wrap}.sm\:flex-nowrap{flex-wrap:nowrap}.sm\:items-start{align-items:flex-start}.sm\:items-end{align-items:flex-end}.sm\:items-center{align-items:center}.sm\:justify-end{justify-content:flex-end}.sm\:justify-between{justify-content:space-between}.sm\:gap-1\.5{gap:.375rem}.sm\:gap-2{gap:.5rem}.sm\:gap-3{gap:.75rem}.sm\:gap-4{gap:1rem}.sm\:self-start{align-self:flex-start}.sm\:p-4{padding:1rem}.sm\:p-6{padding:1.5rem}.sm\:px-3{padding-left:.75rem;padding-right:.75rem}.sm\:px-4{padding-left:1rem;padding-right:1rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:py-2{padding-top:.5rem;padding-bottom:.5rem}.sm\:py-6{padding-top:1.5rem;padding-bottom:1.5rem}.sm\:pl-4{padding-left:1rem}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}.sm\:text-sm{font-size:.875rem;line-height:1.25rem}.sm\:text-xs{font-size:.75rem;line-height:1rem}}@media (min-width: 768px){.md\:ml-6{margin-left:1.5rem}.md\:block{display:block}.md\:inline-flex{display:inline-flex}.md\:table-cell{display:table-cell}.md\:min-w-\[900px\]{min-width:900px}.md\:flex-1{flex:1 1 0%}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:items-start{align-items:flex-start}.md\:justify-between{justify-content:space-between}.md\:gap-8{gap:2rem}}@media (min-width: 1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:col-span-3{grid-column:span 3 / span 3}.lg\:flex{display:flex}.lg\:table{display:table}.lg\:table-cell{display:table-cell}.lg\:hidden{display:none}.lg\:w-\[130px\]{width:130px}.lg\:w-\[180px\]{width:180px}.lg\:w-\[60px\]{width:60px}.lg\:w-\[70px\]{width:70px}.lg\:w-\[72px\]{width:72px}.lg\:w-\[96px\]{width:96px}.lg\:min-w-\[18rem\]{min-width:18rem}.lg\:min-w-\[4rem\]{min-width:4rem}.lg\:max-w-\[18rem\]{max-width:18rem}.lg\:max-w-\[4rem\]{max-width:4rem}.lg\:basis-\[18rem\]{flex-basis:18rem}.lg\:basis-\[4rem\]{flex-basis:4rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:flex-col{flex-direction:column}.lg\:border-b-0{border-bottom-width:0px}.lg\:border-r{border-right-width:1px}.lg\:border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.lg\:px-8{padding-left:2rem;padding-right:2rem}.lg\:align-top{vertical-align:top}.dark\:lg\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}}@media (min-width: 1280px){.xl\:w-\[108px\]{width:108px}.xl\:w-\[150px\]{width:150px}.xl\:w-\[200px\]{width:200px}.xl\:w-\[64px\]{width:64px}.xl\:w-\[78px\]{width:78px}.xl\:w-\[80px\]{width:80px}.xl\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.xl\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1536px){.\32xl\:w-\[128px\]{width:128px}.\32xl\:w-\[180px\]{width:180px}.\32xl\:w-\[240px\]{width:240px}.\32xl\:w-\[72px\]{width:72px}.\32xl\:w-\[90px\]{width:90px}.\32xl\:w-\[96px\]{width:96px}}.metric-container{position:relative;display:inline-flex;align-items:center;overflow:visible;min-height:1em}.metric-value{display:inline-flex;align-items:center;position:relative;z-index:2}.metric-ghost{position:absolute;top:0;left:0;z-index:1;pointer-events:none}@keyframes ghostSlideUp{0%{transform:translateY(0);opacity:1;filter:blur(0)}to{transform:translateY(-20px);opacity:0;filter:blur(2px)}}@keyframes ghostSlideDown{0%{transform:translateY(0);opacity:1;filter:blur(0)}to{transform:translateY(20px);opacity:0;filter:blur(2px)}}@keyframes enterFromBelow{0%{transform:translateY(15px);opacity:0;filter:blur(1px);color:#22c55e}50%{color:#22c55e}to{transform:translateY(0);opacity:1;filter:blur(0);color:inherit}}@keyframes enterFromAbove{0%{transform:translateY(-15px);opacity:0;filter:blur(1px);color:#ef4444}50%{color:#ef4444}to{transform:translateY(0);opacity:1;filter:blur(0);color:inherit}}.metric-ghost-up{animation:ghostSlideUp .4s ease-out forwards;color:#9ca3af}.metric-ghost-down{animation:ghostSlideDown .4s ease-out forwards;color:#9ca3af}.metric-entering-up{animation:enterFromBelow .4s ease-out}.metric-entering-down{animation:enterFromAbove .4s ease-out}.dark .metric-ghost-up,.dark .metric-ghost-down{color:#6b7280}.dark .metric-entering-up{animation:enterFromBelowDark .4s ease-out}.dark .metric-entering-down{animation:enterFromAboveDark .4s ease-out}@keyframes enterFromBelowDark{0%{transform:translateY(15px);opacity:0;filter:blur(1px);color:#4ade80}50%{color:#4ade80}to{transform:translateY(0);opacity:1;filter:blur(0);color:inherit}}@keyframes enterFromAboveDark{0%{transform:translateY(-15px);opacity:0;filter:blur(1px);color:#f87171}50%{color:#f87171}to{transform:translateY(0);opacity:1;filter:blur(0);color:inherit}}.metric-entering-up:before,.metric-entering-down:before{content:"";position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:150%;height:150%;pointer-events:none;border-radius:50%;animation:pulseGlow .4s ease-out}.metric-entering-up:before{background:radial-gradient(circle,rgba(34,197,94,.3) 0%,transparent 60%)}.metric-entering-down:before{background:radial-gradient(circle,rgba(239,68,68,.3) 0%,transparent 60%)}@keyframes pulseGlow{0%{opacity:0;transform:translate(-50%,-50%) scale(.5)}50%{opacity:1}to{opacity:0;transform:translate(-50%,-50%) scale(1.5)}}@keyframes nodeClick{0%{transform:scale(1)}50%{transform:scale(.98);box-shadow:inset 0 1px 3px #0000001a}to{transform:scale(1)}}.node-click{animation:nodeClick .15s ease-out}
diff --git a/frontend-modern/dist/index.html b/frontend-modern/dist/index.html
deleted file mode 100644
index 216decd0a5..0000000000
--- a/frontend-modern/dist/index.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <meta name="theme-color" content="#000000" />
- <link rel="icon" type="image/svg+xml" href="/logo.svg" />
- <title>Pulse</title>
- <script type="module" crossorigin src="/assets/index-BTYq3hC4.js"></script>
- <link rel="stylesheet" crossorigin href="/assets/index-C-bZ849w.css">
- </head>
- <body>
- <noscript>You need to enable JavaScript to run this app.</noscript>
- <div id="root"></div>
-
- </body>
-</html>
\ No newline at end of file
diff --git a/frontend-modern/dist/logo.svg b/frontend-modern/dist/logo.svg
deleted file mode 100644
index 22b2ec6613..0000000000
--- a/frontend-modern/dist/logo.svg
+++ /dev/null
@@ -1,16 +0,0 @@
-<svg width="256" height="256" viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">
- <title>Pulse Logo</title>
- <style>
- .pulse-bg { fill: #2563eb; }
- .pulse-ring { fill: none; stroke: #ffffff; stroke-width: 14; opacity: 0.92; }
- .pulse-center { fill: #ffffff; }
- @media (prefers-color-scheme: dark) {
- .pulse-bg { fill: #3b82f6; }
- .pulse-ring { stroke: #dbeafe; }
- .pulse-center { fill: #dbeafe; }
- }
- </style>
- <circle class="pulse-bg" cx="128" cy="128" r="122"/>
- <circle class="pulse-ring" cx="128" cy="128" r="84"/>
- <circle class="pulse-center" cx="128" cy="128" r="26"/>
-</svg>
\ No newline at end of file
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index 987156affd..f2291b20d2 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -938,8 +938,17 @@ function AppLayout(props: {
>
{platform.icon}
<span>{platform.label}</span>
- <Show when={disabled() && !platform.live}>
- <span class="ml-1 text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-600">Add host</span>
+ <Show when={!platform.live}>
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ navigate(platform.settingsRoute);
+ }}
+ class="ml-1 text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-600 hover:text-blue-500 focus-visible:outline-none focus-visible:ring-0"
+ >
+ Add host
+ </button>
</Show>
</div>
);
diff --git a/frontend-modern/src/components/Alerts/ThresholdsTable.tsx b/frontend-modern/src/components/Alerts/ThresholdsTable.tsx
index f22699f9a0..48b0bb1825 100644
--- a/frontend-modern/src/components/Alerts/ThresholdsTable.tsx
+++ b/frontend-modern/src/components/Alerts/ThresholdsTable.tsx
@@ -1018,48 +1018,49 @@ const snapshotOverridesCount = createMemo(() => {
// Get PBS instances from props
const pbsInstances = props.pbsInstances || [];
- const pbsServers = pbsInstances
- .filter((pbs) => (pbs.cpu || 0) > 0 || (pbs.memory || 0) > 0)
- .map((pbs) => {
- // PBS IDs already have "pbs-" prefix from backend, don't double it
- const pbsId = pbs.id;
- const override = overridesMap.get(pbsId);
-
- // Check if any threshold values actually differ from defaults
- const hasCustomThresholds =
- override?.thresholds &&
- Object.keys(override.thresholds).some((key) => {
- const k = key as keyof typeof override.thresholds;
- // PBS uses node defaults for CPU/Memory
- return (
- override.thresholds[k] !== undefined &&
- override.thresholds[k] !== props.nodeDefaults[k as keyof typeof props.nodeDefaults]
- );
- });
+ const pbsServers = pbsInstances.map((pbs) => {
+ // Offline PBS instances report zero metrics; keep them visible so connectivity toggles stay usable
+ // PBS IDs already have "pbs-" prefix from backend, don't double it
+ const pbsId = pbs.id;
+ const override = overridesMap.get(pbsId);
+ // Check if any threshold values actually differ from defaults
+ const hasCustomThresholds =
+ override?.thresholds &&
+ Object.keys(override.thresholds).some((key) => {
+ const k = key as keyof typeof override.thresholds;
+ // PBS uses node defaults for CPU/Memory
+ return (
+ override.thresholds[k] !== undefined &&
+ override.thresholds[k] !== props.nodeDefaults[k as keyof typeof props.nodeDefaults]
+ );
+ });
- return {
- id: pbsId,
- name: pbs.name,
- type: 'pbs' as const,
- resourceType: 'PBS',
- host: pbs.host,
- status: pbs.status,
- cpu: pbs.cpu,
- memory: pbs.memory,
- memoryUsed: pbs.memoryUsed,
- memoryTotal: pbs.memoryTotal,
- uptime: pbs.uptime,
- hasOverride: hasCustomThresholds || false,
- disabled: false,
- disableConnectivity: override?.disableConnectivity || false,
- thresholds: override?.thresholds || {},
- defaults: {
- cpu: props.nodeDefaults.cpu,
- memory: props.nodeDefaults.memory,
- },
- };
- });
+ const disableConnectivity = override?.disableConnectivity || false;
+ const hasOverride = hasCustomThresholds || disableConnectivity;
+
+ return {
+ id: pbsId,
+ name: pbs.name,
+ type: 'pbs' as const,
+ resourceType: 'PBS',
+ host: pbs.host,
+ status: pbs.status,
+ cpu: pbs.cpu,
+ memory: pbs.memory,
+ memoryUsed: pbs.memoryUsed,
+ memoryTotal: pbs.memoryTotal,
+ uptime: pbs.uptime,
+ hasOverride,
+ disabled: false,
+ disableConnectivity,
+ thresholds: override?.thresholds || {},
+ defaults: {
+ cpu: props.nodeDefaults.cpu,
+ memory: props.nodeDefaults.memory,
+ },
+ };
+ });
if (search) {
return pbsServers.filter(
diff --git a/frontend-modern/src/components/Backups/UnifiedBackups.tsx b/frontend-modern/src/components/Backups/UnifiedBackups.tsx
index 76b7790df5..6ab83cef55 100644
--- a/frontend-modern/src/components/Backups/UnifiedBackups.tsx
+++ b/frontend-modern/src/components/Backups/UnifiedBackups.tsx
@@ -1,4 +1,5 @@
import { Component, createSignal, Show, For, createMemo, createEffect, onMount } from 'solid-js';
+import { useNavigate } from '@solidjs/router';
import { useWebSocket } from '@/App';
import { formatBytes, formatAbsoluteTime, formatRelativeTime, formatUptime } from '@/utils/format';
import { createLocalStorageBooleanSignal, STORAGE_KEYS } from '@/utils/localStorage';
@@ -24,6 +25,7 @@ interface DateGroup {
}
const UnifiedBackups: Component = () => {
+ const navigate = useNavigate();
const { state } = useWebSocket();
const pveBackupsState = createMemo(() => state.backups?.pve ?? state.pveBackups);
const pbsBackupsState = createMemo(() => state.backups?.pbs ?? state.pbsBackups);
@@ -1141,12 +1143,7 @@ const UnifiedBackups: Component = () => {
actions={
<button
type="button"
- onClick={() => {
- const settingsTab = document.querySelector(
- '[role="tab"]:last-child',
- ) as HTMLElement;
- settingsTab?.click();
- }}
+ onClick={() => navigate('/settings')}
class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Go to Settings
diff --git a/frontend-modern/src/components/Dashboard/Dashboard.tsx b/frontend-modern/src/components/Dashboard/Dashboard.tsx
index 77052a1a90..84610bd100 100644
--- a/frontend-modern/src/components/Dashboard/Dashboard.tsx
+++ b/frontend-modern/src/components/Dashboard/Dashboard.tsx
@@ -1,4 +1,5 @@
import { createSignal, createMemo, createEffect, For, Show, onMount } from 'solid-js';
+import { useNavigate } from '@solidjs/router';
import type { VM, Container, Node } from '@/types/api';
import { GuestRow } from './GuestRow';
import { useWebSocket } from '@/App';
@@ -28,6 +29,7 @@ type StatusMode = 'all' | 'running' | 'stopped';
type GroupingMode = 'grouped' | 'flat';
export function Dashboard(props: DashboardProps) {
+ const navigate = useNavigate();
const ws = useWebSocket();
const { connected, activeAlerts, initialDataReceived, reconnecting, reconnect } = ws;
const [search, setSearch] = createSignal('');
@@ -639,12 +641,7 @@ export function Dashboard(props: DashboardProps) {
actions={
<button
type="button"
- onClick={() => {
- const settingsTab = document.querySelector(
- '[role="tab"]:last-child',
- ) as HTMLElement;
- settingsTab?.click();
- }}
+ onClick={() => navigate('/settings')}
class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Go to Settings
diff --git a/frontend-modern/src/components/FirstRunSetup.tsx b/frontend-modern/src/components/FirstRunSetup.tsx
index 69f152cd31..06c7420fcb 100644
--- a/frontend-modern/src/components/FirstRunSetup.tsx
+++ b/frontend-modern/src/components/FirstRunSetup.tsx
@@ -580,7 +580,10 @@ IMPORTANT: Keep these credentials secure!
</button>
<button
type="button"
- onClick={() => window.location.reload()}
+ onClick={() => {
+ const basePath = import.meta.env.BASE_URL || '/';
+ window.location.assign(basePath);
+ }}
class="flex-1 py-3 px-4 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors"
>
Continue to Login
diff --git a/frontend-modern/src/components/Settings/Settings.tsx b/frontend-modern/src/components/Settings/Settings.tsx
index 802bef027c..1326fc0fd5 100644
--- a/frontend-modern/src/components/Settings/Settings.tsx
+++ b/frontend-modern/src/components/Settings/Settings.tsx
@@ -329,7 +329,6 @@ const Settings: Component<SettingsProps> = (props) => {
if (currentTab() !== 'pve') {
setCurrentTab('pve');
}
- navigate('/settings/pve', { replace: true });
return;
}
diff --git a/frontend-modern/src/components/Storage/Storage.tsx b/frontend-modern/src/components/Storage/Storage.tsx
index 4ba60479ab..c80a2b37aa 100644
--- a/frontend-modern/src/components/Storage/Storage.tsx
+++ b/frontend-modern/src/components/Storage/Storage.tsx
@@ -1,4 +1,5 @@
import { Component, For, Show, createSignal, createMemo, createEffect, onMount } from 'solid-js';
+import { useNavigate } from '@solidjs/router';
import { useWebSocket } from '@/App';
import { getAlertStyles } from '@/utils/alerts';
import { formatBytes } from '@/utils/format';
@@ -14,6 +15,7 @@ import { ProxmoxSectionNav } from '@/components/Proxmox/ProxmoxSectionNav';
import { getNodeDisplayName } from '@/utils/nodes';
const Storage: Component = () => {
+ const navigate = useNavigate();
const { state, connected, activeAlerts, initialDataReceived } = useWebSocket();
const [viewMode, setViewMode] = createSignal<'node' | 'storage'>('node');
const [tabView, setTabView] = createSignal<'pools' | 'disks'>('pools');
@@ -671,12 +673,7 @@ const Storage: Component = () => {
actions={
<button
type="button"
- onClick={() => {
- const settingsTab = document.querySelector(
- '[role=\"tab\"]:last-child',
- ) as HTMLElement;
- settingsTab?.click();
- }}
+ onClick={() => navigate('/settings')}
class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Go to Settings
diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.go
index 89c8f64478..d0a2b85ab0 100644
--- a/internal/alerts/alerts.go
+++ b/internal/alerts/alerts.go
@@ -766,7 +766,8 @@ func (m *Manager) UpdateConfig(config AlertConfig) {
config.TimeThresholds = make(map[string]int)
}
ensureDelay := func(key string) {
- if delay, ok := config.TimeThresholds[key]; !ok || delay <= 0 {
+ delay, ok := config.TimeThresholds[key]
+ if !ok || delay < 0 {
config.TimeThresholds[key] = defaultDelaySeconds
}
}
@@ -774,7 +775,7 @@ func (m *Manager) UpdateConfig(config AlertConfig) {
ensureDelay("node")
ensureDelay("storage")
ensureDelay("pbs")
- if delay, ok := config.TimeThresholds["all"]; ok && delay <= 0 {
+ if delay, ok := config.TimeThresholds["all"]; ok && delay < 0 {
config.TimeThresholds["all"] = defaultDelaySeconds
}
config.DockerIgnoredContainerPrefixes = NormalizeDockerIgnoredPrefixes(config.DockerIgnoredContainerPrefixes)
@@ -5299,7 +5300,7 @@ func (m *Manager) checkQuarantineMetric(pmg models.PMGInstance, metricType strin
}
// calculateTrimmedBaseline computes a robust baseline from historical samples
-// using trimmed mean with median fallback as specified by Codex
+// using trimmed mean with median fallback for statistical robustness
func calculateTrimmedBaseline(samples []float64) (baseline float64, trustworthy bool) {
sampleCount := len(samples)
@@ -5488,7 +5489,7 @@ func (m *Manager) checkAnomalyMetric(pmg models.PMGInstance, tracker *pmgAnomaly
baseline = 1.0 // Treat as 1 for ratio math
}
- // Determine thresholds based on Codex spec
+ // Determine warning and critical thresholds
var warnRatio, critRatio float64
var warnDelta, critDelta float64
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go
index 3e42fff5a2..f49bd06a38 100644
--- a/internal/api/config_handlers.go
+++ b/internal/api/config_handlers.go
@@ -3914,11 +3914,14 @@ elif [ "$TEMP_MONITORING_AVAILABLE" = true ]; then
IS_RPI=true
fi
+ TEMPERATURE_SETUP_SUCCESS=false
+
# Install lm-sensors if not present (skip on Raspberry Pi)
if ! command -v sensors &> /dev/null; then
if [ "$IS_RPI" = true ]; then
echo " ℹ️ Raspberry Pi detected - using native RPi temperature interface"
echo " Pulse will read temperature from /sys/class/thermal/thermal_zone0/temp"
+ TEMPERATURE_SETUP_SUCCESS=true
else
echo " ✓ Installing lm-sensors..."
@@ -3939,6 +3942,7 @@ elif [ "$TEMP_MONITORING_AVAILABLE" = true ]; then
if apt-get install -y lm-sensors > /dev/null 2>&1; then
sensors-detect --auto > /dev/null 2>&1 || true
echo " ✓ lm-sensors installed successfully"
+ TEMPERATURE_SETUP_SUCCESS=true
else
echo ""
echo " ⚠️ Could not install lm-sensors"
@@ -3957,15 +3961,21 @@ elif [ "$TEMP_MONITORING_AVAILABLE" = true ]; then
fi
else
echo " ✓ lm-sensors package verified"
+ TEMPERATURE_SETUP_SUCCESS=true
fi
echo ""
- echo "✓ Temperature monitoring enabled"
- if [ "$IS_RPI" = true ]; then
- echo " Using Raspberry Pi native temperature interface"
+ if [ "$TEMPERATURE_SETUP_SUCCESS" = true ]; then
+ echo "✓ Temperature monitoring enabled"
+ if [ "$IS_RPI" = true ]; then
+ echo " Using Raspberry Pi native temperature interface"
+ fi
+ echo " Temperature data will appear in the dashboard within 10 seconds"
+ TEMPERATURE_ENABLED=true
+ else
+ echo "✗ Temperature monitoring could not be enabled"
+ echo " Resolve the installation issues above and rerun this step."
fi
- echo " Temperature data will appear in the dashboard within 10 seconds"
- TEMPERATURE_ENABLED=true
# Configure automatic ProxyJump if needed (for containerized Pulse)
if [ "$CONFIGURE_PROXYJUMP" = true ] && [ -n "$PROXY_JUMP_HOST" ]; then
diff --git a/internal/api/router.go b/internal/api/router.go
index dcf392bd45..f6c8aacc4c 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -6,12 +6,14 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
+ "net"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
+ "strconv"
"strings"
"sync"
"time"
@@ -51,6 +53,8 @@ type Router struct {
settingsMu sync.RWMutex
cachedAllowEmbedding bool
cachedAllowedOrigins string
+ publicURLMu sync.Mutex
+ publicURLDetected bool
}
// NewRouter creates a new router instance
@@ -1038,6 +1042,13 @@ func (r *Router) SetMonitor(m *monitoring.Monitor) {
if r.systemSettingsHandler != nil {
r.systemSettingsHandler.SetMonitor(m)
}
+ if m != nil {
+ if url := strings.TrimSpace(r.config.PublicURL); url != "" {
+ if mgr := m.GetNotificationManager(); mgr != nil {
+ mgr.SetPublicURL(url)
+ }
+ }
+ }
}
// reloadSystemSettings loads system settings from disk and caches them
@@ -1077,6 +1088,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
// Get cached system settings (loaded once at startup, not from disk every request)
+ r.capturePublicURLFromRequest(req)
r.settingsMu.RLock()
allowEmbedding := r.cachedAllowEmbedding
allowedEmbedOrigins := r.cachedAllowedOrigins
@@ -1307,6 +1319,155 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}), allowEmbedding, allowedEmbedOrigins).ServeHTTP(w, req)
}
+func (r *Router) capturePublicURLFromRequest(req *http.Request) {
+ if req == nil || r == nil || r.config == nil {
+ return
+ }
+
+ if r.config.EnvOverrides != nil && r.config.EnvOverrides["publicURL"] {
+ return
+ }
+
+ rawHost := firstForwardedValue(req.Header.Get("X-Forwarded-Host"))
+ if rawHost == "" {
+ rawHost = req.Host
+ }
+ hostWithPort, hostOnly := sanitizeForwardedHost(rawHost)
+ if hostWithPort == "" {
+ return
+ }
+ if isLoopbackHost(hostOnly) {
+ return
+ }
+
+ rawProto := firstForwardedValue(req.Header.Get("X-Forwarded-Proto"))
+ if rawProto == "" {
+ rawProto = firstForwardedValue(req.Header.Get("X-Forwarded-Scheme"))
+ }
+ scheme := strings.ToLower(strings.TrimSpace(rawProto))
+ switch scheme {
+ case "https", "http":
+ // supported values
+ default:
+ if req.TLS != nil {
+ scheme = "https"
+ } else {
+ scheme = "http"
+ }
+ }
+ if scheme == "" {
+ scheme = "http"
+ }
+
+ if _, _, err := net.SplitHostPort(hostWithPort); err != nil {
+ if forwardedPort := firstForwardedValue(req.Header.Get("X-Forwarded-Port")); forwardedPort != "" {
+ if shouldAppendForwardedPort(forwardedPort, scheme) {
+ if strings.Contains(hostWithPort, ":") && !strings.HasPrefix(hostWithPort, "[") {
+ hostWithPort = fmt.Sprintf("[%s]", hostWithPort)
+ } else if strings.HasPrefix(hostWithPort, "[") && !strings.Contains(hostWithPort, "]") {
+ hostWithPort = fmt.Sprintf("[%s]", strings.TrimPrefix(hostWithPort, "["))
+ }
+ hostWithPort = fmt.Sprintf("%s:%s", hostWithPort, forwardedPort)
+ }
+ }
+ }
+
+ candidate := fmt.Sprintf("%s://%s", scheme, hostWithPort)
+ normalizedCandidate := strings.TrimRight(strings.TrimSpace(candidate), "/")
+
+ r.publicURLMu.Lock()
+ if r.publicURLDetected {
+ r.publicURLMu.Unlock()
+ return
+ }
+
+ current := strings.TrimRight(strings.TrimSpace(r.config.PublicURL), "/")
+ if current != "" && current == normalizedCandidate {
+ r.publicURLDetected = true
+ r.publicURLMu.Unlock()
+ return
+ }
+
+ r.config.PublicURL = normalizedCandidate
+ r.publicURLDetected = true
+ r.publicURLMu.Unlock()
+
+ log.Info().
+ Str("publicURL", normalizedCandidate).
+ Msg("Detected public URL from inbound request; using for notifications")
+
+ if r.monitor != nil {
+ if mgr := r.monitor.GetNotificationManager(); mgr != nil {
+ mgr.SetPublicURL(normalizedCandidate)
+ }
+ }
+}
+
+func firstForwardedValue(header string) string {
+ if header == "" {
+ return ""
+ }
+ parts := strings.Split(header, ",")
+ if len(parts) == 0 {
+ return ""
+ }
+ return strings.TrimSpace(parts[0])
+}
+
+func sanitizeForwardedHost(raw string) (string, string) {
+ host := strings.TrimSpace(raw)
+ if host == "" {
+ return "", ""
+ }
+
+ host = strings.TrimPrefix(host, "http://")
+ host = strings.TrimPrefix(host, "https://")
+ host = strings.TrimSpace(strings.TrimSuffix(host, "/"))
+ if host == "" {
+ return "", ""
+ }
+
+ hostOnly := host
+ if h, _, err := net.SplitHostPort(hostOnly); err == nil {
+ hostOnly = h
+ }
+ hostOnly = strings.Trim(hostOnly, "[]")
+
+ return host, hostOnly
+}
+
+func isLoopbackHost(host string) bool {
+ if host == "" {
+ return true
+ }
+ lower := strings.ToLower(host)
+ if lower == "localhost" {
+ return true
+ }
+ if ip := net.ParseIP(host); ip != nil {
+ if ip.IsLoopback() || ip.IsUnspecified() {
+ return true
+ }
+ }
+ return false
+}
+
+func shouldAppendForwardedPort(port, scheme string) bool {
+ if port == "" {
+ return false
+ }
+ if _, err := strconv.Atoi(port); err != nil {
+ return false
+ }
+ if scheme == "https" && port == "443" {
+ return false
+ }
+ if scheme == "http" && port == "80" {
+ return false
+ }
+ return true
+}
+
// detectLegacySSH checks if Pulse is using legacy SSH for temperature monitoring
//
// ⚠️ MIGRATION SCAFFOLDING - TEMPORARY CODE
diff --git a/internal/api/router_integration_test.go b/internal/api/router_integration_test.go
index 6073e606ae..c641dd03b0 100644
--- a/internal/api/router_integration_test.go
+++ b/internal/api/router_integration_test.go
@@ -28,6 +28,7 @@ type integrationServer struct {
server *httptest.Server
monitor *monitoring.Monitor
hub *internalws.Hub
+ config *config.Config
}
func newIntegrationServer(t *testing.T) *integrationServer {
@@ -50,6 +51,7 @@ func newIntegrationServerWithConfig(t *testing.T, customize func(*config.Config)
DemoMode: false,
AllowedOrigins: "*",
ConcurrentPolling: true,
+ EnvOverrides: make(map[string]bool),
}
if customize != nil {
@@ -92,6 +94,7 @@ func newIntegrationServerWithConfig(t *testing.T, customize func(*config.Config)
server: srv,
monitor: monitor,
hub: hub,
+ config: cfg,
}
}
@@ -568,6 +571,67 @@ func TestSessionCookieAllowsAuthenticatedAccess(t *testing.T) {
}
}
+func TestPublicURLDetectionUsesForwardedHeaders(t *testing.T) {
+ srv := newIntegrationServer(t)
+
+ req, err := http.NewRequest(http.MethodGet, srv.server.URL+"/api/health", nil)
+ if err != nil {
+ t.Fatalf("failed to build request: %v", err)
+ }
+ req.Header.Set("X-Forwarded-Proto", "https")
+ req.Header.Set("X-Forwarded-Host", "pulse.example.com")
+ req.Header.Set("X-Forwarded-Port", "8443")
+
+ res, err := srv.server.Client().Do(req)
+ if err != nil {
+ t.Fatalf("health request failed: %v", err)
+ }
+ res.Body.Close()
+
+ expected := "https://pulse.example.com:8443"
+ if got := srv.config.PublicURL; got != expected {
+ t.Fatalf("expected config public URL %q, got %q", expected, got)
+ }
+
+ if mgr := srv.monitor.GetNotificationManager(); mgr != nil {
+ if actual := mgr.GetPublicURL(); actual != expected {
+ t.Fatalf("expected notification manager public URL %q, got %q", expected, actual)
+ }
+ }
+}
+
+func TestPublicURLDetectionRespectsEnvOverride(t *testing.T) {
+ const overrideURL = "https://from-env.example.com"
+
+ srv := newIntegrationServerWithConfig(t, func(cfg *config.Config) {
+ cfg.PublicURL = overrideURL
+ cfg.EnvOverrides["publicURL"] = true
+ })
+
+ req, err := http.NewRequest(http.MethodGet, srv.server.URL+"/api/health", nil)
+ if err != nil {
+ t.Fatalf("failed to build request: %v", err)
+ }
+ req.Header.Set("X-Forwarded-Proto", "https")
+ req.Header.Set("X-Forwarded-Host", "ignored.example.org")
+
+ res, err := srv.server.Client().Do(req)
+ if err != nil {
+ t.Fatalf("health request failed: %v", err)
+ }
+ res.Body.Close()
+
+ if got := srv.config.PublicURL; got != overrideURL {
+ t.Fatalf("expected config public URL to remain %q, got %q", overrideURL, got)
+ }
+
+ if mgr := srv.monitor.GetNotificationManager(); mgr != nil {
+ if actual := mgr.GetPublicURL(); actual != overrideURL {
+ t.Fatalf("expected notification manager public URL %q, got %q", overrideURL, actual)
+ }
+ }
+}
+
func readExpectedVersion(t *testing.T) string {
t.Helper()
diff --git a/internal/config/config.go b/internal/config/config.go
index e71fd7fa60..914b67dac1 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -700,6 +700,7 @@ func Load() (*Config, error) {
}
if publicURL := os.Getenv("PULSE_PUBLIC_URL"); publicURL != "" {
cfg.PublicURL = publicURL
+ cfg.EnvOverrides["publicURL"] = true
log.Info().Str("url", publicURL).Msg("Public URL configured from PULSE_PUBLIC_URL env var")
} else {
// Try to auto-detect public URL if not explicitly configured
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index b06319fbc8..bc9b2889a0 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -8,6 +8,7 @@ import (
"net"
"net/url"
"os"
+ "path/filepath"
"sort"
"strconv"
"strings"
@@ -1299,9 +1300,14 @@ func isRunningInContainer() bool {
// New creates a new Monitor instance
func New(cfg *config.Config) (*Monitor, error) {
- // Initialize temperature collector with default SSH settings
+ // Initialize temperature collector with sensors SSH key
// Will use root user for now - can be made configurable later
- tempCollector := NewTemperatureCollector("root", "")
+ homeDir := os.Getenv("HOME")
+ if homeDir == "" {
+ homeDir = "/home/pulse"
+ }
+ sshKeyPath := filepath.Join(homeDir, ".ssh/id_ed25519_sensors")
+ tempCollector := NewTemperatureCollector("root", sshKeyPath)
// Security warning if running in container with SSH temperature monitoring
checkContainerizedTempMonitoring()
@@ -3089,10 +3095,10 @@ func (m *Monitor) pollPVEInstance(ctx context.Context, instanceName string, clie
// Use optimized parallel polling for better performance
if instanceCfg.MonitorVMs {
- m.pollVMsWithNodesOptimized(ctx, instanceName, client, nodes)
+ m.pollVMsWithNodes(ctx, instanceName, client, nodes)
}
if instanceCfg.MonitorContainers {
- m.pollContainersWithNodesOptimized(ctx, instanceName, client, nodes)
+ m.pollContainersWithNodes(ctx, instanceName, client, nodes)
}
}
}
@@ -3104,7 +3110,7 @@ func (m *Monitor) pollPVEInstance(ctx context.Context, instanceName string, clie
case <-ctx.Done():
return
default:
- m.pollStorageWithNodesOptimized(ctx, instanceName, client, nodes)
+ m.pollStorageWithNodes(ctx, instanceName, client, nodes)
}
}
@@ -3849,1260 +3855,6 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
return true
}
-// pollVMs polls VMs from a PVE instance
-// Deprecated: This function should not be called directly as it causes duplicate GetNodes calls.
-// Use pollVMsWithNodes instead.
-func (m *Monitor) pollVMs(ctx context.Context, instanceName string, client PVEClientInterface) {
- log.Warn().Str("instance", instanceName).Msg("pollVMs called directly - this causes duplicate GetNodes calls and syslog spam on non-clustered nodes")
-
- // Get all nodes first
- nodes, err := client.GetNodes(ctx)
- if err != nil {
- monErr := errors.WrapConnectionError("get_nodes_for_vms", instanceName, err)
- log.Error().Err(monErr).Str("instance", instanceName).Msg("Failed to get nodes for VM polling")
- return
- }
-
- m.pollVMsWithNodes(ctx, instanceName, client, nodes)
-}
-
-// pollVMsWithNodes polls VMs using a provided nodes list to avoid duplicate GetNodes calls
-func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
- var allVMs []models.VM
- for _, node := range nodes {
- // Skip offline nodes to avoid 595 errors when trying to access their resources
- if node.Status != "online" {
- log.Debug().
- Str("node", node.Node).
- Str("status", node.Status).
- Msg("Skipping offline node for VM polling")
- continue
- }
-
- vms, err := client.GetVMs(ctx, node.Node)
- if err != nil {
- monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_vms", instanceName, err).WithNode(node.Node)
- log.Error().Err(monErr).Str("node", node.Node).Msg("Failed to get VMs")
- continue
- }
-
- for _, vm := range vms {
- // Skip templates if configured
- if vm.Template == 1 {
- continue
- }
-
- // Parse tags
- var tags []string
- if vm.Tags != "" {
- tags = strings.Split(vm.Tags, ";")
-
- // Log if Pulse-specific tags are detected
- for _, tag := range tags {
- switch tag {
- case "pulse-no-alerts", "pulse-monitor-only", "pulse-relaxed":
- log.Info().
- Str("vm", vm.Name).
- Str("node", node.Node).
- Str("tag", tag).
- Msg("Pulse control tag detected on VM (legacy API)")
- }
- }
- }
-
- // Avoid duplicating node name in ID when instance name equals node name
- var guestID string
- if instanceName == node.Node {
- guestID = fmt.Sprintf("%s-%d", node.Node, vm.VMID)
- } else {
- guestID = fmt.Sprintf("%s-%s-%d", instanceName, node.Node, vm.VMID)
- }
-
- guestRaw := VMMemoryRaw{
- ListingMem: vm.Mem,
- ListingMaxMem: vm.MaxMem,
- Agent: vm.Agent,
- }
- memorySource := "listing-mem"
-
- // Initialize I/O metrics from VM listing (may be 0 for disk I/O)
- diskReadBytes := int64(vm.DiskRead)
- diskWriteBytes := int64(vm.DiskWrite)
- networkInBytes := int64(vm.NetIn)
- networkOutBytes := int64(vm.NetOut)
-
- // For running VMs, try to get detailed status with balloon info
- memUsed := uint64(0)
- memTotal := vm.MaxMem
- var ipAddresses []string
- var networkInterfaces []models.GuestNetworkInterface
- var osName, osVersion string
-
- if vm.Status == "running" {
- // Try to get detailed VM status for more accurate memory reporting and disk I/O
- if status, err := client.GetVMStatus(ctx, node.Node, vm.VMID); err == nil && status != nil {
- guestRaw.StatusMaxMem = status.MaxMem
- guestRaw.StatusMem = status.Mem
- guestRaw.StatusFreeMem = status.FreeMem
- guestRaw.Balloon = status.Balloon
- guestRaw.BalloonMin = status.BalloonMin
- guestRaw.Agent = status.Agent
- memAvailable := uint64(0)
- if status.MemInfo != nil {
- guestRaw.MemInfoUsed = status.MemInfo.Used
- guestRaw.MemInfoFree = status.MemInfo.Free
- guestRaw.MemInfoTotal = status.MemInfo.Total
- guestRaw.MemInfoAvailable = status.MemInfo.Available
- guestRaw.MemInfoBuffers = status.MemInfo.Buffers
- guestRaw.MemInfoCached = status.MemInfo.Cached
- guestRaw.MemInfoShared = status.MemInfo.Shared
-
- switch {
- case status.MemInfo.Available > 0:
- memAvailable = status.MemInfo.Available
- memorySource = "meminfo-available"
- case status.MemInfo.Free > 0 ||
- status.MemInfo.Buffers > 0 ||
- status.MemInfo.Cached > 0:
- memAvailable = status.MemInfo.Free +
- status.MemInfo.Buffers +
- status.MemInfo.Cached
- memorySource = "meminfo-derived"
- }
- }
-
- // Use actual disk I/O values from detailed status
- diskReadBytes = int64(status.DiskRead)
- diskWriteBytes = int64(status.DiskWrite)
- networkInBytes = int64(status.NetIn)
- networkOutBytes = int64(status.NetOut)
-
- // If balloon is enabled, use balloon as the total available memory
- if status.Balloon > 0 && status.Balloon < status.MaxMem {
- memTotal = status.Balloon
- guestRaw.DerivedFromBall = true
- } else {
- guestRaw.DerivedFromBall = false
- }
-
- // If we have free memory from guest agent, calculate actual usage
- switch {
- case memAvailable > 0:
- if memAvailable > memTotal {
- memAvailable = memTotal
- }
- memUsed = memTotal - memAvailable
- case status.FreeMem > 0:
- // Guest agent reports free memory, so calculate used
- memUsed = memTotal - status.FreeMem
- memorySource = "status-freemem"
- case status.Mem > 0:
- // No guest agent free memory data, but we have actual memory usage
- // Use the reported memory usage from Proxmox
- memUsed = status.Mem
- memorySource = "status-mem"
- default:
- // No memory data available at all - show 0% usage
- memUsed = 0
- memorySource = "status-unavailable"
- }
- if memUsed > memTotal {
- memUsed = memTotal
- }
-
- guestIPs, guestIfaces, guestOSName, guestOSVersion := m.fetchGuestAgentMetadata(ctx, client, instanceName, node.Node, vm.Name, vm.VMID, status)
- if len(guestIPs) > 0 {
- ipAddresses = guestIPs
- }
- if len(guestIfaces) > 0 {
- networkInterfaces = guestIfaces
- }
- if guestOSName != "" {
- osName = guestOSName
- }
- if guestOSVersion != "" {
- osVersion = guestOSVersion
- }
- } else {
- // Failed to get detailed status - show 0% usage
- memUsed = 0
- memorySource = "status-unavailable"
- }
- } else {
- // VM is not running, show 0 usage
- memUsed = 0
- memorySource = "powered-off"
- }
-
- // Set CPU to 0 for non-running VMs to avoid false alerts
- // VMs can have status: running, stopped, paused, suspended
- cpuUsage := safeFloat(vm.CPU)
- if vm.Status != "running" {
- cpuUsage = 0
- }
-
- // Try to get actual disk usage from guest agent if available
- diskUsed := uint64(vm.Disk)
- diskTotal := uint64(vm.MaxDisk)
- diskFree := diskTotal - diskUsed
- diskUsage := safePercentage(float64(diskUsed), float64(diskTotal))
- diskStatusReason := "" // Empty string means we have data
- var individualDisks []models.Disk // Store individual filesystems for multi-disk monitoring
-
- // If VM shows 0 disk usage but has allocated disk, it's likely guest agent issue
- // Set to -1 to indicate "unknown" rather than showing misleading 0%
- if diskUsed == 0 && diskTotal > 0 && vm.Status == "running" {
- diskUsage = -1
- diskStatusReason = "no-data"
- }
-
- // For running VMs with 0 disk usage, always try guest agent (even if agent flag is 0)
- // The agent flag might not be reliable or the API might return 0 incorrectly
- if vm.Status == "running" && (vm.Agent > 0 || (diskUsed == 0 && diskTotal > 0)) {
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Int("agent", vm.Agent).
- Uint64("diskUsed", diskUsed).
- Uint64("diskTotal", diskTotal).
- Bool("diskIsZero", diskUsed == 0).
- Msg("Attempting to get filesystem info from guest agent (legacy API)")
-
- fsInfo, err := client.GetVMFSInfo(ctx, node.Node, vm.VMID)
- if err != nil {
- // Log more helpful error messages based on the error type
- errMsg := err.Error()
- if strings.Contains(errMsg, "500") || strings.Contains(errMsg, "QEMU guest agent is not running") {
- diskStatusReason = "agent-not-running"
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Msg("Guest agent enabled in VM config but not running inside guest OS. Install and start qemu-guest-agent in the VM (legacy API)")
- } else if strings.Contains(errMsg, "timeout") {
- diskStatusReason = "agent-timeout"
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Msg("Guest agent timeout - agent may be installed but not responding (legacy API)")
- } else if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "401") || strings.Contains(errMsg, "authentication error") {
- // Permission error - user/token lacks required permissions
- diskStatusReason = "permission-denied"
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Msg("VM disk monitoring permission denied (legacy API). Check permissions:")
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Msg("• Proxmox 9: Ensure token/user has VM.GuestAgent.Audit privilege (Pulse setup adds this via PulseMonitor role)")
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Msg("• Proxmox 8: Ensure token/user has VM.Monitor privilege (Pulse setup adds this via PulseMonitor role)")
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Msg("• All versions: Sys.Audit is recommended for Ceph metrics and applied when available")
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Msg("• Re-run Pulse setup script if node was added before v4.7")
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Msg("• Verify guest agent is installed and running inside the VM")
- } else {
- diskStatusReason = "agent-error"
- log.Debug().
- Err(err).
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Msg("Failed to get filesystem info from guest agent (legacy API)")
- }
- } else if len(fsInfo) == 0 {
- diskStatusReason = "no-filesystems"
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Msg("Guest agent returned no filesystem info - agent may need restart or VM may have no mounted filesystems (legacy API)")
- } else {
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("filesystems", len(fsInfo)).
- Msg("Got filesystem info from guest agent (legacy API)")
- // Aggregate disk usage from all filesystems
- // Focus on actual filesystems, skip special mounts like /dev, /proc, /sys
- var totalBytes, usedBytes uint64
- var skippedFS []string
- for _, fs := range fsInfo {
- if reason, skip := readOnlyFilesystemReason(fs.Type, fs.TotalBytes, fs.UsedBytes); skip {
- log.Debug().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Str("mountpoint", fs.Mountpoint).
- Str("type", fs.Type).
- Str("skipReason", reason).
- Uint64("total", fs.TotalBytes).
- Uint64("used", fs.UsedBytes).
- Msg("Skipping read-only filesystem from guest agent (legacy API)")
- skippedFS = append(skippedFS, fmt.Sprintf("%s(%s,read-only-%s)", fs.Mountpoint, fs.Type, reason))
- continue
- }
- // Skip special filesystems and mounts
- if fs.Type == "tmpfs" || fs.Type == "devtmpfs" ||
- strings.HasPrefix(fs.Mountpoint, "/dev") ||
- strings.HasPrefix(fs.Mountpoint, "/proc") ||
- strings.HasPrefix(fs.Mountpoint, "/sys") ||
- strings.HasPrefix(fs.Mountpoint, "/run") ||
- fs.Mountpoint == "/boot/efi" ||
- fs.Mountpoint == "System Reserved" || // Windows System Reserved partition
- strings.Contains(fs.Mountpoint, "System Reserved") { // Various Windows reserved formats
- skippedFS = append(skippedFS, fmt.Sprintf("%s(%s)", fs.Mountpoint, fs.Type))
- continue
- }
-
- // Only count real filesystems (ext4, xfs, btrfs, ntfs, etc.) with valid data
- if fs.TotalBytes > 0 {
- totalBytes += fs.TotalBytes
- usedBytes += fs.UsedBytes
- individualDisks = append(individualDisks, models.Disk{
- Total: int64(fs.TotalBytes),
- Used: int64(fs.UsedBytes),
- Free: int64(fs.TotalBytes - fs.UsedBytes),
- Usage: safePercentage(float64(fs.UsedBytes), float64(fs.TotalBytes)),
- Mountpoint: fs.Mountpoint,
- Type: fs.Type,
- Device: fs.Disk,
- })
- log.Debug().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Str("mountpoint", fs.Mountpoint).
- Str("type", fs.Type).
- Uint64("total", fs.TotalBytes).
- Uint64("used", fs.UsedBytes).
- Msg("Including filesystem in disk usage calculation (legacy API)")
- } else if fs.TotalBytes == 0 && len(fs.Mountpoint) > 0 {
- log.Debug().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Str("mountpoint", fs.Mountpoint).
- Str("type", fs.Type).
- Msg("Skipping filesystem with zero total bytes (legacy API)")
- }
- }
-
- if len(skippedFS) > 0 {
- log.Debug().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Strs("skipped", skippedFS).
- Msg("Skipped special filesystems (legacy API)")
- }
-
- // If we got valid data from guest agent, use it
- if totalBytes > 0 {
- diskTotal = totalBytes
- diskUsed = usedBytes
- diskFree = totalBytes - usedBytes
- diskUsage = safePercentage(float64(usedBytes), float64(totalBytes))
- diskStatusReason = "" // Clear reason - we got data!
-
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Uint64("totalBytes", totalBytes).
- Uint64("usedBytes", usedBytes).
- Float64("usage", diskUsage).
- Msg("Successfully retrieved disk usage from guest agent (node API showed 0)")
- } else {
- diskStatusReason = "special-filesystems-only"
- log.Info().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("filesystems_found", len(fsInfo)).
- Msg("Guest agent provided filesystem info but no usable filesystems found (all were special mounts) (legacy API)")
- }
- }
- } else {
- if vm.Agent == 0 && diskUsed == 0 && diskTotal > 0 {
- diskStatusReason = "agent-disabled"
- log.Debug().
- Str("instance", instanceName).
- Str("vm", vm.Name).
- Int("vmid", vm.VMID).
- Int("agent", vm.Agent).
- Msg("VM does not have guest agent enabled in config (legacy API)")
- }
- }
-
- // Calculate I/O rates after we have the actual values
- sampleTime := time.Now()
- currentMetrics := IOMetrics{
- DiskRead: diskReadBytes,
- DiskWrite: diskWriteBytes,
- NetworkIn: networkInBytes,
- NetworkOut: networkOutBytes,
- Timestamp: sampleTime,
- }
- diskReadRate, diskWriteRate, netInRate, netOutRate := m.rateTracker.CalculateRates(guestID, currentMetrics)
-
- memTotalBytes := clampToInt64(memTotal)
- memUsedBytes := clampToInt64(memUsed)
- if memTotalBytes > 0 && memUsedBytes > memTotalBytes {
- memUsedBytes = memTotalBytes
- }
- memFreeBytes := memTotalBytes - memUsedBytes
- if memFreeBytes < 0 {
- memFreeBytes = 0
- }
- memory := models.Memory{
- Total: memTotalBytes,
- Used: memUsedBytes,
- Free: memFreeBytes,
- Usage: safePercentage(float64(memUsed), float64(memTotal)),
- }
- if guestRaw.Balloon > 0 {
- memory.Balloon = clampToInt64(guestRaw.Balloon)
- }
-
- modelVM := models.VM{
- ID: guestID,
- VMID: vm.VMID,
- Name: vm.Name,
- Node: node.Node,
- Instance: instanceName,
- Status: vm.Status,
- Type: "qemu",
- CPU: cpuUsage, // Already in percentage
- CPUs: vm.CPUs,
- Memory: memory,
- Disk: models.Disk{
- Total: int64(diskTotal),
- Used: int64(diskUsed),
- Free: int64(diskFree),
- Usage: diskUsage,
- },
- Disks: individualDisks,
- IPAddresses: ipAddresses,
- OSName: osName,
- OSVersion: osVersion,
- NetworkInterfaces: networkInterfaces,
- DiskStatusReason: diskStatusReason,
- NetworkIn: maxInt64(0, int64(netInRate)),
- NetworkOut: maxInt64(0, int64(netOutRate)),
- DiskRead: maxInt64(0, int64(diskReadRate)),
- DiskWrite: maxInt64(0, int64(diskWriteRate)),
- Uptime: int64(vm.Uptime),
- Template: vm.Template == 1,
- Tags: tags,
- Lock: vm.Lock,
- LastSeen: sampleTime,
- }
- allVMs = append(allVMs, modelVM)
-
- m.recordGuestSnapshot(instanceName, modelVM.Type, node.Node, vm.VMID, GuestMemorySnapshot{
- Name: vm.Name,
- Status: vm.Status,
- RetrievedAt: sampleTime,
- MemorySource: memorySource,
- Memory: modelVM.Memory,
- Raw: guestRaw,
- })
-
- // Record metrics history
- m.metricsHistory.AddGuestMetric(modelVM.ID, "cpu", modelVM.CPU*100, sampleTime)
- m.metricsHistory.AddGuestMetric(modelVM.ID, "memory", modelVM.Memory.Usage, sampleTime)
- m.metricsHistory.AddGuestMetric(modelVM.ID, "disk", modelVM.Disk.Usage, sampleTime)
- m.metricsHistory.AddGuestMetric(modelVM.ID, "diskread", float64(modelVM.DiskRead), sampleTime)
- m.metricsHistory.AddGuestMetric(modelVM.ID, "diskwrite", float64(modelVM.DiskWrite), sampleTime)
- m.metricsHistory.AddGuestMetric(modelVM.ID, "netin", float64(modelVM.NetworkIn), sampleTime)
- m.metricsHistory.AddGuestMetric(modelVM.ID, "netout", float64(modelVM.NetworkOut), sampleTime)
-
- // Check thresholds for alerts
- m.alertManager.CheckGuest(modelVM, instanceName)
- }
- }
-
- m.state.UpdateVMsForInstance(instanceName, allVMs)
-}
-
-// pollContainers polls containers from a PVE instance
-// Deprecated: This function should not be called directly as it causes duplicate GetNodes calls.
-// Use pollContainersWithNodes instead.
-func (m *Monitor) pollContainers(ctx context.Context, instanceName string, client PVEClientInterface) {
- log.Warn().Str("instance", instanceName).Msg("pollContainers called directly - this causes duplicate GetNodes calls and syslog spam on non-clustered nodes")
-
- // Get all nodes first
- nodes, err := client.GetNodes(ctx)
- if err != nil {
- monErr := errors.WrapConnectionError("get_nodes_for_containers", instanceName, err)
- log.Error().Err(monErr).Str("instance", instanceName).Msg("Failed to get nodes for container polling")
- return
- }
-
- m.pollContainersWithNodes(ctx, instanceName, client, nodes)
-}
-
-// pollContainersWithNodes polls containers using a provided nodes list to avoid duplicate GetNodes calls
-func (m *Monitor) pollContainersWithNodes(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
-
- var allContainers []models.Container
- for _, node := range nodes {
- // Skip offline nodes to avoid 595 errors when trying to access their resources
- if node.Status != "online" {
- log.Debug().
- Str("node", node.Node).
- Str("status", node.Status).
- Msg("Skipping offline node for container polling")
- continue
- }
-
- containers, err := client.GetContainers(ctx, node.Node)
- if err != nil {
- monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_containers", instanceName, err).WithNode(node.Node)
- log.Error().Err(monErr).Str("node", node.Node).Msg("Failed to get containers")
- continue
- }
-
- vmIDs := make([]int, 0, len(containers))
- for _, ct := range containers {
- if ct.Template == 1 {
- continue
- }
- vmIDs = append(vmIDs, int(ct.VMID))
- }
-
- rootUsageOverrides := m.collectContainerRootUsage(ctx, client, node.Node, vmIDs)
-
- for _, ct := range containers {
- // Skip templates if configured
- if ct.Template == 1 {
- continue
- }
-
- // Parse tags
- var tags []string
- if ct.Tags != "" {
- tags = strings.Split(ct.Tags, ";")
-
- // Log if Pulse-specific tags are detected
- for _, tag := range tags {
- switch tag {
- case "pulse-no-alerts", "pulse-monitor-only", "pulse-relaxed":
- log.Info().
- Str("container", ct.Name).
- Str("node", node.Node).
- Str("tag", tag).
- Msg("Pulse control tag detected on container (legacy API)")
- }
- }
- }
-
- // Calculate I/O rates
- // Avoid duplicating node name in ID when instance name equals node name
- var guestID string
- if instanceName == node.Node {
- guestID = fmt.Sprintf("%s-%d", node.Node, int(ct.VMID))
- } else {
- guestID = fmt.Sprintf("%s-%s-%d", instanceName, node.Node, int(ct.VMID))
- }
- currentMetrics := IOMetrics{
- DiskRead: int64(ct.DiskRead),
- DiskWrite: int64(ct.DiskWrite),
- NetworkIn: int64(ct.NetIn),
- NetworkOut: int64(ct.NetOut),
- Timestamp: time.Now(),
- }
- diskReadRate, diskWriteRate, netInRate, netOutRate := m.rateTracker.CalculateRates(guestID, currentMetrics)
-
- // Set CPU to 0 for non-running containers to avoid false alerts
- // Containers can have status: running, stopped, paused, suspended
- cpuUsage := safeFloat(ct.CPU)
- if ct.Status != "running" {
- cpuUsage = 0
- }
-
- // For containers, memory reporting is more accurate than VMs
- // ct.Mem shows actual usage for running containers
- memUsed := uint64(0)
- memTotal := ct.MaxMem
-
- if ct.Status == "running" {
- // For running containers, ct.Mem is actual usage
- memUsed = ct.Mem
- }
-
- memTotalBytes := clampToInt64(memTotal)
- memUsedBytes := clampToInt64(memUsed)
- if memTotalBytes > 0 && memUsedBytes > memTotalBytes {
- memUsedBytes = memTotalBytes
- }
- memFreeBytes := memTotalBytes - memUsedBytes
- if memFreeBytes < 0 {
- memFreeBytes = 0
- }
- memUsagePercent := safePercentage(float64(memUsedBytes), float64(memTotalBytes))
-
- diskTotalBytes := clampToInt64(ct.MaxDisk)
- diskUsedBytes := clampToInt64(ct.Disk)
- if diskTotalBytes > 0 && diskUsedBytes > diskTotalBytes {
- diskUsedBytes = diskTotalBytes
- }
- diskFreeBytes := diskTotalBytes - diskUsedBytes
- if diskFreeBytes < 0 {
- diskFreeBytes = 0
- }
- diskUsagePercent := safePercentage(float64(diskUsedBytes), float64(diskTotalBytes))
-
- // Convert -1 to nil for I/O metrics when VM is not running
- // We'll use -1 to indicate "no data" which will be converted to null for the frontend
- modelCT := models.Container{
- ID: guestID,
- VMID: int(ct.VMID),
- Name: ct.Name,
- Node: node.Node,
- Instance: instanceName,
- Status: ct.Status,
- Type: "lxc",
- CPU: cpuUsage, // Already in percentage
- CPUs: int(ct.CPUs),
- Memory: models.Memory{
- Total: memTotalBytes,
- Used: memUsedBytes,
- Free: memFreeBytes,
- Usage: memUsagePercent,
- },
- Disk: models.Disk{
- Total: diskTotalBytes,
- Used: diskUsedBytes,
- Free: diskFreeBytes,
- Usage: diskUsagePercent,
- },
- NetworkIn: maxInt64(0, int64(netInRate)),
- NetworkOut: maxInt64(0, int64(netOutRate)),
- DiskRead: maxInt64(0, int64(diskReadRate)),
- DiskWrite: maxInt64(0, int64(diskWriteRate)),
- Uptime: int64(ct.Uptime),
- Template: ct.Template == 1,
- Tags: tags,
- Lock: ct.Lock,
- LastSeen: time.Now(),
- }
-
- if override, ok := rootUsageOverrides[int(ct.VMID)]; ok {
- overrideUsed := clampToInt64(override.Used)
- overrideTotal := clampToInt64(override.Total)
-
- if overrideUsed > 0 && (modelCT.Disk.Used == 0 || overrideUsed < modelCT.Disk.Used) {
- modelCT.Disk.Used = overrideUsed
- }
-
- if overrideTotal > 0 {
- modelCT.Disk.Total = overrideTotal
- }
-
- if modelCT.Disk.Total > 0 && modelCT.Disk.Used > modelCT.Disk.Total {
- modelCT.Disk.Used = modelCT.Disk.Total
- }
-
- modelCT.Disk.Free = modelCT.Disk.Total - modelCT.Disk.Used
- if modelCT.Disk.Free < 0 {
- modelCT.Disk.Free = 0
- }
-
- modelCT.Disk.Usage = safePercentage(float64(modelCT.Disk.Used), float64(modelCT.Disk.Total))
- }
-
- allContainers = append(allContainers, modelCT)
-
- // Record metrics history
- now := time.Now()
- m.metricsHistory.AddGuestMetric(modelCT.ID, "cpu", modelCT.CPU*100, now)
- m.metricsHistory.AddGuestMetric(modelCT.ID, "memory", modelCT.Memory.Usage, now)
- m.metricsHistory.AddGuestMetric(modelCT.ID, "disk", modelCT.Disk.Usage, now)
- m.metricsHistory.AddGuestMetric(modelCT.ID, "diskread", float64(modelCT.DiskRead), now)
- m.metricsHistory.AddGuestMetric(modelCT.ID, "diskwrite", float64(modelCT.DiskWrite), now)
- m.metricsHistory.AddGuestMetric(modelCT.ID, "netin", float64(modelCT.NetworkIn), now)
- m.metricsHistory.AddGuestMetric(modelCT.ID, "netout", float64(modelCT.NetworkOut), now)
-
- // Check thresholds for alerts
- log.Info().Str("container", modelCT.Name).Msg("Checking container alerts")
- m.alertManager.CheckGuest(modelCT, instanceName)
- }
- }
-
- m.state.UpdateContainersForInstance(instanceName, allContainers)
-}
-
-// pollStorage polls storage from a PVE instance
-// Deprecated: This function should not be called directly as it causes duplicate GetNodes calls.
-// Use pollStorageWithNodes instead.
-func (m *Monitor) pollStorage(ctx context.Context, instanceName string, client PVEClientInterface) {
- log.Warn().Str("instance", instanceName).Msg("pollStorage called directly - this causes duplicate GetNodes calls and syslog spam on non-clustered nodes")
-
- // Get all nodes first
- nodes, err := client.GetNodes(ctx)
- if err != nil {
- monErr := errors.WrapConnectionError("get_nodes_for_storage", instanceName, err)
- log.Error().Err(monErr).Str("instance", instanceName).Msg("Failed to get nodes for storage polling")
- return
- }
-
- m.pollStorageWithNodes(ctx, instanceName, client, nodes)
-}
-
-// pollStorageWithNodes polls storage using a provided nodes list to avoid duplicate GetNodes calls
-func (m *Monitor) pollStorageWithNodes(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
-
- // Get cluster storage configuration for shared/enabled status
- clusterStorages, err := client.GetAllStorage(ctx)
- clusterStorageAvailable := err == nil
- if err != nil {
- monErr := errors.WrapAPIError("get_cluster_storage", instanceName, err, 0)
- log.Warn().Err(monErr).Str("instance", instanceName).Msg("Failed to get cluster storage config - will continue with node storage only")
- }
-
- // Create a map for quick lookup of cluster storage config
- clusterStorageMap := make(map[string]proxmox.Storage)
- cephDetected := false
- if clusterStorageAvailable {
- for _, cs := range clusterStorages {
- clusterStorageMap[cs.Storage] = cs
- if !cephDetected && isCephStorageType(cs.Type) {
- cephDetected = true
- }
- }
- }
-
- var allStorage []models.Storage
- sharedStorageIndex := make(map[string]int)
-
- addUniqueString := func(target *[]string, value string) {
- if value == "" {
- return
- }
- for _, existing := range *target {
- if existing == value {
- return
- }
- }
- *target = append(*target, value)
- }
-
- // Get storage from each node (this includes capacity info)
- log.Debug().Str("instance", instanceName).Int("nodeCount", len(nodes)).Msg("Starting storage polling for nodes")
-
- for _, node := range nodes {
- // Skip offline nodes to avoid 595 errors when trying to access their resources
- if node.Status != "online" {
- log.Debug().
- Str("node", node.Node).
- Str("status", node.Status).
- Msg("Skipping offline node for storage polling")
- continue
- }
-
- log.Debug().Str("node", node.Node).Msg("Getting storage for node")
- nodeStorage, err := client.GetStorage(ctx, node.Node)
- if err != nil {
- monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_node_storage", instanceName, err).WithNode(node.Node)
- log.Warn().Err(monErr).Str("node", node.Node).Msg("Failed to get node storage - continuing with other nodes")
- continue
- }
-
- log.Debug().Str("node", node.Node).Int("storageCount", len(nodeStorage)).Msg("Retrieved storage for node")
-
- for _, storage := range nodeStorage {
- if reason, skip := readOnlyFilesystemReason(storage.Type, storage.Total, storage.Used); skip {
- log.Debug().
- Str("node", node.Node).
- Str("storage", storage.Storage).
- Str("type", storage.Type).
- Str("skipReason", reason).
- Uint64("total", storage.Total).
- Uint64("used", storage.Used).
- Msg("Skipping read-only storage mount")
- continue
- }
- // Get cluster config for this storage
- clusterConfig, hasClusterConfig := clusterStorageMap[storage.Storage]
-
- // Determine if shared based on cluster configuration
- shared := hasClusterConfig && clusterConfig.Shared == 1
-
- // For shared storage, only include it once
- storageKey := storage.Storage
- if shared {
- if idx, exists := sharedStorageIndex[storageKey]; exists {
- existing := &allStorage[idx]
- addUniqueString(&existing.Nodes, node.Node)
- addUniqueString(&existing.NodeIDs, fmt.Sprintf("%s-%s", instanceName, node.Node))
- existing.NodeCount = len(existing.Nodes)
- continue
- }
- }
-
- // Use appropriate node name
- nodeID := node.Node
- storageID := fmt.Sprintf("%s-%s-%s", instanceName, nodeID, storage.Storage)
- if shared {
- nodeID = "shared"
- // Use instance-specific ID for shared storage to prevent conflicts between clusters
- storageID = fmt.Sprintf("%s-shared-%s", instanceName, storage.Storage)
- }
-
- modelStorage := models.Storage{
- ID: storageID,
- Name: storage.Storage,
- Node: nodeID,
- Instance: instanceName,
- Type: storage.Type,
- Status: "available",
- Total: int64(storage.Total),
- Used: int64(storage.Used),
- Free: int64(storage.Available),
- Usage: 0,
- Content: sortContent(storage.Content),
- Shared: shared,
- Enabled: true,
- Active: true,
- }
-
- nodeIdentifier := fmt.Sprintf("%s-%s", instanceName, node.Node)
- modelStorage.Nodes = []string{node.Node}
- modelStorage.NodeIDs = []string{nodeIdentifier}
- modelStorage.NodeCount = len(modelStorage.Nodes)
-
- // Override with cluster config if available
- if hasClusterConfig {
- // Sort content values for consistent display
- if clusterConfig.Content != "" {
- contentParts := strings.Split(clusterConfig.Content, ",")
- sort.Strings(contentParts)
- modelStorage.Content = strings.Join(contentParts, ",")
- } else {
- modelStorage.Content = clusterConfig.Content
- }
- modelStorage.Enabled = clusterConfig.Enabled == 1
- modelStorage.Active = clusterConfig.Active == 1
- }
-
- // Calculate usage percentage
- if modelStorage.Total > 0 {
- modelStorage.Usage = safePercentage(float64(modelStorage.Used), float64(modelStorage.Total))
- }
-
- // Determine status based on active/enabled flags
- if storage.Active == 1 || modelStorage.Active {
- modelStorage.Status = "available"
- } else if modelStorage.Enabled {
- modelStorage.Status = "inactive"
- } else {
- modelStorage.Status = "disabled"
- }
-
- allStorage = append(allStorage, modelStorage)
- if shared {
- sharedStorageIndex[storageKey] = len(allStorage) - 1
- }
-
- // Record storage metrics history
- now := time.Now()
- m.metricsHistory.AddStorageMetric(modelStorage.ID, "usage", modelStorage.Usage, now)
- m.metricsHistory.AddStorageMetric(modelStorage.ID, "used", float64(modelStorage.Used), now)
- m.metricsHistory.AddStorageMetric(modelStorage.ID, "total", float64(modelStorage.Total), now)
- m.metricsHistory.AddStorageMetric(modelStorage.ID, "avail", float64(modelStorage.Free), now)
-
- // Check thresholds for alerts
- log.Info().
- Str("storage", modelStorage.Name).
- Str("id", modelStorage.ID).
- Float64("usage", modelStorage.Usage).
- Str("status", modelStorage.Status).
- Msg("Calling CheckStorage for storage device")
- m.alertManager.CheckStorage(modelStorage)
- }
- }
-
- // Update storage for this instance only
- var instanceStorage []models.Storage
- for _, st := range allStorage {
- st.Instance = instanceName
- instanceStorage = append(instanceStorage, st)
- }
-
- log.Info().
- Str("instance", instanceName).
- Int("storageCount", len(instanceStorage)).
- Bool("clusterConfigAvailable", clusterStorageAvailable).
- Msg("Updating storage for instance")
-
- if !cephDetected {
- for _, storage := range instanceStorage {
- if isCephStorageType(storage.Type) {
- cephDetected = true
- break
- }
- }
- }
-
- m.state.UpdateStorageForInstance(instanceName, instanceStorage)
-
- // Refresh Ceph cluster state now that storage has been updated
- m.pollCephCluster(ctx, instanceName, client, cephDetected)
-}
-
-// pollBackupTasks polls backup tasks from a PVE instance
-func (m *Monitor) pollBackupTasks(ctx context.Context, instanceName string, client PVEClientInterface) {
- log.Debug().Str("instance", instanceName).Msg("Polling backup tasks")
-
- tasks, err := client.GetBackupTasks(ctx)
- if err != nil {
- monErr := errors.WrapAPIError("get_backup_tasks", instanceName, err, 0)
- log.Error().Err(monErr).Str("instance", instanceName).Msg("Failed to get backup tasks")
- return
- }
-
- var backupTasks []models.BackupTask
- for _, task := range tasks {
- // Extract VMID from task ID (format: "UPID:node:pid:starttime:type:vmid:user@realm:")
- vmid := 0
- if task.ID != "" {
- if vmidInt, err := strconv.Atoi(task.ID); err == nil {
- vmid = vmidInt
- }
- }
-
- taskID := fmt.Sprintf("%s-%s", instanceName, task.UPID)
-
- backupTask := models.BackupTask{
- ID: taskID,
- Node: task.Node,
- Type: task.Type,
- VMID: vmid,
- Status: task.Status,
- StartTime: time.Unix(task.StartTime, 0),
- }
-
- if task.EndTime > 0 {
- backupTask.EndTime = time.Unix(task.EndTime, 0)
- }
-
- backupTasks = append(backupTasks, backupTask)
- }
-
- // Update state with new backup tasks for this instance
- m.state.UpdateBackupTasksForInstance(instanceName, backupTasks)
-}
-
-// pollPBSInstance polls a single PBS instance
-func (m *Monitor) pollPBSInstance(ctx context.Context, instanceName string, client *pbs.Client) {
- // Check if context is cancelled
- select {
- case <-ctx.Done():
- log.Debug().Str("instance", instanceName).Msg("Polling cancelled")
- return
- default:
- }
-
- log.Debug().Str("instance", instanceName).Msg("Polling PBS instance")
-
- // Get instance config
- var instanceCfg *config.PBSInstance
- for _, cfg := range m.config.PBSInstances {
- if cfg.Name == instanceName {
- instanceCfg = &cfg
- log.Debug().
- Str("instance", instanceName).
- Bool("monitorDatastores", cfg.MonitorDatastores).
- Msg("Found PBS instance config")
- break
- }
- }
- if instanceCfg == nil {
- log.Error().Str("instance", instanceName).Msg("PBS instance config not found")
- return
- }
-
- // Initialize PBS instance with default values
- pbsInst := models.PBSInstance{
- ID: "pbs-" + instanceName,
- Name: instanceName,
- Host: instanceCfg.Host,
- Status: "offline",
- Version: "unknown",
- ConnectionHealth: "unhealthy",
- LastSeen: time.Now(),
- }
-
- // Try to get version first
- version, versionErr := client.GetVersion(ctx)
- if versionErr == nil {
- // Version succeeded - PBS is online
- pbsInst.Status = "online"
- pbsInst.Version = version.Version
- pbsInst.ConnectionHealth = "healthy"
- m.resetAuthFailures(instanceName, "pbs")
- m.state.SetConnectionHealth("pbs-"+instanceName, true)
-
- log.Debug().
- Str("instance", instanceName).
- Str("version", version.Version).
- Bool("monitorDatastores", instanceCfg.MonitorDatastores).
- Msg("PBS version retrieved successfully")
- } else {
- log.Debug().Err(versionErr).Str("instance", instanceName).Msg("Failed to get PBS version, trying fallback")
-
- // Version failed, try datastores as fallback (like test connection does)
- ctx2, cancel2 := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel2()
-
- _, datastoreErr := client.GetDatastores(ctx2)
- if datastoreErr == nil {
- // Datastores succeeded - PBS is online but version unavailable
- pbsInst.Status = "online"
- pbsInst.Version = "connected"
- pbsInst.ConnectionHealth = "healthy"
- m.resetAuthFailures(instanceName, "pbs")
- m.state.SetConnectionHealth("pbs-"+instanceName, true)
-
- log.Info().
- Str("instance", instanceName).
- Msg("PBS connected (version unavailable but datastores accessible)")
- } else {
- // Both failed - PBS is offline
- pbsInst.Status = "offline"
- pbsInst.ConnectionHealth = "error"
- monErr := errors.WrapConnectionError("get_pbs_version", instanceName, versionErr)
- log.Error().Err(monErr).Str("instance", instanceName).Msg("Failed to connect to PBS")
- m.state.SetConnectionHealth("pbs-"+instanceName, false)
-
- // Track auth failure if it's an authentication error
- if errors.IsAuthError(versionErr) || errors.IsAuthError(datastoreErr) {
- m.recordAuthFailure(instanceName, "pbs")
- // Don't continue if auth failed
- return
- }
- }
- }
-
- // Get node status (CPU, memory, etc.)
- // Note: This requires Sys.Audit permission on PBS which read-only tokens often don't have
- nodeStatus, err := client.GetNodeStatus(ctx)
- if err != nil {
- // Log as debug instead of error since this is often a permission issue
- log.Debug().Err(err).Str("instance", instanceName).Msg("Could not get PBS node status (may need Sys.Audit permission)")
- } else if nodeStatus != nil {
- // Only process if we got actual status data (might be nil due to permissions)
- pbsInst.CPU = nodeStatus.CPU
- if nodeStatus.Memory.Total > 0 {
- pbsInst.Memory = float64(nodeStatus.Memory.Used) / float64(nodeStatus.Memory.Total) * 100
- pbsInst.MemoryUsed = nodeStatus.Memory.Used
- pbsInst.MemoryTotal = nodeStatus.Memory.Total
- }
- pbsInst.Uptime = nodeStatus.Uptime
-
- log.Debug().
- Str("instance", instanceName).
- Float64("cpu", pbsInst.CPU).
- Float64("memory", pbsInst.Memory).
- Int64("uptime", pbsInst.Uptime).
- Msg("PBS node status retrieved")
- }
-
- // Poll datastores if enabled
- log.Debug().Bool("monitorDatastores", instanceCfg.MonitorDatastores).Str("instance", instanceName).Msg("Checking if datastore monitoring is enabled")
- if instanceCfg.MonitorDatastores {
- datastores, err := client.GetDatastores(ctx)
- if err != nil {
- monErr := errors.WrapAPIError("get_datastores", instanceName, err, 0)
- log.Error().Err(monErr).Str("instance", instanceName).Msg("Failed to get datastores")
- } else {
- log.Info().
- Str("instance", instanceName).
- Int("count", len(datastores)).
- Msg("Got PBS datastores")
-
- for _, ds := range datastores {
- // Use whichever fields are populated
- total := ds.Total
- if total == 0 && ds.TotalSpace > 0 {
- total = ds.TotalSpace
- }
- used := ds.Used
- if used == 0 && ds.UsedSpace > 0 {
- used = ds.UsedSpace
- }
- avail := ds.Avail
- if avail == 0 && ds.AvailSpace > 0 {
- avail = ds.AvailSpace
- }
-
- // If still 0, try to calculate from each other
- if total == 0 && used > 0 && avail > 0 {
- total = used + avail
- }
-
- log.Debug().
- Str("store", ds.Store).
- Int64("total", total).
- Int64("used", used).
- Int64("avail", avail).
- Int64("orig_total", ds.Total).
- Int64("orig_total_space", ds.TotalSpace).
- Msg("PBS datastore details")
-
- modelDS := models.PBSDatastore{
- Name: ds.Store,
- Total: total,
- Used: used,
- Free: avail,
- Usage: safePercentage(float64(used), float64(total)),
- Status: "available",
- DeduplicationFactor: ds.DeduplicationFactor,
- }
-
- // Discover namespaces for this datastore
- namespaces, err := client.ListNamespaces(ctx, ds.Store, "", 0)
- if err != nil {
- log.Warn().Err(err).
- Str("instance", instanceName).
- Str("datastore", ds.Store).
- Msg("Failed to list namespaces")
- } else {
- // Convert PBS namespaces to model namespaces
- for _, ns := range namespaces {
- nsPath := ns.NS
- if nsPath == "" {
- nsPath = ns.Path
- }
- if nsPath == "" {
- nsPath = ns.Name
- }
-
- modelNS := models.PBSNamespace{
- Path: nsPath,
- Parent: ns.Parent,
- Depth: strings.Count(nsPath, "/"),
- }
- modelDS.Namespaces = append(modelDS.Namespaces, modelNS)
- }
-
- // Always include root namespace
- hasRoot := false
- for _, ns := range modelDS.Namespaces {
- if ns.Path == "" {
- hasRoot = true
- break
- }
- }
- if !hasRoot {
- modelDS.Namespaces = append([]models.PBSNamespace{{Path: "", Depth: 0}}, modelDS.Namespaces...)
- }
- }
-
- pbsInst.Datastores = append(pbsInst.Datastores, modelDS)
- }
- }
- }
-
- // Update state - merge with existing instances
- m.state.UpdatePBSInstance(pbsInst)
- log.Info().
- Str("instance", instanceName).
- Str("id", pbsInst.ID).
- Int("datastores", len(pbsInst.Datastores)).
- Msg("PBS instance updated in state")
-
- // Check PBS metrics against alert thresholds
- if m.alertManager != nil {
- m.alertManager.CheckPBS(pbsInst)
- }
-
- // Poll backups if enabled
- if instanceCfg.MonitorBackups {
- if len(pbsInst.Datastores) == 0 {
- log.Debug().
- Str("instance", instanceName).
- Msg("No PBS datastores available for backup polling")
- } else {
- if !m.config.EnableBackupPolling {
- log.Debug().
- Str("instance", instanceName).
- Msg("Skipping PBS backup polling - globally disabled")
- } else {
- now := time.Now()
-
- m.mu.RLock()
- lastPoll := m.lastPBSBackupPoll[instanceName]
- m.mu.RUnlock()
-
- shouldPoll, reason, newLast := m.shouldRunBackupPoll(lastPoll, now)
- if !shouldPoll {
- if reason != "" {
- log.Debug().
- Str("instance", instanceName).
- Str("reason", reason).
- Msg("Skipping PBS backup polling this cycle")
- }
- } else {
- datastoreSnapshot := make([]models.PBSDatastore, len(pbsInst.Datastores))
- copy(datastoreSnapshot, pbsInst.Datastores)
-
- m.mu.Lock()
- if m.pbsBackupPollers[instanceName] {
- m.mu.Unlock()
- log.Debug().
- Str("instance", instanceName).
- Msg("PBS backup polling already in progress")
- } else {
- m.pbsBackupPollers[instanceName] = true
- m.lastPBSBackupPoll[instanceName] = newLast
- m.mu.Unlock()
-
- go func(ds []models.PBSDatastore, inst string, start time.Time, pbsClient *pbs.Client) {
- defer func() {
- m.mu.Lock()
- delete(m.pbsBackupPollers, inst)
- m.lastPBSBackupPoll[inst] = time.Now()
- m.mu.Unlock()
- }()
-
- log.Info().
- Str("instance", inst).
- Int("datastores", len(ds)).
- Msg("Starting background PBS backup polling")
-
- backupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
- defer cancel()
-
- m.pollPBSBackups(backupCtx, inst, pbsClient, ds)
-
- log.Info().
- Str("instance", inst).
- Dur("duration", time.Since(start)).
- Msg("Completed background PBS backup polling")
- }(datastoreSnapshot, instanceName, now, client)
- }
- }
- }
- }
- } else {
- log.Debug().
- Str("instance", instanceName).
- Msg("PBS backup monitoring disabled")
- }
-}
-
// pollPMGInstance polls a single Proxmox Mail Gateway instance
func (m *Monitor) pollPMGInstance(ctx context.Context, instanceName string, client *pmg.Client) {
select {
diff --git a/internal/monitoring/monitor_optimized.go b/internal/monitoring/monitor_polling.go
similarity index 97%
rename from internal/monitoring/monitor_optimized.go
rename to internal/monitoring/monitor_polling.go
index bd6c2aa2b0..5ac04f9a0e 100644
--- a/internal/monitoring/monitor_optimized.go
+++ b/internal/monitoring/monitor_polling.go
@@ -56,8 +56,8 @@ func convertPoolInfoToModel(poolInfo *proxmox.ZFSPoolInfo) *models.ZFSPool {
return modelPool
}
-// pollVMsWithNodesOptimized polls VMs from all nodes in parallel using goroutines
-func (m *Monitor) pollVMsWithNodesOptimized(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
+// pollVMsWithNodes polls VMs from all nodes in parallel using goroutines
+func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
startTime := time.Now()
// Channel to collect VM results from each node
@@ -655,8 +655,8 @@ func (m *Monitor) pollVMsWithNodesOptimized(ctx context.Context, instanceName st
Msg("Parallel VM polling completed")
}
-// pollContainersWithNodesOptimized polls containers from all nodes in parallel using goroutines
-func (m *Monitor) pollContainersWithNodesOptimized(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
+// pollContainersWithNodes polls containers from all nodes in parallel using goroutines
+func (m *Monitor) pollContainersWithNodes(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
startTime := time.Now()
// Channel to collect container results from each node
@@ -898,8 +898,8 @@ func (m *Monitor) pollContainersWithNodesOptimized(ctx context.Context, instance
Msg("Parallel container polling completed")
}
-// pollStorageWithNodesOptimized polls storage from all nodes in parallel using goroutines
-func (m *Monitor) pollStorageWithNodesOptimized(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
+// pollStorageWithNodes polls storage from all nodes in parallel using goroutines
+func (m *Monitor) pollStorageWithNodes(ctx context.Context, instanceName string, client PVEClientInterface, nodes []proxmox.Node) {
startTime := time.Now()
// Get cluster storage configuration first (single call)
@@ -1254,9 +1254,19 @@ func (m *Monitor) pollStorageWithNodesOptimized(ctx context.Context, instanceNam
}
}
- // Check alerts for all storage devices
+ // Record metrics and check alerts for all storage devices
for _, storage := range allStorage {
- m.alertManager.CheckStorage(storage)
+ if m.metricsHistory != nil {
+ timestamp := time.Now()
+ m.metricsHistory.AddStorageMetric(storage.ID, "usage", storage.Usage, timestamp)
+ m.metricsHistory.AddStorageMetric(storage.ID, "used", float64(storage.Used), timestamp)
+ m.metricsHistory.AddStorageMetric(storage.ID, "total", float64(storage.Total), timestamp)
+ m.metricsHistory.AddStorageMetric(storage.ID, "avail", float64(storage.Free), timestamp)
+ }
+
+ if m.alertManager != nil {
+ m.alertManager.CheckStorage(storage)
+ }
}
if !cephDetected {
diff --git a/internal/monitoring/monitor_storage_test.go b/internal/monitoring/monitor_storage_test.go
new file mode 100644
index 0000000000..537efc0672
--- /dev/null
+++ b/internal/monitoring/monitor_storage_test.go
@@ -0,0 +1,201 @@
+package monitoring
+
+import (
+ "context"
+ "fmt"
+ "math"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+)
+
+// fakeStorageClient provides minimal PVE responses needed by the optimized storage poller.
+type fakeStorageClient struct {
+ allStorage []proxmox.Storage
+ storageByNode map[string][]proxmox.Storage
+}
+
+func (f *fakeStorageClient) GetNodes(ctx context.Context) ([]proxmox.Node, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetNodeStatus(ctx context.Context, node string) (*proxmox.NodeStatus, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetNodeRRDData(ctx context.Context, node string, timeframe string, cf string, ds []string) ([]proxmox.NodeRRDPoint, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetVMs(ctx context.Context, node string) ([]proxmox.VM, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetContainers(ctx context.Context, node string) ([]proxmox.Container, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetStorage(ctx context.Context, node string) ([]proxmox.Storage, error) {
+ if storages, ok := f.storageByNode[node]; ok {
+ return storages, nil
+ }
+ return nil, fmt.Errorf("unexpected node: %s", node)
+}
+
+func (f *fakeStorageClient) GetAllStorage(ctx context.Context) ([]proxmox.Storage, error) {
+ return f.allStorage, nil
+}
+
+func (f *fakeStorageClient) GetBackupTasks(ctx context.Context) ([]proxmox.Task, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetStorageContent(ctx context.Context, node, storage string) ([]proxmox.StorageContent, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetVMSnapshots(ctx context.Context, node string, vmid int) ([]proxmox.Snapshot, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetContainerSnapshots(ctx context.Context, node string, vmid int) ([]proxmox.Snapshot, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetVMStatus(ctx context.Context, node string, vmid int) (*proxmox.VMStatus, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetContainerStatus(ctx context.Context, node string, vmid int) (*proxmox.Container, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetClusterResources(ctx context.Context, resourceType string) ([]proxmox.ClusterResource, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) IsClusterMember(ctx context.Context) (bool, error) {
+ return false, nil
+}
+
+func (f *fakeStorageClient) GetVMFSInfo(ctx context.Context, node string, vmid int) ([]proxmox.VMFileSystem, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetVMNetworkInterfaces(ctx context.Context, node string, vmid int) ([]proxmox.VMNetworkInterface, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetVMAgentInfo(ctx context.Context, node string, vmid int) (map[string]interface{}, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetZFSPoolStatus(ctx context.Context, node string) ([]proxmox.ZFSPoolStatus, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetZFSPoolsWithDetails(ctx context.Context, node string) ([]proxmox.ZFSPoolInfo, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetDisks(ctx context.Context, node string) ([]proxmox.Disk, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetCephStatus(ctx context.Context) (*proxmox.CephStatus, error) {
+ return nil, nil
+}
+
+func (f *fakeStorageClient) GetCephDF(ctx context.Context) (*proxmox.CephDF, error) {
+ return nil, nil
+}
+
+func TestPollStorageWithNodesOptimizedRecordsMetricsAndAlerts(t *testing.T) {
+ t.Setenv("PULSE_DATA_DIR", t.TempDir())
+
+ monitor := &Monitor{
+ state: &models.State{},
+ metricsHistory: NewMetricsHistory(16, time.Hour),
+ alertManager: alerts.NewManager(),
+ }
+ t.Cleanup(func() {
+ monitor.alertManager.Stop()
+ })
+
+ // Ensure storage alerts trigger immediately for the test.
+ cfg := monitor.alertManager.GetConfig()
+ cfg.MinimumDelta = 0
+ if cfg.TimeThresholds == nil {
+ cfg.TimeThresholds = make(map[string]int)
+ }
+ cfg.TimeThresholds["storage"] = 0
+ monitor.alertManager.UpdateConfig(cfg)
+
+ storage := proxmox.Storage{
+ Storage: "local",
+ Type: "dir",
+ Content: "images",
+ Active: 1,
+ Enabled: 1,
+ Shared: 0,
+ Total: 1000,
+ Used: 900,
+ Available: 100,
+ }
+
+ client := &fakeStorageClient{
+ allStorage: []proxmox.Storage{storage},
+ storageByNode: map[string][]proxmox.Storage{
+ "node1": {storage},
+ },
+ }
+
+ nodes := []proxmox.Node{
+ {Node: "node1", Status: "online"},
+ }
+
+ monitor.pollStorageWithNodesOptimized(context.Background(), "inst1", client, nodes)
+
+ metrics := monitor.metricsHistory.GetAllStorageMetrics("inst1-node1-local", time.Minute)
+ if len(metrics["usage"]) != 1 {
+ t.Fatalf("expected one usage metric entry, got %d", len(metrics["usage"]))
+ }
+ if len(metrics["used"]) != 1 {
+ t.Fatalf("expected one used metric entry, got %d", len(metrics["used"]))
+ }
+ if len(metrics["total"]) != 1 {
+ t.Fatalf("expected one total metric entry, got %d", len(metrics["total"]))
+ }
+ if len(metrics["avail"]) != 1 {
+ t.Fatalf("expected one avail metric entry, got %d", len(metrics["avail"]))
+ }
+
+ if diff := math.Abs(metrics["usage"][0].Value - 90); diff > 0.001 {
+ t.Fatalf("expected usage metric 90, diff %.4f", diff)
+ }
+ if diff := math.Abs(metrics["used"][0].Value - 900); diff > 0.001 {
+ t.Fatalf("expected used metric 900, diff %.4f", diff)
+ }
+ if diff := math.Abs(metrics["total"][0].Value - 1000); diff > 0.001 {
+ t.Fatalf("expected total metric 1000, diff %.4f", diff)
+ }
+ if diff := math.Abs(metrics["avail"][0].Value - 100); diff > 0.001 {
+ t.Fatalf("expected avail metric 100, diff %.4f", diff)
+ }
+
+ alerts := monitor.alertManager.GetActiveAlerts()
+ found := false
+ for _, alert := range alerts {
+ if alert.ID == "inst1-node1-local-usage" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected storage usage alert to be active")
+ }
+}
+
diff --git a/internal/monitoring/temperature.go b/internal/monitoring/temperature.go
index eed195b4f0..256ef9fffd 100644
--- a/internal/monitoring/temperature.go
+++ b/internal/monitoring/temperature.go
@@ -3,24 +3,43 @@ package monitoring
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"math"
+ "os"
"os/exec"
+ "path/filepath"
"strconv"
"strings"
+ "sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ssh/knownhosts"
"github.com/rcourtman/pulse-go-rewrite/internal/tempproxy"
"github.com/rs/zerolog/log"
)
+const (
+ proxyFailureThreshold = 3
+ proxyRetryInterval = 5 * time.Minute
+)
+
+type temperatureProxy interface {
+ IsAvailable() bool
+ GetTemperature(nodeHost string) (string, error)
+}
+
// TemperatureCollector handles SSH-based temperature collection from Proxmox nodes
type TemperatureCollector struct {
- sshUser string // SSH user (typically "root" or "pulse-monitor")
- sshKeyPath string // Path to SSH private key
- proxyClient *tempproxy.Client // Optional: unix socket client for proxy
- useProxy bool // Whether to use proxy for temperature collection
+ sshUser string // SSH user (typically "root" or "pulse-monitor")
+ sshKeyPath string // Path to SSH private key
+ proxyClient temperatureProxy // Optional: unix socket client for proxy
+ useProxy bool // Whether to use proxy for temperature collection
+ hostKeys knownhosts.Manager
+ proxyMu sync.Mutex
+ proxyFailures int
+ proxyCooldownUntil time.Time
}
// NewTemperatureCollector creates a new temperature collector
@@ -30,6 +49,17 @@ func NewTemperatureCollector(sshUser, sshKeyPath string) *TemperatureCollector {
sshKeyPath: sshKeyPath,
}
+ homeDir := os.Getenv("HOME")
+ if homeDir == "" {
+ homeDir = "/home/pulse"
+ }
+ knownHostsPath := filepath.Join(homeDir, ".ssh", "known_hosts_sensors")
+ if manager, err := knownhosts.NewManager(knownHostsPath); err != nil {
+ log.Warn().Err(err).Str("path", knownHostsPath).Msg("Failed to initialize temperature known_hosts manager")
+ } else {
+ tc.hostKeys = manager
+ }
+
// Check if proxy is available
proxyClient := tempproxy.NewClient()
if proxyClient.IsAvailable() {
@@ -53,9 +83,10 @@ func (tc *TemperatureCollector) CollectTemperature(ctx context.Context, nodeHost
var err error
// Use proxy if available, otherwise fall back to direct SSH
- if tc.useProxy && tc.proxyClient != nil {
+ if tc.isProxyEnabled() {
output, err = tc.proxyClient.GetTemperature(host)
if err != nil {
+ tc.handleProxyFailure(err)
log.Debug().
Str("node", nodeName).
Str("host", host).
@@ -63,8 +94,19 @@ func (tc *TemperatureCollector) CollectTemperature(ctx context.Context, nodeHost
Msg("Failed to collect temperature data via proxy")
return &models.Temperature{Available: false}, nil
}
+ tc.handleProxySuccess()
} else {
- // Direct SSH (legacy method)
+ // SECURITY: Block SSH fallback when running in containers (unless dev mode)
+ // Container compromise = SSH key compromise = root access to infrastructure
+ devModeAllowSSH := os.Getenv("PULSE_DEV_ALLOW_CONTAINER_SSH") == "true"
+ if isRunningInContainer() && !devModeAllowSSH {
+ log.Error().
+ Str("node", nodeName).
+ Msg("SECURITY BLOCK: SSH temperature collection disabled in containers - deploy pulse-sensor-proxy")
+ return &models.Temperature{Available: false}, nil
+ }
+
+ // Direct SSH (legacy method for non-containerized deployments)
// Try sensors first, fall back to Raspberry Pi method if that fails
output, err = tc.runSSHCommand(ctx, host, "sensors -j 2>/dev/null")
if err != nil || strings.TrimSpace(output) == "" {
@@ -108,13 +150,33 @@ func (tc *TemperatureCollector) CollectTemperature(ctx context.Context, nodeHost
// runSSHCommand executes a command on a remote node via SSH
func (tc *TemperatureCollector) runSSHCommand(ctx context.Context, host, command string) (string, error) {
+ if err := tc.ensureHostKey(ctx, host); err != nil {
+ return "", err
+ }
+
// Build SSH command with appropriate options
sshArgs := []string{
- "-o", "StrictHostKeyChecking=no",
- "-o", "UserKnownHostsFile=/dev/null",
- "-o", "ConnectTimeout=5",
- "-o", "BatchMode=yes", // No password prompts
+ "-o", "StrictHostKeyChecking=yes",
+ "-o", "BatchMode=yes",
"-o", "LogLevel=ERROR", // Suppress host key warnings that break JSON parsing
+ "-o", "ConnectTimeout=5",
+ }
+
+ if tc.hostKeys != nil && tc.hostKeys.Path() != "" {
+ sshArgs = append(sshArgs,
+ "-o", fmt.Sprintf("UserKnownHostsFile=%s", tc.hostKeys.Path()),
+ "-o", "GlobalKnownHostsFile=/dev/null",
+ )
+ }
+
+ // Explicitly use SSH config file if it exists (for ProxyJump configuration)
+ homeDir := os.Getenv("HOME")
+ if homeDir == "" {
+ homeDir = "/home/pulse"
+ }
+ sshConfigPath := filepath.Join(homeDir, ".ssh/config")
+ if _, err := os.Stat(sshConfigPath); err == nil {
+ sshArgs = append(sshArgs, "-F", sshConfigPath)
}
// Add key if specified
@@ -193,7 +255,8 @@ func (tc *TemperatureCollector) parseSensorsJSON(jsonStr string) (*models.Temper
strings.Contains(chipLower, "k8temp") ||
strings.Contains(chipLower, "acpitz") ||
strings.Contains(chipLower, "it87") ||
- strings.Contains(chipLower, "cpu_thermal") { // Raspberry Pi CPU temperature
+ strings.Contains(chipLower, "cpu_thermal") || // Raspberry Pi CPU temperature
+ strings.Contains(chipLower, "rpitemp") {
foundCPUChip = true
tc.parseCPUTemps(chipMap, temp)
}
@@ -268,8 +331,12 @@ func (tc *TemperatureCollector) parseCPUTemps(chipMap map[string]interface{}, te
// Look for generic temperature sensors (e.g., "temp1" on Raspberry Pi)
if strings.HasPrefix(sensorName, "temp") || strings.HasPrefix(sensorName, "Temp") {
if tempVal := extractTempInput(sensorMap); !math.IsNaN(tempVal) && tempVal > 0 {
- temp.CPUPackage = tempVal
- temp.CPUMax = tempVal
+ if temp.CPUPackage <= 0 {
+ temp.CPUPackage = tempVal
+ }
+ if tempVal > temp.CPUMax {
+ temp.CPUMax = tempVal
+ }
break // Use the first valid generic temp sensor
}
}
@@ -379,3 +446,88 @@ func extractHostname(hostURL string) string {
return host
}
+
+func (tc *TemperatureCollector) ensureHostKey(ctx context.Context, host string) error {
+ if tc.hostKeys == nil {
+ return nil
+ }
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ return tc.hostKeys.Ensure(ctx, host)
+}
+
+func (tc *TemperatureCollector) isProxyEnabled() bool {
+ if tc.proxyClient == nil {
+ return false
+ }
+
+ tc.proxyMu.Lock()
+ restored := false
+ if !tc.useProxy {
+ now := time.Now()
+ if now.After(tc.proxyCooldownUntil) {
+ if tc.proxyClient.IsAvailable() {
+ tc.useProxy = true
+ tc.proxyFailures = 0
+ tc.proxyCooldownUntil = time.Time{}
+ restored = true
+ } else {
+ tc.proxyCooldownUntil = now.Add(proxyRetryInterval)
+ }
+ }
+ }
+ useProxy := tc.useProxy
+ tc.proxyMu.Unlock()
+
+ if restored {
+ log.Info().Msg("Temperature proxy connection restored; resuming proxy collection")
+ }
+
+ return useProxy
+}
+
+func (tc *TemperatureCollector) handleProxySuccess() {
+ if tc.proxyClient == nil {
+ return
+ }
+ tc.proxyMu.Lock()
+ tc.proxyFailures = 0
+ tc.proxyMu.Unlock()
+}
+
+func (tc *TemperatureCollector) handleProxyFailure(err error) {
+ if tc.proxyClient == nil || !tc.shouldDisableProxy(err) {
+ return
+ }
+
+ tc.proxyMu.Lock()
+ tc.proxyFailures++
+ disable := tc.proxyFailures >= proxyFailureThreshold && tc.useProxy
+ if disable {
+ tc.useProxy = false
+ tc.proxyCooldownUntil = time.Now().Add(proxyRetryInterval)
+ tc.proxyFailures = 0
+ }
+ tc.proxyMu.Unlock()
+
+ if disable {
+ log.Warn().
+ Err(err).
+ Dur("cooldown", proxyRetryInterval).
+ Msg("Temperature proxy disabled after repeated failures; will retry later")
+ }
+}
+
+func (tc *TemperatureCollector) shouldDisableProxy(err error) bool {
+ var proxyErr *tempproxy.ProxyError
+ if errors.As(err, &proxyErr) {
+ switch proxyErr.Type {
+ case tempproxy.ErrorTypeTransport, tempproxy.ErrorTypeTimeout, tempproxy.ErrorTypeSSH:
+ return true
+ default:
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/monitoring/temperature_test.go b/internal/monitoring/temperature_test.go
index 1aa9070c25..d2d58ebc30 100644
--- a/internal/monitoring/temperature_test.go
+++ b/internal/monitoring/temperature_test.go
@@ -1,6 +1,59 @@
package monitoring
-import "testing"
+import (
+ "context"
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/tempproxy"
+)
+
+type stubProxyResponse struct {
+ output string
+ err error
+}
+
+type stubTemperatureProxy struct {
+ mu sync.Mutex
+ available bool
+ responses []stubProxyResponse
+ responseFunc func(call int) stubProxyResponse
+ callCount int
+}
+
+func (s *stubTemperatureProxy) IsAvailable() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.available
+}
+
+func (s *stubTemperatureProxy) GetTemperature(host string) (string, error) {
+ s.mu.Lock()
+ call := s.callCount
+ s.callCount++
+
+ resp := stubProxyResponse{}
+ switch {
+ case call < len(s.responses):
+ resp = s.responses[call]
+ case s.responseFunc != nil:
+ resp = s.responseFunc(call)
+ case len(s.responses) > 0:
+ resp = s.responses[len(s.responses)-1]
+ }
+ s.mu.Unlock()
+
+ return resp.output, resp.err
+}
+
+func (s *stubTemperatureProxy) setAvailable(v bool) {
+ s.mu.Lock()
+ s.available = v
+ s.mu.Unlock()
+}
func TestParseSensorsJSON_NoTemperatureData(t *testing.T) {
collector := &TemperatureCollector{}
@@ -80,6 +133,47 @@ func TestParseSensorsJSON_WithCpuAndNvmeData(t *testing.T) {
}
}
+func TestParseSensorsJSON_RPiWrapper(t *testing.T) {
+ collector := &TemperatureCollector{}
+
+ jsonStr := `{"rpitemp-virtual":{"temp1":{"temp1_input":47.5}}}`
+
+ temp, err := collector.parseSensorsJSON(jsonStr)
+ if err != nil {
+ t.Fatalf("unexpected error parsing wrapper output: %v", err)
+ }
+ if temp == nil {
+ t.Fatalf("expected temperature struct, got nil")
+ }
+ if !temp.HasCPU {
+ t.Fatalf("expected HasCPU to be true for wrapper output")
+ }
+ if temp.CPUPackage != 47.5 {
+ t.Fatalf("expected cpu package temperature 47.5, got %.2f", temp.CPUPackage)
+ }
+ if !temp.Available {
+ t.Fatalf("expected temperature to be available for wrapper output")
+ }
+}
+
+func TestShouldDisableProxy(t *testing.T) {
+ collector := &TemperatureCollector{}
+
+ if !collector.shouldDisableProxy(fmt.Errorf("plain")) {
+ t.Fatalf("expected plain errors to disable proxy")
+ }
+
+ transportErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport}
+ if !collector.shouldDisableProxy(transportErr) {
+ t.Fatalf("expected transport errors to disable proxy")
+ }
+
+ sensorErr := &tempproxy.ProxyError{Type: tempproxy.ErrorTypeSensor}
+ if collector.shouldDisableProxy(sensorErr) {
+ t.Fatalf("sensor errors should not disable proxy")
+ }
+}
+
// TestParseSensorsJSON_NVMeOnly tests that NVMe-only systems don't show "No CPU sensor"
func TestParseSensorsJSON_NVMeOnly(t *testing.T) {
collector := &TemperatureCollector{}
@@ -166,3 +260,274 @@ func TestParseSensorsJSON_ZeroTemperature(t *testing.T) {
t.Fatalf("expected core temperature to be 0.0, got %.2f", temp.Cores[0].Temp)
}
}
+
+func TestParseRPiTemperature(t *testing.T) {
+ collector := &TemperatureCollector{}
+ temp, err := collector.parseRPiTemperature("48720\n")
+ if err != nil {
+ t.Fatalf("unexpected error parsing RPi thermal zone output: %v", err)
+ }
+ if !temp.Available {
+ t.Fatalf("expected temperature to be marked available")
+ }
+ if !temp.HasCPU {
+ t.Fatalf("expected HasCPU to be true for RPi thermal zone output")
+ }
+ expected := 48.72
+ if diff := temp.CPUPackage - expected; diff > 1e-6 || diff < -1e-6 {
+ t.Fatalf("expected cpu package temperature %.2f, got %.2f", expected, temp.CPUPackage)
+ }
+ if temp.CPUMax != temp.CPUPackage {
+ t.Fatalf("expected cpu max to match package temperature %.2f, got %.2f", temp.CPUPackage, temp.CPUMax)
+ }
+ if temp.LastUpdate.IsZero() {
+ t.Fatalf("expected LastUpdate to be set")
+ }
+ if elapsed := time.Since(temp.LastUpdate); elapsed > 2*time.Second {
+ t.Fatalf("expected LastUpdate to be recent, got %s", elapsed)
+ }
+}
+
+func TestParseSensorsJSON_PiPartialSensors(t *testing.T) {
+ collector := &TemperatureCollector{}
+
+ jsonStr := `{
+ "cpu_thermal-virtual-0": {
+ "Adapter": "Virtual device",
+ "temp1": {"temp1_input": 51.625}
+ }
+ }`
+
+ temp, err := collector.parseSensorsJSON(jsonStr)
+ if err != nil {
+ t.Fatalf("unexpected error parsing Pi sensors output: %v", err)
+ }
+ if !temp.Available {
+ t.Fatalf("expected temperature to be available when cpu_thermal sensor present")
+ }
+ if !temp.HasCPU {
+ t.Fatalf("expected HasCPU to be true when cpu_thermal sensor present")
+ }
+ if temp.CPUPackage != 51.625 {
+ t.Fatalf("expected cpu package temperature 51.625, got %.3f", temp.CPUPackage)
+ }
+ if temp.CPUMax != 51.625 {
+ t.Fatalf("expected cpu max temperature 51.625, got %.3f", temp.CPUMax)
+ }
+ if len(temp.Cores) != 0 {
+ t.Fatalf("expected no per-core temperatures, got %d entries", len(temp.Cores))
+ }
+}
+
+func TestParseSensorsJSON_CoretempAndRPiFallback(t *testing.T) {
+ collector := &TemperatureCollector{}
+
+ jsonStr := `{
+ "coretemp-isa-0000": {
+ "Package id 0": {"temp1_input": 65.0},
+ "Core 0": {"temp2_input": 63.0},
+ "Core 1": {"temp3_input": 62.5}
+ },
+ "cpu_thermal-virtual-0": {
+ "temp1": {"temp1_input": 50.0}
+ }
+ }`
+
+ temp, err := collector.parseSensorsJSON(jsonStr)
+ if err != nil {
+ t.Fatalf("unexpected error parsing mixed sensors output: %v", err)
+ }
+ if temp.CPUPackage != 65.0 {
+ t.Fatalf("expected cpu package temperature 65.0 from coretemp, got %.2f", temp.CPUPackage)
+ }
+ if temp.CPUMax < 63.0 {
+ t.Fatalf("expected cpu max to reflect hottest core (>=63.0), got %.2f", temp.CPUMax)
+ }
+ if !temp.HasCPU {
+ t.Fatalf("expected HasCPU to be true when CPU sensors present")
+ }
+ if !temp.Available {
+ t.Fatalf("expected temperature to be available when CPU sensors present")
+ }
+}
+
+func TestTemperatureCollector_DisablesProxyAfterFailures(t *testing.T) {
+ stub := &stubTemperatureProxy{
+ responses: []stubProxyResponse{
+ {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transport failure 1"}},
+ {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transport failure 2"}},
+ {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transport failure 3"}},
+ },
+ }
+ stub.setAvailable(true)
+
+ collector := &TemperatureCollector{
+ proxyClient: stub,
+ useProxy: true,
+ }
+
+ ctx := context.Background()
+ for i := 0; i < proxyFailureThreshold; i++ {
+ temp, err := collector.CollectTemperature(ctx, "https://node.example", "node")
+ if err != nil {
+ t.Fatalf("unexpected error on proxy failure %d: %v", i+1, err)
+ }
+ if temp.Available {
+ t.Fatalf("expected temperature to be unavailable after proxy failure %d", i+1)
+ }
+ }
+
+ if collector.useProxy {
+ t.Fatalf("expected proxy to be disabled after %d failures", proxyFailureThreshold)
+ }
+ if collector.proxyFailures != 0 {
+ t.Fatalf("expected proxy failure counter to reset after disable, got %d", collector.proxyFailures)
+ }
+ if collector.proxyCooldownUntil.IsZero() {
+ t.Fatalf("expected proxy cooldown to be scheduled after disable")
+ }
+ if time.Until(collector.proxyCooldownUntil) <= 0 {
+ t.Fatalf("expected proxy cooldown to be in the future, got %s", collector.proxyCooldownUntil)
+ }
+}
+
+func TestTemperatureCollector_ProxyReenablesAfterCooldown(t *testing.T) {
+ stub := &stubTemperatureProxy{}
+ stub.setAvailable(true)
+
+ collector := &TemperatureCollector{
+ proxyClient: stub,
+ useProxy: false,
+ proxyCooldownUntil: time.Now().Add(-time.Minute),
+ }
+
+ if !collector.isProxyEnabled() {
+ t.Fatalf("expected proxy to re-enable when available after cooldown")
+ }
+ if !collector.useProxy {
+ t.Fatalf("expected useProxy to be true after proxy restored")
+ }
+ if !collector.proxyCooldownUntil.IsZero() {
+ t.Fatalf("expected cooldown to reset after proxy restoration, got %s", collector.proxyCooldownUntil)
+ }
+ if collector.proxyFailures != 0 {
+ t.Fatalf("expected proxy failure counter to reset after restoration, got %d", collector.proxyFailures)
+ }
+}
+
+func TestTemperatureCollector_ProxyCooldownExtendsWhenUnavailable(t *testing.T) {
+ stub := &stubTemperatureProxy{}
+ stub.setAvailable(false)
+
+ collector := &TemperatureCollector{
+ proxyClient: stub,
+ useProxy: false,
+ proxyCooldownUntil: time.Now().Add(-time.Minute),
+ }
+
+ before := time.Now()
+ if collector.isProxyEnabled() {
+ t.Fatalf("expected proxy to remain disabled while unavailable")
+ }
+ if collector.useProxy {
+ t.Fatalf("expected useProxy to remain false while proxy unavailable")
+ }
+ if !collector.proxyCooldownUntil.After(before) {
+ t.Fatalf("expected cooldown to be pushed into the future, got %s", collector.proxyCooldownUntil)
+ }
+}
+
+func TestTemperatureCollector_SuccessResetsFailureCount(t *testing.T) {
+ successJSON := `{"coretemp-isa-0000":{"Package id 0":{"temp1_input": 45.0}}}`
+ stub := &stubTemperatureProxy{
+ responses: []stubProxyResponse{
+ {err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transient failure"}},
+ {output: successJSON},
+ },
+ }
+ stub.setAvailable(true)
+
+ collector := &TemperatureCollector{
+ proxyClient: stub,
+ useProxy: true,
+ }
+
+ ctx := context.Background()
+ if temp, err := collector.CollectTemperature(ctx, "https://node.example", "node"); err != nil {
+ t.Fatalf("unexpected error during proxy failure: %v", err)
+ } else if temp.Available {
+ t.Fatalf("expected unavailable temperature on proxy failure")
+ }
+ if collector.proxyFailures != 1 {
+ t.Fatalf("expected proxy failure counter to increment to 1, got %d", collector.proxyFailures)
+ }
+
+ temp, err := collector.CollectTemperature(ctx, "https://node.example", "node")
+ if err != nil {
+ t.Fatalf("unexpected error on proxy success: %v", err)
+ }
+ if temp == nil || !temp.Available {
+ t.Fatalf("expected valid temperature after proxy success")
+ }
+ if collector.proxyFailures != 0 {
+ t.Fatalf("expected proxy failure counter reset after success, got %d", collector.proxyFailures)
+ }
+ if !collector.useProxy {
+ t.Fatalf("expected proxy to remain enabled after success")
+ }
+}
+
+func TestTemperatureCollector_ConcurrentCollectTemperature(t *testing.T) {
+ successJSON := `{"coretemp-isa-0000":{"Package id 0":{"temp1_input": 55.0}}}`
+ var callCounter int32
+ stub := &stubTemperatureProxy{
+ responseFunc: func(int) stubProxyResponse {
+ n := atomic.AddInt32(&callCounter, 1)
+ if n%2 == 1 {
+ return stubProxyResponse{
+ err: &tempproxy.ProxyError{Type: tempproxy.ErrorTypeTransport, Message: "transient transport error"},
+ }
+ }
+ return stubProxyResponse{output: successJSON}
+ },
+ }
+ stub.setAvailable(true)
+
+ collector := &TemperatureCollector{
+ proxyClient: stub,
+ useProxy: true,
+ }
+
+ const goroutines = 16
+ const iterations = 32
+
+ var wg sync.WaitGroup
+ wg.Add(goroutines)
+
+ ctx := context.Background()
+ for i := 0; i < goroutines; i++ {
+ go func() {
+ defer wg.Done()
+ for j := 0; j < iterations; j++ {
+ temp, err := collector.CollectTemperature(ctx, "https://node.example", "node")
+ if err != nil {
+ t.Errorf("collect temperature returned error: %v", err)
+ return
+ }
+ if temp == nil {
+ t.Errorf("expected non-nil temperature result")
+ return
+ }
+ }
+ }()
+ }
+
+ wg.Wait()
+
+ if !collector.useProxy {
+ t.Fatalf("expected proxy to remain enabled during concurrent collection")
+ }
+ if collector.proxyFailures >= proxyFailureThreshold {
+ t.Fatalf("expected proxy failures to stay below disable threshold, got %d", collector.proxyFailures)
+ }
+}
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index ff138a5ea7..8492869b00 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -268,8 +268,9 @@ type AppriseConfig struct {
// NewNotificationManager creates a new notification manager
func NewNotificationManager(publicURL string) *NotificationManager {
- if publicURL != "" {
- log.Info().Str("publicURL", publicURL).Msg("NotificationManager initialized with public URL")
+ cleanURL := strings.TrimRight(strings.TrimSpace(publicURL), "/")
+ if cleanURL != "" {
+ log.Info().Str("publicURL", cleanURL).Msg("NotificationManager initialized with public URL")
} else {
log.Info().Msg("NotificationManager initialized without public URL - webhook links may not work")
}
@@ -290,11 +291,36 @@ func NewNotificationManager(publicURL string) *NotificationManager {
groupByGuest: false,
webhookHistory: make([]WebhookDelivery, 0, WebhookHistoryMaxSize),
webhookRateLimits: make(map[string]*webhookRateLimit),
- publicURL: publicURL,
+ publicURL: cleanURL,
appriseExec: defaultAppriseExec,
}
}
+// SetPublicURL updates the public URL used for webhook payloads.
+func (n *NotificationManager) SetPublicURL(publicURL string) {
+ trimmed := strings.TrimRight(strings.TrimSpace(publicURL), "/")
+ if trimmed == "" {
+ return
+ }
+
+ n.mu.Lock()
+ if n.publicURL == trimmed {
+ n.mu.Unlock()
+ return
+ }
+ n.publicURL = trimmed
+ n.mu.Unlock()
+
+ log.Info().Str("publicURL", trimmed).Msg("NotificationManager public URL updated")
+}
+
+// GetPublicURL returns the configured public URL for notifications.
+func (n *NotificationManager) GetPublicURL() string {
+ n.mu.RLock()
+ defer n.mu.RUnlock()
+ return n.publicURL
+}
+
// SetEmailConfig updates email configuration
func (n *NotificationManager) SetEmailConfig(config EmailConfig) {
n.mu.Lock()
diff --git a/internal/ssh/knownhosts/manager.go b/internal/ssh/knownhosts/manager.go
new file mode 100644
index 0000000000..eb076f832b
--- /dev/null
+++ b/internal/ssh/knownhosts/manager.go
@@ -0,0 +1,279 @@
+package knownhosts
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Manager exposes operations for ensuring SSH host keys exist locally.
+type Manager interface {
+ // Ensure guarantees that the host key for the provided host exists in the
+ // managed known_hosts file.
+ Ensure(ctx context.Context, host string) error
+ // Path returns the absolute path to the managed known_hosts file.
+ Path() string
+}
+
+type manager struct {
+ path string
+ cache map[string]struct{}
+ mu sync.Mutex
+ keyscanFn keyscanFunc
+ keyscanTimeout time.Duration
+}
+
+type keyscanFunc func(ctx context.Context, host string, timeout time.Duration) ([]byte, error)
+
+const (
+ defaultKeyscanTimeout = 5 * time.Second
+)
+
+var (
+ // ErrNoHostKeys is returned when ssh-keyscan yields no usable entries.
+ ErrNoHostKeys = errors.New("knownhosts: no host keys discovered")
+)
+
+// Option allows customizing Manager construction.
+type Option func(*manager)
+
+// WithTimeout overrides the ssh-keyscan timeout (defaults to 5 seconds).
+func WithTimeout(d time.Duration) Option {
+ return func(m *manager) {
+ if d > 0 {
+ m.keyscanTimeout = d
+ }
+ }
+}
+
+// WithKeyscanFunc overrides the function used to fetch host keys (mainly for tests).
+func WithKeyscanFunc(fn keyscanFunc) Option {
+ return func(m *manager) {
+ if fn != nil {
+ m.keyscanFn = fn
+ }
+ }
+}
+
+// NewManager returns a Manager writing to the supplied known_hosts path.
+func NewManager(path string, opts ...Option) (Manager, error) {
+ if strings.TrimSpace(path) == "" {
+ return nil, fmt.Errorf("knownhosts: empty path")
+ }
+
+ m := &manager{
+ path: path,
+ cache: make(map[string]struct{}),
+ keyscanFn: defaultKeyscan,
+ keyscanTimeout: defaultKeyscanTimeout,
+ }
+
+ for _, opt := range opts {
+ opt(m)
+ }
+
+ return m, nil
+}
+
+// Ensure implements Manager.Ensure.
+func (m *manager) Ensure(ctx context.Context, host string) error {
+ if strings.TrimSpace(host) == "" {
+ return fmt.Errorf("knownhosts: missing host")
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if _, ok := m.cache[host]; ok {
+ return nil
+ }
+
+ if err := m.ensureKnownHostsFile(); err != nil {
+ return err
+ }
+
+ exists, err := hostKeyExists(m.path, host)
+ if err != nil {
+ return err
+ }
+ if exists {
+ m.cache[host] = struct{}{}
+ return nil
+ }
+
+ keyData, err := m.keyscanFn(ctx, host, m.keyscanTimeout)
+ if err != nil {
+ return fmt.Errorf("knownhosts: ssh-keyscan failed for %s: %w", host, err)
+ }
+
+ entries := sanitizeKeyscanOutput(host, keyData)
+ if len(entries) == 0 {
+ return fmt.Errorf("%w for %s", ErrNoHostKeys, host)
+ }
+
+ if err := appendHostKey(m.path, entries); err != nil {
+ return err
+ }
+
+ m.cache[host] = struct{}{}
+ return nil
+}
+
+// Path implements Manager.Path.
+func (m *manager) Path() string {
+ return m.path
+}
+
+func (m *manager) ensureKnownHostsFile() error {
+ dir := filepath.Dir(m.path)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return fmt.Errorf("knownhosts: mkdir %s: %w", dir, err)
+ }
+
+ if _, err := os.Stat(m.path); err == nil {
+ return nil
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+
+ f, err := os.OpenFile(m.path, os.O_CREATE|os.O_WRONLY, 0o600)
+ if err != nil {
+ return fmt.Errorf("knownhosts: create %s: %w", m.path, err)
+ }
+ return f.Close()
+}
+
+func hostKeyExists(path, host string) (bool, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ if hostLineMatches(host, scanner.Text()) {
+ return true, nil
+ }
+ }
+ return false, scanner.Err()
+}
+
+func appendHostKey(path string, entries [][]byte) error {
+ f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
+ if err != nil {
+ return fmt.Errorf("knownhosts: open %s: %w", path, err)
+ }
+ defer f.Close()
+
+ for _, entry := range entries {
+ if len(entry) == 0 {
+ continue
+ }
+ if _, err := f.Write(append(entry, '\n')); err != nil {
+ return fmt.Errorf("knownhosts: write entry: %w", err)
+ }
+ }
+ return nil
+}
+
+func sanitizeKeyscanOutput(host string, raw []byte) [][]byte {
+ var entries [][]byte
+
+ lines := bytes.Split(raw, []byte{'\n'})
+ for _, line := range lines {
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ continue
+ }
+ if hostLineMatches(host, string(line)) {
+ entries = append(entries, line)
+ }
+ }
+
+ return entries
+}
+
+func hostLineMatches(host, line string) bool {
+ trimmed := strings.TrimSpace(line)
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+ return false
+ }
+ if strings.HasPrefix(trimmed, "|") {
+ return false // hashed entry; we only manage clear-text hosts
+ }
+
+ fields := strings.Fields(trimmed)
+ if len(fields) == 0 {
+ return false
+ }
+
+ return hostFieldMatches(host, fields[0])
+}
+
+func hostFieldMatches(host, field string) bool {
+ for _, part := range strings.Split(field, ",") {
+ for _, candidate := range hostCandidates(part) {
+ if strings.EqualFold(candidate, host) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func hostCandidates(part string) []string {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ return nil
+ }
+
+ if strings.HasPrefix(part, "[") {
+ if idx := strings.Index(part, "]"); idx != -1 {
+ host := part[1:idx]
+ candidates := []string{part}
+ if host != "" {
+ candidates = append(candidates, host)
+ }
+ return candidates
+ }
+ }
+
+ candidates := []string{part}
+ if strings.Count(part, ":") == 1 {
+ if idx := strings.Index(part, ":"); idx > 0 {
+ candidates = append(candidates, part[:idx])
+ }
+ }
+
+ return candidates
+}
+
+func defaultKeyscan(ctx context.Context, host string, timeout time.Duration) ([]byte, error) {
+ seconds := int(timeout.Round(time.Second) / time.Second)
+ if seconds <= 0 {
+ seconds = int(defaultKeyscanTimeout / time.Second)
+ }
+
+ scanCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+
+ cmd := exec.CommandContext(scanCtx, "ssh-keyscan", "-T", strconv.Itoa(seconds), host)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return nil, fmt.Errorf("%w (output: %s)", err, strings.TrimSpace(string(output)))
+ }
+ return output, nil
+}
diff --git a/internal/ssh/knownhosts/manager_test.go b/internal/ssh/knownhosts/manager_test.go
new file mode 100644
index 0000000000..9d741c0e29
--- /dev/null
+++ b/internal/ssh/knownhosts/manager_test.go
@@ -0,0 +1,133 @@
+package knownhosts
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestEnsureCreatesFileAndCaches(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "known_hosts")
+
+ var calls int
+ keyscan := func(ctx context.Context, host string, timeout time.Duration) ([]byte, error) {
+ calls++
+ return []byte(host + " ssh-ed25519 AAAA"), nil
+ }
+
+ mgr, err := NewManager(path, WithKeyscanFunc(keyscan))
+ if err != nil {
+ t.Fatalf("NewManager: %v", err)
+ }
+
+ ctx := context.Background()
+ if err := mgr.Ensure(ctx, "example.com"); err != nil {
+ t.Fatalf("Ensure: %v", err)
+ }
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("known_hosts not created: %v", err)
+ }
+
+ if err := mgr.Ensure(ctx, "example.com"); err != nil {
+ t.Fatalf("Ensure second call: %v", err)
+ }
+ if calls != 1 {
+ t.Fatalf("expected keyscan once, got %d", calls)
+ }
+}
+
+func TestEnsureUsesSanitizedOutput(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "known_hosts")
+
+ keyscan := func(ctx context.Context, host string, timeout time.Duration) ([]byte, error) {
+ return []byte(`# comment
+example.com ssh-ed25519 AAAA
+example.com,192.0.2.10 ssh-rsa BBBB
+other.com ssh-ed25519 CCCC
+`), nil
+ }
+
+ mgr, err := NewManager(path, WithKeyscanFunc(keyscan))
+ if err != nil {
+ t.Fatalf("NewManager: %v", err)
+ }
+
+ if err := mgr.Ensure(context.Background(), "example.com"); err != nil {
+ t.Fatalf("Ensure: %v", err)
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("ReadFile: %v", err)
+ }
+ if want := "example.com ssh-ed25519 AAAA\nexample.com,192.0.2.10 ssh-rsa BBBB\n"; string(data) != want {
+ t.Fatalf("unexpected known_hosts contents\nwant:\n%s\ngot:\n%s", want, data)
+ }
+}
+
+func TestEnsureReturnsErrorWhenNoEntries(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "known_hosts")
+
+ mgr, err := NewManager(path, WithKeyscanFunc(func(ctx context.Context, host string, timeout time.Duration) ([]byte, error) {
+ return []byte("|1|hash|salt ssh-ed25519 AAAA\n"), nil
+ }))
+ if err != nil {
+ t.Fatalf("NewManager: %v", err)
+ }
+
+ err = mgr.Ensure(context.Background(), "example.com")
+ if !errors.Is(err, ErrNoHostKeys) {
+ t.Fatalf("expected ErrNoHostKeys, got %v", err)
+ }
+}
+
+func TestEnsureRespectsContextCancellation(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "known_hosts")
+
+ keyscan := func(ctx context.Context, host string, timeout time.Duration) ([]byte, error) {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+
+ mgr, err := NewManager(path, WithKeyscanFunc(keyscan), WithTimeout(50*time.Millisecond))
+ if err != nil {
+ t.Fatalf("NewManager: %v", err)
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ if err := mgr.Ensure(ctx, "example.com"); err == nil {
+ t.Fatalf("expected context error, got nil")
+ }
+}
+
+func TestHostCandidates(t *testing.T) {
+ tests := []struct {
+ input string
+ want []string
+ }{
+ {"example.com", []string{"example.com"}},
+ {"example.com:2222", []string{"example.com:2222", "example.com"}},
+ {"[example.com]:2222", []string{"[example.com]:2222", "example.com"}},
+ }
+
+ for _, tt := range tests {
+ got := hostCandidates(tt.input)
+ if len(got) != len(tt.want) {
+ t.Fatalf("hostCandidates(%q) len = %d, want %d", tt.input, len(got), len(tt.want))
+ }
+ for i := range got {
+ if got[i] != tt.want[i] {
+ t.Fatalf("hostCandidates(%q)[%d] = %q, want %q", tt.input, i, got[i], tt.want[i])
+ }
+ }
+ }
+}
diff --git a/pkg/proxmox/cluster_client.go b/pkg/proxmox/cluster_client.go
index fecc176bd5..a7a1f7f185 100644
--- a/pkg/proxmox/cluster_client.go
+++ b/pkg/proxmox/cluster_client.go
@@ -4,6 +4,8 @@ import (
"context"
"fmt"
"math/rand"
+ "regexp"
+ "strconv"
"strings"
"sync"
"time"
@@ -22,6 +24,24 @@ type ClusterClient struct {
lastHealthCheck map[string]time.Time // Track last health check time
lastUsedIndex int // For round-robin
config ClientConfig // Base config (auth info)
+ rateLimitUntil map[string]time.Time // Cooldown window for rate-limited endpoints
+}
+
+const (
+ rateLimitBaseDelay = 150 * time.Millisecond
+ rateLimitMaxJitter = 200 * time.Millisecond
+ rateLimitRetryBudget = 2
+)
+
+var statusCodePattern = regexp.MustCompile(`(?i)(?:api error|status)\s+(\d{3})`)
+
+var transientRateLimitStatusCodes = map[int]struct{}{
+ 408: {},
+ 425: {}, // Too Early
+ 429: {},
+ 502: {},
+ 503: {},
+ 504: {},
}
// NewClusterClient creates a new cluster-aware client
@@ -33,6 +53,7 @@ func NewClusterClient(name string, config ClientConfig, endpoints []string) *Clu
nodeHealth: make(map[string]bool),
lastHealthCheck: make(map[string]time.Time),
config: config,
+ rateLimitUntil: make(map[string]time.Time),
}
// Initialize all endpoints as unknown (will be tested on first use)
@@ -163,12 +184,26 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)
// Get list of healthy endpoints
var healthyEndpoints []string
+ var coolingEndpoints []string
+ now := time.Now()
for endpoint, healthy := range cc.nodeHealth {
if healthy {
+ if cooldown, exists := cc.rateLimitUntil[endpoint]; exists {
+ if now.Before(cooldown) {
+ coolingEndpoints = append(coolingEndpoints, endpoint)
+ continue
+ }
+ delete(cc.rateLimitUntil, endpoint)
+ }
healthyEndpoints = append(healthyEndpoints, endpoint)
}
}
+ if len(healthyEndpoints) == 0 && len(coolingEndpoints) > 0 {
+ // Nothing is immediately available, fall back to endpoints that are in cooldown
+ healthyEndpoints = append(healthyEndpoints, coolingEndpoints...)
+ }
+
log.Debug().
Str("cluster", cc.name).
Int("healthy", len(healthyEndpoints)).
@@ -238,28 +273,38 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)
cancel()
if testErr != nil {
- // Check if this is a VM-specific error that shouldn't mark the node unhealthy
- testErrStr := testErr.Error()
- if strings.Contains(testErrStr, "No QEMU guest agent") ||
- strings.Contains(testErrStr, "QEMU guest agent is not running") ||
- strings.Contains(testErrStr, "guest agent") {
- // This is a VM-specific issue, not a connectivity problem
- // The node is actually healthy, so don't mark it unhealthy
+ // Check if this is a transient rate limit error that shouldn't mark the node unhealthy
+ if isRateLimited, _ := isTransientRateLimitError(testErr); isRateLimited {
log.Debug().
Str("cluster", cc.name).
Str("endpoint", selectedEndpoint).
Err(testErr).
- Msg("Ignoring VM-specific error during connectivity test")
- // Continue with client creation since the node is actually accessible
+ Msg("Ignoring transient rate limit error during connectivity test")
+ // Continue with client creation since the node is accessible, just rate limited
} else {
- // Mark as unhealthy for real connectivity issues
- cc.nodeHealth[selectedEndpoint] = false
- log.Warn().
- Str("cluster", cc.name).
- Str("endpoint", selectedEndpoint).
- Err(testErr).
- Msg("Cluster endpoint failed connectivity test")
- return nil, fmt.Errorf("endpoint %s failed connectivity test: %w", selectedEndpoint, testErr)
+ // Check if this is a VM-specific error that shouldn't mark the node unhealthy
+ testErrStr := testErr.Error()
+ if strings.Contains(testErrStr, "No QEMU guest agent") ||
+ strings.Contains(testErrStr, "QEMU guest agent is not running") ||
+ strings.Contains(testErrStr, "guest agent") {
+ // This is a VM-specific issue, not a connectivity problem
+ // The node is actually healthy, so don't mark it unhealthy
+ log.Debug().
+ Str("cluster", cc.name).
+ Str("endpoint", selectedEndpoint).
+ Err(testErr).
+ Msg("Ignoring VM-specific error during connectivity test")
+ // Continue with client creation since the node is actually accessible
+ } else {
+ // Mark as unhealthy for real connectivity issues
+ cc.nodeHealth[selectedEndpoint] = false
+ log.Warn().
+ Str("cluster", cc.name).
+ Str("endpoint", selectedEndpoint).
+ Err(testErr).
+ Msg("Cluster endpoint failed connectivity test")
+ return nil, fmt.Errorf("endpoint %s failed connectivity test: %w", selectedEndpoint, testErr)
+ }
}
}
@@ -400,7 +445,9 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {
// executeWithFailover executes a function with automatic failover
func (cc *ClusterClient) executeWithFailover(ctx context.Context, fn func(*Client) error) error {
- maxRetries := len(cc.endpoints)
+ baseRetries := len(cc.endpoints)
+ maxRetries := baseRetries + rateLimitRetryBudget
+ var lastErr error
log.Debug().
Str("cluster", cc.name).
@@ -434,6 +481,7 @@ func (cc *ClusterClient) executeWithFailover(ctx context.Context, fn func(*Clien
if err == nil {
return nil
}
+ lastErr = err
// Check error type and content
errStr := err.Error()
@@ -467,6 +515,34 @@ func (cc *ClusterClient) executeWithFailover(ctx context.Context, fn func(*Clien
return err
}
+ if isRateLimited, statusCode := isTransientRateLimitError(err); isRateLimited {
+ backoff := calculateRateLimitBackoff(i)
+ cc.applyRateLimitCooldown(clientEndpoint, backoff)
+
+ event := log.Warn().
+ Str("cluster", cc.name).
+ Str("endpoint", clientEndpoint).
+ Err(err).
+ Dur("backoff", backoff).
+ Int("attempt", i+1)
+ if statusCode != 0 {
+ event = event.Int("status", statusCode)
+ }
+ event.Msg("Rate limited by cluster node, retrying with backoff")
+
+ timer := time.NewTimer(backoff)
+ select {
+ case <-ctx.Done():
+ if !timer.Stop() {
+ <-timer.C
+ }
+ return fmt.Errorf("context canceled while backing off after rate limit: %w", ctx.Err())
+ case <-timer.C:
+ }
+
+ continue
+ }
+
// Check if it's an auth error - don't retry on auth errors
if IsAuthError(err) {
return err
@@ -483,9 +559,75 @@ func (cc *ClusterClient) executeWithFailover(ctx context.Context, fn func(*Clien
Msg("Failed on cluster node, trying next")
}
+ if lastErr != nil {
+ return fmt.Errorf("all cluster nodes failed for %s: %w", cc.name, lastErr)
+ }
+
return fmt.Errorf("all cluster nodes failed for %s", cc.name)
}
+func (cc *ClusterClient) applyRateLimitCooldown(endpoint string, backoff time.Duration) {
+ if endpoint == "" {
+ return
+ }
+
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ if cc.rateLimitUntil == nil {
+ cc.rateLimitUntil = make(map[string]time.Time)
+ }
+ cc.rateLimitUntil[endpoint] = time.Now().Add(backoff)
+}
+
+func calculateRateLimitBackoff(attempt int) time.Duration {
+ // Linear backoff with jitter keeps retries gentle while avoiding thundering herd
+ base := rateLimitBaseDelay * time.Duration(attempt+1)
+ if rateLimitMaxJitter <= 0 {
+ return base
+ }
+
+ jitter := time.Duration(rand.Int63n(rateLimitMaxJitter.Nanoseconds()+1)) * time.Nanosecond
+ return base + jitter
+}
+
+func isTransientRateLimitError(err error) (bool, int) {
+ if err == nil {
+ return false, 0
+ }
+
+ errStr := err.Error()
+ statusCode := extractStatusCode(errStr)
+ if statusCode != 0 {
+ if _, ok := transientRateLimitStatusCodes[statusCode]; ok {
+ return true, statusCode
+ }
+ }
+
+ lowerErr := strings.ToLower(errStr)
+ if strings.Contains(lowerErr, "rate limit") || strings.Contains(lowerErr, "too many requests") {
+ if statusCode == 0 {
+ statusCode = 429
+ }
+ return true, statusCode
+ }
+
+ return false, statusCode
+}
+
+func extractStatusCode(errStr string) int {
+ matches := statusCodePattern.FindStringSubmatch(errStr)
+ if len(matches) != 2 {
+ return 0
+ }
+
+ code, err := strconv.Atoi(matches[1])
+ if err != nil {
+ return 0
+ }
+
+ return code
+}
+
// GetHealthStatus returns the health status of all nodes
func (cc *ClusterClient) GetHealthStatus() map[string]bool {
cc.mu.RLock()
diff --git a/pkg/proxmox/cluster_client_test.go b/pkg/proxmox/cluster_client_test.go
new file mode 100644
index 0000000000..f1e63bc3dc
--- /dev/null
+++ b/pkg/proxmox/cluster_client_test.go
@@ -0,0 +1,65 @@
+package proxmox
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestClusterClientHandlesRateLimitWithoutMarkingUnhealthy(t *testing.T) {
+ var requestCount int32
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api2/json/nodes":
+ current := atomic.AddInt32(&requestCount, 1)
+ if current == 1 {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusTooManyRequests)
+ fmt.Fprint(w, `{"error":"rate limited"}`)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"data":[{"node":"node1","status":"online","cpu":0,"maxcpu":1,"mem":0,"maxmem":1,"disk":0,"maxdisk":1,"uptime":1,"level":"normal"}]}`)
+ default:
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"data":{}}`)
+ }
+ }))
+ defer server.Close()
+
+ cfg := ClientConfig{
+ Host: server.URL,
+ TokenName: "pulse@pve!token",
+ TokenValue: "sometokenvalue",
+ VerifySSL: false,
+ Timeout: 2 * time.Second,
+ }
+
+ cc := NewClusterClient("test-cluster", cfg, []string{server.URL})
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ nodes, err := cc.GetNodes(ctx)
+ if err != nil {
+ t.Fatalf("expected GetNodes to succeed after retry, got error: %v", err)
+ }
+
+ if len(nodes) != 1 {
+ t.Fatalf("expected 1 node after retry, got %d", len(nodes))
+ }
+
+ health := cc.GetHealthStatus()
+ if healthy, ok := health[server.URL]; !ok || !healthy {
+ t.Fatalf("expected endpoint %s to remain healthy, got health map: %+v", server.URL, health)
+ }
+
+ if atomic.LoadInt32(&requestCount) < 2 {
+ t.Fatalf("expected at least 2 requests to backend, got %d", requestCount)
+ }
+}
diff --git a/scripts/context-audit-claude.sh b/scripts/context-audit-claude.sh
deleted file mode 100755
index 6d87044fc3..0000000000
--- a/scripts/context-audit-claude.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/usr/bin/env bash
-# Identify files that will bloat Claude Code's context window.
-
-set -euo pipefail
-
-ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
-cd "$ROOT_DIR"
-
-echo "Scanning modified files that exceed size thresholds..."
-echo
-
-git status --short | awk '{print $2}' | while read -r file; do
- [ -f "$file" ] || continue
- bytes=$(wc -c < "$file")
- if [ "$bytes" -ge 65536 ]; then
- lines=$(wc -l < "$file")
- printf "%8d bytes %7d lines %s\n" "$bytes" "$lines" "$file"
- fi
-done
-
-echo
-echo "Tip: stash or split these files when you do not need Claude to inspect them directly."
diff --git a/scripts/create-sensor-user.sh b/scripts/create-sensor-user.sh
new file mode 100755
index 0000000000..9bdb2e238d
--- /dev/null
+++ b/scripts/create-sensor-user.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [[ $EUID -ne 0 ]]; then
+ echo "Run as root." >&2
+ exit 1
+fi
+
+SERVICE_USER="pulse-sensor"
+SERVICE_GROUP="$SERVICE_USER"
+HOME_DIR="/opt/pulse/sensor-proxy"
+BIN_DIR="$HOME_DIR/bin"
+CONFIG_DIR="$HOME_DIR/etc"
+SSH_DIR="$HOME_DIR/.ssh"
+LOG_DIR="/var/log/pulse/sensor-proxy"
+SUDOERS_FILE="/etc/sudoers.d/pulse-sensor-proxy"
+NOLOGIN_SHELL="/usr/sbin/nologin"
+
+if id -u "$SERVICE_USER" >/dev/null 2>&1; then
+ usermod --home "$HOME_DIR" --shell "$NOLOGIN_SHELL" "$SERVICE_USER"
+else
+ useradd --system --home "$HOME_DIR" --shell "$NOLOGIN_SHELL" --user-group "$SERVICE_USER"
+fi
+
+install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$HOME_DIR"
+install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$BIN_DIR"
+install -d -o root -g "$SERVICE_GROUP" -m 0750 "$CONFIG_DIR"
+install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0700 "$SSH_DIR"
+install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$LOG_DIR"
+
+TMP_SUDOERS="$(mktemp)"
+trap 'rm -f "$TMP_SUDOERS"' EXIT
+
+cat >"$TMP_SUDOERS" <<'EOF'
+pulse-sensor ALL=(root) NOPASSWD: /usr/bin/sensors, /usr/sbin/ipmitool
+EOF
+
+install -o root -g root -m 0440 "$TMP_SUDOERS" "$SUDOERS_FILE"
+
+if ! visudo -cf "$SUDOERS_FILE" >/dev/null; then
+ echo "sudoers validation failed" >&2
+ exit 1
+fi
+
+echo "User $(id "$SERVICE_USER")"
+namei -om "$BIN_DIR" >/dev/null
+namei -om "$CONFIG_DIR" >/dev/null
+namei -om "$SSH_DIR" >/dev/null
+namei -om "$LOG_DIR" >/dev/null
+
+echo "Sudo privileges for $SERVICE_USER:"
+sudo -l -U "$SERVICE_USER" || true
+
+echo "pulse-sensor service account ready."
diff --git a/scripts/dev-orchestrator.sh b/scripts/dev-orchestrator.sh
index 5fbe4080e7..cd76bdf94b 100755
--- a/scripts/dev-orchestrator.sh
+++ b/scripts/dev-orchestrator.sh
@@ -1,6 +1,6 @@
#!/bin/bash
# Dev Environment Orchestrator
-# Provides complete state detection and control for Claude Code
+# Provides complete state detection and control for development tools
set -eo pipefail
@@ -239,7 +239,7 @@ cmd_status() {
echo -e " Built: $([ "$frontend_built" = "true" ] && echo -e "${GREEN}Yes${NC}" || echo -e "${RED}No${NC}")"
fi
- # JSON output for Claude
+ # JSON output for automation tools
if [ "$1" = "--json" ]; then
echo ""
echo "$state"
diff --git a/scripts/docker-build.sh b/scripts/docker-build.sh
new file mode 100755
index 0000000000..75c9cb2be2
--- /dev/null
+++ b/scripts/docker-build.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Simple wrapper that enables BuildKit and forwards all arguments.
+# To skip building multi-arch agents set BUILD_AGENT=0 before invoking.
+
+export DOCKER_BUILDKIT=1
+
+docker build "$@"
diff --git a/scripts/harden-sensor-proxy.sh b/scripts/harden-sensor-proxy.sh
new file mode 100755
index 0000000000..81f2b3f0cf
--- /dev/null
+++ b/scripts/harden-sensor-proxy.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+FORCE_COMMAND="${FORCE_COMMAND:-/opt/pulse/bin/sensor-proxy-wrapper}"
+CONF_PATH="/etc/ssh/sshd_config.d/pulse-sensor-proxy.conf"
+
+if [[ ! -x "$FORCE_COMMAND" ]]; then
+ echo "Error: FORCE_COMMAND '$FORCE_COMMAND' not found or not executable" >&2
+ exit 1
+fi
+
+TMP_CONF="$(mktemp)"
+trap 'rm -f "$TMP_CONF"' EXIT
+
+cat >"$TMP_CONF" <<EOF
+# Hardening for Pulse sensor proxy access
+PasswordAuthentication no
+KbdInteractiveAuthentication no
+ChallengeResponseAuthentication no
+PermitRootLogin no
+AllowAgentForwarding no
+AllowTcpForwarding no
+PermitTunnel no
+X11Forwarding no
+PermitUserEnvironment no
+ForceCommand $FORCE_COMMAND
+EOF
+
+install -o root -g root -m 0644 "$TMP_CONF" "$CONF_PATH"
+
+sshd -t
+systemctl reload sshd
+
+echo "sshd hardening applied to $CONF_PATH"
+
+# Verification
+echo "Verifying hardening settings:"
+sshd -T | grep -E 'passwordauthentication|allowagentforwarding|allowtcpforwarding|x11forwarding|permittunnel' || true
diff --git a/scripts/hot-dev.sh b/scripts/hot-dev.sh
index f96f97c3b6..bc60615350 100755
--- a/scripts/hot-dev.sh
+++ b/scripts/hot-dev.sh
@@ -47,6 +47,14 @@ export FRONTEND_PORT PORT
export FRONTEND_DEV_HOST FRONTEND_DEV_PORT
export PULSE_DEV_API_HOST PULSE_DEV_API_PORT PULSE_DEV_API_URL PULSE_DEV_WS_URL
+# Auto-detect pulse-sensor-proxy socket if available
+if [[ -z ${PULSE_SENSOR_PROXY_SOCKET:-} ]]; then
+ if [[ -S /mnt/pulse-proxy/pulse-sensor-proxy.sock ]]; then
+ export PULSE_SENSOR_PROXY_SOCKET=/mnt/pulse-proxy/pulse-sensor-proxy.sock
+ printf "[hot-dev] Detected pulse-sensor-proxy socket at %s\n" "${PULSE_SENSOR_PROXY_SOCKET}"
+ fi
+fi
+
EXTRA_CLEANUP_PORT=$((PULSE_DEV_API_PORT + 1))
cat <<BANNER
diff --git a/scripts/install-docker.sh b/scripts/install-docker.sh
index 0f266f2001..5450142a2f 100644
--- a/scripts/install-docker.sh
+++ b/scripts/install-docker.sh
@@ -41,7 +41,7 @@ echo " Pulse Turnkey Docker Installation"
echo "============================================"
echo ""
-# Check if running as root (early check per Codex feedback)
+# Check if running as root (early check for better error messages)
if [ "$EUID" -ne 0 ]; then
echo "❌ ERROR: This script must be run as root"
echo ""
diff --git a/scripts/install-sensor-proxy.sh b/scripts/install-sensor-proxy.sh
index 59203955ad..32dbf7f012 100755
--- a/scripts/install-sensor-proxy.sh
+++ b/scripts/install-sensor-proxy.sh
@@ -236,6 +236,7 @@ fi
print_info "Setting up directories with proper ownership..."
install -d -o pulse-sensor-proxy -g pulse-sensor-proxy -m 0750 /var/lib/pulse-sensor-proxy
install -d -o pulse-sensor-proxy -g pulse-sensor-proxy -m 0700 "$SSH_DIR"
+install -m 0600 -o pulse-sensor-proxy -g pulse-sensor-proxy /dev/null "$SSH_DIR/known_hosts"
install -d -o pulse-sensor-proxy -g pulse-sensor-proxy -m 0755 /etc/pulse-sensor-proxy
# Create config file with ACL for Docker containers (standalone mode)
diff --git a/scripts/secure-sensor-files.sh b/scripts/secure-sensor-files.sh
new file mode 100755
index 0000000000..67a940bbb9
--- /dev/null
+++ b/scripts/secure-sensor-files.sh
@@ -0,0 +1,89 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [[ $EUID -ne 0 ]]; then
+ echo "Run as root." >&2
+ exit 1
+fi
+
+SERVICE_USER="pulse-sensor"
+SERVICE_GROUP="$SERVICE_USER"
+HOME_DIR="/opt/pulse/sensor-proxy"
+BIN_PATH="$HOME_DIR/bin/pulse-sensor-proxy"
+SSH_DIR="$HOME_DIR/.ssh"
+PRIVATE_KEY="$SSH_DIR/id_ed25519"
+PUBLIC_KEY="$SSH_DIR/id_ed25519.pub"
+KNOWN_HOSTS="$SSH_DIR/known_hosts"
+LOG_DIR="/var/log/pulse/sensor-proxy"
+LOG_FILE="$LOG_DIR/proxy.log"
+AUDIT_LOG="$LOG_DIR/audit.log"
+
+umask 077
+
+install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0700 "$SSH_DIR"
+
+if [[ ! -f "$PRIVATE_KEY" ]]; then
+ sudo -u "$SERVICE_USER" ssh-keygen -t ed25519 -N '' -C "pulse-sensor@$(hostname -f)" -f "$PRIVATE_KEY"
+else
+ chown "$SERVICE_USER:$SERVICE_GROUP" "$PRIVATE_KEY"
+ chmod 0600 "$PRIVATE_KEY"
+fi
+
+chown "$SERVICE_USER:$SERVICE_GROUP" "$PRIVATE_KEY"
+chmod 0600 "$PRIVATE_KEY"
+
+if [[ -f "$PUBLIC_KEY" ]]; then
+ chown "$SERVICE_USER:$SERVICE_GROUP" "$PUBLIC_KEY"
+ chmod 0640 "$PUBLIC_KEY"
+else
+ sudo -u "$SERVICE_USER" ssh-keygen -y -f "$PRIVATE_KEY" >"$PUBLIC_KEY"
+ chown "$SERVICE_USER:$SERVICE_GROUP" "$PUBLIC_KEY"
+ chmod 0640 "$PUBLIC_KEY"
+fi
+
+if [[ ! -f "$KNOWN_HOSTS" ]]; then
+ install -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0640 /dev/null "$KNOWN_HOSTS"
+else
+ chown "$SERVICE_USER:$SERVICE_GROUP" "$KNOWN_HOSTS"
+ chmod 0640 "$KNOWN_HOSTS"
+fi
+
+install -d -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0750 "$LOG_DIR"
+
+for log_path in "$LOG_FILE" "$AUDIT_LOG"; do
+ if [[ ! -f "$log_path" ]]; then
+ install -o "$SERVICE_USER" -g "$SERVICE_GROUP" -m 0640 /dev/null "$log_path"
+ else
+ chown "$SERVICE_USER:$SERVICE_GROUP" "$log_path"
+ chmod 0640 "$log_path"
+ fi
+
+ if command -v chattr >/dev/null 2>&1; then
+ if ! lsattr "$log_path" 2>/dev/null | grep -q 'a'; then
+ chattr +a "$log_path" || echo "Warning: could not set append-only attribute on $log_path" >&2
+ fi
+ else
+ echo "Warning: chattr not available; skipping append-only for $log_path." >&2
+ fi
+done
+
+if [[ -f "$BIN_PATH" ]]; then
+ chown root:"$SERVICE_GROUP" "$BIN_PATH"
+ chmod 0750 "$BIN_PATH"
+fi
+
+echo "SSH artifacts:"
+ls -l "$PRIVATE_KEY" "$PUBLIC_KEY" "$KNOWN_HOSTS"
+
+echo "Log files:"
+ls -l "$LOG_FILE" "$AUDIT_LOG"
+if command -v lsattr >/dev/null 2>&1; then
+ lsattr "$LOG_FILE" "$AUDIT_LOG" || true
+fi
+
+if [[ -f "$BIN_PATH" ]]; then
+ echo "Binary permissions:"
+ ls -l "$BIN_PATH"
+fi
+
+echo "sensor proxy file permissions secured."
diff --git a/scripts/setup-log-forwarding.sh b/scripts/setup-log-forwarding.sh
new file mode 100755
index 0000000000..00609b8681
--- /dev/null
+++ b/scripts/setup-log-forwarding.sh
@@ -0,0 +1,62 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [[ $EUID -ne 0 ]]; then
+ echo "Run as root" >&2
+ exit 1
+fi
+
+REMOTE_HOST=${REMOTE_HOST:-logs.pulse.example}
+REMOTE_PORT=${REMOTE_PORT:-6514}
+CERT_DIR=${CERT_DIR:-/etc/pulse/log-forwarding}
+CA_CERT=${CA_CERT:-$CERT_DIR/ca.crt}
+CLIENT_CERT=${CLIENT_CERT:-$CERT_DIR/client.crt}
+CLIENT_KEY=${CLIENT_KEY:-$CERT_DIR/client.key}
+
+install -d -m 0750 "$CERT_DIR"
+
+CONF_PATH=/etc/rsyslog.d/pulse-sensor-proxy.conf
+cat <<EOF >"$CONF_PATH"
+module(load="imfile" PollingInterval="5")
+
+input(type="imfile"
+ File="/var/log/pulse/sensor-proxy/audit.log"
+ Tag="pulse.audit"
+ Facility="local4"
+ Severity="notice"
+ PersistStateInterval="100"
+ addMetadata="on")
+
+input(type="imfile"
+ File="/var/log/pulse/sensor-proxy/proxy.log"
+ Tag="pulse.app"
+ Facility="local4"
+ Severity="info"
+ PersistStateInterval="100"
+ addMetadata="on")
+
+action(type="omfile"
+ File="/var/log/pulse/sensor-proxy/forwarding.log"
+ Template="RSYSLOG_TraditionalFileFormat"
+ DirCreateMode="0750"
+ FileCreateMode="0640")
+
+if (\$programname == 'pulse.audit' or \$programname == 'pulse.app') then {
+ action(type="omrelp"
+ target="$REMOTE_HOST"
+ port="$REMOTE_PORT"
+ tls="on"
+ tls.caCert="$CA_CERT"
+ tls.myCert="$CLIENT_CERT"
+ tls.myPrivKey="$CLIENT_KEY"
+ queue.type="LinkedList"
+ queue.size="50000"
+ queue.dequeuebatchsize="500"
+ queue.workerthreads="2"
+ action.resumeRetryCount="-1")
+ stop
+}
+EOF
+
+systemctl restart rsyslog
+echo "Log forwarding enabled to $REMOTE_HOST:$REMOTE_PORT"
diff --git a/security/apparmor/pulse-sensor-proxy.apparmor b/security/apparmor/pulse-sensor-proxy.apparmor
new file mode 100644
index 0000000000..adcbc2ebdc
--- /dev/null
+++ b/security/apparmor/pulse-sensor-proxy.apparmor
@@ -0,0 +1,75 @@
+#include <tunables/global>
+
+profile pulse-sensor-proxy /opt/pulse/sensor-proxy/bin/pulse-sensor-proxy flags=(attach_disconnected,mediate_deleted) {
+ capability chown,
+ capability dac_override,
+ capability dac_read_search,
+ capability setgid,
+ capability setuid,
+
+ network inet stream,
+ network inet6 stream,
+ network unix stream,
+ deny network raw,
+
+ @{PROC}/@{pid}/fd/** r,
+ @{PROC}/@{pid}/cmdline r,
+ @{PROC}/@{pid}/stat r,
+ @{PROC}/@{pid}/status r,
+
+ /opt/pulse/sensor-proxy/bin/pulse-sensor-proxy mr,
+ /opt/pulse/sensor-proxy/bin/* mr,
+ /opt/pulse/sensor-proxy/.ssh/** rwk,
+ /opt/pulse/sensor-proxy/etc/** r,
+ /opt/pulse/sensor-proxy/** r,
+ /var/log/pulse/sensor-proxy/** rw,
+ /run/pulse-sensor-proxy/** rw,
+
+ /etc/hosts r,
+ /etc/hostname r,
+ /etc/resolv.conf r,
+ /etc/pulse-sensor-proxy/** r,
+
+ /usr/bin/ssh mr,
+ /usr/bin/socat mr,
+ /usr/bin/sensors mr,
+ /usr/sbin/ipmitool mr,
+ /bin/bash mr,
+ /bin/sh mr,
+ /bin/cat mr,
+ /bin/echo mr,
+ /usr/bin/tee mr,
+
+ /usr/lib/** mr,
+ /lib/** mr,
+
+ deny /etc/shadow rwl,
+ deny /root/** rwxl,
+
+ ptrace (read) peer=pulse-sensor-proxy,
+
+ signal (receive) set=(hup term int usr1 usr2),
+ signal (send) set=(term) peer=pulse-sensor-proxy,
+
+ /usr/bin/ssh ixr,
+ /usr/bin/sensors ixr,
+ /usr/sbin/ipmitool ixr,
+ /bin/sh ixr,
+ /bin/cat ixr,
+ /bin/echo ixr,
+ /usr/bin/tee ixr,
+
+ deny mount,
+ deny ptrace,
+ deny sys_module,
+ deny sys_rawio,
+ deny sys_admin,
+
+ @{HOME}/.cache/** rw,
+
+ include <abstractions/base>
+ include <abstractions/authentication>
+ include <abstractions/nameservice>
+ include <abstractions/openssl>
+ include <abstractions/user-tmp>
+}
diff --git a/security/seccomp/pulse-sensor-proxy.json b/security/seccomp/pulse-sensor-proxy.json
new file mode 100644
index 0000000000..e1e9b65e94
--- /dev/null
+++ b/security/seccomp/pulse-sensor-proxy.json
@@ -0,0 +1,102 @@
+{
+ "defaultAction": "SCMP_ACT_ERRNO",
+ "architectures": [
+ "SCMP_ARCH_X86_64",
+ "SCMP_ARCH_AARCH64"
+ ],
+ "syscalls": [
+ {
+ "names": [
+ "accept",
+ "accept4",
+ "access",
+ "bind",
+ "brk",
+ "capget",
+ "capset",
+ "chdir",
+ "chmod",
+ "chown",
+ "clock_gettime",
+ "close",
+ "connect",
+ "dup",
+ "dup2",
+ "epoll_create1",
+ "epoll_ctl",
+ "epoll_wait",
+ "eventfd2",
+ "execve",
+ "exit",
+ "exit_group",
+ "fchmod",
+ "fchown",
+ "fcntl",
+ "fdatasync",
+ "fstat",
+ "fsync",
+ "ftruncate",
+ "futex",
+ "getdents64",
+ "getegid",
+ "geteuid",
+ "getgid",
+ "getpeername",
+ "getpid",
+ "getppid",
+ "getrandom",
+ "getrlimit",
+ "getsockname",
+ "getsockopt",
+ "gettid",
+ "getuid",
+ "ioctl",
+ "lseek",
+ "madvise",
+ "mkdir",
+ "mmap",
+ "mprotect",
+ "munmap",
+ "newfstatat",
+ "open",
+ "openat",
+ "pipe2",
+ "prctl",
+ "pread64",
+ "pwrite64",
+ "read",
+ "readlink",
+ "recvfrom",
+ "recvmmsg",
+ "recvmsg",
+ "rename",
+ "rt_sigaction",
+ "rt_sigprocmask",
+ "rt_sigreturn",
+ "sendmmsg",
+ "sendmsg",
+ "sendto",
+ "setgid",
+ "setgroups",
+ "setrlimit",
+ "setsid",
+ "setsockopt",
+ "setuid",
+ "shutdown",
+ "sigaltstack",
+ "socket",
+ "socketpair",
+ "stat",
+ "statx",
+ "symlink",
+ "tgkill",
+ "unlink",
+ "unlinkat",
+ "wait4",
+ "write",
+ "writev"
+ ],
+ "action": "SCMP_ACT_ALLOW"
+ }
+ ]
+}