package app import ( "fmt" "os" "os/exec" "path/filepath" "regexp" "strings" ) const sshUserFileName = ".reims-go-ssh-user" var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) // sshHostAlias returns a stable ~/.ssh/config Host alias for a VM. func sshHostAlias(vmName string) string { var b strings.Builder b.WriteString("reims-") for _, r := range strings.ToLower(strings.TrimSpace(vmName)) { if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' { b.WriteRune(r) } else { b.WriteByte('-') } } return b.String() } // GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset). func (a *App) GetVMSSHUser(name string) string { d, err := a.GetVMDetail(name) if err != nil || d.Directory == "" { return "" } b, err := os.ReadFile(filepath.Join(d.Directory, sshUserFileName)) if err != nil { return "" } return strings.TrimSpace(string(b)) } // SetVMSSHUser persists the preferred SSH login user for a VM. func (a *App) SetVMSSHUser(name, user string) error { user = strings.TrimSpace(user) if user != "" && !safeSSHUserRe.MatchString(user) { return fmt.Errorf("invalid SSH username %q", user) } d, err := a.GetVMDetail(name) if err != nil { return err } if d.Directory == "" { return fmt.Errorf("VM directory not found") } p := filepath.Join(d.Directory, sshUserFileName) if user == "" { _ = os.Remove(p) return nil } return os.WriteFile(p, []byte(user+"\n"), 0o644) } // OpenSSHTerminal launches an interactive Windows Terminal (falling back to // PowerShell) connected to the VM's forwarded SSH port. func (a *App) OpenSSHTerminal(name, user string) error { d, err := a.GetVMDetail(name) if err != nil { return err } if !d.Network || d.SSHPort <= 0 { return fmt.Errorf("SSH port forwarding is not enabled for %s", name) } user = strings.TrimSpace(user) if user == "" { user = a.GetVMSSHUser(name) } else if !safeSSHUserRe.MatchString(user) { return fmt.Errorf("invalid SSH username %q", user) } else { _ = a.SetVMSSHUser(name, user) } target := "127.0.0.1" if user != "" { target = user + "@127.0.0.1" } portStr := fmt.Sprintf("%d", d.SSHPort) var cmd *exec.Cmd if wt, err := exec.LookPath("wt.exe"); err == nil { cmd = exec.Command(wt, "new-tab", "--title", name, "ssh", "-p", portStr, target) } else if ps, err := exec.LookPath("powershell.exe"); err == nil { cmd = exec.Command(ps, "-NoExit", "-Command", fmt.Sprintf("ssh -p %s %s", portStr, target)) } else { return fmt.Errorf("neither Windows Terminal (wt.exe) nor powershell.exe was found") } if err := cmd.Start(); err != nil { return fmt.Errorf("open SSH terminal: %w", err) } a.emitLog(name, fmt.Sprintf("Opened SSH terminal (%s -p %s)", target, portStr)) return nil } // WriteSSHConfig idempotently writes or updates a Host block for the VM in // ~/.ssh/config and returns the configured Host alias (e.g. "reims-macos-tahoe"). func (a *App) WriteSSHConfig(name, user string) (string, error) { d, err := a.GetVMDetail(name) if err != nil { return "", err } if !d.Network || d.SSHPort <= 0 { return "", fmt.Errorf("SSH port forwarding is not enabled for %s", name) } user = strings.TrimSpace(user) if user == "" { user = a.GetVMSSHUser(name) } else if !safeSSHUserRe.MatchString(user) { return "", fmt.Errorf("invalid SSH username %q", user) } else { _ = a.SetVMSSHUser(name, user) } home, err := os.UserHomeDir() if err != nil { return "", fmt.Errorf("locate home directory: %w", err) } sshDir := filepath.Join(home, ".ssh") if err := os.MkdirAll(sshDir, 0o700); err != nil { return "", fmt.Errorf("create ~/.ssh: %w", err) } cfgPath := filepath.Join(sshDir, "config") alias := sshHostAlias(name) if err := upsertSSHConfigBlock(cfgPath, name, alias, d.SSHPort, user); err != nil { return "", err } a.emitLog(name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (127.0.0.1:%d)", alias, d.SSHPort)) return alias, nil } // OpenVSCodeSSH ensures the VM's Host block is present in ~/.ssh/config and // launches VS Code (falling back to Cursor) in Remote-SSH mode. func (a *App) OpenVSCodeSSH(name, user string) error { alias, err := a.WriteSSHConfig(name, user) if err != nil { return err } var bin string for _, cand := range []string{"code.cmd", "code", "cursor.cmd", "cursor"} { if p, err := exec.LookPath(cand); err == nil { bin = p break } } if bin == "" { return fmt.Errorf("VS Code or Cursor CLI not found on PATH (Host %s has been written to ~/.ssh/config)", alias) } cmd := exec.Command(bin, "--remote", "ssh-remote+"+alias) if err := cmd.Start(); err != nil { return fmt.Errorf("launch editor Remote-SSH: %w", err) } a.emitLog(name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias)) return nil } func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error { startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName) endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName) var block strings.Builder block.WriteString(startMark) block.WriteByte('\n') fmt.Fprintf(&block, "Host %s\n", alias) block.WriteString(" HostName 127.0.0.1\n") fmt.Fprintf(&block, " Port %d\n", port) if user != "" { fmt.Fprintf(&block, " User %s\n", user) } block.WriteString(" StrictHostKeyChecking accept-new\n") block.WriteString(endMark) block.WriteByte('\n') existingBytes, err := os.ReadFile(cfgPath) if err != nil && !os.IsNotExist(err) { return err } content := strings.ReplaceAll(string(existingBytes), "\r\n", "\n") var updated string if si := strings.Index(content, startMark); si >= 0 { if ei := strings.Index(content[si:], endMark); ei >= 0 { endPos := si + ei + len(endMark) if endPos < len(content) && content[endPos] == '\n' { endPos++ } updated = content[:si] + block.String() + content[endPos:] } } if updated == "" { if content != "" && !strings.HasSuffix(content, "\n") { content += "\n" } if content != "" && !strings.HasSuffix(content, "\n\n") { content += "\n" } updated = content + block.String() } return os.WriteFile(cfgPath, []byte(updated), 0o600) }