ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add connstring, file handlers, and security tests
Juan Denisa79bbc27f77e
diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.goindex 62019b67..d14ed27d 100644--- a/agent/cmd/agent/main.go+++ b/agent/cmd/agent/main.go@@ -14,6 +14,7 @@ import ("github.com/serverkit/agent/internal/agent""github.com/serverkit/agent/internal/agentui""github.com/serverkit/agent/internal/config"+ "github.com/serverkit/agent/internal/connstring""github.com/serverkit/agent/internal/logger""github.com/serverkit/agent/internal/setupui"pollclient "github.com/serverkit/agent/internal/transport/poll"@@ -103,20 +104,34 @@ func registerCmd() *cobra.Command {var token stringvar serverURL stringvar name string+ var connStr stringcmd := &cobra.Command{Use: "register",Short: "Register this agent with a ServerKit instance",RunE: func(cmd *cobra.Command, args []string) error {+ // --connection-string is the modern entry path: a single+ // pasteable blob from the panel that already contains the+ // URL and token. When present, it overrides the legacy+ // flags so users don't have to copy three things.+ if connStr != "" {+ decoded, err := connstring.Decode(connStr)+ if err != nil {+ return fmt.Errorf("invalid connection string: %w", err)+ }+ return runRegister(decoded.Token, decoded.URL, name)+ }+ if token == "" || serverURL == "" {+ return fmt.Errorf("provide either --connection-string or both --token and --server")+ }return runRegister(token, serverURL, name)},}- cmd.Flags().StringVarP(&token, "token", "t", "", "registration token (required)")- cmd.Flags().StringVarP(&serverURL, "server", "s", "", "ServerKit server URL (required)")+ cmd.Flags().StringVarP(&connStr, "connection-string", "c", "", "panel connection string (single value, replaces --token + --server)")+ cmd.Flags().StringVarP(&token, "token", "t", "", "registration token (use with --server)")+ cmd.Flags().StringVarP(&serverURL, "server", "s", "", "ServerKit server URL (use with --token)")cmd.Flags().StringVarP(&name, "name", "n", "", "display name for this server")- cmd.MarkFlagRequired("token")- cmd.MarkFlagRequired("server")return cmd}diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.goindex ee6ffa14..f292b6c2 100644--- a/agent/internal/agent/agent.go+++ b/agent/internal/agent/agent.go@@ -9,11 +9,10 @@ import ("encoding/hex""encoding/json""fmt"+ "io""net""os""path/filepath"- "runtime"- "strings""sync""time"@@ -162,7 +161,12 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {subscriptions: make(map[string]context.CancelFunc),handlers: make(map[string]CommandHandler),startTime: time.Now(),- restartCh: make(chan struct{}),+ // Buffered so an IPC restart fired before the agent's main+ // select{} reaches the receive doesn't hang the IPC handler.+ // At most one restart can be in-flight at a time anyway —+ // Restart() uses a non-blocking send and returns "already in+ // progress" if the slot is full.+ restartCh: make(chan struct{}, 1),}// Probe capabilities up-front so connectionWatcher can ship them on@@ -307,7 +311,17 @@ func (a *Agent) registerHandlers() {a.handlers[protocol.ActionSystemdListUnits] = a.handleSystemdListUnitsa.handlers[protocol.ActionSystemdLogs] = a.handleSystemdLogsa.handlers[protocol.ActionSystemdLogsFollow] = a.handleSystemdLogsFollow- a.handlers[protocol.ActionSystemExec] = a.handleSystemExec++ // system:exec is gated on Features.Exec rather than registered+ // unconditionally — the previous version installed the handler+ // regardless of the feature flag, which made the flag misleading+ // (Exec=false still let the panel run any command). The handler+ // itself enforces this too, but failing fast at registration means+ // the panel sees a clean "unknown action" instead of a runtime+ // error and can disable the feature in its UI.+ if a.cfg.Features.Exec {+ a.handlers[protocol.ActionSystemExec] = a.handleSystemExec+ }// Agent commandsa.handlers[protocol.ActionAgentUpdate] = a.handleAgentUpdate@@ -340,8 +354,18 @@ func (a *Agent) Run(ctx context.Context) error {a.log.Info("Starting agent","agent_id", a.cfg.Agent.ID,"version", Version,- "features", fmt.Sprintf("docker=%v metrics=%v ipc=%v", a.cfg.Features.Docker, a.cfg.Features.Metrics, a.cfg.IPC.Enabled),+ "features", fmt.Sprintf("docker=%v metrics=%v ipc=%v exec=%v file_access=%v", a.cfg.Features.Docker, a.cfg.Features.Metrics, a.cfg.IPC.Enabled, a.cfg.Features.Exec, a.cfg.Features.FileAccess),)+ // Surface insecure-TLS at WARN every startup so a misconfigured+ // deployment script can't silently disable certificate verification+ // across every TLS dial in the agent (we have four independent+ // tls.Configs respecting this env var). The user explicitly opted+ // in via env var, so don't refuse to start — just make it loud.+ if os.Getenv("SERVERKIT_INSECURE_TLS") == "true" {+ a.log.Warn("SERVERKIT_INSECURE_TLS=true: TLS certificate verification is DISABLED for all panel connections; only use this for local development")+ a.events.Append(events.KindInfo, events.SeverityWarn,+ "Insecure TLS mode enabled (SERVERKIT_INSECURE_TLS)", nil)+ }a.events.Append(events.KindServiceStart, events.SeverityInfo,"Agent service started",map[string]interface{}{"version": Version})@@ -432,6 +456,21 @@ func (a *Agent) discoveryLoop(ctx context.Context) {conn.SetReadDeadline(time.Now().Add(1 * time.Second))n, remoteAddr, err := conn.ReadFromUDP(buf)if err != nil {+ // A read deadline timeout is the normal case (no+ // inbound discovery this second) — fall through and+ // wait again. A real socket error (closed FD, ICMP+ // unreachable storms) used to busy-loop here at+ // 100% CPU; sleep briefly so the loop doesn't spin+ // while still being responsive to ctx cancellation.+ if ne, ok := err.(net.Error); ok && ne.Timeout() {+ continue+ }+ a.log.Debug("UDP discovery read error", "error", err)+ select {+ case <-ctx.Done():+ return+ case <-time.After(250 * time.Millisecond):+ }continue}@@ -768,9 +807,11 @@ func (a *Agent) handleCommand(data []byte) {return}- // Execute command with enforced maximum timeout+ // Execute command with enforced maximum timeout. The ceiling is+ // configurable via Security.MaxExecTimeout; resolveMaxExecTimeout+ // returns the operator's value or the default safety net.start := time.Now()- maxTimeout := 5 * time.Minute+ maxTimeout := a.resolveMaxExecTimeout()cmdTimeout := time.Duration(cmd.Timeout) * time.Millisecondif cmdTimeout <= 0 || cmdTimeout > maxTimeout {@@ -897,8 +938,16 @@ func (a *Agent) streamMetrics(ctx context.Context, channel string) {}}-// cleanup performs cleanup on shutdown-// handleCredentialUpdate handles credential rotation from server+// handleCredentialUpdate handles credential rotation from server.+//+// Before applying the rotation we verify an HMAC over the new+// credentials computed with the agent's current secret. The session-+// level WS auth alone is not sufficient: the panel is a large surface+// and a session token leak (or a panel-side bug that lets an+// authenticated user cross server boundaries) would otherwise let an+// attacker rotate any agent's credentials to ones they control. The+// extra check means an attacker has to also know the agent's current+// secret — which is exactly what we're trying to protect.func (a *Agent) handleCredentialUpdate(data []byte) {var msg protocol.CredentialUpdateMessageif err := json.Unmarshal(data, &msg); err != nil {@@ -908,6 +957,21 @@ func (a *Agent) handleCredentialUpdate(data []byte) {a.log.Info("Received credential update request", "rotation_id", msg.RotationID)+ if err := a.verifyCredentialRotation(msg); err != nil {+ a.log.Warn("Rejecting credential rotation", "rotation_id", msg.RotationID, "error", err)+ a.events.Append(events.KindAuthFailed, events.SeverityWarn,+ "Credential rotation rejected: "+err.Error(),+ map[string]interface{}{"rotation_id": msg.RotationID})+ ack := protocol.CredentialUpdateAck{+ Message: protocol.NewMessage(protocol.TypeCredentialUpdateAck, auth.GenerateNonce()),+ RotationID: msg.RotationID,+ Success: false,+ Error: err.Error(),+ }+ a.ws.Send(ack)+ return+ }+// Update authenticator with new credentialsa.auth.UpdateCredentials(msg.APIKey, msg.APISecret)@@ -930,6 +994,35 @@ func (a *Agent) handleCredentialUpdate(data []byte) {a.ws.Send(ack)}+// verifyCredentialRotation checks the HMAC the panel attaches to a+// rotation message against the agent's current secret. Returns nil+// only when the signature is present, well-formed, and matches.+//+// The panel must compute hex(HMAC-SHA256(+// "rotation_id:agent_id:new_api_key:new_api_secret",+// current_api_secret)).+func (a *Agent) verifyCredentialRotation(msg protocol.CredentialUpdateMessage) error {+ if msg.RotationID == "" || msg.APIKey == "" || msg.APISecret == "" {+ return fmt.Errorf("rotation message missing required fields")+ }+ if msg.HMACSig == "" {+ return fmt.Errorf("rotation message missing hmac signature")+ }+ currentSecret := a.auth.GetAPISecret()+ if currentSecret == "" {+ return fmt.Errorf("agent has no current secret; refusing to rotate")+ }+ payload := fmt.Sprintf("%s:%s:%s:%s",+ msg.RotationID, a.cfg.Agent.ID, msg.APIKey, msg.APISecret)+ mac := hmac.New(sha256.New, []byte(currentSecret))+ mac.Write([]byte(payload))+ expected := hex.EncodeToString(mac.Sum(nil))+ if !hmac.Equal([]byte(msg.HMACSig), []byte(expected)) {+ return fmt.Errorf("hmac signature mismatch")+ }+ return nil+}+// saveCredentials saves new credentials to the key filefunc (a *Agent) saveCredentials(apiKey, apiSecret string) error {// Update config with new credentials@@ -1068,13 +1161,20 @@ func (a *Agent) handleDockerContainerLogs(ctx context.Context, params json.RawMe}defer reader.Close()- // Read logs into buffer- buf := make([]byte, 1024*1024) // 1MB max- n, _ := reader.Read(buf)- logs := string(buf[:n])+ // Drain the stream up to a 1 MB cap. The previous implementation+ // did a single Read() and dropped the error — Docker's stream+ // framing means one Read returns whatever happens to be in the+ // first chunk (often a few KB), so the panel's "logs" command+ // got a tiny prefix of the requested tail. io.ReadAll over a+ // LimitReader gives the panel the full payload it asked for.+ const maxLogBytes = 1024 * 1024+ data, err := io.ReadAll(io.LimitReader(reader, maxLogBytes))+ if err != nil {+ return nil, fmt.Errorf("read docker logs: %w", err)+ }return map[string]interface{}{- "logs": logs,+ "logs": string(data),}, nil}@@ -1167,158 +1267,7 @@ func (a *Agent) handleSystemProcesses(ctx context.Context, params json.RawMessagreturn a.metrics.ListProcesses(ctx)}-// File command handlers--func (a *Agent) handleFileRead(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Path string `json:"path"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.Path == "" {- return nil, fmt.Errorf("path is required")- }- if err := a.validateFileAccess(p.Path); err != nil {- return nil, err- }-- data, err := os.ReadFile(p.Path)- if err != nil {- return nil, fmt.Errorf("failed to read file: %w", err)- }-- return map[string]interface{}{- "path": p.Path,- "content": base64.StdEncoding.EncodeToString(data),- "size": len(data),- }, nil-}--func (a *Agent) handleFileWrite(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Path string `json:"path"`- Content string `json:"content"` // base64 encoded- Mode uint32 `json:"mode"`- CreateDirs bool `json:"create_dirs"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.Path == "" {- return nil, fmt.Errorf("path is required")- }- if err := a.validateFileAccess(p.Path); err != nil {- return nil, err- }-- data, err := base64.StdEncoding.DecodeString(p.Content)- if err != nil {- return nil, fmt.Errorf("invalid base64 content: %w", err)- }-- mode := os.FileMode(0644)- if p.Mode != 0 {- mode = os.FileMode(p.Mode)- }-- if p.CreateDirs {- if err := os.MkdirAll(filepath.Dir(p.Path), 0755); err != nil {- return nil, fmt.Errorf("failed to create parent directories: %w", err)- }- }-- if err := os.WriteFile(p.Path, data, mode); err != nil {- return nil, fmt.Errorf("failed to write file: %w", err)- }-- return map[string]interface{}{- "success": true,- "path": p.Path,- "size": len(data),- }, nil-}--func (a *Agent) handleFileList(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Path string `json:"path"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.Path == "" {- p.Path = "/"- }- if err := a.validateFileAccess(p.Path); err != nil {- return nil, err- }-- entries, err := os.ReadDir(p.Path)- if err != nil {- return nil, fmt.Errorf("failed to list directory: %w", err)- }-- var files []map[string]interface{}- for _, entry := range entries {- info, err := entry.Info()- if err != nil {- continue- }- files = append(files, map[string]interface{}{- "name": entry.Name(),- "is_dir": entry.IsDir(),- "size": info.Size(),- "modified": info.ModTime().UnixMilli(),- })- }-- return map[string]interface{}{- "path": p.Path,- "files": files,- }, nil-}--func (a *Agent) validateFileAccess(path string) error {- allowedPaths := a.cfg.Security.AllowedPaths- if len(allowedPaths) == 0 {- return fmt.Errorf("file access denied: no allowed_paths configured")- }-- target, err := filepath.Abs(filepath.Clean(path))- if err != nil {- return fmt.Errorf("invalid path: %w", err)- }-- for _, allowedPath := range allowedPaths {- if strings.TrimSpace(allowedPath) == "" {- continue- }- allowed, err := filepath.Abs(filepath.Clean(allowedPath))- if err != nil {- continue- }-- if pathWithinAllowedRoot(target, allowed) {- return nil- }- }-- return fmt.Errorf("file access denied for path: %s", path)-}--func pathWithinAllowedRoot(target, allowed string) bool {- if runtime.GOOS == "windows" {- target = strings.ToLower(target)- allowed = strings.ToLower(allowed)- }-- if target == allowed {- return true- }-- allowedWithSeparator := strings.TrimRight(allowed, string(os.PathSeparator)) + string(os.PathSeparator)- return strings.HasPrefix(target, allowedWithSeparator)-}+// File command handlers live in file_handlers.go.// Docker Compose command handlersdiff --git a/agent/internal/agent/file_handlers.go b/agent/internal/agent/file_handlers.gonew file mode 100644index 00000000..d719ee6b--- /dev/null+++ b/agent/internal/agent/file_handlers.go@@ -0,0 +1,230 @@+package agent++// File-access handlers (file:read, file:write, file:list) and the+// allowlist-aware path validator they share. Lives separately from+// agent.go so the security-sensitive path-resolution logic is easy to+// find and review without scrolling through 2000 lines of unrelated+// command handlers.+//+// Every handler in this file goes through validateFileAccess, which+// resolves symlinks before comparing against AllowedPaths — without+// that, an operator-allowed root containing a symlink to /etc would+// let the panel read or write arbitrary files. handleFileWrite also+// re-validates the parent directory before MkdirAll so CreateDirs+// can't escape via a not-yet-existing path that crosses a symlink+// boundary.++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+)++func (a *Agent) handleFileRead(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Path string `json:"path"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if p.Path == "" {+ return nil, fmt.Errorf("path is required")+ }+ if err := a.validateFileAccess(p.Path); err != nil {+ return nil, err+ }++ data, err := os.ReadFile(p.Path)+ if err != nil {+ return nil, fmt.Errorf("failed to read file: %w", err)+ }++ return map[string]interface{}{+ "path": p.Path,+ "content": base64.StdEncoding.EncodeToString(data),+ "size": len(data),+ }, nil+}++func (a *Agent) handleFileWrite(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Path string `json:"path"`+ Content string `json:"content"` // base64 encoded+ Mode uint32 `json:"mode"`+ CreateDirs bool `json:"create_dirs"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if p.Path == "" {+ return nil, fmt.Errorf("path is required")+ }+ if err := a.validateFileAccess(p.Path); err != nil {+ return nil, err+ }++ data, err := base64.StdEncoding.DecodeString(p.Content)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 content: %w", err)+ }++ mode := os.FileMode(0644)+ if p.Mode != 0 {+ // Mask off SUID/SGID/sticky bits — the panel has no business+ // requesting them and a compromised panel could otherwise drop+ // a setuid binary into an allowed path. If an operator+ // genuinely needs to write a setuid file they can chmod it via+ // system:exec (which is independently gated).+ mode = os.FileMode(p.Mode) & os.ModePerm+ }++ if p.CreateDirs {+ // Re-validate the parent directory under the symlink-resolved+ // rules — MkdirAll otherwise lets the panel create directories+ // outside AllowedPaths if the requested path is something like+ // /var/lib/serverkit/<symlink>/foo and <symlink> escapes.+ parent := filepath.Dir(p.Path)+ if err := a.validateFileAccess(parent); err != nil {+ return nil, fmt.Errorf("parent dir not allowed: %w", err)+ }+ if err := os.MkdirAll(parent, 0755); err != nil {+ return nil, fmt.Errorf("failed to create parent directories: %w", err)+ }+ }++ if err := os.WriteFile(p.Path, data, mode); err != nil {+ return nil, fmt.Errorf("failed to write file: %w", err)+ }++ return map[string]interface{}{+ "success": true,+ "path": p.Path,+ "size": len(data),+ }, nil+}++func (a *Agent) handleFileList(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Path string `json:"path"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if p.Path == "" {+ p.Path = "/"+ }+ if err := a.validateFileAccess(p.Path); err != nil {+ return nil, err+ }++ entries, err := os.ReadDir(p.Path)+ if err != nil {+ return nil, fmt.Errorf("failed to list directory: %w", err)+ }++ var files []map[string]interface{}+ for _, entry := range entries {+ info, err := entry.Info()+ if err != nil {+ continue+ }+ files = append(files, map[string]interface{}{+ "name": entry.Name(),+ "is_dir": entry.IsDir(),+ "size": info.Size(),+ "modified": info.ModTime().UnixMilli(),+ })+ }++ return map[string]interface{}{+ "path": p.Path,+ "files": files,+ }, nil+}++func (a *Agent) validateFileAccess(path string) error {+ allowedPaths := a.cfg.Security.AllowedPaths+ if len(allowedPaths) == 0 {+ return fmt.Errorf("file access denied: no allowed_paths configured")+ }++ target, err := resolveSymlinkPath(path)+ if err != nil {+ return fmt.Errorf("invalid path: %w", err)+ }++ for _, allowedPath := range allowedPaths {+ if strings.TrimSpace(allowedPath) == "" {+ continue+ }+ allowed, err := resolveSymlinkPath(allowedPath)+ if err != nil {+ continue+ }++ if pathWithinAllowedRoot(target, allowed) {+ return nil+ }+ }++ return fmt.Errorf("file access denied for path: %s", path)+}++// resolveSymlinkPath returns an absolute, symlink-free path for use in+// allowlist comparison. Without this, an operator-allowed root that+// contains a symlink (eg. /var/lib/serverkit/data → /etc) lets the+// panel read or write any file the symlink points at — strings.HasPrefix+// matches the unresolved target string, which never sees the escape.+//+// For paths that don't yet exist (handleFileWrite creating a new file+// in an allowed directory), EvalSymlinks fails. Fall back to resolving+// the deepest existing ancestor and reattaching the unresolved suffix+// so a fresh file path is still validated against the real allowed+// root rather than its symlink alias.+func resolveSymlinkPath(p string) (string, error) {+ abs, err := filepath.Abs(filepath.Clean(p))+ if err != nil {+ return "", err+ }+ if resolved, err := filepath.EvalSymlinks(abs); err == nil {+ return resolved, nil+ }+ // Path (or some ancestor) doesn't exist yet. Walk up to the+ // nearest existing ancestor, resolve that, then reattach the+ // missing suffix. This is the standard pattern for allowlist+ // checks against not-yet-created files; the suffix can't+ // introduce a new symlink because nothing on disk corresponds+ // to it yet.+ dir := abs+ suffix := ""+ for {+ parent := filepath.Dir(dir)+ if parent == dir {+ return abs, nil+ }+ if resolved, err := filepath.EvalSymlinks(parent); err == nil {+ return filepath.Join(resolved, filepath.Base(dir), suffix), nil+ }+ suffix = filepath.Join(filepath.Base(dir), suffix)+ dir = parent+ }+}++func pathWithinAllowedRoot(target, allowed string) bool {+ if runtime.GOOS == "windows" {+ target = strings.ToLower(target)+ allowed = strings.ToLower(allowed)+ }++ if target == allowed {+ return true+ }++ allowedWithSeparator := strings.TrimRight(allowed, string(os.PathSeparator)) + string(os.PathSeparator)+ return strings.HasPrefix(target, allowedWithSeparator)+}diff --git a/agent/internal/agent/security_test.go b/agent/internal/agent/security_test.gonew file mode 100644index 00000000..eb7a84e6--- /dev/null+++ b/agent/internal/agent/security_test.go@@ -0,0 +1,199 @@+package agent++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "testing"++ "github.com/serverkit/agent/internal/auth"+ "github.com/serverkit/agent/internal/config"+ "github.com/serverkit/agent/pkg/protocol"+)++func TestCommandBlocked(t *testing.T) {+ cases := []struct {+ name string+ blocked []string+ cmd string+ want bool+ }{+ {"empty list allows everything", nil, "/bin/ls", false},+ {"absolute path match", []string{"/usr/bin/rm"}, "/usr/bin/rm", true},+ {"basename match against absolute path", []string{"rm"}, "/usr/bin/rm", true},+ {"absolute-to-basename match", []string{"/sbin/shutdown"}, "/usr/local/sbin/shutdown", true},+ {"unrelated command not blocked", []string{"/usr/bin/rm"}, "/usr/bin/ls", false},+ {"blank entries ignored", []string{"", " ", "/usr/bin/rm"}, "/usr/bin/rm", true},+ {"blank entries don't deny everything", []string{"", " "}, "/bin/ls", false},+ {"whitespace trimmed on entries", []string{" /bin/dd "}, "/bin/dd", true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := commandBlocked(tc.blocked, tc.cmd); got != tc.want {+ t.Fatalf("commandBlocked(%v, %q) = %v, want %v", tc.blocked, tc.cmd, got, tc.want)+ }+ })+ }+}++func TestResolveMaxExecTimeout(t *testing.T) {+ a := &Agent{cfg: &config.Config{}}+ got := a.resolveMaxExecTimeout()+ if got != defaultMaxExecTimeout {+ t.Fatalf("default fallback: got %s, want %s", got, defaultMaxExecTimeout)+ }++ a.cfg.Security.MaxExecTimeout = defaultMaxExecTimeout / 2+ if got := a.resolveMaxExecTimeout(); got != defaultMaxExecTimeout/2 {+ t.Fatalf("operator override: got %s, want %s", got, defaultMaxExecTimeout/2)+ }++ a.cfg.Security.MaxExecTimeout = -1+ if got := a.resolveMaxExecTimeout(); got != defaultMaxExecTimeout {+ t.Fatalf("negative ignored: got %s, want %s", got, defaultMaxExecTimeout)+ }+}++func TestValidateFileAccessAllowsConfiguredRoot(t *testing.T) {+ root := t.TempDir()+ a := &Agent{cfg: &config.Config{+ Security: config.SecurityConfig{AllowedPaths: []string{root}},+ }}+ target := filepath.Join(root, "sub", "file.txt")+ // Create the parent so EvalSymlinks succeeds for the parent walk.+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := a.validateFileAccess(target); err != nil {+ t.Fatalf("expected access allowed for %s: %v", target, err)+ }+}++func TestValidateFileAccessDeniesOutsideRoot(t *testing.T) {+ root := t.TempDir()+ other := t.TempDir()+ a := &Agent{cfg: &config.Config{+ Security: config.SecurityConfig{AllowedPaths: []string{root}},+ }}+ if err := a.validateFileAccess(filepath.Join(other, "file.txt")); err == nil {+ t.Fatalf("expected access denied for path outside allowed root")+ }+}++func TestValidateFileAccessDeniesSymlinkEscape(t *testing.T) {+ if runtime.GOOS == "windows" {+ // Windows symlink creation requires elevated privileges or+ // SeCreateSymbolicLinkPrivilege in CI; skip rather than make+ // the test environmentally fragile.+ t.Skip("symlink test requires non-Windows environment")+ }+ root := t.TempDir()+ secret := t.TempDir()+ a := &Agent{cfg: &config.Config{+ Security: config.SecurityConfig{AllowedPaths: []string{root}},+ }}+ // Drop a symlink inside the allowed root that points outside it.+ // The pre-fix validateFileAccess would let the escape through+ // because filepath.Clean doesn't resolve symlinks.+ link := filepath.Join(root, "escape")+ if err := os.Symlink(secret, link); err != nil {+ t.Fatalf("symlink: %v", err)+ }+ target := filepath.Join(link, "file.txt")+ if err := a.validateFileAccess(target); err == nil {+ t.Fatalf("expected symlink escape to be denied; %s resolved past allowed root", target)+ }+}++func TestValidateFileAccessNoAllowedPaths(t *testing.T) {+ a := &Agent{cfg: &config.Config{}}+ if err := a.validateFileAccess("/anything"); err == nil {+ t.Fatalf("expected denial when AllowedPaths is empty")+ }+}++func TestVerifyCredentialRotation(t *testing.T) {+ currentSecret := "current-secret-value"+ rotationID := "rot-123"+ agentID := "agent-uuid"+ newKey := "sk_newkey"+ newSecret := "new-secret-value"++ a := &Agent{+ cfg: &config.Config{Agent: config.AgentConfig{ID: agentID}},+ auth: auth.New(agentID, "sk_oldkey", currentSecret),+ }++ sign := func(secret string) string {+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write([]byte(fmt.Sprintf("%s:%s:%s:%s", rotationID, agentID, newKey, newSecret)))+ return hex.EncodeToString(mac.Sum(nil))+ }++ t.Run("valid signature accepted", func(t *testing.T) {+ msg := protocol.CredentialUpdateMessage{+ RotationID: rotationID,+ APIKey: newKey,+ APISecret: newSecret,+ HMACSig: sign(currentSecret),+ }+ if err := a.verifyCredentialRotation(msg); err != nil {+ t.Fatalf("expected valid rotation accepted, got: %v", err)+ }+ })++ t.Run("missing signature rejected", func(t *testing.T) {+ msg := protocol.CredentialUpdateMessage{+ RotationID: rotationID,+ APIKey: newKey,+ APISecret: newSecret,+ }+ if err := a.verifyCredentialRotation(msg); err == nil {+ t.Fatalf("expected rejection for missing signature")+ }+ })++ t.Run("wrong-secret signature rejected", func(t *testing.T) {+ msg := protocol.CredentialUpdateMessage{+ RotationID: rotationID,+ APIKey: newKey,+ APISecret: newSecret,+ HMACSig: sign("attacker-guessed-secret"),+ }+ if err := a.verifyCredentialRotation(msg); err == nil {+ t.Fatalf("expected rejection when HMAC computed with wrong secret")+ }+ })++ t.Run("missing required field rejected", func(t *testing.T) {+ msg := protocol.CredentialUpdateMessage{+ RotationID: "",+ APIKey: newKey,+ APISecret: newSecret,+ HMACSig: sign(currentSecret),+ }+ if err := a.verifyCredentialRotation(msg); err == nil {+ t.Fatalf("expected rejection for missing rotation_id")+ }+ })++ t.Run("agent without secret refuses rotation", func(t *testing.T) {+ empty := &Agent{+ cfg: &config.Config{Agent: config.AgentConfig{ID: agentID}},+ auth: auth.New(agentID, "", ""),+ }+ msg := protocol.CredentialUpdateMessage{+ RotationID: rotationID,+ APIKey: newKey,+ APISecret: newSecret,+ HMACSig: sign(""),+ }+ if err := empty.verifyCredentialRotation(msg); err == nil {+ t.Fatalf("expected rejection when agent has no current secret")+ }+ })+}diff --git a/agent/internal/agent/workflow_handlers.go b/agent/internal/agent/workflow_handlers.goindex 1857cf91..4dee27aa 100644--- a/agent/internal/agent/workflow_handlers.go+++ b/agent/internal/agent/workflow_handlers.go@@ -20,6 +20,7 @@ import ("errors""fmt""os/exec"+ "path/filepath""runtime""strings""time"@@ -33,9 +34,11 @@ const (// systemctl operations are quick; if one hangs longer than 30s// something is wrong (mount-blocked unit, hung shutdown).systemdOpTimeout = 30 * time.Second- // Default exec ceiling. Caller can override per-request via- // "timeout_seconds" param, capped at this value.- maxExecTimeout = 10 * time.Minute+ // Hard ceiling on exec timeouts when the operator hasn't set+ // Security.MaxExecTimeout. The configured value, if any, wins —+ // this is just the safety net so a misconfigured agent can't run+ // arbitrary commands forever.+ defaultMaxExecTimeout = 10 * time.Minute)// ───── packages ────────────────────────────────────────────────────@@ -363,13 +366,60 @@ func (a *Agent) handleSystemdDisable(ctx context.Context, params json.RawMessage// ───── system:exec ─────────────────────────────────────────────────+// commandBlocked reports whether cmd matches one of the operator's+// configured BlockedCommands entries. Comparison is exact-match against+// either the full path or the basename, after both sides are+// normalised — operators tend to write either "/usr/bin/rm" or just+// "rm" and we want to honour both. Empty entries are ignored so a+// stray newline in YAML doesn't deny everything.+func commandBlocked(blocked []string, cmd string) bool {+ if len(blocked) == 0 {+ return false+ }+ cmdAbs := strings.TrimSpace(cmd)+ cmdBase := filepath.Base(cmdAbs)+ for _, raw := range blocked {+ entry := strings.TrimSpace(raw)+ if entry == "" {+ continue+ }+ if entry == cmdAbs || entry == cmdBase {+ return true+ }+ if filepath.Base(entry) == cmdBase {+ return true+ }+ }+ return false+}++// resolveMaxExecTimeout honours the operator's Security.MaxExecTimeout+// when set (any positive duration), otherwise falls back to the+// hardcoded ceiling. Negative or zero values are treated as "unset"+// rather than "no timeout"; the agent never runs an unbounded+// subprocess.+func (a *Agent) resolveMaxExecTimeout() time.Duration {+ if a.cfg != nil && a.cfg.Security.MaxExecTimeout > 0 {+ return a.cfg.Security.MaxExecTimeout+ }+ return defaultMaxExecTimeout+}+// handleSystemExec runs an arbitrary command, captures stdout/stderr,// and returns the exit code. The first token must be an absolute path// (same rule as cron commands) so a misconfigured caller can't depend// on $PATH state of the agent process. Output is truncated to keep the// command envelope reasonable; the runner can poll a file if it needs// the full output of a chatty install.+//+// This handler is only registered when cfg.Features.Exec is true (see+// agent.go:registerHandlers). When Exec is disabled, the panel sees an+// "unknown action" error rather than the command silently running.func (a *Agent) handleSystemExec(ctx context.Context, params json.RawMessage) (interface{}, error) {+ if a.cfg == nil || !a.cfg.Features.Exec {+ return nil, errors.New("system:exec is disabled by agent config (features.exec=false)")+ }+var p struct {Command string `json:"command"`Args []string `json:"args"`@@ -389,10 +439,14 @@ func (a *Agent) handleSystemExec(ctx context.Context, params json.RawMessage) (iif strings.ContainsAny(cmd, ";&|`$<>\n\r") {return nil, errors.New("command contains shell metacharacters; pass arguments via args[]")}+ if commandBlocked(a.cfg.Security.BlockedCommands, cmd) {+ return nil, fmt.Errorf("command %q is blocked by agent security config", cmd)+ }+ maxTimeout := a.resolveMaxExecTimeout()timeout := time.Duration(p.TimeoutSeconds) * time.Second- if timeout <= 0 || timeout > maxExecTimeout {- timeout = maxExecTimeout+ if timeout <= 0 || timeout > maxTimeout {+ timeout = maxTimeout}cctx, cancel := context.WithTimeout(ctx, timeout)defer cancel()diff --git a/agent/internal/agentui/actions.go b/agent/internal/agentui/actions.goindex e32a503d..06c03e34 100644--- a/agent/internal/agentui/actions.go+++ b/agent/internal/agentui/actions.go@@ -3,7 +3,9 @@ package agentuiimport ("encoding/json""net/http"+ "os""os/exec"+ "strings""time""github.com/serverkit/agent/internal/config"@@ -35,6 +37,39 @@ func (a *localActions) register(mux *http.ServeMux) {mux.HandleFunc("/local/wizard", a.handleWizard)mux.HandleFunc("/local/diag", a.handleDiag)mux.HandleFunc("/local/status", a.handleStatus)+ mux.HandleFunc("/local/ipc-token", a.handleIPCToken)+}++// handleIPCToken returns the agent's IPC bearer token to the in-process+// React UI so it can authenticate against the agent service's HTTP API.+// Both processes run on the same machine under the same user, so the+// console process can read the token file directly — this endpoint+// just hides the OS-specific path from the JS side.+//+// Returns 503 (not 401) when the token isn't ready yet so the UI can+// distinguish "agent service hasn't started writing the file" from+// "you got the wrong credential" — the former resolves itself when the+// service starts, the latter is a real config bug.+func (a *localActions) handleIPCToken(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ data, err := os.ReadFile(config.IPCTokenPath())+ if err != nil {+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{+ "error": "ipc token not yet available; is the agent service running?",+ })+ return+ }+ tok := strings.TrimSpace(string(data))+ if tok == "" {+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{+ "error": "ipc token file empty",+ })+ return+ }+ writeJSON(w, http.StatusOK, map[string]string{"token": tok})}// handleStatus reports whether the agent has been paired by readingdiff --git a/agent/internal/agentui/pairer.go b/agent/internal/agentui/pairer.goindex 2b36aecc..aec8af88 100644--- a/agent/internal/agentui/pairer.go+++ b/agent/internal/agentui/pairer.go@@ -5,9 +5,15 @@ import ("encoding/json""errors""net/http"+ "os"+ "path/filepath"+ "strings""sync""time"+ "github.com/serverkit/agent/internal/agent"+ "github.com/serverkit/agent/internal/config"+ "github.com/serverkit/agent/internal/connstring""github.com/serverkit/agent/internal/logger""github.com/serverkit/agent/internal/pairdriver")@@ -45,6 +51,7 @@ func (p *pairer) register(mux *http.ServeMux) {mux.HandleFunc("/local/pair/start", p.handleStart)mux.HandleFunc("/local/pair/state", p.handleState)mux.HandleFunc("/local/pair/cancel", p.handleCancel)+ mux.HandleFunc("/local/pair/connection-string", p.handleConnectionString)}type pairStartRequest struct {@@ -201,3 +208,151 @@ func (p *pairer) handleCancel(w http.ResponseWriter, r *http.Request) {p.mu.Unlock()writeJSON(w, http.StatusOK, map[string]bool{"ok": true})}++type connStringRequest struct {+ ConnectionString string `json:"connection_string"`+}++// handleConnectionString accepts a single sk_conn_v1.<...> blob, decodes+// it into a panel URL + registration token, and runs the legacy+// /api/v1/servers/register flow against the panel — the same one the+// `serverkit-agent register` CLI uses. We reuse the existing pairer+// state machine ("enrolling" -> "claimed") so the React wizard's polling+// loop doesn't need a separate state for this entry path.+//+// Note: this bypasses the pair-code/passphrase flow entirely. The token+// inside the connection string IS the credential — the panel mints the+// agent's permanent api_key/api_secret server-side once we POST to+// /register, which is exactly what the operator wanted: "one string from+// the panel, one paste in the agent."+func (p *pairer) handleConnectionString(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ var req connStringRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"})+ return+ }+ decoded, err := connstring.Decode(req.ConnectionString)+ if err != nil {+ // Surface decoder errors directly: "unknown version" / "missing+ // url or token" are actionable for the user, where as a generic+ // "invalid input" wouldn't tell them whether to regenerate or+ // upgrade.+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})+ return+ }++ panelURL := pairdriver.NormalizePanelURL(decoded.URL)++ // Mark the pairer state machine "in-flight" so the wizard's poll+ // loop renders a spinner instead of bouncing back to the form.+ p.mu.Lock()+ if p.cancel != nil {+ p.cancel()+ }+ ctx, cancel := context.WithCancel(context.Background())+ p.cancel = cancel+ p.state = "enrolling"+ p.errMsg = ""+ p.code = ""+ p.codeFmt = ""+ p.pass = ""+ p.panelURL = panelURL+ p.server = ""+ p.mu.Unlock()++ go p.runConnectionStringFlow(ctx, panelURL, decoded.Token)++ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})+}++// runConnectionStringFlow performs the actual register + persist + service+// restart sequence. Mirrors the OnClaimed path of the pair-code flow so+// the user-visible end state ("agent running, panel reconnected") is+// identical regardless of which entry path they took.+func (p *pairer) runConnectionStringFlow(ctx context.Context, panelURL, token string) {+ reg := agent.NewRegistration(p.log)++ result, err := reg.Register(panelURL, token, "")+ if err != nil {+ p.failConnString("register: " + err.Error())+ return+ }+ if ctx.Err() != nil {+ // User clicked Cancel between the network call and the save.+ return+ }++ if err := saveRegistrationCredentials(p.configPath, panelURL, result); err != nil {+ p.failConnString("save credentials: " + err.Error())+ return+ }++ p.mu.Lock()+ p.state = "claimed"+ p.server = result.Name+ p.mu.Unlock()++ // Same restart-and-verify dance as the pair-code claim path. Earlier+ // versions skipped this and left users staring at "successfully+ // paired" on a service that never actually picked up the new config.+ if err := runServiceCmd("stop"); err != nil {+ p.log.Info("Service stop reported error (likely already stopped)", "error", err)+ }+ if err := runServiceCmd("start"); err != nil {+ p.log.Error("Failed to start service after pairing", "error", err)+ p.failConnString("Pairing succeeded but the agent service failed to start: " + err.Error() ++ "\n\nTry: restart the machine, or open Actions → Restart agent.")+ return+ }+ if err := waitForServiceRunning(20 * time.Second); err != nil {+ p.log.Error("Service did not reach RUNNING after pairing", "error", err)+ p.failConnString("Pairing succeeded but the agent service didn't come up within 20s. " ++ "This usually means another agent process is holding port 19780 — " ++ "try ending all serverkit-agent.exe processes from Task Manager and reopen the wizard.\n\n" ++ "Detail: " + err.Error())+ return+ }+ p.log.Info("Agent service running after connection-string pair", "server", result.Name)+}++func (p *pairer) failConnString(msg string) {+ p.mu.Lock()+ p.state = "error"+ p.errMsg = msg+ p.mu.Unlock()+}++// saveRegistrationCredentials persists the result of a /register call to+// disk in the same shape as pairdriver.saveCredentials does for the+// claim flow. Lives here rather than in registration.go because the CLI+// `register` command does its own (slightly older-shaped) save and we+// don't want to disturb that path.+func saveRegistrationCredentials(configPath, panelURL string, r *agent.RegistrationResult) error {+ cfg, err := config.Load(configPath)+ if err != nil {+ cfg = config.Default()+ }+ wsURL := strings.TrimSuffix(panelURL, "/")+ wsURL = strings.Replace(wsURL, "https://", "wss://", 1)+ wsURL = strings.Replace(wsURL, "http://", "ws://", 1)+ cfg.Server.URL = wsURL + "/agent"+ cfg.Agent.ID = r.AgentID+ cfg.Agent.Name = r.Name+ cfg.Auth.APIKey = r.APIKey+ cfg.Auth.APISecret = r.APISecret++ if configPath == "" {+ configPath = config.DefaultConfigPath()+ }+ if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {+ return err+ }+ if err := cfg.Save(configPath); err != nil {+ return err+ }+ return cfg.SaveCredentials()+}diff --git a/agent/internal/config/config.go b/agent/internal/config/config.goindex a943b14c..5095bd89 100644--- a/agent/internal/config/config.go+++ b/agent/internal/config/config.go@@ -348,6 +348,18 @@ func defaultLogPath() string {return "/var/log/serverkit-agent/agent.log"}+// IPCTokenPath returns the absolute path to the agent's IPC bearer-token+// file. The token gates the local HTTP API the desktop console and tray+// app use; clients must pass it as `Authorization: Bearer <token>`.+// Living next to the existing key file means it inherits the same 0600+// directory ACLs and ships with the same backup/restore policies.+func IPCTokenPath() string {+ if runtime.GOOS == "windows" {+ return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "ipc.token")+ }+ return "/etc/serverkit-agent/ipc.token"+}+func defaultAllowedPaths() []string {if runtime.GOOS == "windows" {return []string{filepath.Join(os.Getenv("ProgramData"), "ServerKit")}diff --git a/agent/internal/connstring/connstring.go b/agent/internal/connstring/connstring.gonew file mode 100644index 00000000..80e98003--- /dev/null+++ b/agent/internal/connstring/connstring.go@@ -0,0 +1,92 @@+// Package connstring decodes the panel's "connection string" — a single+// base64-packed blob the user copies from the ServerKit panel and pastes+// into the agent's pairing wizard. It bundles the panel URL plus a+// single-use registration token, replacing the older flow where the user+// typed those into separate fields.+//+// Format: ``sk_conn_v1.<base64url(json_payload)>``+//+// The version prefix exists so older agents reject newer payloads cleanly+// instead of mis-parsing them. Today's payload is intentionally tiny —+// just the URL, the token, and an optional expiry the agent treats as+// advisory (the panel is the authoritative source of truth on whether the+// token is still good).+package connstring++import (+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "time"+)++const (+ // Prefix is the version tag that introduces every v1 connection string.+ Prefix = "sk_conn_v1."+)++// Decoded is the payload encoded inside a connection string.+type Decoded struct {+ URL string `json:"url"`+ Token string `json:"token"`+ ExpiresAt time.Time `json:"-"` // parsed from the raw payload below+ // Raw expiry kept verbatim so we can show the user the panel's exact+ // formatting (or "never") without re-stringifying.+ ExpiresAtRaw string `json:"expires_at,omitempty"`+}++// ErrUnknownVersion is returned when the prefix is missing or names a+// version this build doesn't understand. Callers should surface this as+// "your panel is newer than this agent" rather than a generic decode error+// — it's almost always the cause.+var ErrUnknownVersion = errors.New("connstring: unknown version prefix")++// Decode parses a connection string. Whitespace surrounding the input is+// stripped (paste-from-clipboard often picks up a trailing newline).+func Decode(s string) (*Decoded, error) {+ s = strings.TrimSpace(s)+ if s == "" {+ return nil, errors.New("connstring: empty input")+ }+ if !strings.HasPrefix(s, Prefix) {+ return nil, ErrUnknownVersion+ }+ payload := strings.TrimPrefix(s, Prefix)++ // We use the URL-safe alphabet without padding on the panel side; allow+ // either padded or unpadded inputs here so a hand-edited string still+ // decodes.+ raw, err := base64.RawURLEncoding.DecodeString(payload)+ if err != nil {+ raw, err = base64.URLEncoding.DecodeString(payload)+ }+ if err != nil {+ return nil, fmt.Errorf("connstring: base64 decode: %w", err)+ }++ // Parse twice — once into the public Decoded struct (gets URL+Token),+ // then into a small auxiliary struct to capture the expiry as both a+ // time.Time and the original string.+ var out Decoded+ if err := json.Unmarshal(raw, &out); err != nil {+ return nil, fmt.Errorf("connstring: json decode: %w", err)+ }+ if out.URL == "" || out.Token == "" {+ return nil, errors.New("connstring: payload missing url or token")+ }++ var aux struct {+ ExpiresAt string `json:"expires_at"`+ }+ _ = json.Unmarshal(raw, &aux)+ out.ExpiresAtRaw = aux.ExpiresAt+ if aux.ExpiresAt != "" {+ if t, perr := time.Parse(time.RFC3339, aux.ExpiresAt); perr == nil {+ out.ExpiresAt = t+ }+ }++ return &out, nil+}diff --git a/agent/internal/connstring/connstring_test.go b/agent/internal/connstring/connstring_test.gonew file mode 100644index 00000000..37612e7f--- /dev/null+++ b/agent/internal/connstring/connstring_test.go@@ -0,0 +1,102 @@+package connstring++import (+ "encoding/base64"+ "errors"+ "strings"+ "testing"+)++// helper: encode the panel's payload format so the test stays readable+// even as we tweak fields. Mirrors backend/app/services/connection_string.py+// — keep the two in sync.+func encode(payload string) string {+ return Prefix + base64.RawURLEncoding.EncodeToString([]byte(payload))+}++func TestDecode_Roundtrip(t *testing.T) {+ s := encode(`{"url":"https://panel.example.com","token":"sk_reg_abc","expires_at":"2026-05-08T17:00:00Z"}`)+ got, err := Decode(s)+ if err != nil {+ t.Fatalf("decode: %v", err)+ }+ if got.URL != "https://panel.example.com" {+ t.Errorf("url = %q", got.URL)+ }+ if got.Token != "sk_reg_abc" {+ t.Errorf("token = %q", got.Token)+ }+ if got.ExpiresAtRaw != "2026-05-08T17:00:00Z" {+ t.Errorf("expires_at_raw = %q", got.ExpiresAtRaw)+ }+ if got.ExpiresAt.IsZero() {+ t.Errorf("expires_at not parsed: %v", got.ExpiresAt)+ }+}++func TestDecode_TrimsWhitespace(t *testing.T) {+ s := encode(`{"url":"https://x","token":"t"}`)+ // Clipboard pastes often have a trailing newline; verify Decode+ // doesn't reject a string just because of that.+ if _, err := Decode("\n " + s + " \n"); err != nil {+ t.Fatalf("decode with whitespace: %v", err)+ }+}++func TestDecode_RejectsUnknownVersion(t *testing.T) {+ _, err := Decode("sk_conn_v9.aaaa")+ if !errors.Is(err, ErrUnknownVersion) {+ t.Errorf("want ErrUnknownVersion, got %v", err)+ }++ _, err = Decode("not-a-connection-string")+ if !errors.Is(err, ErrUnknownVersion) {+ t.Errorf("want ErrUnknownVersion for missing prefix, got %v", err)+ }+}++func TestDecode_RejectsEmpty(t *testing.T) {+ if _, err := Decode(""); err == nil {+ t.Errorf("want error for empty input")+ }+ if _, err := Decode(" "); err == nil {+ t.Errorf("want error for whitespace-only input")+ }+}++func TestDecode_RejectsMissingFields(t *testing.T) {+ cases := []string{+ `{"token":"t"}`,+ `{"url":"https://x"}`,+ `{}`,+ }+ for _, payload := range cases {+ _, err := Decode(encode(payload))+ if err == nil {+ t.Errorf("expected error for payload %q", payload)+ continue+ }+ if !strings.Contains(err.Error(), "missing url or token") {+ t.Errorf("payload %q: unexpected error %v", payload, err)+ }+ }+}++func TestDecode_RejectsCorruptBase64(t *testing.T) {+ // Garbage after the prefix isn't valid base64 in either alphabet.+ _, err := Decode(Prefix + "!!!not-base64!!!")+ if err == nil {+ t.Errorf("want error for corrupt base64")+ }+}++func TestDecode_AcceptsPaddedBase64(t *testing.T) {+ // Some clipboards (notably pasting through certain terminals) round-+ // trip the URL-safe alphabet through a padded form. Decode tolerates+ // either, so a hand-edited string still works.+ payload := []byte(`{"url":"https://x","token":"t"}`)+ padded := Prefix + base64.URLEncoding.EncodeToString(payload)+ if _, err := Decode(padded); err != nil {+ t.Errorf("padded decode: %v", err)+ }+}diff --git a/agent/internal/ipc/auth_test.go b/agent/internal/ipc/auth_test.gonew file mode 100644index 00000000..5b696c5c--- /dev/null+++ b/agent/internal/ipc/auth_test.go@@ -0,0 +1,142 @@+package ipc++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"+)++func TestBearerToken(t *testing.T) {+ cases := []struct {+ name string+ header string+ query string+ want string+ }{+ {"no auth header, no query", "", "", ""},+ {"valid bearer", "Bearer abc123", "", "abc123"},+ {"case-insensitive scheme", "bearer abc123", "", "abc123"},+ {"trims whitespace", "Bearer abc123 ", "", "abc123"},+ {"non-bearer scheme", "Basic abc123", "", ""},+ {"query string fallback", "", "tok-from-query", "tok-from-query"},+ {"header wins over query", "Bearer header-tok", "query-tok", "header-tok"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ r := httptest.NewRequest(http.MethodGet, "/x", nil)+ if tc.header != "" {+ r.Header.Set("Authorization", tc.header)+ }+ if tc.query != "" {+ q := r.URL.Query()+ q.Set("token", tc.query)+ r.URL.RawQuery = q.Encode()+ }+ if got := bearerToken(r); got != tc.want {+ t.Fatalf("bearerToken: got %q, want %q", got, tc.want)+ }+ })+ }+}++func TestAuthMiddleware(t *testing.T) {+ const tok = "secret-token-value"+ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok"))+ })+ mw := authMiddleware(tok, inner)++ t.Run("health is exempt", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodGet, "/health", nil)+ w := httptest.NewRecorder()+ mw.ServeHTTP(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("/health blocked: got %d", w.Code)+ }+ })++ t.Run("missing token rejected", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodGet, "/status", nil)+ w := httptest.NewRecorder()+ mw.ServeHTTP(w, r)+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401, got %d", w.Code)+ }+ })++ t.Run("wrong token rejected", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodGet, "/status", nil)+ r.Header.Set("Authorization", "Bearer wrong-token")+ w := httptest.NewRecorder()+ mw.ServeHTTP(w, r)+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401, got %d", w.Code)+ }+ })++ t.Run("correct token allowed", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodGet, "/status", nil)+ r.Header.Set("Authorization", "Bearer "+tok)+ w := httptest.NewRecorder()+ mw.ServeHTTP(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ })++ t.Run("OPTIONS bypasses auth (CORS preflight)", func(t *testing.T) {+ r := httptest.NewRequest(http.MethodOptions, "/status", nil)+ w := httptest.NewRecorder()+ mw.ServeHTTP(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("CORS preflight blocked: got %d", w.Code)+ }+ })+}++func TestLoadOrGenerateToken(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "ipc.token")++ // First call creates the file with a fresh token.+ tok1, err := loadOrGenerateToken(path)+ if err != nil {+ t.Fatalf("first generate: %v", err)+ }+ if len(tok1) < 32 {+ t.Fatalf("token too short: %q", tok1)+ }++ // Second call reuses the same token (so a tray app already running+ // keeps working through agent restarts).+ tok2, err := loadOrGenerateToken(path)+ if err != nil {+ t.Fatalf("second load: %v", err)+ }+ if tok1 != tok2 {+ t.Fatalf("token regenerated unexpectedly: %q vs %q", tok1, tok2)+ }+}++func TestLoadOrGenerateTokenRegeneratesOnTooShort(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "ipc.token")++ // Pre-seed with a short value (eg. truncated file). loadOrGenerateToken+ // should treat it as corrupted and write a fresh one rather than honour+ // the stub credential.+ if err := os.WriteFile(path, []byte("short"), 0o600); err != nil {+ t.Fatal(err)+ }++ tok, err := loadOrGenerateToken(path)+ if err != nil {+ t.Fatalf("regen: %v", err)+ }+ if tok == "short" || len(tok) < 32 {+ t.Fatalf("expected regenerated token, got %q", tok)+ }+}diff --git a/agent/internal/ipc/server.go b/agent/internal/ipc/server.goindex c3662c08..d337f5be 100644--- a/agent/internal/ipc/server.go+++ b/agent/internal/ipc/server.go@@ -2,9 +2,15 @@ package ipcimport ("context"+ "crypto/rand"+ "crypto/subtle"+ "encoding/hex""fmt""net""net/http"+ "os"+ "path/filepath"+ "strings""time""github.com/serverkit/agent/internal/config"@@ -108,6 +114,14 @@ type Server struct {server *http.Serverprovider StatusProviderstartTime time.Time+ // token is the bearer credential that gates every endpoint except+ // /health. Loaded from disk if present (so a tray app already+ // running survives an agent restart) or generated on first start.+ // Localhost binding alone isn't enough — any local process on the+ // box (browser tab, malicious npm postinstall, low-priv service+ // account) could otherwise read panel URL / agent ID / logs and+ // trigger /restart without authorisation.+ token string}// NewServer creates a new IPC server@@ -127,6 +141,15 @@ func (s *Server) Start(ctx context.Context) error {return nil}+ // Load or generate the bearer token before binding the listener.+ // Token failures are fatal — running the IPC API without auth+ // would expose /restart and /logs to any local process.+ tok, err := loadOrGenerateToken(config.IPCTokenPath())+ if err != nil {+ return fmt.Errorf("ipc token: %w", err)+ }+ s.token = tok+mux := http.NewServeMux()// Register handlers@@ -152,7 +175,7 @@ func (s *Server) Start(ctx context.Context) error {s.server = &http.Server{Addr: addr,- Handler: corsMiddleware(mux),+ Handler: corsMiddleware(authMiddleware(s.token, mux)),ReadTimeout: 5 * time.Second,WriteTimeout: 10 * time.Second,IdleTimeout: 60 * time.Second,@@ -219,14 +242,94 @@ func corsMiddleware(next http.Handler) http.Handler {})}-// isLocalhost checks if the origin is from localhost+// isLocalhost checks if the origin is from localhost. Strict suffix+// matching against a small allowlist keeps this honest — earlier+// substring slicing was easy to mis-edit and survives only because+// browsers send a fixed-format Origin header.func isLocalhost(origin string) bool {- return origin == "http://localhost" ||- origin == "https://localhost" ||- origin == "http://127.0.0.1" ||- origin == "https://127.0.0.1" ||- len(origin) > 17 && origin[:17] == "http://localhost:" ||- len(origin) > 18 && origin[:18] == "https://localhost:" ||- len(origin) > 17 && origin[:17] == "http://127.0.0.1:" ||- len(origin) > 18 && origin[:18] == "https://127.0.0.1:"+ switch origin {+ case "http://localhost", "https://localhost",+ "http://127.0.0.1", "https://127.0.0.1":+ return true+ }+ for _, prefix := range []string{+ "http://localhost:", "https://localhost:",+ "http://127.0.0.1:", "https://127.0.0.1:",+ } {+ if strings.HasPrefix(origin, prefix) {+ return true+ }+ }+ return false+}++// authMiddleware enforces a constant-time bearer-token check on every+// request. /health is exempt so external probes (systemd watchdog,+// external monitoring) can verify the agent is reachable without+// being trusted with the token. Every other endpoint exposes data+// (panel URL, agent ID, logs, metrics) or actions (restart, log+// rotation) that a malicious local process must not reach.+func authMiddleware(expected string, next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // Always allow CORS preflight to pass through; the actual+ // request that follows still has to authenticate.+ if r.Method == http.MethodOptions {+ next.ServeHTTP(w, r)+ return+ }+ if r.URL.Path == "/health" {+ next.ServeHTTP(w, r)+ return+ }+ got := bearerToken(r)+ if got == "" || subtle.ConstantTimeCompare([]byte(got), []byte(expected)) != 1 {+ w.Header().Set("WWW-Authenticate", `Bearer realm="serverkit-agent"`)+ http.Error(w, "unauthorized", http.StatusUnauthorized)+ return+ }+ next.ServeHTTP(w, r)+ })+}++func bearerToken(r *http.Request) string {+ h := r.Header.Get("Authorization")+ if h == "" {+ // Fallback to query string for places where setting headers+ // is awkward (eg. EventSource URLs in older browsers). The+ // token is only valid on 127.0.0.1 anyway, so this isn't a+ // new exposure.+ return r.URL.Query().Get("token")+ }+ const prefix = "Bearer "+ if len(h) > len(prefix) && strings.EqualFold(h[:len(prefix)], prefix) {+ return strings.TrimSpace(h[len(prefix):])+ }+ return ""+}++// loadOrGenerateToken returns a per-host IPC bearer token. The file is+// reused across runs so a tray app that picked up the token on first+// launch keeps working through agent restarts; only when the file is+// missing or unreadable do we generate a fresh one.+func loadOrGenerateToken(path string) (string, error) {+ if data, err := os.ReadFile(path); err == nil {+ tok := strings.TrimSpace(string(data))+ if len(tok) >= 32 {+ return tok, nil+ }+ // File exists but contents are too short — treat as+ // corrupted and regenerate.+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ return "", fmt.Errorf("create token dir: %w", err)+ }+ buf := make([]byte, 32)+ if _, err := rand.Read(buf); err != nil {+ return "", fmt.Errorf("generate token: %w", err)+ }+ tok := hex.EncodeToString(buf)+ if err := os.WriteFile(path, []byte(tok), 0o600); err != nil {+ return "", fmt.Errorf("write token: %w", err)+ }+ return tok, nil}diff --git a/agent/internal/tray/client.go b/agent/internal/tray/client.goindex c3398287..67e18c1b 100644--- a/agent/internal/tray/client.go+++ b/agent/internal/tray/client.go@@ -4,8 +4,11 @@ import ("encoding/json""fmt""net/http"+ "os"+ "strings""time"+ "github.com/serverkit/agent/internal/config""github.com/serverkit/agent/internal/ipc")@@ -13,6 +16,13 @@ import (type Client struct {baseURL stringhttpClient *http.Client+ // token is the bearer credential the IPC server requires on every+ // endpoint except /health. Loaded lazily from disk on each request+ // so the tray picks up token rotations without restart. An empty+ // token still lets /health probes work (the only endpoint the+ // IPC server leaves unauthenticated), but every other call will+ // 401 — IsAgentRunning() therefore stays accurate.+ token string}// NewClient creates a new IPC client@@ -25,9 +35,38 @@ func NewClient(address string, port int) *Client {}}+// loadToken reads the IPC token from the well-known path the agent+// service writes on startup. Best-effort: a missing file just means+// "agent never finished initialising the IPC server" — the caller+// gets a 401 and surfaces it as an unreachable agent.+func (c *Client) loadToken() string {+ if data, err := os.ReadFile(config.IPCTokenPath()); err == nil {+ return strings.TrimSpace(string(data))+ }+ return ""+}++// authedRequest builds a GET/POST with the Authorization header set.+// Centralising the header lets us swap to a different scheme later+// without touching every endpoint method.+func (c *Client) authedRequest(method, url string) (*http.Request, error) {+ req, err := http.NewRequest(method, url, nil)+ if err != nil {+ return nil, err+ }+ if tok := c.loadToken(); tok != "" {+ req.Header.Set("Authorization", "Bearer "+tok)+ }+ return req, nil+}+// GetStatus fetches the agent statusfunc (c *Client) GetStatus() (*ipc.AgentStatus, error) {- resp, err := c.httpClient.Get(c.baseURL + "/status")+ req, err := c.authedRequest(http.MethodGet, c.baseURL+"/status")+ if err != nil {+ return nil, err+ }+ resp, err := c.httpClient.Do(req)if err != nil {return nil, err}@@ -47,7 +86,11 @@ func (c *Client) GetStatus() (*ipc.AgentStatus, error) {// GetMetrics fetches detailed system metricsfunc (c *Client) GetMetrics() (*ipc.DetailedMetrics, error) {- resp, err := c.httpClient.Get(c.baseURL + "/metrics")+ req, err := c.authedRequest(http.MethodGet, c.baseURL+"/metrics")+ if err != nil {+ return nil, err+ }+ resp, err := c.httpClient.Do(req)if err != nil {return nil, err}@@ -67,7 +110,11 @@ func (c *Client) GetMetrics() (*ipc.DetailedMetrics, error) {// GetConnection fetches WebSocket connection infofunc (c *Client) GetConnection() (*ipc.ConnectionInfo, error) {- resp, err := c.httpClient.Get(c.baseURL + "/connection")+ req, err := c.authedRequest(http.MethodGet, c.baseURL+"/connection")+ if err != nil {+ return nil, err+ }+ resp, err := c.httpClient.Do(req)if err != nil {return nil, err}@@ -87,7 +134,11 @@ func (c *Client) GetConnection() (*ipc.ConnectionInfo, error) {// GetLogs fetches recent log linesfunc (c *Client) GetLogs(lines int) ([]string, error) {- resp, err := c.httpClient.Get(fmt.Sprintf("%s/logs?lines=%d", c.baseURL, lines))+ req, err := c.authedRequest(http.MethodGet, fmt.Sprintf("%s/logs?lines=%d", c.baseURL, lines))+ if err != nil {+ return nil, err+ }+ resp, err := c.httpClient.Do(req)if err != nil {return nil, err}@@ -109,7 +160,12 @@ func (c *Client) GetLogs(lines int) ([]string, error) {// Restart requests agent restartfunc (c *Client) Restart() error {- resp, err := c.httpClient.Post(c.baseURL+"/restart", "application/json", nil)+ req, err := c.authedRequest(http.MethodPost, c.baseURL+"/restart")+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")+ resp, err := c.httpClient.Do(req)if err != nil {return err}diff --git a/agent/internal/ws/client.go b/agent/internal/ws/client.goindex 1cf84c5b..3fe21e03 100644--- a/agent/internal/ws/client.go+++ b/agent/internal/ws/client.go@@ -441,34 +441,67 @@ func (c *Client) Run(ctx context.Context) error {c.mu.Unlock()}- // Start read/write/ping loops+ // Per-iteration ctx so we can cancel readLoop/writeLoop/pingLoop+ // together when any one of them errors. The previous code only+ // read the first error off errCh and let the other two+ // goroutines leak until the next reconnect's conn.Close+ // happened to cause a read error in them — every flap leaked+ // goroutines that, in tunnel-flap scenarios, accumulated+ // quickly. With per-iteration cancellation each connection+ // owns exactly three goroutines for its lifetime.+ loopCtx, cancelLoop := context.WithCancel(ctx)errCh := make(chan error, 3)+ var wg sync.WaitGroup+ wg.Add(3)go func() {- errCh <- c.readLoop(ctx)+ defer wg.Done()+ errCh <- c.readLoop(loopCtx)}()-go func() {- errCh <- c.writeLoop(ctx)+ defer wg.Done()+ errCh <- c.writeLoop(loopCtx)}()-go func() {- errCh <- c.pingLoop(ctx)+ defer wg.Done()+ errCh <- c.pingLoop(loopCtx)}()// Wait for errorerr := <-errChc.log.Warn("Connection loop ended", "error", err)- // Mark as disconnected+ // Mark as disconnected before draining sendCh so any+ // concurrent Send() callers see the disconnected state and+ // fail fast rather than queueing onto a buffer about to+ // be flushed.c.mu.Lock()c.connected = falsec.mu.Unlock()- // Close connection+ // Cancel siblings and close the conn so readLoop unblocks+ // from its read deadline. Then wait for both siblings to+ // drain their error onto errCh — leaving them running was+ // the goroutine leak.+ cancelLoop()if c.conn != nil {c.conn.Close()}+ wg.Wait()+ // Drain the remaining errCh entries so the channel doesn't+ // retain references to err values.+ for len(errCh) > 0 {+ <-errCh+ }++ // Drain stale messages buffered while the previous connection+ // was already failing. Replaying these on a fresh session+ // would ship heartbeats/results from a dead WS to a new auth+ // context — and worse, if the buffer ever filled mid-flap,+ // every subsequent Send() would return "send channel full"+ // permanently. Replace the channel with a fresh one so we+ // also drop any blocked senders cleanly.+ c.drainSendCh()// Check if context is cancelledselect {@@ -480,6 +513,21 @@ func (c *Client) Run(ctx context.Context) error {}}+// drainSendCh empties any pending outbound messages from the previous+// connection. Called after a disconnect so we don't ship stale frames+// (heartbeats, command results) on the next session — they were+// computed against the old auth context and the panel will either+// reject them or attribute them to the wrong session window.+func (c *Client) drainSendCh() {+ for {+ select {+ case <-c.sendCh:+ default:+ return+ }+ }+}+// readLoop reads Socket.IO messages from the WebSocketfunc (c *Client) readLoop(ctx context.Context) error {// Read deadline = pingInterval * 2.5 + 5s grace. Any inbound message@@ -661,6 +709,16 @@ func (c *Client) handleReconnect(ctx context.Context) {// Send queues a message for sendingfunc (c *Client) Send(msg interface{}) error {+ c.mu.RLock()+ connected := c.connected+ c.mu.RUnlock()+ if !connected {+ // Refuse to queue when there's nothing draining the channel.+ // Otherwise a backlog accumulates while the agent is offline+ // and floods the panel on reconnect with stale heartbeats.+ return fmt.Errorf("not connected")+ }+data, err := json.Marshal(msg)if err != nil {return fmt.Errorf("failed to marshal message: %w", err)diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.goindex 3938111c..d029bba4 100644--- a/agent/pkg/protocol/messages.go+++ b/agent/pkg/protocol/messages.go@@ -371,12 +371,25 @@ const (ChannelJob = "job:%s")-// CredentialUpdateMessage is sent by server to rotate credentials+// CredentialUpdateMessage is sent by server to rotate credentials.+//+// HMACSig is computed by the panel as+// hex(HMAC-SHA256("rotation_id:agent_id:new_api_key:new_api_secret",+// current_api_secret))+// where current_api_secret is the agent's secret prior to rotation.+// The agent recomputes this with its own current secret and rejects+// the rotation if they don't match. This prevents a panel session+// hijack from silently rotating an agent's credential set to ones an+// attacker controls — the existing socket-level auth is necessary but+// not sufficient because the panel has many ways to issue messages+// downward and we want defence-in-depth specifically on the rotation+// path.type CredentialUpdateMessage struct {MessageRotationID string `json:"rotation_id"`APIKey string `json:"api_key"`APISecret string `json:"api_secret"`+ HMACSig string `json:"hmac_sig"`}// CredentialUpdateAck is sent by agent after updating credentialsdiff --git a/agent/ui/src/ipc/client.js b/agent/ui/src/ipc/client.jsindex 1a11b31f..92e7fa53 100644--- a/agent/ui/src/ipc/client.js+++ b/agent/ui/src/ipc/client.js@@ -1,6 +1,8 @@// Tiny client for the agent's local IPC server. Always 127.0.0.1 — the IPC-// server refuses non-loopback binds — so we don't worry about CORS, auth, or-// retries beyond the simple ones the hooks already handle.+// server refuses non-loopback binds — and gates every endpoint except+// /health behind a bearer token. We fetch the token from the in-process+// asset server (/local/ipc-token), which reads it off disk: the React UI+// can't read filesystem paths, but the Go console process running it can.const DEFAULT_PORT = 19780;@@ -15,11 +17,62 @@ const PORT =const BASE = `http://127.0.0.1:${PORT}`;+// Cache the token in-module so we don't re-fetch on every IPC call.+// Refresh on 401 so a token rotation (rare; only if the file is wiped+// and the agent restarts) gets picked up without a UI reload.+let _tokenPromise = null;++async function fetchToken() {+ const res = await fetch('/local/ipc-token');+ if (!res.ok) {+ // 503 means "agent service not running yet" — propagate so the+ // hook can decide whether to retry.+ const err = new Error(`token fetch failed: ${res.status}`);+ err.status = res.status;+ throw err;+ }+ const json = await res.json();+ return json.token;+}++async function ipcToken() {+ if (!_tokenPromise) {+ _tokenPromise = fetchToken().catch((err) => {+ // Don't cache failure — next call will retry.+ _tokenPromise = null;+ throw err;+ });+ }+ return _tokenPromise;+}++function invalidateToken() {+ _tokenPromise = null;+}++async function authedHeaders(extra) {+ let headers = { Accept: 'application/json', ...(extra || {}) };+ try {+ const tok = await ipcToken();+ if (tok) headers.Authorization = `Bearer ${tok}`;+ } catch {+ // Fall through with no Authorization header. /health still works+ // and any other endpoint will return 401, which the hooks already+ // surface as "agent unreachable".+ }+ return headers;+}+async function get(path) {- const res = await fetch(`${BASE}${path}`, {- method: 'GET',- headers: { Accept: 'application/json' },- });+ const headers = await authedHeaders();+ let res = await fetch(`${BASE}${path}`, { method: 'GET', headers });+ if (res.status === 401) {+ // Token might be stale (file rewritten on agent restart). One+ // retry with a freshly fetched token before bubbling the error.+ invalidateToken();+ const retryHeaders = await authedHeaders();+ res = await fetch(`${BASE}${path}`, { method: 'GET', headers: retryHeaders });+ }if (!res.ok) {const text = await res.text().catch(() => '');throw new Error(`IPC ${path} ${res.status}: ${text || res.statusText}`);@@ -28,11 +81,21 @@ async function get(path) {}async function post(path, body) {- const res = await fetch(`${BASE}${path}`, {+ const headers = await authedHeaders({ 'Content-Type': 'application/json' });+ let res = await fetch(`${BASE}${path}`, {method: 'POST',- headers: { 'Content-Type': 'application/json', Accept: 'application/json' },+ headers,body: body ? JSON.stringify(body) : null,});+ if (res.status === 401) {+ invalidateToken();+ const retryHeaders = await authedHeaders({ 'Content-Type': 'application/json' });+ res = await fetch(`${BASE}${path}`, {+ method: 'POST',+ headers: retryHeaders,+ body: body ? JSON.stringify(body) : null,+ });+ }if (!res.ok) {const text = await res.text().catch(() => '');throw new Error(`IPC ${path} ${res.status}: ${text || res.statusText}`);@@ -99,4 +162,10 @@ export const local = {localCall('/local/pair/start', { panel_url: panelUrl, server_name: serverName }),pairState: () => localGet('/local/pair/state'),pairCancel: () => localCall('/local/pair/cancel'),+ // The single-string entry path. The agent decodes the string, calls+ // /api/v1/servers/register on the panel, and lands on the same+ // "claimed" state the pair-code flow ends in — so polling /state+ // works unchanged.+ pairConnectionString: (connectionString) =>+ localCall('/local/pair/connection-string', { connection_string: connectionString }),};diff --git a/agent/ui/src/pages/Pair.jsx b/agent/ui/src/pages/Pair.jsxindex f21f2b0e..cda41380 100644--- a/agent/ui/src/pages/Pair.jsx+++ b/agent/ui/src/pages/Pair.jsx@@ -29,23 +29,44 @@ function CopyValue({ value, large }) {);}-function FormStage({ onSubmit, busy, defaultName }) {+function FormStage({ onConnectionString, onPairCode, busy, defaultName }) {+ // Default to the connection-string tab — that's the modern entry path+ // (one paste, one click). The legacy pair-code form stays available+ // for users who already started from the panel's "Pair existing+ // agent" tab, or who can't paste from clipboard for some reason.+ const [mode, setMode] = useState('connection-string');+ const [connString, setConnString] = useState('');const [panelUrl, setPanelUrl] = useState('');const [name, setName] = useState(defaultName || '');const [error, setError] = useState('');- function submit(e) {+ function submitConnString(e) {+ e.preventDefault();+ const trimmed = connString.trim();+ if (!trimmed) {+ setError('Paste the connection string from your panel.');+ return;+ }+ if (!trimmed.startsWith('sk_conn_')) {+ setError('That doesn’t look like a connection string. Generate one from the panel’s Add Server screen.');+ return;+ }+ setError('');+ onConnectionString(trimmed);+ }++ function submitPairCode(e) {e.preventDefault();if (!panelUrl.trim()) {setError('Panel URL is required');return;}setError('');- onSubmit(panelUrl.trim(), name.trim());+ onPairCode(panelUrl.trim(), name.trim());}return (- <form onSubmit={submit} className="wizard">+ <div className="wizard"><div className="wizard__head"><div className="wizard__brand"><Server size={28} />@@ -54,45 +75,97 @@ function FormStage({ onSubmit, busy, defaultName }) {<p className="wizard__sub">Connect this machine to your ServerKit panel.</p></div>- <div className="wizard__body">- <label className="field">- <span className="field__label">Panel URL</span>- <input- type="text"- className="field__input"- placeholder="https://panel.example.com"- value={panelUrl}- onChange={(e) => setPanelUrl(e.target.value)}- autoFocus- spellCheck={false}- />- <span className="field__hint">The full URL of your ServerKit control panel.</span>- </label>-- <label className="field">- <span className="field__label">Server name <span className="muted">(optional)</span></span>- <input- type="text"- className="field__input"- placeholder="Defaults to hostname"- value={name}- onChange={(e) => setName(e.target.value)}- spellCheck={false}- />- <span className="field__hint">How this machine appears in your panel.</span>- </label>-- {error && <div className="banner banner--warn">{error}</div>}-- <button type="submit" className="btn btn--primary btn--large" disabled={busy}>- {busy ? (- <><Loader2 size={16} className="spin" /> Connecting…</>- ) : (- <>Connect <ArrowRight size={16} /></>- )}+ <div className="wizard__tabs" role="tablist">+ <button+ type="button"+ role="tab"+ aria-selected={mode === 'connection-string'}+ className={'wizard__tab ' + (mode === 'connection-string' ? 'is-active' : '')}+ onClick={() => { setMode('connection-string'); setError(''); }}+ >+ Connection string+ </button>+ <button+ type="button"+ role="tab"+ aria-selected={mode === 'pair-code'}+ className={'wizard__tab ' + (mode === 'pair-code' ? 'is-active' : '')}+ onClick={() => { setMode('pair-code'); setError(''); }}+ >+ Pair code</button></div>- </form>++ {mode === 'connection-string' ? (+ <form onSubmit={submitConnString} className="wizard__body">+ <label className="field">+ <span className="field__label">Connection string</span>+ <textarea+ className="field__input field__input--mono"+ rows={4}+ placeholder="sk_conn_v1...."+ value={connString}+ onChange={(e) => setConnString(e.target.value)}+ autoFocus+ spellCheck={false}+ />+ <span className="field__hint">+ Generate it in the panel: <strong>Add Server → Connection string</strong>.+ The hostname of this machine becomes the server name automatically.+ </span>+ </label>++ {error && <div className="banner banner--warn">{error}</div>}++ <button type="submit" className="btn btn--primary btn--large" disabled={busy}>+ {busy ? (+ <><Loader2 size={16} className="spin" /> Connecting…</>+ ) : (+ <>Connect <ArrowRight size={16} /></>+ )}+ </button>+ </form>+ ) : (+ <form onSubmit={submitPairCode} className="wizard__body">+ <label className="field">+ <span className="field__label">Panel URL</span>+ <input+ type="text"+ className="field__input"+ placeholder="https://panel.example.com"+ value={panelUrl}+ onChange={(e) => setPanelUrl(e.target.value)}+ autoFocus+ spellCheck={false}+ />+ <span className="field__hint">The full URL of your ServerKit control panel.</span>+ </label>++ <label className="field">+ <span className="field__label">Server name <span className="muted">(optional)</span></span>+ <input+ type="text"+ className="field__input"+ placeholder="Defaults to hostname"+ value={name}+ onChange={(e) => setName(e.target.value)}+ spellCheck={false}+ />+ <span className="field__hint">How this machine appears in your panel.</span>+ </label>++ {error && <div className="banner banner--warn">{error}</div>}++ <button type="submit" className="btn btn--primary btn--large" disabled={busy}>+ {busy ? (+ <><Loader2 size={16} className="spin" /> Connecting…</>+ ) : (+ <>Connect <ArrowRight size={16} /></>+ )}+ </button>+ </form>+ )}+ </div>);}@@ -202,7 +275,7 @@ export default function Pair() {};}, []);- async function handleSubmit(panelUrl, name) {+ async function handlePairCode(panelUrl, name) {setBusy(true);try {await local.pairStart(panelUrl, name);@@ -215,6 +288,21 @@ export default function Pair() {}}+ async function handleConnectionString(value) {+ setBusy(true);+ try {+ await local.pairConnectionString(value);+ // Optimistic transition: the agent's poll loop will catch up+ // and report claimed/error within a second or two, but moving+ // off the form right away keeps the UI from feeling stuck.+ setState({ state: 'enrolling' });+ } catch (err) {+ setState({ state: 'error', error: err.message });+ } finally {+ setBusy(false);+ }+ }+async function handleCancel() {await local.pairCancel();setState({ state: 'idle' });@@ -227,7 +315,42 @@ export default function Pair() {return <ErrorStage state={state} onRetry={() => setState({ state: 'idle' })} />;}if (state.state === 'enrolling' || state.state === 'waiting') {- return <PairCodeStage state={state} onCancel={handleCancel} />;+ // The pair-code wizard shows a code+passphrase pane, but the+ // connection-string flow has nothing for the user to copy at this+ // stage — it's just "wait for /register to come back." Pick the+ // pane based on whether we have a code yet.+ if (state.code || state.code_formatted) {+ return <PairCodeStage state={state} onCancel={handleCancel} />;+ }+ return <ConnectingStage onCancel={handleCancel} />;}- return <FormStage onSubmit={handleSubmit} busy={busy} />;+ return (+ <FormStage+ onConnectionString={handleConnectionString}+ onPairCode={handlePairCode}+ busy={busy}+ />+ );+}++function ConnectingStage({ onCancel }) {+ return (+ <div className="wizard">+ <div className="wizard__head">+ <h1 className="wizard__title">Registering this server…</h1>+ <p className="wizard__sub">+ Talking to the panel and saving credentials. This usually takes a few seconds.+ </p>+ </div>+ <div className="wizard__body">+ <div className="wizard__status">+ <Loader2 size={14} className="spin" />+ <span>Waiting for the panel to confirm registration…</span>+ </div>+ <button type="button" className="btn" onClick={onCancel}>+ Cancel+ </button>+ </div>+ </div>+ );}diff --git a/agent/ui/src/styles/main.scss b/agent/ui/src/styles/main.scssindex 289ad33d..06f35b8f 100644--- a/agent/ui/src/styles/main.scss+++ b/agent/ui/src/styles/main.scss@@ -756,6 +756,52 @@ a {padding: $space-sm 0;}+// Tabs sit above the wizard body — let the user pick between the+// connection-string and pair-code entry paths. Keep them visually quiet+// so the form below remains the focal point.+.wizard__tabs {+ display: flex;+ gap: 4px;+ max-width: 460px;+ margin: 0 auto $space-sm;+ padding: 4px;+ background: $bg-elevated;+ border: 1px solid $border-default;+ border-radius: $radius-md;+}++.wizard__tab {+ flex: 1;+ padding: 8px 12px;+ border: 0;+ border-radius: $radius-sm;+ background: transparent;+ color: $text-tertiary;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ transition: background 120ms, color 120ms;++ &:hover {+ color: $text-primary;+ }++ &.is-active {+ background: $bg-card;+ color: $text-primary;+ box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2);+ }+}++.field__input--mono {+ font-family: 'JetBrains Mono', 'Consolas', ui-monospace, monospace;+ font-size: 12px;+ line-height: 1.5;+ resize: vertical;+ min-height: 80px;+ word-break: break-all;+}+// Form fields used by the wizard.field {display: flex;diff --git a/backend/app/api/servers.py b/backend/app/api/servers.pyindex 1d0222a6..24078413 100644--- a/backend/app/api/servers.py+++ b/backend/app/api/servers.py@@ -6,6 +6,7 @@ Endpoints for managing remote servers and their agents.import osimport hashlib+import hmacimport requestsfrom datetime import datetime, timedeltafrom flask import Blueprint, request, jsonify, Response, current_app, redirect@@ -17,8 +18,58 @@ from app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand,from app.services.agent_registry import agent_registryfrom app.services.agent_fleet_service import fleet_servicefrom app.services.discovery_service import discovery_service+from app.services import connection_string as connection_string_codecfrom app.middleware.rbac import admin_required, developer_required++# Default token lifetime when the caller doesn't specify one. 7 days is+# the sweet spot from the design discussion: long enough that "I'll set+# this up later tonight" survives, short enough that an abandoned string+# doesn't linger forever as a usable bearer credential.+_DEFAULT_TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60++# Sentinel placeholder name used while a server row exists but no agent+# has registered against it yet. The register endpoint replaces this+# with the agent's reported hostname; the prefix check there is the+# reason the format here must stay stable.+_PLACEHOLDER_NAME_PREFIX = "Pending pairing ("+++def _placeholder_name(server_id: str) -> str:+ """Generate the placeholder name shown in the panel until pairing+ completes. Includes a short id suffix so multiple unpaired rows are+ distinguishable."""+ return f"{_PLACEHOLDER_NAME_PREFIX}{server_id[:8]})"+++def _is_placeholder_name(name) -> bool:+ """True if the given name is the placeholder we issued at create+ time. Used by the register endpoint to decide whether overwriting+ with the agent's hostname is safe (a user-chosen name shouldn't be+ clobbered on re-pair)."""+ return isinstance(name, str) and name.startswith(_PLACEHOLDER_NAME_PREFIX)+++def _resolve_token_expiry(expires_in):+ """Convert an ``expires_in`` request field to a concrete datetime.++ - missing / None → default 7 days+ - positive int seconds → that many seconds from now+ - -1 → "never" (100 years out — DB-safe sentinel)+ """+ if expires_in is None:+ seconds = _DEFAULT_TOKEN_TTL_SECONDS+ elif expires_in == -1:+ return datetime.utcnow() + timedelta(days=365 * 100)+ else:+ try:+ seconds = int(expires_in)+ except (TypeError, ValueError):+ seconds = _DEFAULT_TOKEN_TTL_SECONDS+ if seconds <= 0:+ seconds = _DEFAULT_TOKEN_TTL_SECONDS+ return datetime.utcnow() + timedelta(seconds=seconds)+servers_bp = Blueprint('servers', __name__)@@ -227,16 +278,21 @@ def list_servers():@developer_requireddef create_server():"""- Create a new server and generate registration token.+ Create a new server slot and generate a connection string.- Returns server info with registration token for agent installation.+ The user no longer types a server name here — the agent's hostname+ becomes the name on first register. We just allocate a row, mint a+ single-use registration token, and bundle URL+token+expiry into one+ pasteable string.++ Body fields (all optional):+ expires_in: token TTL in seconds. -1 = never, missing = 7 days.+ description, group_id, tags, permissions, permission_profile,+ allowed_ips: passed through unchanged."""- data = request.get_json()+ data = request.get_json() or {}user_id = get_jwt_identity()- if not data.get('name'):- return jsonify({'error': 'Name is required'}), 400-# Generate registration tokenregistration_token = Server.generate_registration_token()@@ -252,24 +308,44 @@ def create_server():elif permissions is None:permissions = ['*']+ expires_at = _resolve_token_expiry(data.get('expires_in'))+server = Server(- name=data['name'],+ # Temporary name — replaced with the agent's hostname when the+ # agent calls /register. _is_placeholder_name() in the register+ # endpoint detects this and overwrites it; user-chosen names are+ # left alone.+ name=_PLACEHOLDER_NAME_PREFIX + "...)",description=data.get('description'),group_id=data.get('group_id'),tags=data.get('tags', []),permissions=permissions,allowed_ips=data.get('allowed_ips', []),registered_by=user_id,- registration_token_expires=datetime.utcnow() + timedelta(hours=24)+ registration_token_expires=expires_at,)server.set_registration_token(registration_token)db.session.add(server)db.session.commit()+ # Now that the row has its UUID, give it a placeholder with a short+ # id suffix so multiple unpaired rows are distinguishable in the UI.+ server.name = _placeholder_name(server.id)+ db.session.commit()++ panel_url = _get_external_base_url()+ conn_string = connection_string_codec.encode(+ url=panel_url,+ token=registration_token,+ expires_at=expires_at,+ )+result = server.to_dict()result['registration_token'] = registration_tokenresult['registration_expires'] = server.registration_token_expires.isoformat()+ result['connection_string'] = conn_string+ result['panel_url'] = panel_urlreturn jsonify(result), 201@@ -396,22 +472,41 @@ def delete_server(server_id):@jwt_required()@developer_requireddef regenerate_token(server_id):- """Regenerate registration token for a server"""+ """Regenerate the registration token for a server and return a fresh+ connection string.++ Used both for first-pair (panel just created the row) and re-pair+ (the agent was uninstalled / reinstalled and lost its credentials).+ Body is optional; only ``expires_in`` is read (same semantics as+ create_server).+ """server = Server.query.get(server_id)if not server:return jsonify({'error': 'Server not found'}), 404+ data = request.get_json(silent=True) or {}+ expires_at = _resolve_token_expiry(data.get('expires_in'))+registration_token = Server.generate_registration_token()server.set_registration_token(registration_token)- server.registration_token_expires = datetime.utcnow() + timedelta(hours=24)+ server.registration_token_expires = expires_atserver.status = 'pending'server.agent_id = Nonedb.session.commit()+ panel_url = _get_external_base_url()+ conn_string = connection_string_codec.encode(+ url=panel_url,+ token=registration_token,+ expires_at=expires_at,+ )+return jsonify({'registration_token': registration_token,- 'registration_expires': server.registration_token_expires.isoformat()+ 'registration_expires': server.registration_token_expires.isoformat(),+ 'connection_string': conn_string,+ 'panel_url': panel_url,})@@ -475,9 +570,15 @@ def register_agent():server.agent_version = data.get('agent_version')- # Update name if provided and different- if data.get('name') and not server.name:- server.name = data['name']+ # Replace the panel-issued placeholder name with whatever the agent+ # reports — preferring the OS hostname over the agent's optional+ # top-level "name" field. Once a user has renamed the server in the+ # UI, the placeholder check fails and we leave their name alone, so+ # re-pair after reinstall doesn't clobber renames.+ if _is_placeholder_name(server.name):+ reported_name = (system_info.get('hostname') if system_info else None) or data.get('name')+ if reported_name:+ server.name = reported_namedb.session.commit()@@ -826,7 +927,30 @@ def rotate_api_key(server_id):new_api_key, new_api_secret, rotation_id = server.start_key_rotation()db.session.commit()- # Send credential update to agent+ # Send credential update to agent. The agent verifies an HMAC over+ # the new credentials computed with its *current* secret before+ # applying the rotation, so a session-level WS auth bypass alone+ # can't be used to silently rotate fleet credentials to attacker-+ # controlled values. The agent expects:+ # hex(HMAC-SHA256("rotation_id:agent_id:new_api_key:new_api_secret",+ # current_api_secret))+ current_secret = server.get_api_secret() or ''+ if not current_secret:+ # Agents paired before the api_secret_encrypted column existed+ # can't be verified. Better to fail the rotation than silently+ # ship an unsigned credential update — operators can re-pair to+ # establish a verifiable secret on disk.+ return jsonify({+ 'error': 'Server has no recoverable secret on file; re-pair the agent before rotating.',+ 'code': 'NO_CURRENT_SECRET'+ }), 409+ payload = f'{rotation_id}:{server.agent_id}:{new_api_key}:{new_api_secret}'+ sig = hmac.new(+ current_secret.encode('utf-8'),+ payload.encode('utf-8'),+ hashlib.sha256,+ ).hexdigest()+agent = agent_registry.get_agent(server_id)if agent and agent_registry._socketio:agent_registry._socketio.emit(@@ -835,7 +959,8 @@ def rotate_api_key(server_id):'type': 'credential_update','rotation_id': rotation_id,'api_key': new_api_key,- 'api_secret': new_api_secret+ 'api_secret': new_api_secret,+ 'hmac_sig': sig,},room=agent.socket_id,namespace='/agent'diff --git a/backend/app/services/connection_string.py b/backend/app/services/connection_string.pynew file mode 100644index 00000000..2602b717--- /dev/null+++ b/backend/app/services/connection_string.py@@ -0,0 +1,98 @@+"""+Connection string codec.++A connection string is a single pasteable blob the user copies from the+panel and pastes into the agent's pairing wizard. It bundles the panel+URL + a single-use registration token + an optional expiry, replacing+the older flow where the user typed the URL and token into separate+fields.++Format: ``sk_conn_v1.<base64url(json_payload)>``++The version prefix is intentional — if we ever need to add fields the+agent must understand (a different signing scheme, a fleet ID, …) the+agent can refuse to decode unknown versions instead of silently+mis-parsing. Today's payload is deliberately tiny:++ {+ "url": "https://panel.example.com",+ "token": "sk_reg_xxx",+ "expires_at": "2026-05-08T17:00:00Z" # or null for "never"+ }++Note: the panel never *reads* connection strings — the agent does.+``decode`` is exported only for tests and for symmetry, so the codec+has a single owner.+"""++import base64+import json+from datetime import datetime+from typing import Optional+++VERSION_PREFIX = "sk_conn_v1."+++def encode(url: str, token: str, expires_at: Optional[datetime]) -> str:+ """Pack the three fields into a single sk_conn_v1.<...> string.++ expires_at=None means the token has no expiry (panel-side feature+ knob — the registration token is single-use either way, so a missing+ expiry is safe).+ """+ if not url or not token:+ raise ValueError("url and token are required")++ payload = {+ "url": url.rstrip("/"),+ "token": token,+ "expires_at": expires_at.isoformat() + "Z" if expires_at else None,+ }+ raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")+ encoded = base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")+ return VERSION_PREFIX + encoded+++def decode(s: str) -> dict:+ """Reverse of encode. Raises ValueError on any parse / version error.++ Returns a dict with keys ``url``, ``token``, ``expires_at`` (the+ latter as a datetime or None).+ """+ if not isinstance(s, str) or not s.startswith(VERSION_PREFIX):+ raise ValueError("not a v1 connection string")++ body = s[len(VERSION_PREFIX):]+ # urlsafe_b64decode requires correct padding; we strip it on encode+ # to keep the string short, so re-pad here.+ pad = "=" * (-len(body) % 4)+ try:+ raw = base64.urlsafe_b64decode(body + pad)+ except Exception as exc:+ raise ValueError(f"invalid base64: {exc}") from exc++ try:+ data = json.loads(raw.decode("utf-8"))+ except Exception as exc:+ raise ValueError(f"invalid json: {exc}") from exc++ url = data.get("url")+ token = data.get("token")+ if not isinstance(url, str) or not isinstance(token, str):+ raise ValueError("missing url or token")++ expires_raw = data.get("expires_at")+ expires_at: Optional[datetime] = None+ if expires_raw is not None:+ if not isinstance(expires_raw, str):+ raise ValueError("expires_at must be ISO 8601 string or null")+ # Tolerate trailing Z (UTC marker) which datetime.fromisoformat+ # didn't accept until 3.11.+ cleaned = expires_raw[:-1] if expires_raw.endswith("Z") else expires_raw+ try:+ expires_at = datetime.fromisoformat(cleaned)+ except Exception as exc:+ raise ValueError(f"invalid expires_at: {exc}") from exc++ return {"url": url, "token": token, "expires_at": expires_at}diff --git a/backend/tests/test_connection_string.py b/backend/tests/test_connection_string.pynew file mode 100644index 00000000..badecfb4--- /dev/null+++ b/backend/tests/test_connection_string.py@@ -0,0 +1,72 @@+"""Tests for app.services.connection_string codec."""++from datetime import datetime++import pytest++from app.services import connection_string as cs+++def test_encode_decode_round_trip():+ expires = datetime(2026, 5, 8, 17, 0, 0)+ s = cs.encode(url='https://panel.example.com', token='sk_reg_abc', expires_at=expires)+ assert s.startswith('sk_conn_v1.')++ decoded = cs.decode(s)+ assert decoded['url'] == 'https://panel.example.com'+ assert decoded['token'] == 'sk_reg_abc'+ assert decoded['expires_at'] == expires+++def test_encode_strips_trailing_slash_from_url():+ s = cs.encode(url='https://panel.example.com/', token='t', expires_at=None)+ assert cs.decode(s)['url'] == 'https://panel.example.com'+++def test_encode_with_no_expiry():+ s = cs.encode(url='https://panel.example.com', token='t', expires_at=None)+ decoded = cs.decode(s)+ assert decoded['expires_at'] is None+++def test_decode_rejects_missing_version_prefix():+ # Plain base64 without our prefix should be rejected — protects+ # agents from silently accepting a future format they don't understand.+ with pytest.raises(ValueError, match='v1'):+ cs.decode('not_a_connection_string')+++def test_decode_rejects_unknown_version():+ with pytest.raises(ValueError, match='v1'):+ cs.decode('sk_conn_v2.abc')+++def test_decode_rejects_bad_base64():+ with pytest.raises(ValueError, match='base64'):+ cs.decode('sk_conn_v1.!!!not_base64!!!')+++def test_decode_rejects_missing_fields():+ import base64+ import json++ raw = json.dumps({'url': 'https://x'}).encode() # no token+ body = base64.urlsafe_b64encode(raw).rstrip(b'=').decode()+ with pytest.raises(ValueError, match='missing url or token'):+ cs.decode('sk_conn_v1.' + body)+++def test_encode_rejects_empty_inputs():+ with pytest.raises(ValueError):+ cs.encode(url='', token='t', expires_at=None)+ with pytest.raises(ValueError):+ cs.encode(url='https://x', token='', expires_at=None)+++def test_decode_handles_iso_with_z_suffix():+ # encode() emits ISO with a trailing Z. fromisoformat() didn't accept+ # that until 3.11, so the codec strips it explicitly — guard against+ # regressions if anyone touches that branch.+ expires = datetime(2026, 5, 8, 17, 0, 0)+ s = cs.encode(url='https://x', token='t', expires_at=expires)+ assert cs.decode(s)['expires_at'] == expiresdiff --git a/backend/tests/test_servers_api_pairing.py b/backend/tests/test_servers_api_pairing.pynew file mode 100644index 00000000..d578fdc0--- /dev/null+++ b/backend/tests/test_servers_api_pairing.py@@ -0,0 +1,124 @@+"""End-to-end tests for the connection-string pairing flow.++Covers:+- Creating a server with no name returns a placeholder + connection string.+- Registering with a hostname replaces the placeholder.+- A second register (re-pair) does NOT clobber a user-chosen name.+- regenerate-token produces a new connection string.+"""++from app.services import connection_string as cs+from app.models.server import Server+from app import db+++def _create_server(client, auth_headers, expires_in=None):+ body = {}+ if expires_in is not None:+ body['expires_in'] = expires_in+ return client.post('/api/v1/servers', headers=auth_headers, json=body)+++def test_create_server_without_name_returns_connection_string(client, auth_headers, app):+ resp = _create_server(client, auth_headers)+ assert resp.status_code == 201, resp.get_json()++ data = resp.get_json()+ assert 'connection_string' in data+ assert data['connection_string'].startswith('sk_conn_v1.')+ assert data['name'].startswith('Pending pairing (')++ # Token in the connection string matches the registration_token in the response+ decoded = cs.decode(data['connection_string'])+ assert decoded['token'] == data['registration_token']+ assert decoded['url'] # whatever the test client reports as host+ assert decoded['expires_at'] is not None # default 7d, not "never"+++def test_create_server_with_never_expiry(client, auth_headers, app):+ resp = _create_server(client, auth_headers, expires_in=-1)+ assert resp.status_code == 201+ decoded = cs.decode(resp.get_json()['connection_string'])+ # 100 years out is the "never" sentinel — far enough in the future+ # that any sane "is this still valid" check passes.+ assert decoded['expires_at'].year >= 2100+++def test_register_replaces_placeholder_with_hostname(client, auth_headers, app):+ create_resp = _create_server(client, auth_headers)+ server_id = create_resp.get_json()['id']+ token = create_resp.get_json()['registration_token']++ register_resp = client.post('/api/v1/servers/register', json={+ 'token': token,+ 'system_info': {'hostname': 'web-01.prod', 'os': 'linux'},+ 'agent_version': '1.0.0',+ })+ assert register_resp.status_code == 200, register_resp.get_json()++ with app.app_context():+ server = Server.query.get(server_id)+ assert server.name == 'web-01.prod'+ assert server.hostname == 'web-01.prod'+++def test_re_register_does_not_overwrite_user_chosen_name(client, auth_headers, app):+ """If the user renamed the server in the UI before the agent reinstalls,+ the second register must not overwrite that name."""+ create_resp = _create_server(client, auth_headers)+ server_id = create_resp.get_json()['id']+ token1 = create_resp.get_json()['registration_token']++ # First pair: placeholder → hostname+ client.post('/api/v1/servers/register', json={+ 'token': token1,+ 'system_info': {'hostname': 'web-01'},+ })++ # User renames in the UI (simulated directly on the model)+ with app.app_context():+ server = Server.query.get(server_id)+ server.name = 'My Production Web Server'+ db.session.commit()++ # Regenerate token + re-pair (agent reinstalled)+ regen_resp = client.post(+ f'/api/v1/servers/{server_id}/regenerate-token',+ headers=auth_headers,+ json={},+ )+ assert regen_resp.status_code == 200+ token2 = regen_resp.get_json()['registration_token']+ assert 'connection_string' in regen_resp.get_json()++ client.post('/api/v1/servers/register', json={+ 'token': token2,+ 'system_info': {'hostname': 'web-01-new-hostname'},+ })++ with app.app_context():+ server = Server.query.get(server_id)+ assert server.name == 'My Production Web Server'+ # Hostname still updates — that field tracks reality, name is for humans+ assert server.hostname == 'web-01-new-hostname'+++def test_regenerate_token_returns_connection_string(client, auth_headers, app):+ create_resp = _create_server(client, auth_headers)+ server_id = create_resp.get_json()['id']+ original_token = create_resp.get_json()['registration_token']++ regen_resp = client.post(+ f'/api/v1/servers/{server_id}/regenerate-token',+ headers=auth_headers,+ json={'expires_in': 3600}, # 1 hour+ )+ assert regen_resp.status_code == 200+ body = regen_resp.get_json()+ assert body['connection_string'].startswith('sk_conn_v1.')++ new_token = body['registration_token']+ assert new_token != original_token++ decoded = cs.decode(body['connection_string'])+ assert decoded['token'] == new_tokendiff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsxindex 8b1b325d..7dd618fa 100644--- a/frontend/src/pages/ServerDetail.jsx+++ b/frontend/src/pages/ServerDetail.jsx@@ -104,35 +104,26 @@ const ServerDetail = () => {}}- async function handleRegenerateToken() {- const tokenConfirmed = await confirm({ title: 'Regenerate Token', message: 'Generate a new registration token? The old token will be invalidated.', variant: 'warning' });- if (!tokenConfirmed) return;-- try {- const result = await api.generateRegistrationToken(id);- toast.success('New registration token generated');- setServer(prev => ({- ...prev,- registration_token: result.registration_token,- registration_expires: result.registration_expires- }));- } catch (err) {- toast.error(err.message || 'Failed to generate token');- }+ // Both the inline "Generate Token" header button and the SettingsTab+ // regenerate button funnel through the same modal — the modal owns the+ // expiry picker and the connection-string display, so the header path+ // doesn't need its own confirm dialog. Reaching the modal effectively+ // *is* the confirmation: the actual token mint happens when the user+ // clicks "Generate" inside it.+ async function handleOpenTokenModal() {+ setShowTokenModal(true);}- async function handleGenerateToken() {- try {- const result = await api.generateRegistrationToken(id);- setServer(prev => ({- ...prev,- registration_token: result.registration_token,- registration_expires: result.registration_expires- }));- setShowTokenModal(true);- } catch (err) {- toast.error(err.message || 'Failed to generate token');- }+ function handleTokenGenerated(result) {+ // Mirror the new token onto the in-memory server so the existing+ // AgentRegistrationSection (rendered in SettingsTab) reflects it+ // without a full reload.+ setServer(prev => ({+ ...prev,+ registration_token: result.registration_token,+ registration_expires: result.registration_expires,+ connection_string: result.connection_string,+ }));}if (loading) {@@ -190,6 +181,17 @@ const ServerDetail = () => {<div className="server-detail-header__identity"><div className="server-detail-header__title-row"><h1>{server.name}</h1>+ <CopyChip+ label="name"+ value={server.name}+ title="Copy server name"+ />+ <CopyChip+ label="id"+ value={server.id}+ title="Copy server ID"+ mono+ /><span className={`status-pill status-pill--${server.status || 'pending'}`}><span className="status-pill__dot" />{server.status || 'pending'}@@ -228,8 +230,8 @@ const ServerDetail = () => {<Button variant="outline" asChild><Link to={`/servers/${id}/docker`}>Docker</Link></Button>- <Button onClick={handleGenerateToken}>- <KeyIcon /> Generate Token+ <Button onClick={handleOpenTokenModal}>+ <KeyIcon /> Connection String</Button></div></header>@@ -285,7 +287,7 @@ const ServerDetail = () => {<SettingsTabserver={server}onUpdate={loadServer}- onRegenerateToken={handleRegenerateToken}+ onRegenerateToken={handleOpenTokenModal}onDelete={handleDeleteServer}/></TabsContent>@@ -296,6 +298,7 @@ const ServerDetail = () => {<TokenModalserver={server}onClose={() => setShowTokenModal(false)}+ onGenerated={handleTokenGenerated}/>)}<ConfirmDialog@@ -1463,76 +1466,23 @@ const MetricsTab = ({ serverId, metrics }) => {const AgentRegistrationSection = ({ server, onRegenerateToken }) => {- const [copied, setCopied] = useState(false);- const toast = useToast();-- const token = server.registration_token;const expires = server.registration_expires;const isExpired = expires && new Date(expires) < new Date();-- const linuxScript = token ? `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh | sudo bash -s -- \\- --server "${window.location.origin}" \\- --token "${token}"` : '';-- const windowsScript = token ? `irm ${window.location.origin}/api/v1/servers/install.ps1 | iex-Install-ServerKitAgent -Server "${window.location.origin}" -Token "${token}"` : '';-- function copyToClipboard(text) {- navigator.clipboard.writeText(text);- setCopied(true);- toast.success('Copied to clipboard');- setTimeout(() => setCopied(false), 2000);- }+ const isOnline = server.status === 'online';return (<div className="form-section">- <h3>Agent Installation</h3>-- {token && !isExpired ? (- <div className="install-active">- <div className="token-status">- <span className="token-status-dot active" />- <span>Token active — expires {new Date(expires).toLocaleString()}</span>- </div>-- <div className="install-script-block">- <div className="install-script-header">- <TerminalIcon />- <span>Linux</span>- <Button variant="outline" size="sm" onClick={() => copyToClipboard(linuxScript)}>- <CopyIcon /> Copy- </Button>- </div>- <pre className="install-script-code">{linuxScript}</pre>- </div>-- <div className="install-script-block">- <div className="install-script-header">- <WindowsIcon />- <span>Windows (PowerShell)</span>- <Button variant="outline" size="sm" onClick={() => copyToClipboard(windowsScript)}>- <CopyIcon /> Copy- </Button>- </div>- <pre className="install-script-code">{windowsScript}</pre>- </div>-- <Button variant="outline" onClick={onRegenerateToken}>- <RefreshIcon /> Regenerate Token- </Button>- </div>- ) : (- <div className="install-inactive">- <p className="section-description">- {isExpired- ? 'The registration token has expired. Generate a new one to install or reinstall the agent.'- : 'Generate a registration token to install the agent on your server.'}- </p>- <Button onClick={onRegenerateToken}>- <KeyIcon /> Generate Token- </Button>- </div>- )}+ <h3>Connection String</h3>+ <p className="section-description">+ Generate a fresh connection string to pair (or re-pair) this server.+ Useful after reinstalling the agent — old credentials are gone, but a+ new string brings the agent right back to this row.+ {isOnline && ' This server is currently online; regenerating only affects re-pairing.'}+ {isExpired && ' The previous token has expired.'}+ </p>+ <Button onClick={onRegenerateToken}>+ <KeyIcon /> Generate Connection String+ </Button></div>);};@@ -1898,87 +1848,180 @@ const SettingsTab = ({ server, onUpdate, onRegenerateToken, onDelete }) => {};-const TokenModal = ({ server, onClose }) => {- const toast = useToast();- const token = server.registration_token;- const expires = server.registration_expires;-- const linuxScript = token ? `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh | sudo bash -s -- \\- --server "${window.location.origin}" \\- --token "${token}"` : '';+// Token-lifetime presets shown in the regenerate modal. Mirrors the values+// the Add Server modal uses (frontend/src/pages/Servers.jsx). Keep them in+// sync if you tweak either list.+const TOKEN_EXPIRY_OPTIONS = [+ { label: '1 hour', value: 60 * 60 },+ { label: '24 hours', value: 24 * 60 * 60 },+ { label: '7 days', value: 7 * 24 * 60 * 60 },+ { label: '30 days', value: 30 * 24 * 60 * 60 },+ { label: 'Never', value: -1 },+];- const windowsScript = token ? `irm ${window.location.origin}/api/v1/servers/install.ps1 | iex-Install-ServerKitAgent -Server "${window.location.origin}" -Token "${token}"` : '';+const TokenModal = ({ server, onClose, onGenerated }) => {+ const toast = useToast();+ const [expiresIn, setExpiresIn] = useState(7 * 24 * 60 * 60);+ const [generating, setGenerating] = useState(false);+ // Result of the most recent generation in *this* modal session. We+ // don't fall back to server.connection_string because the panel only+ // ever returns the connection string at create/regenerate time — once+ // the modal closes, the value is gone, so showing a stale one would+ // be misleading.+ const [result, setResult] = useState(null);++ async function handleGenerate() {+ setGenerating(true);+ try {+ const data = await api.generateRegistrationToken(server.id, { expires_in: expiresIn });+ setResult(data);+ onGenerated?.(data);+ toast.success('Connection string generated');+ } catch (err) {+ toast.error(err.message || 'Failed to generate connection string');+ } finally {+ setGenerating(false);+ }+ }function copyToClipboard(text) {navigator.clipboard.writeText(text);toast.success('Copied to clipboard');}+ const linuxScript = result ? `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh | sudo bash -s -- \\+ --server "${window.location.origin}" \\+ --token "${result.registration_token}"` : '';+ const windowsScript = result ? `irm ${window.location.origin}/api/v1/servers/install.ps1 | iex+Install-ServerKitAgent -Server "${window.location.origin}" -Token "${result.registration_token}"` : '';+return (<div className="modal-overlay" onClick={onClose}><div className="modal modal-lg" onClick={e => e.stopPropagation()}><div className="modal-header">- <h2>Agent Installation Token</h2>+ <h2>Connection String</h2><button className="modal-close" onClick={onClose}>×</button></div>+<div className="install-instructions">- <div className="token-status">- <span className="token-status-dot active" />- <span>Token active — expires {new Date(expires).toLocaleString()}</span>- </div>+ {!result ? (+ <>+ <p className="section-description">+ Generate a single pasteable string the agent can consume.+ The token inside is single-use — burned the moment any+ agent registers with it.+ </p>- <div className="install-tabs">- <div className="install-tab">- <div className="install-tab-header">- <TerminalIcon />- <div className="install-tab-title">- <span>Linux</span>- <span className="install-tab-description">Linux server with curl, tar, sudo, and systemd</span>+ <div className="form-row">+ <div className="form-group">+ <label>Token expires</label>+ <select+ value={expiresIn}+ onChange={(e) => setExpiresIn(Number(e.target.value))}+ >+ {TOKEN_EXPIRY_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select></div>- <Button variant="outline" size="sm" onClick={() => copyToClipboard(linuxScript)}>- <CopyIcon /> Copy+ </div>++ <div className="modal-actions">+ <Button variant="outline" onClick={onClose}>Cancel</Button>+ <Button onClick={handleGenerate} disabled={generating}>+ {generating ? 'Generating…' : 'Generate'}</Button></div>- <pre className="install-script">{linuxScript}</pre>- </div>+ </>+ ) : (+ <>+ <div className="token-status">+ <span className="token-status-dot active" />+ <span>+ Active — expires {new Date(result.registration_expires).toLocaleString()}+ </span>+ </div>- <div className="install-tab">- <div className="install-tab-header">- <WindowsIcon />- <div className="install-tab-title">- <span>Windows (PowerShell)</span>- <span className="install-tab-description">Run as Administrator</span>+ <div className="connection-string-field">+ <div className="connection-string-field__header">+ <KeyIcon />+ <span>Connection string</span>+ <Button variant="outline" size="sm" onClick={() => copyToClipboard(result.connection_string)}>+ <CopyIcon /> Copy+ </Button></div>- <Button variant="outline" size="sm" onClick={() => copyToClipboard(windowsScript)}>- <CopyIcon /> Copy- </Button>+ <pre className="connection-string-field__value">{result.connection_string}</pre></div>- <pre className="install-script">{windowsScript}</pre>- </div>- </div>- <div className="install-info">- <h4>What happens next?</h4>- <ol>- <li>Copy and run the install script on your server</li>- <li>The agent downloads, installs, and registers automatically</li>- <li>Your server will appear as <strong>Pending</strong> until the agent connects, then switch to <strong>Online</strong></li>- </ol>- <p className="text-muted">- The registration token expires in 24 hours. You can regenerate it from the server settings page.- </p>- </div>+ <details className="install-fallback">+ <summary>Need to install the agent first? Use the one-liner installer.</summary>+ <div className="install-tabs" style={{ marginTop: '0.75rem' }}>+ <div className="install-tab">+ <div className="install-tab-header">+ <TerminalIcon />+ <div className="install-tab-title">+ <span>Linux</span>+ <span className="install-tab-description">curl, tar, sudo, and systemd</span>+ </div>+ <Button variant="outline" size="sm" onClick={() => copyToClipboard(linuxScript)}>+ <CopyIcon /> Copy+ </Button>+ </div>+ <pre className="install-script">{linuxScript}</pre>+ </div>+ <div className="install-tab">+ <div className="install-tab-header">+ <WindowsIcon />+ <div className="install-tab-title">+ <span>Windows (PowerShell)</span>+ <span className="install-tab-description">Run as Administrator</span>+ </div>+ <Button variant="outline" size="sm" onClick={() => copyToClipboard(windowsScript)}>+ <CopyIcon /> Copy+ </Button>+ </div>+ <pre className="install-script">{windowsScript}</pre>+ </div>+ </div>+ </details>- <div className="modal-actions">- <Button onClick={onClose}>Close</Button>- </div>+ <div className="modal-actions">+ <Button variant="outline" onClick={() => setResult(null)}>+ Generate another+ </Button>+ <Button onClick={onClose}>Done</Button>+ </div>+ </>+ )}</div></div></div>);};+const CopyChip = ({ label, value, title, mono }) => {+ const toast = useToast();+ const handleCopy = (e) => {+ e.preventDefault();+ e.stopPropagation();+ if (!value) return;+ navigator.clipboard.writeText(value);+ toast.success(`${label[0].toUpperCase()}${label.slice(1)} copied`);+ };+ return (+ <button+ type="button"+ className={`copy-chip${mono ? ' copy-chip--mono' : ''}`}+ onClick={handleCopy}+ title={title || `Copy ${label}`}+ >+ <span className="copy-chip__label">{label}</span>+ <code className="copy-chip__value">{value}</code>+ <CopyIcon />+ </button>+ );+};+// Iconsconst FolderTinyIcon = () => (<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">diff --git a/frontend/src/pages/Servers.jsx b/frontend/src/pages/Servers.jsxindex 33277fde..c6f54635 100644--- a/frontend/src/pages/Servers.jsx+++ b/frontend/src/pages/Servers.jsx@@ -94,16 +94,15 @@ const Servers = () => {async function handleCopyInstall(server) {try {const result = await api.generateRegistrationToken(server.id);- const token = result?.registration_token || result?.token;- if (!token) {- toast.error('Could not generate install command');+ const connString = result?.connection_string;+ if (!connString) {+ toast.error('Could not generate connection string');return;}- const script = `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh | sudo bash -s -- \\\n --server "${window.location.origin}" \\\n --token "${token}"`;- await navigator.clipboard.writeText(script);- toast.success('Install command copied to clipboard');+ await navigator.clipboard.writeText(connString);+ toast.success('Connection string copied to clipboard');} catch (err) {- toast.error(err.message || 'Failed to generate install command');+ toast.error(err.message || 'Failed to generate connection string');}}@@ -561,7 +560,7 @@ const ServerRow = ({ server, selected, onToggle, onPing, onDelete, onCopyInstall</button>{status === 'pending' && (<button type="button" className="row-menu__item" role="menuitem" onClick={() => { closeMenu(); onCopyInstall(); }}>- <CopyIcon /> Copy install command+ <CopyIcon /> Copy connection string</button>)}<Link to={`/servers/${server.id}/docker`} className="row-menu__item" role="menuitem" onClick={closeMenu}>@@ -765,19 +764,25 @@ const PairAgentForm = ({ groups, onClose, onClaimed }) => {);};+// Token-lifetime presets shown in the "Add Server" expiry dropdown. The value+// is in seconds; -1 is a sentinel for "never" (the backend turns it into a+// far-future date). Default is 7 days — long enough to set up later that+// evening, short enough that an abandoned string doesn't linger forever as a+// usable bearer credential.+const EXPIRY_OPTIONS = [+ { label: '1 hour', value: 60 * 60 },+ { label: '24 hours', value: 24 * 60 * 60 },+ { label: '7 days', value: 7 * 24 * 60 * 60 },+ { label: '30 days', value: 30 * 24 * 60 * 60 },+ { label: 'Never', value: -1 },+];+const DEFAULT_EXPIRY = 7 * 24 * 60 * 60;+const AddServerModal = ({ groups, onClose, onCreated }) => {- const [mode, setMode] = useState('pair');+ const [mode, setMode] = useState('install');const [step, setStep] = useState(1);- const [formData, setFormData] = useState({- name: '',- description: '',- group_id: '',- hostname: '',- ip_address: '',- permission_profile: 'deployment_runner',- permissions: []- });- const [showOptional, setShowOptional] = useState(false);+ const [groupId, setGroupId] = useState('');+ const [expiresIn, setExpiresIn] = useState(DEFAULT_EXPIRY);const [registrationData, setRegistrationData] = useState(null);const [loading, setLoading] = useState(false);const [error, setError] = useState('');@@ -789,7 +794,14 @@ const AddServerModal = ({ groups, onClose, onCreated }) => {setLoading(true);try {- const result = await api.createServer(formData);+ // The backend now derives the server name from the agent's+ // hostname on /register, so we just send what the user can+ // actually pick: the token's lifetime and (optionally) which+ // group the row should land in.+ const result = await api.createServer({+ expires_in: expiresIn,+ group_id: groupId || undefined,+ });setRegistrationData(result);setStep(2);} catch (err) {@@ -799,16 +811,12 @@ const AddServerModal = ({ groups, onClose, onCreated }) => {}}- function handleChange(e) {- const { name, value } = e.target;- setFormData(prev => ({ ...prev, [name]: value }));- }-function copyToClipboard(text) {navigator.clipboard.writeText(text);toast.success('Copied to clipboard');}+ const connectionString = registrationData?.connection_string || '';const linuxInstallScript = registrationData ? `curl -fsSL ${window.location.origin}/api/v1/servers/install.sh | sudo bash -s -- \\--server "${window.location.origin}" \\--token "${registrationData.registration_token}"` : '';@@ -821,10 +829,10 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio<div className="modal server-setup-modal" onClick={e => e.stopPropagation()}><div className="modal-header"><div>- <h2>{step === 1 ? 'Add Server' : (mode === 'pair' ? 'Pair Agent' : 'Install Agent')}</h2>+ <h2>{step === 1 ? 'Add Server' : (mode === 'pair' ? 'Pair Agent' : 'Connect Agent')}</h2><p>{step === 2 && mode !== 'pair'- ? 'Run one command on the target machine to bring it online.'+ ? 'Paste the connection string into the agent, or run the one-liner installer.': step === 2? 'Enter the 6-char code shown on the agent and your passphrase.': 'Connect an existing agent or set up a brand-new machine.'}@@ -837,17 +845,17 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio<div className="mode-switcher"><buttontype="button"- className={`mode-switcher__tab${mode === 'pair' ? ' is-active' : ''}`}- onClick={() => setMode('pair')}+ className={`mode-switcher__tab${mode === 'install' ? ' is-active' : ''}`}+ onClick={() => setMode('install')}>- Pair existing agent+ Connection string</button><buttontype="button"- className={`mode-switcher__tab${mode === 'install' ? ' is-active' : ''}`}- onClick={() => setMode('install')}+ className={`mode-switcher__tab${mode === 'pair' ? ' is-active' : ''}`}+ onClick={() => setMode('pair')}>- Install new agent+ Pair code</button></div>)}@@ -863,24 +871,17 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio<div className="server-setup-form__body">{error && <div className="error-message">{error}</div>}- <div className="form-group">- <label>Server Name *</label>- <Input- type="text"- name="name"- value={formData.name}- onChange={handleChange}- placeholder="prod-web-01"- autoFocus- required- />- <span className="form-hint">A friendly label. The agent itself reports the real hostname when it connects.</span>- </div>+ <p className="section-description">+ Generate a single connection string. Paste it into the agent's+ pairing wizard, or use it with the one-liner installer. The+ agent's hostname becomes the server name on first connect — you+ can rename it later from the server's Settings tab.+ </p><div className="form-row"><div className="form-group"><label>Group</label>- <select name="group_id" value={formData.group_id} onChange={handleChange}>+ <select value={groupId} onChange={(e) => setGroupId(e.target.value)}><option value="">No Group</option>{groups.map(group => (<option key={group.id} value={group.id}>{group.name}</option>@@ -888,63 +889,18 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio</select></div><div className="form-group">- <label>Access Profile</label>- <select name="permission_profile" value={formData.permission_profile} onChange={handleChange}>- <option value="deployment_runner">Deployment Runner</option>- <option value="docker_manager">Docker Manager</option>- <option value="docker_readonly">Docker Read-Only</option>- <option value="full_access">Full Access</option>+ <label>Token expires</label>+ <select+ value={expiresIn}+ onChange={(e) => setExpiresIn(Number(e.target.value))}+ >+ {EXPIRY_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}</select>+ <span className="form-hint">Single-use. Burned the moment an agent registers with it.</span></div></div>-- <button- type="button"- className="form-disclosure"- onClick={() => setShowOptional(v => !v)}- aria-expanded={showOptional}- >- <span className={`form-disclosure__chevron${showOptional ? ' is-open' : ''}`}>›</span>- Optional details- <span className="form-disclosure__hint">description, hostname, IP</span>- </button>-- {showOptional && (- <div className="form-disclosure__panel">- <div className="form-group">- <label>Description</label>- <textarea- name="description"- value={formData.description}- onChange={handleChange}- placeholder="What this server is used for…"- rows={2}- />- </div>- <div className="form-row">- <div className="form-group">- <label>Hostname</label>- <Input- type="text"- name="hostname"- value={formData.hostname}- onChange={handleChange}- placeholder="server.example.com"- />- </div>- <div className="form-group">- <label>IP Address</label>- <Input- type="text"- name="ip_address"- value={formData.ip_address}- onChange={handleChange}- placeholder="192.168.1.100"- />- </div>- </div>- </div>- )}</div><div className="modal-actions">@@ -952,7 +908,7 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratioCancel</Button><Button type="submit" disabled={loading}>- {loading ? 'Creating…' : 'Create & Get Install Script'}+ {loading ? 'Generating…' : 'Generate Connection String'}</Button></div></form>@@ -962,37 +918,45 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio<div className="success-banner"><CheckCircleIcon /><div>- <strong>Agent token created</strong>- <p className="success-subtitle">Run the install script on your target machine to connect the agent.</p>+ <strong>Connection string ready</strong>+ <p className="success-subtitle">Paste this into the agent, or run the installer.</p></div></div>- <div className="install-tabs">- <InstallTab- title="Linux"- description="Linux server with curl, tar, sudo, and systemd"- icon={<TerminalIcon />}- script={linuxInstallScript}- onCopy={() => copyToClipboard(linuxInstallScript)}- />- <InstallTab- title="Windows (PowerShell)"- description="Run as Administrator"- icon={<WindowsIcon />}- script={windowsInstallScript}- onCopy={() => copyToClipboard(windowsInstallScript)}- />- </div>+ <ConnectionStringField+ value={connectionString}+ onCopy={() => copyToClipboard(connectionString)}+ />++ <details className="install-fallback">+ <summary>Need to install the agent first? Use the one-liner installer.</summary>+ <div className="install-tabs" style={{ marginTop: '0.75rem' }}>+ <InstallTab+ title="Linux"+ description="curl, tar, sudo, and systemd"+ icon={<TerminalIcon />}+ script={linuxInstallScript}+ onCopy={() => copyToClipboard(linuxInstallScript)}+ />+ <InstallTab+ title="Windows (PowerShell)"+ description="Run as Administrator"+ icon={<WindowsIcon />}+ script={windowsInstallScript}+ onCopy={() => copyToClipboard(windowsInstallScript)}+ />+ </div>+ </details><div className="install-info"><h4>What happens next?</h4><ol>- <li>Copy and run the install script on your server</li>- <li>The agent downloads, installs, and registers automatically</li>- <li>Your server will appear as <strong>Pending</strong> until the agent connects, then switch to <strong>Online</strong></li>+ <li>Open the agent on your target machine and paste the connection string.</li>+ <li>The agent registers automatically and reports its hostname back as the server name.</li>+ <li>The row in this list will switch from <strong>Pending</strong> to <strong>Online</strong>.</li></ol><p className="text-muted">- The registration token expires in 24 hours. You can regenerate it from the server details page.+ The token is single-use. If you reinstall the agent later, generate a new connection string from the server's Settings tab.</p></div></div>@@ -1009,6 +973,21 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio);};+const ConnectionStringField = ({ value, onCopy }) => {+ return (+ <div className="connection-string-field">+ <div className="connection-string-field__header">+ <KeyIcon />+ <span>Connection string</span>+ <Button variant="outline" size="sm" onClick={onCopy}>+ <CopyIcon /> Copy+ </Button>+ </div>+ <pre className="connection-string-field__value">{value}</pre>+ </div>+ );+};+const InstallTab = ({ title, description, icon, script, onCopy }) => {return (<div className="install-tab">@@ -1267,4 +1246,10 @@ const MoreIcon = () => (</svg>);+const KeyIcon = () => (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>+ </svg>+);+export default Servers;diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.jsindex 84cac707..29e6b80c 100644--- a/frontend/src/services/api/servers.js+++ b/frontend/src/services/api/servers.js@@ -44,9 +44,14 @@ export async function pingServer(id) {}// Server Registration-export async function generateRegistrationToken(serverId) {+//+// Optionally pass { expires_in } to control token lifetime in seconds.+// -1 means "never expires"; missing means the panel default (7 days).+// Response includes connection_string + registration_token + registration_expires.+export async function generateRegistrationToken(serverId, body = {}) {return this.request(`/servers/${serverId}/regenerate-token`, {- method: 'POST'+ method: 'POST',+ body});}diff --git a/frontend/src/styles/pages/_servers.scss b/frontend/src/styles/pages/_servers.scssindex 5b845089..2f778bf7 100644--- a/frontend/src/styles/pages/_servers.scss+++ b/frontend/src/styles/pages/_servers.scss@@ -775,6 +775,12 @@&__body {display: grid;+ // Pack rows to the top. Grid's default align-content is+ // "stretch", which makes every form-group expand to fill the+ // drawer height when the form is shorter than the panel —+ // that's the source of the huge vertical gaps between Pair+ // code / Passphrase / Server name when the drawer is tall.+ align-content: start;gap: $space-4;padding: $space-5 $space-6;overflow-y: auto;@@ -2164,6 +2170,61 @@word-break: break-all;}+// Hero block on the "connection string ready" screen and the regenerate+// drawer. Keeps the one pasteable blob visually heavier than the install+// scripts (which are now an "I haven't installed the agent yet" fallback).+.connection-string-field {+ margin-top: $space-5;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ background: $bg-elevated;+ overflow: hidden;+}++.connection-string-field__header {+ display: flex;+ align-items: center;+ gap: $space-3;+ padding: $space-3 $space-4;+ background: $bg-card;+ border-bottom: 1px solid $border-subtle;++ > span {+ flex: 1;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ }+}++.connection-string-field__value {+ padding: $space-4 $space-5;+ margin: 0;+ font-family: $font-mono;+ font-size: $font-size-sm;+ line-height: $line-height-relaxed;+ color: $text-primary;+ background: $bg-body;+ overflow-x: auto;+ white-space: pre-wrap;+ word-break: break-all;+}++.install-fallback {+ margin-top: $space-5;++ summary {+ cursor: pointer;+ font-size: $font-size-sm;+ color: $text-secondary;+ padding: $space-2 0;++ &:hover {+ color: $text-primary;+ }+ }+}+.install-info {margin-top: $space-6;padding: $space-5;@@ -2835,6 +2896,53 @@}}+ .copy-chip {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ padding: 2px $space-2;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ color: $text-tertiary;+ font-size: $font-size-xs;+ cursor: pointer;+ transition: all 0.12s ease;++ &:hover {+ color: $text-primary;+ border-color: $border-active;+ background: $bg-card;+ }++ &__label {+ text-transform: uppercase;+ letter-spacing: 0.05em;+ font-weight: $font-weight-semibold;+ color: $text-tertiary;+ }++ &__value {+ color: $text-secondary;+ font-family: $font-mono;+ font-size: $font-size-xs;+ background: transparent;+ padding: 0;+ max-width: 22ch;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &--mono &__value {+ font-size: 11px;+ }++ svg {+ opacity: 0.6;+ }+ }+&__meta {display: flex;align-items: center;