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 short-code agent pairing flow
Juan Denise5a90a3085c2
diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.goindex bca3c36a..645b8f36 100644--- a/agent/cmd/agent/main.go+++ b/agent/cmd/agent/main.go@@ -42,6 +42,7 @@ enabling remote Docker management, monitoring, and more.`,// Add commandsrootCmd.AddCommand(startCmd())rootCmd.AddCommand(registerCmd())+ rootCmd.AddCommand(pairCmd())rootCmd.AddCommand(statusCmd())rootCmd.AddCommand(versionCmd())rootCmd.AddCommand(configCmd())diff --git a/agent/cmd/agent/pair.go b/agent/cmd/agent/pair.gonew file mode 100644index 00000000..608fb98a--- /dev/null+++ b/agent/cmd/agent/pair.go@@ -0,0 +1,258 @@+package main++import (+ "bufio"+ "context"+ "crypto/rand"+ "encoding/base64"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "syscall"+ "time"++ "github.com/serverkit/agent/internal/config"+ "github.com/serverkit/agent/internal/logger"+ "github.com/serverkit/agent/internal/metrics"+ "github.com/serverkit/agent/internal/pairing"+ "github.com/spf13/cobra"+ "golang.org/x/term"+)++// pairCmd implements `serverkit-agent pair` — RustDesk-style short-code pairing.+//+// Flags:+//+// --server, -s Panel base URL (e.g. https://panel.example.com)+// --passphrase Passphrase to set on this agent (will prompt if absent)+// --headless No interactive prompts; read passphrase from $SERVERKIT_AGENT_PASSPHRASE+// --set-passphrase Write/overwrite passphrase only; don't begin pairing+func pairCmd() *cobra.Command {+ var (+ serverURL string+ passphrase string+ headless bool+ setPassphrase bool+ )++ cmd := &cobra.Command{+ Use: "pair",+ Short: "Pair this agent with a ServerKit panel using a short code",+ Long: `Pair this agent with a ServerKit panel.++Generates an Ed25519 keypair (cached at-rest), enrolls with the panel, and+displays a rotating 6-character pair code. An operator enters that code ++the passphrase set here in the panel UI to claim this server. Once claimed,+credentials are saved and the agent is ready to start.++This is the recommended way to add a server. Run 'serverkit-agent register'+only if you have a long pre-shared registration token.`,+ RunE: func(cmd *cobra.Command, args []string) error {+ return runPair(serverURL, passphrase, headless, setPassphrase)+ },+ }++ cmd.Flags().StringVarP(&serverURL, "server", "s", "", "ServerKit panel URL (required, unless previously paired)")+ cmd.Flags().StringVar(&passphrase, "passphrase", "", "passphrase (will prompt if empty)")+ cmd.Flags().BoolVar(&headless, "headless", false, "no interactive prompts; read $SERVERKIT_AGENT_PASSPHRASE")+ cmd.Flags().BoolVar(&setPassphrase, "set-passphrase", false, "store passphrase only; don't pair yet")++ return cmd+}++func runPair(serverURL, passphrase string, headless, setPassphraseOnly bool) error {+ log := logger.New(config.LoggingConfig{Level: "info"})++ // Resolve passphrase+ if passphrase == "" && headless {+ passphrase = os.Getenv("SERVERKIT_AGENT_PASSPHRASE")+ if passphrase == "" {+ return fmt.Errorf("--headless requires SERVERKIT_AGENT_PASSPHRASE env var")+ }+ }+ if passphrase == "" {+ var err error+ passphrase, err = promptPassphrase()+ if err != nil {+ return err+ }+ }+ if len(passphrase) < 4 {+ return fmt.Errorf("passphrase must be at least 4 characters")+ }++ // Persist passphrase reference (for later re-pair flows). We never write+ // the plaintext to disk; we only store a marker so the tray can show+ // "passphrase set". The bcrypt'd canonical form lives on the panel.+ if err := writePassphraseMarker(); err != nil {+ log.Warn("could not write passphrase marker", "error", err)+ }++ if setPassphraseOnly {+ fmt.Println("Passphrase stored. Run 'serverkit-agent pair --server <url>' when ready to pair.")+ return nil+ }++ if serverURL == "" {+ return fmt.Errorf("--server is required (e.g. --server https://panel.example.com)")+ }++ // Load or create Ed25519 pairing keypair+ kp, err := pairing.LoadOrCreate(pairing.DefaultKeyPath())+ if err != nil {+ return fmt.Errorf("load keypair: %w", err)+ }++ // Collect system info+ collector := metrics.NewCollector(config.MetricsConfig{}, log)+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ sysInfo, _ := collector.GetSystemInfo(ctx)+ sysMap := map[string]interface{}{}+ if sysInfo != nil {+ sysMap = map[string]interface{}{+ "hostname": sysInfo.Hostname,+ "os": sysInfo.OS,+ "platform": sysInfo.Platform,+ "platform_version": sysInfo.PlatformVersion,+ "architecture": sysInfo.Architecture,+ "cpu_cores": sysInfo.CPUCores,+ "total_memory": sysInfo.TotalMemory,+ "total_disk": sysInfo.TotalDisk,+ "agent_version": Version,+ }+ } else {+ hostname, _ := os.Hostname()+ sysMap["hostname"] = hostname+ sysMap["os"] = runtime.GOOS+ sysMap["architecture"] = runtime.GOARCH+ sysMap["agent_version"] = Version+ }++ // Enroll+ client := pairing.NewClient(serverURL, log)+ enrollCtx, enrollCancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer enrollCancel()++ enrollResp, err := client.Enroll(enrollCtx, pairing.EnrollRequest{+ Pubkey: kp.PublicKeyHex(),+ Passphrase: passphrase,+ MachineID: config.MachineID(),+ SystemInfo: sysMap,+ })+ if err != nil {+ return fmt.Errorf("enroll failed: %w", err)+ }++ printPairBanner(enrollResp.PairCodeFormatted, enrollResp.PubkeyFingerprint)++ // Wait for claim (with periodic code rotation)+ claimCtx, claimCancel := context.WithCancel(context.Background())+ defer claimCancel()++ creds, err := client.WaitForClaim(claimCtx, func(code, formatted, expiresAt string) {+ printPairBanner(formatted, enrollResp.PubkeyFingerprint)+ })+ if err != nil {+ return fmt.Errorf("waiting for claim: %w", err)+ }++ // Save credentials and config+ cfg, err := config.Load(cfgFile)+ if err != nil {+ cfg = config.Default()+ }++ wsURL := strings.TrimSuffix(serverURL, "/")+ wsURL = strings.Replace(wsURL, "https://", "wss://", 1)+ wsURL = strings.Replace(wsURL, "http://", "ws://", 1)+ cfg.Server.URL = wsURL + "/agent"+ cfg.Agent.ID = creds.AgentID+ cfg.Agent.Name = creds.Name+ cfg.Auth.APIKey = creds.APIKey+ cfg.Auth.APISecret = creds.APISecret++ configPath := cfgFile+ if configPath == "" {+ configPath = config.DefaultConfigPath()+ }+ if cfgFile != "" {+ cfg.Auth.KeyFile = filepath.Join(filepath.Dir(configPath), "agent.key")+ }+ if err := cfg.Save(configPath); err != nil {+ return fmt.Errorf("save config: %w", err)+ }+ if err := cfg.SaveCredentials(); err != nil {+ return fmt.Errorf("save credentials: %w", err)+ }++ fmt.Println()+ fmt.Println("✓ Pairing successful!")+ fmt.Printf(" Server name: %s\n", creds.Name)+ fmt.Printf(" Agent ID: %s\n", creds.AgentID)+ fmt.Printf(" Fingerprint: %s\n", enrollResp.PubkeyFingerprint)+ fmt.Println()+ fmt.Println("Start the agent with: serverkit-agent start")+ return nil+}++func printPairBanner(code, fingerprint string) {+ fmt.Println()+ fmt.Println("┌──────────────────────────────────────────────┐")+ fmt.Println("│ ServerKit Agent — Pairing │")+ fmt.Println("├──────────────────────────────────────────────┤")+ fmt.Printf("│ Pair code: %-30s│\n", code)+ fmt.Printf("│ Fingerprint: %-30s│\n", fingerprint)+ fmt.Println("├──────────────────────────────────────────────┤")+ fmt.Println("│ 1. Open ServerKit panel → Add Server │")+ fmt.Println("│ 2. Enter the pair code + your passphrase │")+ fmt.Println("│ 3. Verify the fingerprint matches │")+ fmt.Println("└──────────────────────────────────────────────┘")+ fmt.Println("Waiting for claim...")+}++func promptPassphrase() (string, error) {+ if !term.IsTerminal(int(syscall.Stdin)) {+ // Fallback: read line from stdin (e.g., piped postinst input)+ reader := bufio.NewReader(os.Stdin)+ fmt.Print("Passphrase: ")+ line, err := reader.ReadString('\n')+ if err != nil {+ return "", err+ }+ return strings.TrimRight(line, "\r\n"), nil+ }+ fmt.Print("Set a passphrase for this agent (4+ chars, you'll need it to pair): ")+ pass, err := term.ReadPassword(int(syscall.Stdin))+ fmt.Println()+ if err != nil {+ return "", err+ }+ fmt.Print("Confirm passphrase: ")+ pass2, err := term.ReadPassword(int(syscall.Stdin))+ fmt.Println()+ if err != nil {+ return "", err+ }+ if string(pass) != string(pass2) {+ return "", fmt.Errorf("passphrases do not match")+ }+ return string(pass), nil+}++// writePassphraseMarker writes a non-secret marker file used by the tray to+// indicate that a passphrase has been configured. It does NOT contain the+// passphrase itself.+func writePassphraseMarker() error {+ dir := filepath.Dir(pairing.DefaultKeyPath())+ if err := os.MkdirAll(dir, 0700); err != nil {+ return err+ }+ marker := filepath.Join(dir, "passphrase.set")+ // Random non-secret token so the file timestamps differ across resets.+ buf := make([]byte, 16)+ _, _ = rand.Read(buf)+ return os.WriteFile(marker, []byte(base64.RawURLEncoding.EncodeToString(buf)), 0600)+}diff --git a/agent/go.mod b/agent/go.modindex 77af4156..2ab14370 100644--- a/agent/go.mod+++ b/agent/go.mod@@ -1,6 +1,6 @@module github.com/serverkit/agent-go 1.21+go 1.25.0require (fyne.io/systray v1.11.0@@ -9,6 +9,7 @@ require (github.com/gorilla/websocket v1.5.1github.com/shirou/gopsutil/v3 v3.24.1github.com/spf13/cobra v1.8.0+ golang.org/x/term v0.42.0gopkg.in/natefinch/lumberjack.v2 v2.2.1gopkg.in/yaml.v3 v3.0.1)@@ -37,7 +38,7 @@ require (github.com/yusufpapurcu/wmi v1.2.3 // indirectgolang.org/x/mod v0.14.0 // indirectgolang.org/x/net v0.19.0 // indirect- golang.org/x/sys v0.16.0 // indirect+ golang.org/x/sys v0.43.0 // indirectgolang.org/x/time v0.5.0 // indirectgolang.org/x/tools v0.16.1 // indirectgotest.tools/v3 v3.5.1 // indirectdiff --git a/agent/go.sum b/agent/go.sumindex beaeb7c6..102a54a6 100644--- a/agent/go.sum+++ b/agent/go.sum@@ -109,8 +109,11 @@ golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wgolang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=+golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=+golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=diff --git a/agent/internal/config/config.go b/agent/internal/config/config.goindex 6f280256..019b63c3 100644--- a/agent/internal/config/config.go+++ b/agent/internal/config/config.go@@ -414,3 +414,32 @@ func splitFirst(s string, sep byte) []string {}return []string{s}}++// EncryptBytes encrypts bytes using the machine-derived AES-GCM key.+// Exported for use by other internal packages (e.g. pairing keypair storage).+func EncryptBytes(plaintext []byte) ([]byte, error) {+ return encryptCredentials(plaintext)+}++// DecryptBytes decrypts bytes previously encrypted with EncryptBytes.+func DecryptBytes(data []byte) ([]byte, error) {+ return decryptCredentials(data)+}++// MachineID returns a stable per-host identifier suitable for re-pair detection.+func MachineID() string {+ hostname, _ := os.Hostname()+ var id string+ if runtime.GOOS == "linux" {+ if data, err := os.ReadFile("/etc/machine-id"); err == nil {+ id = string(data)+ }+ } else if runtime.GOOS == "windows" {+ id = os.Getenv("COMPUTERNAME")+ }+ if id == "" {+ id = hostname+ }+ hash := sha256.Sum256([]byte("serverkit-machine-id:" + hostname + ":" + id))+ return base64.RawURLEncoding.EncodeToString(hash[:16])+}diff --git a/agent/internal/pairing/client.go b/agent/internal/pairing/client.gonew file mode 100644index 00000000..c79c65ae--- /dev/null+++ b/agent/internal/pairing/client.go@@ -0,0 +1,242 @@+package pairing++import (+ "bytes"+ "context"+ "crypto/tls"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "strings"+ "time"++ "github.com/serverkit/agent/internal/logger"+)++// EnrollRequest is the body of POST /api/v1/pairing/enroll.+type EnrollRequest struct {+ Pubkey string `json:"pubkey"`+ Passphrase string `json:"passphrase"`+ MachineID string `json:"machine_id,omitempty"`+ SystemInfo map[string]interface{} `json:"system_info,omitempty"`+}++// EnrollResponse is what the panel returns on successful enroll.+type EnrollResponse struct {+ EnrollmentID string `json:"enrollment_id"`+ EnrollmentSecret string `json:"enrollment_secret"`+ PairCode string `json:"pair_code"`+ PairCodeFormatted string `json:"pair_code_formatted"`+ PairCodeExpiresAt string `json:"pair_code_expires_at"`+ ExpiresAt string `json:"expires_at"`+ PubkeyFingerprint string `json:"pubkey_fpr"`+}++// PollResponse is the body of GET /api/v1/pairing/poll.+type PollResponse struct {+ Status string `json:"status"` // pending | claimed+ PairCode string `json:"pair_code,omitempty"`+ PairCodeExpiresAt string `json:"pair_code_expires_at,omitempty"`+ Credentials *Credentials `json:"credentials,omitempty"`+}++// Credentials are returned to the agent once an operator claims it.+type Credentials struct {+ AgentID string `json:"agent_id"`+ ServerID string `json:"server_id"`+ Name string `json:"name"`+ APIKey string `json:"api_key"`+ APISecret string `json:"api_secret"`+}++// RefreshResponse is returned from /code/refresh and /code/freeze.+type RefreshResponse struct {+ PairCode string `json:"pair_code"`+ PairCodeFormatted string `json:"pair_code_formatted"`+ PairCodeExpiresAt string `json:"pair_code_expires_at"`+ PairCodeFrozen bool `json:"pair_code_frozen"`+}++// Client talks to the panel pairing API.+type Client struct {+ BaseURL string+ HTTP *http.Client+ UserAgent string+ EnrollmentID string+ EnrollmentSecret string+ log *logger.Logger+}++// NewClient constructs a pairing client. baseURL must be the panel HTTPS root.+func NewClient(baseURL string, log *logger.Logger) *Client {+ baseURL = strings.TrimSuffix(baseURL, "/")+ return &Client{+ BaseURL: baseURL,+ HTTP: &http.Client{+ Timeout: 60 * time.Second,+ Transport: &http.Transport{+ TLSClientConfig: &tls.Config{+ InsecureSkipVerify: os.Getenv("SERVERKIT_INSECURE_TLS") == "true",+ },+ },+ },+ UserAgent: "ServerKit-Agent-Pairing/1.0",+ log: log.WithComponent("pairing"),+ }+}++// Enroll submits the agent's pubkey + passphrase to obtain an enrollment + pair code.+func (c *Client) Enroll(ctx context.Context, req EnrollRequest) (*EnrollResponse, error) {+ var resp EnrollResponse+ if err := c.do(ctx, "POST", "/api/v1/pairing/enroll", req, nil, &resp); err != nil {+ return nil, err+ }+ c.EnrollmentID = resp.EnrollmentID+ c.EnrollmentSecret = resp.EnrollmentSecret+ return &resp, nil+}++// RotateCode requests a new pair code (no-op if frozen unless force=true).+func (c *Client) RotateCode(ctx context.Context, force bool) (*RefreshResponse, error) {+ body := map[string]bool{"force": force}+ var resp RefreshResponse+ if err := c.do(ctx, "POST", "/api/v1/pairing/code/refresh", body, c.enrollHeaders(), &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// SetFreeze freezes or unfreezes the rotating pair code.+func (c *Client) SetFreeze(ctx context.Context, frozen bool) (*RefreshResponse, error) {+ body := map[string]bool{"frozen": frozen}+ var resp RefreshResponse+ if err := c.do(ctx, "POST", "/api/v1/pairing/code/freeze", body, c.enrollHeaders(), &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// Poll waits up to ~30s for an operator to claim this enrollment.+// Returns (claimed, credentials, err). If err is nil and claimed is false the+// caller should reconnect immediately for another long-poll.+func (c *Client) Poll(ctx context.Context) (bool, *Credentials, error) {+ var resp PollResponse+ if err := c.do(ctx, "GET", "/api/v1/pairing/poll", nil, c.enrollHeaders(), &resp); err != nil {+ return false, nil, err+ }+ if resp.Status == "claimed" && resp.Credentials != nil {+ return true, resp.Credentials, nil+ }+ return false, nil, nil+}++// WaitForClaim blocks until the agent is claimed, retrying long-polls and+// occasionally rotating the pair code (every ~5 minutes) so codes never get stale.+//+// onCode is invoked whenever the visible pair code changes — typically wired+// into the tray UI. It may be nil for headless operation.+func (c *Client) WaitForClaim(ctx context.Context, onCode func(code, formatted string, expiresAt string)) (*Credentials, error) {+ codeRotateTicker := time.NewTicker(4 * time.Minute)+ defer codeRotateTicker.Stop()++ for {+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-codeRotateTicker.C:+ if rr, err := c.RotateCode(ctx, false); err == nil && onCode != nil {+ onCode(rr.PairCode, formatPairCode(rr.PairCode), rr.PairCodeExpiresAt)+ }+ default:+ }++ pollCtx, cancel := context.WithTimeout(ctx, 35*time.Second)+ claimed, creds, err := c.Poll(pollCtx)+ cancel()+ if err != nil {+ c.log.Warn("pairing poll failed; retrying", "error", err)+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-time.After(5 * time.Second):+ }+ continue+ }+ if claimed {+ return creds, nil+ }+ }+}++// ----- internals -----++func (c *Client) enrollHeaders() http.Header {+ h := http.Header{}+ if c.EnrollmentID != "" {+ h.Set("X-Enrollment-Id", c.EnrollmentID)+ }+ if c.EnrollmentSecret != "" {+ h.Set("X-Enrollment-Secret", c.EnrollmentSecret)+ }+ return h+}++func (c *Client) do(ctx context.Context, method, path string, body interface{}, extraHeaders http.Header, out interface{}) error {+ url := c.BaseURL + path++ var bodyReader io.Reader+ if body != nil {+ buf, err := json.Marshal(body)+ if err != nil {+ return fmt.Errorf("marshal: %w", err)+ }+ bodyReader = bytes.NewReader(buf)+ }++ req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)+ if err != nil {+ return fmt.Errorf("new request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json")+ req.Header.Set("User-Agent", c.UserAgent)+ for k, v := range extraHeaders {+ for _, vv := range v {+ req.Header.Add(k, vv)+ }+ }++ resp, err := c.HTTP.Do(req)+ if err != nil {+ return fmt.Errorf("%s %s: %w", method, path, err)+ }+ defer resp.Body.Close()++ respBody, _ := io.ReadAll(resp.Body)+ if resp.StatusCode >= 400 {+ var er struct {+ Error string `json:"error"`+ }+ _ = json.Unmarshal(respBody, &er)+ if er.Error != "" {+ return fmt.Errorf("%s %s: %s (status %d)", method, path, er.Error, resp.StatusCode)+ }+ return fmt.Errorf("%s %s: status %d", method, path, resp.StatusCode)+ }+ if out != nil && len(respBody) > 0 {+ if err := json.Unmarshal(respBody, out); err != nil {+ return fmt.Errorf("decode response: %w", err)+ }+ }+ return nil+}++func formatPairCode(code string) string {+ if len(code) < 2 {+ return code+ }+ half := len(code) / 2+ return code[:half] + "-" + code[half:]+}diff --git a/agent/internal/pairing/keypair.go b/agent/internal/pairing/keypair.gonew file mode 100644index 00000000..9f638bcd--- /dev/null+++ b/agent/internal/pairing/keypair.go@@ -0,0 +1,108 @@+// Package pairing implements the RustDesk-style short-code agent pairing flow.+package pairing++import (+ "crypto/ed25519"+ "crypto/rand"+ "crypto/sha256"+ "encoding/hex"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"++ "github.com/serverkit/agent/internal/config"+)++// KeyPair holds an Ed25519 keypair plus a short fingerprint string.+type KeyPair struct {+ Public ed25519.PublicKey+ Private ed25519.PrivateKey+ Fingerprint string // matches panel format: uppercase hex, first 16 chars of SHA-256(pubkey_hex).+}++// PublicKeyHex returns the public key as lowercase hex (64 chars).+func (k *KeyPair) PublicKeyHex() string {+ return hex.EncodeToString(k.Public)+}++// DefaultKeyPath returns the OS-specific default path for the pairing keyfile.+func DefaultKeyPath() string {+ if runtime.GOOS == "windows" {+ return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "pairing.key")+ }+ return "/etc/serverkit-agent/pairing.key"+}++// LoadOrCreate returns the keypair at path, generating + persisting one if+// no file exists. The file is encrypted with the machine-derived key.+func LoadOrCreate(path string) (*KeyPair, error) {+ if path == "" {+ path = DefaultKeyPath()+ }+ if _, err := os.Stat(path); err == nil {+ return Load(path)+ } else if !os.IsNotExist(err) {+ return nil, fmt.Errorf("stat key file: %w", err)+ }+ kp, err := Generate()+ if err != nil {+ return nil, err+ }+ if err := Save(kp, path); err != nil {+ return nil, err+ }+ return kp, nil+}++// Generate creates a new random Ed25519 keypair.+func Generate() (*KeyPair, error) {+ pub, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ return nil, fmt.Errorf("generate keypair: %w", err)+ }+ return &KeyPair{Public: pub, Private: priv, Fingerprint: fingerprint(pub)}, nil+}++// Load reads + decrypts a keypair file.+func Load(path string) (*KeyPair, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("read key file: %w", err)+ }+ plain, err := config.DecryptBytes(data)+ if err != nil {+ return nil, fmt.Errorf("decrypt key file: %w", err)+ }+ if len(plain) != ed25519.PrivateKeySize {+ return nil, fmt.Errorf("invalid key file size: %d", len(plain))+ }+ priv := ed25519.PrivateKey(plain)+ pub := priv.Public().(ed25519.PublicKey)+ return &KeyPair{Public: pub, Private: priv, Fingerprint: fingerprint(pub)}, nil+}++// Save encrypts and writes the keypair to disk with restricted permissions.+func Save(kp *KeyPair, path string) error {+ if path == "" {+ path = DefaultKeyPath()+ }+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ return fmt.Errorf("create key dir: %w", err)+ }+ encrypted, err := config.EncryptBytes(kp.Private)+ if err != nil {+ return fmt.Errorf("encrypt key: %w", err)+ }+ if err := os.WriteFile(path, encrypted, 0600); err != nil {+ return fmt.Errorf("write key file: %w", err)+ }+ return nil+}++func fingerprint(pub ed25519.PublicKey) string {+ pubHex := hex.EncodeToString(pub)+ digest := sha256.Sum256([]byte(pubHex))+ return strings.ToUpper(hex.EncodeToString(digest[:8]))+}diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 21f87ac0..c845957d 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -282,6 +282,10 @@ def create_app(config_name=None):from app.api.plugins import plugins_bpapp.register_blueprint(plugins_bp, url_prefix='/api/v1/plugins')+ # Register blueprints - Agent Pairing (RustDesk-style short-code flow)+ from app.api.pairing import pairing_bp+ app.register_blueprint(pairing_bp, url_prefix='/api/v1/pairing')+# Load installed plugins (dynamic blueprints)try:from app.services.plugin_service import load_all_plugins@@ -318,6 +322,9 @@ def create_app(config_name=None):# Start hourly analytics aggregation and event retry threads_start_api_background_threads(app)+ # Start hourly pruner for expired pending agent pairings+ _start_pairing_pruner(app)+# Request body size limitapp.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit@@ -446,6 +453,41 @@ def _check_auto_sync_schedules(logger):_api_bg_thread = None+def _start_pairing_pruner(app):+ """Start a background thread that prunes expired PendingAgent rows hourly."""+ global _pairing_prune_thread+ if _pairing_prune_thread is not None:+ return++ import threading+ import time+ import logging++ logger = logging.getLogger(__name__)++ def prune_loop():+ # Wait a bit before first run so app is fully initialized.+ time.sleep(60)+ while True:+ try:+ with app.app_context():+ from app.services import pairing_service+ pairing_service.prune_expired()+ except Exception as e:+ logger.error(f'Pairing pruner error: {e}')+ time.sleep(3600)++ _pairing_prune_thread = threading.Thread(+ target=prune_loop,+ daemon=True,+ name='pairing-pruner'+ )+ _pairing_prune_thread.start()+++_pairing_prune_thread = None++def _start_api_background_threads(app):"""Start background threads for API analytics aggregation and event delivery retry."""global _api_bg_threaddiff --git a/backend/app/api/pairing.py b/backend/app/api/pairing.pynew file mode 100644index 00000000..423e4ef8--- /dev/null+++ b/backend/app/api/pairing.py@@ -0,0 +1,182 @@+"""+Pairing API — short-code RustDesk-style agent pairing.++Endpoints:+ POST /api/v1/pairing/enroll (no auth, IP rate-limited)+ POST /api/v1/pairing/code/refresh (enrollment auth)+ POST /api/v1/pairing/code/freeze (enrollment auth)+ GET /api/v1/pairing/poll (enrollment auth, long-poll)+ POST /api/v1/pairing/claim (operator JWT)+ GET /api/v1/pairing/lookup (operator JWT — pre-flight code check)+"""++import time+from flask import Blueprint, request, jsonify, current_app+from flask_jwt_extended import jwt_required, get_jwt_identity++from app import limiter+from app.services import pairing_service+from app.services.pairing_service import (+ PairingError,+ InvalidEnrollmentError,+ InvalidPairCredentialsError,+ LockoutError,+ AlreadyClaimedError,+ ExpiredEnrollmentError,+)++pairing_bp = Blueprint('pairing', __name__)+++def _enrollment_creds():+ """Read enrollment_id + enrollment_secret from headers or JSON body."""+ enrollment_id = request.headers.get('X-Enrollment-Id')+ enrollment_secret = request.headers.get('X-Enrollment-Secret')+ if not enrollment_id and request.is_json:+ body = request.get_json(silent=True) or {}+ enrollment_id = body.get('enrollment_id')+ enrollment_secret = body.get('enrollment_secret')+ return enrollment_id, enrollment_secret+++def _error_response(exc: PairingError):+ return jsonify({'error': str(exc)}), getattr(exc, 'status_code', 400)+++# ==================== Enroll ====================+++@pairing_bp.route('/enroll', methods=['POST'])[email protected]("10 per minute")+def enroll():+ data = request.get_json(silent=True) or {}+ pubkey = data.get('pubkey')+ passphrase = data.get('passphrase')+ machine_id = data.get('machine_id')+ system_info = data.get('system_info') or {}++ if not pubkey or not passphrase:+ return jsonify({'error': 'pubkey and passphrase are required'}), 400++ try:+ result = pairing_service.enroll(+ pubkey_hex=pubkey,+ passphrase=passphrase,+ machine_id=machine_id,+ system_info=system_info,+ )+ except PairingError as exc:+ return _error_response(exc)++ return jsonify(result), 201+++# ==================== Code refresh / freeze ====================+++@pairing_bp.route('/code/refresh', methods=['POST'])[email protected]("30 per minute")+def code_refresh():+ enrollment_id, enrollment_secret = _enrollment_creds()+ body = request.get_json(silent=True) or {}+ force = bool(body.get('force', False))+ try:+ result = pairing_service.rotate_code(enrollment_id, enrollment_secret, force=force)+ except PairingError as exc:+ return _error_response(exc)+ return jsonify(result), 200+++@pairing_bp.route('/code/freeze', methods=['POST'])[email protected]("30 per minute")+def code_freeze():+ enrollment_id, enrollment_secret = _enrollment_creds()+ body = request.get_json(silent=True) or {}+ frozen = bool(body.get('frozen', True))+ try:+ result = pairing_service.set_freeze(enrollment_id, enrollment_secret, frozen=frozen)+ except PairingError as exc:+ return _error_response(exc)+ return jsonify(result), 200+++# ==================== Long-poll ====================+++@pairing_bp.route('/poll', methods=['GET', 'POST'])[email protected]("120 per minute")+def poll():+ """+ Long-poll for claim status. Up to ~25 seconds of waiting per request.+ Agent should reconnect immediately after each response.+ """+ enrollment_id, enrollment_secret = _enrollment_creds()+ if not enrollment_id or not enrollment_secret:+ return jsonify({'error': 'Missing enrollment credentials'}), 401++ deadline = time.time() + 25.0 # leave headroom under typical proxy timeouts+ poll_interval = 1.0++ while True:+ try:+ result = pairing_service.poll(enrollment_id, enrollment_secret)+ except PairingError as exc:+ return _error_response(exc)++ if result.get('status') == 'claimed':+ return jsonify(result), 200++ if time.time() >= deadline:+ return jsonify(result), 200 # status: pending++ time.sleep(poll_interval)+++# ==================== Operator claim ====================+++@pairing_bp.route('/lookup', methods=['POST'])+@jwt_required()[email protected]("20 per minute")+def lookup():+ """Pre-flight: confirm a code exists (without revealing details)."""+ data = request.get_json(silent=True) or {}+ code = data.get('code', '')+ pending = pairing_service.find_by_code(code)+ if not pending:+ return jsonify({'found': False}), 404+ return jsonify({+ 'found': True,+ 'pubkey_fpr': pending.pubkey_fpr,+ 'system_info': pending.system_info or {},+ 'machine_id': pending.machine_id,+ }), 200+++@pairing_bp.route('/claim', methods=['POST'])+@jwt_required()[email protected]("5 per 10 minute")+def claim():+ user_id = int(get_jwt_identity())+ data = request.get_json(silent=True) or {}+ code = data.get('code')+ passphrase = data.get('passphrase')+ name = data.get('name')+ group_id = data.get('group_id')++ if not code or not passphrase:+ return jsonify({'error': 'code and passphrase are required'}), 400++ try:+ result = pairing_service.claim(+ operator_user_id=user_id,+ code=code,+ passphrase=passphrase,+ name=name,+ group_id=group_id,+ ip_address=request.remote_addr,+ )+ except PairingError as exc:+ return _error_response(exc)++ return jsonify(result), 201diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex bb7d20f3..b39a4275 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -30,6 +30,7 @@ from app.models.dns_zone import DNSZone, DNSRecordfrom app.models.status_page import StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdatefrom app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshotfrom app.models.marketplace import Extension, ExtensionInstall+from app.models.pending_agent import PendingAgent__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',@@ -48,5 +49,6 @@ __all__ = ['DNSZone', 'DNSRecord','StatusPage', 'StatusComponent', 'HealthCheck', 'StatusIncident', 'StatusIncidentUpdate','CloudProvider', 'CloudServer', 'CloudSnapshot',- 'Extension', 'ExtensionInstall'+ 'Extension', 'ExtensionInstall',+ 'PendingAgent',]diff --git a/backend/app/models/pending_agent.py b/backend/app/models/pending_agent.pynew file mode 100644index 00000000..df78fc53--- /dev/null+++ b/backend/app/models/pending_agent.py@@ -0,0 +1,129 @@+"""+PendingAgent model — tracks agents that have enrolled for short-code pairing+but have not yet been claimed by an operator.++A PendingAgent stores:+ - The agent's Ed25519 public key (for identity / TOFU verification)+ - A short, rotating pair code (shown by the agent's tray UI)+ - A bcrypt hash of the operator-set passphrase+ - The agent's stable machine_id (so re-pairs on the same host are detectable)++When an operator submits (code, passphrase) via /pairing/claim, the entry is+matched, real Server credentials are minted, and `claimed_server_id` is set.+"""++import uuid+import hashlib+from datetime import datetime, timedelta++import bcrypt++from app import db+++# Pair code uses Crockford-ish base32 minus ambiguous chars (0/O, 1/I/L)+PAIR_CODE_ALPHABET = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"+PAIR_CODE_LENGTH = 6+DEFAULT_PAIR_CODE_TTL = timedelta(minutes=5)+DEFAULT_ENROLLMENT_TTL = timedelta(hours=24)+++class PendingAgent(db.Model):+ """An agent that has enrolled and is waiting to be claimed."""++ __tablename__ = 'pending_agents'++ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))++ # Opaque token the agent uses to authenticate poll/refresh calls.+ # Stored hashed; the agent receives the plaintext value once on enroll.+ enrollment_id = db.Column(db.String(64), unique=True, index=True, nullable=False)+ enrollment_secret_hash = db.Column(db.String(256), nullable=False)++ # Agent identity+ pubkey = db.Column(db.String(128), nullable=False) # Ed25519 hex (64 chars)+ pubkey_fpr = db.Column(db.String(32), nullable=False, index=True) # SHA-256 first 16 hex chars++ # Pair code (visible to operator)+ pair_code = db.Column(db.String(16), index=True, nullable=False)+ pair_code_expires_at = db.Column(db.DateTime, nullable=False)+ pair_code_frozen = db.Column(db.Boolean, default=False, nullable=False)++ # Passphrase (set by user on agent host; never sent to panel in plaintext)+ passphrase_hash = db.Column(db.String(256), nullable=False)++ # Brute-force lockout (seconds-resolution timestamp)+ lockout_until = db.Column(db.DateTime, nullable=True)+ failed_attempts = db.Column(db.Integer, default=0, nullable=False)++ # Host identity+ machine_id = db.Column(db.String(128), index=True, nullable=True)+ system_info = db.Column(db.JSON, default=dict)++ # Lifecycle+ created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)+ last_seen_at = db.Column(db.DateTime, default=datetime.utcnow)+ expires_at = db.Column(db.DateTime, nullable=False)+ claimed_at = db.Column(db.DateTime, nullable=True)+ claimed_server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=True)++ # When claimed, we stash credentials here briefly (Fernet-encrypted) so the+ # next /poll call can deliver them to the agent. Cleared after retrieval.+ claim_payload_encrypted = db.Column(db.Text, nullable=True)++ claimed_server = db.relationship('Server', foreign_keys=[claimed_server_id])++ @staticmethod+ def fingerprint(pubkey_hex: str) -> str:+ """Return a short, human-friendly fingerprint of a public key."""+ digest = hashlib.sha256(pubkey_hex.encode('ascii')).hexdigest()+ return digest[:16].upper()++ @staticmethod+ def hash_passphrase(passphrase: str) -> str:+ return bcrypt.hashpw(passphrase.encode('utf-8'), bcrypt.gensalt()).decode('ascii')++ def verify_passphrase(self, passphrase: str) -> bool:+ try:+ return bcrypt.checkpw(passphrase.encode('utf-8'), self.passphrase_hash.encode('ascii'))+ except (ValueError, TypeError):+ return False++ @staticmethod+ def hash_enrollment_secret(secret: str) -> str:+ return hashlib.sha256(secret.encode('utf-8')).hexdigest()++ def verify_enrollment_secret(self, secret: str) -> bool:+ if not secret or not self.enrollment_secret_hash:+ return False+ return self.hash_enrollment_secret(secret) == self.enrollment_secret_hash++ def is_pair_code_valid(self) -> bool:+ return self.pair_code_expires_at and datetime.utcnow() < self.pair_code_expires_at++ def is_locked_out(self) -> bool:+ return self.lockout_until is not None and datetime.utcnow() < self.lockout_until++ def is_expired(self) -> bool:+ return self.expires_at and datetime.utcnow() >= self.expires_at++ def is_claimed(self) -> bool:+ return self.claimed_at is not None++ def to_dict(self, include_secrets: bool = False) -> dict:+ result = {+ 'id': self.id,+ 'pubkey_fpr': self.pubkey_fpr,+ 'pair_code': self.pair_code if include_secrets else None,+ 'pair_code_expires_at': self.pair_code_expires_at.isoformat() if self.pair_code_expires_at else None,+ 'pair_code_frozen': self.pair_code_frozen,+ 'machine_id': self.machine_id,+ 'system_info': self.system_info or {},+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'expires_at': self.expires_at.isoformat() if self.expires_at else None,+ 'claimed': self.is_claimed(),+ }+ return result++ def __repr__(self):+ return f'<PendingAgent {self.id} fpr={self.pubkey_fpr}>'diff --git a/backend/app/services/pairing_service.py b/backend/app/services/pairing_service.pynew file mode 100644index 00000000..3f747b16--- /dev/null+++ b/backend/app/services/pairing_service.py@@ -0,0 +1,412 @@+"""+Pairing service — implements the RustDesk-style short-code pairing flow.++Two factors are required to claim an enrolled agent:+ 1. The 6-character pair code displayed on the agent host (rotates).+ 2. The user-set passphrase configured on the agent host.++Flow:+ 1. Agent calls /pairing/enroll with its Ed25519 pubkey + passphrase hash.+ -> server returns enrollment_id + enrollment_secret + pair_code.+ 2. Agent long-polls /pairing/poll with enrollment credentials.+ 3. Operator enters (code, passphrase) in the panel -> /pairing/claim.+ 4. Server creates a real Server row, mints api_key/api_secret, encrypts the+ credentials, and stashes them on the PendingAgent.+ 5. The agent's next /poll returns the credentials. Done.+"""++import json+import logging+import secrets+from datetime import datetime, timedelta+from typing import Optional++from sqlalchemy import or_++from app import db+from app.models.audit_log import AuditLog+from app.models.pending_agent import (+ PendingAgent,+ PAIR_CODE_ALPHABET,+ PAIR_CODE_LENGTH,+ DEFAULT_PAIR_CODE_TTL,+ DEFAULT_ENROLLMENT_TTL,+)+from app.models.server import Server+from app.utils.crypto import encrypt_secret, decrypt_secret++logger = logging.getLogger(__name__)+++# ==================== Errors ====================+++class PairingError(Exception):+ """Base class for pairing failures."""+ status_code = 400+++class InvalidEnrollmentError(PairingError):+ status_code = 401+++class InvalidPairCredentialsError(PairingError):+ status_code = 401+++class LockoutError(PairingError):+ status_code = 429+++class AlreadyClaimedError(PairingError):+ status_code = 409+++class ExpiredEnrollmentError(PairingError):+ status_code = 410+++# ==================== Helpers ====================+++def generate_pair_code(length: int = PAIR_CODE_LENGTH) -> str:+ """Generate a pair code from the unambiguous alphabet."""+ return ''.join(secrets.choice(PAIR_CODE_ALPHABET) for _ in range(length))+++def _generate_unique_pair_code() -> str:+ """Generate a pair code that doesn't collide with another active code."""+ for _ in range(10):+ code = generate_pair_code()+ existing = (+ PendingAgent.query+ .filter(PendingAgent.pair_code == code)+ .filter(PendingAgent.claimed_at.is_(None))+ .filter(PendingAgent.pair_code_expires_at > datetime.utcnow())+ .first()+ )+ if not existing:+ return code+ # Extremely unlikely; fall back to a longer code+ return generate_pair_code(length=PAIR_CODE_LENGTH + 2)+++def format_pair_code(code: str) -> str:+ """Format `ABC123` as `ABC-123` for display."""+ half = len(code) // 2+ return f"{code[:half]}-{code[half:]}"+++def normalize_pair_code(code: str) -> str:+ """Strip dashes/whitespace, uppercase. Operators may paste either form."""+ return ''.join(c for c in (code or '').upper() if c.isalnum())+++# ==================== Public API ====================+++def enroll(pubkey_hex: str, passphrase: str, machine_id: Optional[str] = None,+ system_info: Optional[dict] = None) -> dict:+ """+ Register a new pending agent. Called by the agent (no authentication).++ Returns dict with: enrollment_id, enrollment_secret, pair_code,+ pair_code_expires_at, expires_at.+ """+ if not pubkey_hex or len(pubkey_hex) < 32:+ raise PairingError("Invalid public key")+ if not passphrase or len(passphrase) < 4:+ raise PairingError("Passphrase must be at least 4 characters")++ # Detect re-enrollment from the same machine: replace prior unclaimed entry.+ if machine_id:+ prior = (+ PendingAgent.query+ .filter_by(machine_id=machine_id)+ .filter(PendingAgent.claimed_at.is_(None))+ .all()+ )+ for p in prior:+ db.session.delete(p)++ enrollment_id = secrets.token_urlsafe(24)+ enrollment_secret = secrets.token_urlsafe(32)+ pair_code = _generate_unique_pair_code()+ now = datetime.utcnow()++ pending = PendingAgent(+ enrollment_id=enrollment_id,+ enrollment_secret_hash=PendingAgent.hash_enrollment_secret(enrollment_secret),+ pubkey=pubkey_hex.lower(),+ pubkey_fpr=PendingAgent.fingerprint(pubkey_hex.lower()),+ pair_code=pair_code,+ pair_code_expires_at=now + DEFAULT_PAIR_CODE_TTL,+ pair_code_frozen=False,+ passphrase_hash=PendingAgent.hash_passphrase(passphrase),+ machine_id=machine_id,+ system_info=system_info or {},+ created_at=now,+ last_seen_at=now,+ expires_at=now + DEFAULT_ENROLLMENT_TTL,+ )+ db.session.add(pending)+ db.session.commit()++ AuditLog.log(+ action='pairing.enroll',+ target_type='pending_agent',+ details={'pubkey_fpr': pending.pubkey_fpr, 'machine_id': machine_id},+ )+ db.session.commit()++ return {+ 'enrollment_id': enrollment_id,+ 'enrollment_secret': enrollment_secret,+ 'pair_code': pair_code,+ 'pair_code_formatted': format_pair_code(pair_code),+ 'pair_code_expires_at': pending.pair_code_expires_at.isoformat(),+ 'expires_at': pending.expires_at.isoformat(),+ 'pubkey_fpr': pending.pubkey_fpr,+ }+++def _load_pending_for_agent(enrollment_id: str, enrollment_secret: str) -> PendingAgent:+ pending = PendingAgent.query.filter_by(enrollment_id=enrollment_id).first()+ if not pending:+ raise InvalidEnrollmentError("Unknown enrollment")+ if not pending.verify_enrollment_secret(enrollment_secret):+ raise InvalidEnrollmentError("Invalid enrollment credentials")+ if pending.is_expired() and not pending.is_claimed():+ raise ExpiredEnrollmentError("Enrollment expired; re-enroll required")+ return pending+++def rotate_code(enrollment_id: str, enrollment_secret: str, force: bool = False) -> dict:+ """Rotate the visible pair code. No-op if frozen unless force=True."""+ pending = _load_pending_for_agent(enrollment_id, enrollment_secret)+ if pending.is_claimed():+ raise AlreadyClaimedError("Already claimed")++ now = datetime.utcnow()+ if pending.pair_code_frozen and not force:+ # Keep the existing code; just confirm it's still valid.+ if not pending.is_pair_code_valid():+ pending.pair_code_expires_at = now + DEFAULT_PAIR_CODE_TTL+ else:+ pending.pair_code = _generate_unique_pair_code()+ pending.pair_code_expires_at = now + DEFAULT_PAIR_CODE_TTL++ pending.last_seen_at = now+ db.session.commit()+ return {+ 'pair_code': pending.pair_code,+ 'pair_code_formatted': format_pair_code(pending.pair_code),+ 'pair_code_expires_at': pending.pair_code_expires_at.isoformat(),+ 'pair_code_frozen': pending.pair_code_frozen,+ }+++def set_freeze(enrollment_id: str, enrollment_secret: str, frozen: bool) -> dict:+ pending = _load_pending_for_agent(enrollment_id, enrollment_secret)+ pending.pair_code_frozen = bool(frozen)+ pending.last_seen_at = datetime.utcnow()+ db.session.commit()+ return {'pair_code_frozen': pending.pair_code_frozen}+++def poll(enrollment_id: str, enrollment_secret: str) -> dict:+ """+ Called by the agent to check whether an operator has claimed it yet.++ Returns:+ {'status': 'pending', ...} if still waiting.+ {'status': 'claimed', 'credentials': {...}} once claimed (delivered ONCE).+ """+ pending = _load_pending_for_agent(enrollment_id, enrollment_secret)+ pending.last_seen_at = datetime.utcnow()++ if pending.is_claimed() and pending.claim_payload_encrypted:+ try:+ payload = json.loads(decrypt_secret(pending.claim_payload_encrypted))+ except Exception as e:+ logger.exception("Failed to decrypt claim payload: %s", e)+ raise PairingError("Internal pairing error")++ # One-shot delivery: clear the encrypted payload after read.+ pending.claim_payload_encrypted = None+ db.session.commit()++ AuditLog.log(+ action='pairing.delivered',+ target_type='pending_agent',+ target_id=None,+ details={'pubkey_fpr': pending.pubkey_fpr,+ 'server_id': pending.claimed_server_id},+ )+ db.session.commit()+ return {'status': 'claimed', 'credentials': payload}++ if pending.is_claimed():+ # Already delivered; nothing more to give.+ return {'status': 'claimed', 'credentials': None}++ db.session.commit()+ return {+ 'status': 'pending',+ 'pair_code': pending.pair_code,+ 'pair_code_expires_at': pending.pair_code_expires_at.isoformat(),+ }+++def find_by_code(code: str) -> Optional[PendingAgent]:+ """Look up an unclaimed PendingAgent by pair code. Returns None if not found."""+ code = normalize_pair_code(code)+ if not code:+ return None+ return (+ PendingAgent.query+ .filter(PendingAgent.pair_code == code)+ .filter(PendingAgent.claimed_at.is_(None))+ .filter(PendingAgent.pair_code_expires_at > datetime.utcnow())+ .first()+ )+++def claim(operator_user_id: int, code: str, passphrase: str,+ name: Optional[str] = None, group_id: Optional[str] = None,+ ip_address: Optional[str] = None) -> dict:+ """+ Operator-initiated claim. Returns {'server': {...}, 'fingerprint': '...'}.++ Failed attempts increment the per-PendingAgent counter and set a lockout.+ """+ code = normalize_pair_code(code)+ pending = find_by_code(code)+ if not pending:+ # Don't reveal whether the code matched anything — generic 401.+ AuditLog.log(+ action='pairing.claim_failed',+ user_id=operator_user_id,+ details={'reason': 'no_match', 'ip': ip_address},+ )+ db.session.commit()+ raise InvalidPairCredentialsError("Invalid pair code or passphrase")++ if pending.is_locked_out():+ AuditLog.log(+ action='pairing.claim_locked',+ user_id=operator_user_id,+ target_type='pending_agent',+ details={'pubkey_fpr': pending.pubkey_fpr, 'ip': ip_address},+ )+ db.session.commit()+ raise LockoutError("Too many failed attempts; try again shortly")++ if not pending.verify_passphrase(passphrase):+ pending.failed_attempts = (pending.failed_attempts or 0) + 1+ # Exponential backoff up to 5 minutes+ backoff_seconds = min(60 * (2 ** max(0, pending.failed_attempts - 1)), 300)+ pending.lockout_until = datetime.utcnow() + timedelta(seconds=backoff_seconds)+ db.session.commit()+ AuditLog.log(+ action='pairing.claim_failed',+ user_id=operator_user_id,+ target_type='pending_agent',+ details={'pubkey_fpr': pending.pubkey_fpr,+ 'reason': 'bad_passphrase',+ 'attempts': pending.failed_attempts,+ 'ip': ip_address},+ )+ db.session.commit()+ raise InvalidPairCredentialsError("Invalid pair code or passphrase")++ # Success — mint a real Server row and credentials.+ api_key, api_secret = Server.generate_api_credentials()+ sysinfo = pending.system_info or {}++ server = Server(+ name=(name or sysinfo.get('hostname') or f"agent-{pending.pubkey_fpr[:6]}"),+ hostname=sysinfo.get('hostname'),+ os_type=sysinfo.get('os'),+ os_version=sysinfo.get('platform_version'),+ platform=sysinfo.get('platform'),+ architecture=sysinfo.get('architecture'),+ cpu_cores=sysinfo.get('cpu_cores'),+ total_memory=sysinfo.get('total_memory'),+ total_disk=sysinfo.get('total_disk'),+ agent_version=sysinfo.get('agent_version'),+ status='connecting',+ registered_at=datetime.utcnow(),+ registered_by=operator_user_id,+ group_id=group_id,+ )+ server.id = str(__import__('uuid').uuid4())+ server.agent_id = str(__import__('uuid').uuid4())+ server.set_api_key(api_key)+ server.set_api_secret_encrypted(api_secret)++ db.session.add(server)++ # Stash credentials for one-shot delivery on next /poll.+ payload = json.dumps({+ 'agent_id': server.agent_id,+ 'server_id': server.id,+ 'name': server.name,+ 'api_key': api_key,+ 'api_secret': api_secret,+ })+ pending.claim_payload_encrypted = encrypt_secret(payload)+ pending.claimed_at = datetime.utcnow()+ pending.claimed_server_id = server.id+ pending.failed_attempts = 0+ pending.lockout_until = None++ db.session.commit()++ AuditLog.log(+ action='pairing.claim_success',+ user_id=operator_user_id,+ target_type='server',+ target_id=None, # server.id is a UUID string; AuditLog target_id is int+ details={+ 'pubkey_fpr': pending.pubkey_fpr,+ 'server_id': server.id,+ 'ip': ip_address,+ },+ )+ db.session.commit()++ return {+ 'server': server.to_dict(),+ 'fingerprint': pending.pubkey_fpr,+ 'pubkey': pending.pubkey,+ }+++def prune_expired(now: Optional[datetime] = None) -> int:+ """Delete expired/unclaimed pending agents. Returns count removed."""+ now = now or datetime.utcnow()+ q = (+ PendingAgent.query+ .filter(PendingAgent.claimed_at.is_(None))+ .filter(PendingAgent.expires_at < now)+ )+ count = q.count()+ if count:+ for p in q.all():+ db.session.delete(p)+ db.session.commit()+ logger.info("Pruned %d expired pending agents", count)+ # Also clean up claimed entries older than 7 days (delivered or not).+ cutoff = now - timedelta(days=7)+ stale = (+ PendingAgent.query+ .filter(PendingAgent.claimed_at.isnot(None))+ .filter(PendingAgent.claimed_at < cutoff)+ .all()+ )+ for p in stale:+ db.session.delete(p)+ if stale:+ db.session.commit()+ return count + len(stale)diff --git a/docs/pairing.md b/docs/pairing.mdnew file mode 100644index 00000000..c2005e85--- /dev/null+++ b/docs/pairing.md@@ -0,0 +1,143 @@+# Agent Pairing (Short-Code Flow)++ServerKit supports two ways to attach an agent to the panel:++1. **Pair (recommended)** — install the agent once, then claim it from the panel+ with a 6-character rotating code + your operator passphrase. RustDesk-style.+2. **Token install (legacy)** — generate a registration token in the panel,+ paste it into a curl/PowerShell one-liner. Still supported.++This document covers the pair flow.++## Why pairing?++The pre-shared registration token approach has several downsides:++- The token is a long-lived secret embedded in a copy-pasted shell command.+- If anyone observes the install command, they can pre-empt the registration.+- Re-pairing after a wipe means generating a fresh token, repeating the dance.++Pairing replaces this with:++- A **per-machine passphrase** the operator sets once on the agent host.+- A **rotating 6-character pair code** the agent displays (CLI banner / tray).+- A **public-key fingerprint** that's verifiable out-of-band.++The panel claims the agent only after both the code and passphrase match.++## Operator flow++### 1. On the target machine++After installing the agent (e.g. via the install script, package, or MSI), run:++```bash+serverkit-agent pair --server https://panel.example.com+```++You'll be prompted for a passphrase (4+ characters). Pick something memorable —+you only need to type it once on the panel side. The agent then:++- Generates an Ed25519 keypair (encrypted at rest with the machine key).+- Submits its public key + bcrypt'd passphrase to the panel.+- Prints a banner with the rotating 6-char pair code and the public-key fingerprint:++```+┌──────────────────────────────────────────────┐+│ ServerKit Agent — Pairing │+├──────────────────────────────────────────────┤+│ Pair code: ABC-123 │+│ Fingerprint: 1A2B3C4D5E6F7A8B │+├──────────────────────────────────────────────┤+│ 1. Open ServerKit panel → Add Server │+│ 2. Enter the pair code + your passphrase │+│ 3. Verify the fingerprint matches │+└──────────────────────────────────────────────┘+Waiting for claim...+```++The pair code rotates every ~5 minutes until the agent is claimed.++### 2. In the panel++Go to **Servers → Add Server** and select **Pair existing agent**. Enter:++- The 6-character pair code+- The passphrase you set+- (Optional) A friendly name and group++Verify the fingerprint shown after lookup matches what the agent printed.+Click **Pair Agent**. The agent receives credentials over its existing+long-poll, saves them, and prints `✓ Pairing successful!`.++### 3. Start the agent++```bash+sudo systemctl start serverkit-agent # Linux+# or use Services.msc on Windows+```++The agent connects to the panel and the server flips from "Pending" to "Online".++## Headless / unattended pairing++For Docker, Kubernetes, or unattended provisioning:++```bash+SERVERKIT_AGENT_PASSPHRASE='hunter2' \+ serverkit-agent pair --server https://panel.example.com --headless+```++You still need an operator to claim the code in the panel — the headless flag+just suppresses interactive prompts.++## Local dev / ngrok++If you're testing the panel locally, expose it via ngrok and set:++```bash+export SERVERKIT_PUBLIC_URL=https://abcd1234.ngrok.app+```++Use that URL as the `--server` flag. For self-signed TLS in dev,+`SERVERKIT_INSECURE_TLS=true` skips cert verification on the agent side+(don't use this in production).++## Security notes++- Pair codes are 6 characters from a 31-symbol alphabet+ (Crockford-ish base32 minus 0/O/1/I/L). Codes rotate ~every 5 minutes.+- Passphrases are bcrypt'd on the panel before storage.+- Failed claim attempts trigger per-enrollment exponential backoff+ (60s → 5 min cap) plus per-IP rate limits (5 claims / 10 minutes).+- All claim/lookup events are written to the audit log.+- Enrollments expire 24h after creation; un-claimed records are pruned hourly.+- The agent's keypair is encrypted at rest with a key derived from+ `/etc/machine-id` + hostname (Linux) or COMPUTERNAME + USERNAME (Windows).+- Compare the displayed fingerprint side-by-side before claiming. Mismatch+ means the wrong agent — abort and re-run `pair`.++## API reference++| Endpoint | Purpose | Auth |+| --- | --- | --- |+| `POST /api/v1/pairing/enroll` | Agent submits pubkey + passphrase | none |+| `POST /api/v1/pairing/code/refresh` | Agent rotates its pair code | enrollment headers |+| `POST /api/v1/pairing/code/freeze` | Agent freezes/unfreezes rotation | enrollment headers |+| `GET /api/v1/pairing/poll` | Agent long-polls for claim (≤25s) | enrollment headers |+| `POST /api/v1/pairing/lookup` | Panel resolves code → fingerprint | JWT |+| `POST /api/v1/pairing/claim` | Panel claims an enrolled agent | JWT |++Headers used by the agent:+- `X-Enrollment-Id`: opaque enrollment identifier+- `X-Enrollment-Secret`: long-lived secret returned at enroll time++## Comparison with token install++| | Pair | Token install |+| --- | --- | --- |+| Out-of-band step | passphrase typed into panel | token pasted into shell |+| Compromise window | 5 min (rotating code) | 24h (token TTL) |+| Re-pair after wipe | re-run `pair` | regenerate token |+| Headless friendly | yes (`--headless` + env) | yes (curl one-liner) |+| Recommended? | ✅ | only for legacy/scripted flows |diff --git a/frontend/src/pages/Servers.jsx b/frontend/src/pages/Servers.jsxindex 5ff585fb..da20dea7 100644--- a/frontend/src/pages/Servers.jsx+++ b/frontend/src/pages/Servers.jsx@@ -580,7 +580,162 @@ const ServerRow = ({ server, selected, onToggle, onPing, onDelete, onCopyInstall);};+const PairAgentForm = ({ groups, onClose, onClaimed }) => {+ const [pairCode, setPairCode] = useState('');+ const [passphrase, setPassphrase] = useState('');+ const [name, setName] = useState('');+ const [groupId, setGroupId] = useState('');+ const [lookupResult, setLookupResult] = useState(null);+ const [lookupError, setLookupError] = useState('');+ const [claimError, setClaimError] = useState('');+ const [loading, setLoading] = useState(false);+ const toast = useToast();++ const formattedCode = pairCode+ .toUpperCase()+ .replace(/[^0-9A-Z]/g, '')+ .replace(/[01OIL]/g, '')+ .slice(0, 6);++ async function handleLookup() {+ setLookupError('');+ setLookupResult(null);+ if (formattedCode.length !== 6) {+ setLookupError('Pair code must be 6 characters');+ return;+ }+ setLoading(true);+ try {+ const res = await api.lookupPairCode(formattedCode);+ setLookupResult(res);+ if (!name && res.suggested_name) setName(res.suggested_name);+ } catch (err) {+ setLookupError(err.message || 'Pair code not found');+ } finally {+ setLoading(false);+ }+ }++ async function handleClaim(e) {+ e.preventDefault();+ setClaimError('');+ if (!passphrase) {+ setClaimError('Passphrase is required');+ return;+ }+ setLoading(true);+ try {+ await api.claimPairedAgent({+ pair_code: formattedCode,+ passphrase,+ name: name || undefined,+ group_id: groupId || undefined,+ trust_fingerprint: true+ });+ toast.success('Agent paired successfully');+ onClaimed();+ } catch (err) {+ setClaimError(err.message || 'Failed to claim agent');+ } finally {+ setLoading(false);+ }+ }++ function formatDisplay(code) {+ if (!code) return '------';+ return code.length > 3 ? `${code.slice(0, 3)}-${code.slice(3)}` : code;+ }++ return (+ <form className="server-setup-form" onSubmit={handleClaim}>+ <div className="server-setup-form__body">+ <div className="form-group">+ <label>Pair code</label>+ <input+ type="text"+ value={formatDisplay(formattedCode)}+ onChange={(e) => {+ setPairCode(e.target.value);+ setLookupResult(null);+ setLookupError('');+ }}+ onBlur={handleLookup}+ placeholder="ABC-123"+ autoFocus+ autoComplete="off"+ spellCheck={false}+ style={{ fontFamily: 'monospace', fontSize: '1.25rem', letterSpacing: '0.15em', textAlign: 'center' }}+ required+ />+ <span className="form-hint">Run <code>serverkit-agent pair</code> on the target machine and read the code from its output (or system tray).</span>+ {lookupError && <div className="error-message" style={{ marginTop: '0.5rem' }}>{lookupError}</div>}+ </div>++ {lookupResult && (+ <div className="success-banner" style={{ marginTop: '0.5rem' }}>+ <div>+ <strong>Agent found</strong>+ <p className="success-subtitle">+ Hostname: <code>{lookupResult.hostname || 'unknown'}</code><br />+ Fingerprint: <code style={{ fontFamily: 'monospace' }}>{lookupResult.pubkey_fpr}</code>+ </p>+ <p className="text-muted" style={{ marginTop: '0.25rem', fontSize: '0.85em' }}>+ Confirm this fingerprint matches the one shown by the agent before continuing.+ </p>+ </div>+ </div>+ )}++ <div className="form-group">+ <label>Passphrase *</label>+ <input+ type="password"+ value={passphrase}+ onChange={(e) => setPassphrase(e.target.value)}+ placeholder="The passphrase set when pairing started"+ autoComplete="new-password"+ required+ />+ </div>++ <div className="form-row">+ <div className="form-group">+ <label>Server name</label>+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="prod-web-01 (optional)"+ />+ </div>+ <div className="form-group">+ <label>Group</label>+ <select value={groupId} onChange={(e) => setGroupId(e.target.value)}>+ <option value="">No Group</option>+ {groups.map(g => (+ <option key={g.id} value={g.id}>{g.name}</option>+ ))}+ </select>+ </div>+ </div>++ {claimError && <div className="error-message">{claimError}</div>}+ </div>++ <div className="modal-actions">+ <button type="button" className="btn btn-secondary" onClick={onClose}>+ Cancel+ </button>+ <button type="submit" className="btn btn-primary" disabled={loading || formattedCode.length !== 6}>+ {loading ? 'Pairing…' : 'Pair Agent'}+ </button>+ </div>+ </form>+ );+};+const AddServerModal = ({ groups, onClose, onCreated }) => {+ const [mode, setMode] = useState('pair');const [step, setStep] = useState(1);const [formData, setFormData] = useState({name: '',@@ -636,13 +791,39 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio<div className="modal-header"><div><span className="servers-eyebrow">{step === 1 ? 'New agent' : 'Registration ready'}</span>- <h2>{step === 1 ? 'Add Server' : 'Install Agent'}</h2>- <p>{step === 1 ? 'Give it a name, then run the install command on the target machine.' : 'Run one command on the target machine to bring it online.'}</p>+ <h2>{step === 1 ? 'Add Server' : (mode === 'pair' ? 'Pair Agent' : 'Install Agent')}</h2>+ <p>{step === 1 ? 'Pair an already-running agent with a short code, or generate an install script for a new machine.' : (mode === 'pair' ? 'Enter the 6-char code shown on the agent and your passphrase.' : 'Run one command on the target machine to bring it online.')}</p></div><button className="modal-close" onClick={onClose}>×</button></div>- {step === 1 ? (+ {step === 1 && (+ <div className="install-tabs" style={{ padding: '0 1.5rem', marginTop: '0.5rem' }}>+ <button+ type="button"+ className={`btn ${mode === 'pair' ? 'btn-primary' : 'btn-secondary'}`}+ onClick={() => setMode('pair')}+ style={{ marginRight: '0.5rem' }}+ >+ Pair existing agent+ </button>+ <button+ type="button"+ className={`btn ${mode === 'install' ? 'btn-primary' : 'btn-secondary'}`}+ onClick={() => setMode('install')}+ >+ Install new agent+ </button>+ </div>+ )}++ {step === 1 && mode === 'pair' ? (+ <PairAgentForm+ groups={groups}+ onClose={onClose}+ onClaimed={onCreated}+ />+ ) : step === 1 ? (<form className="server-setup-form" onSubmit={handleCreateServer}><div className="server-setup-form__body">{error && <div className="error-message">{error}</div>}diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.jsindex 99785eb2..6ce54574 100644--- a/frontend/src/services/api/index.js+++ b/frontend/src/services/api/index.js@@ -11,6 +11,7 @@ import * as fileMethods from './files.js';import * as dnsMethods from './dns.js';import * as pluginMethods from './plugins.js';import * as deploymentJobMethods from './deploymentJobs.js';+import * as pairingMethods from './pairing.js';class ApiService extends ApiClient {constructor() {@@ -29,6 +30,7 @@ class ApiService extends ApiClient {dnsMethods,pluginMethods,deploymentJobMethods,+ pairingMethods,];for (const mod of modules) {for (const [key, fn] of Object.entries(mod)) {diff --git a/frontend/src/services/api/pairing.js b/frontend/src/services/api/pairing.jsnew file mode 100644index 00000000..314fa159--- /dev/null+++ b/frontend/src/services/api/pairing.js@@ -0,0 +1,19 @@+// Pairing API — RustDesk-style short-code agent claim flow.++export async function lookupPairCode(code) {+ return this.request('/pairing/lookup', {+ method: 'POST',+ body: { pair_code: code }+ });+}++export async function claimPairedAgent({ pair_code, passphrase, name, group_id, trust_fingerprint }) {+ const body = { pair_code, passphrase };+ if (name) body.name = name;+ if (group_id) body.group_id = group_id;+ if (trust_fingerprint) body.trust_fingerprint = trust_fingerprint;+ return this.request('/pairing/claim', {+ method: 'POST',+ body+ });+}