package app import ( "fmt" "os" "os/exec" "path/filepath" "regexp" "strings" "github.com/Nwflower/reims-go/internal/driver" ) const sshUserFileName = ".reims-go-ssh-user" var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) func sshHostAlias(driverID, vmName string) string { var b strings.Builder b.WriteString("reims-") if id := driver.CanonicalDriverID(driverID); id != "" && id != driver.BuiltinReimsMacOSDriverID { for _, r := range strings.ToLower(id) { if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' { b.WriteRune(r) } else { b.WriteByte('-') } } b.WriteByte('-') } 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() } func sshConfigKey(driverID, name string) string { if id := driver.CanonicalDriverID(driverID); id == "" || id == driver.BuiltinReimsMacOSDriverID { return name } return driver.NewVMRef(driverID, name).Key() } // GetVMSSHUser returns the remembered SSH login user for a VM (empty if unset). func (a *App) GetVMSSHUser(driverID, name string) string { d, err := a.resolveVMInfo(driverID, 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(driverID, name, user string) error { user = strings.TrimSpace(user) if user != "" && !safeSSHUserRe.MatchString(user) { return fmt.Errorf("invalid SSH username %q", user) } d, err := a.resolveVMInfo(driverID, 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) } // sshTarget is where a VM's SSH server answers: the ssh endpoint the driver // reports (a hosted VM may sit on its own address), else the forwarded port. func sshTarget(vm driver.VMInfo) (host string, port int, user string, ok bool) { for _, ep := range vm.Endpoints { if ep.Kind == driver.EndpointSSH && ep.Port > 0 && driver.ValidateEndpoint(ep) == nil { host = ep.Host if host == "" { host = "127.0.0.1" } return host, ep.Port, ep.User, true } } if vm.Network && vm.SSHPort > 0 { return "127.0.0.1", vm.SSHPort, "", true } return "", 0, "", false } // OpenSSHTerminal launches an interactive Windows Terminal (falling back to // PowerShell) connected to the VM's forwarded SSH port. func (a *App) OpenSSHTerminal(driverID, name, user string) error { d, err := a.resolveVMInfo(driverID, name) if err != nil { return err } sshHost, sshPort, endpointUser, ok := sshTarget(d) if !ok { return fmt.Errorf("SSH port forwarding is not enabled for %s", name) } user = strings.TrimSpace(user) if user == "" { user = a.GetVMSSHUser(driverID, name) } else if !safeSSHUserRe.MatchString(user) { return fmt.Errorf("invalid SSH username %q", user) } else { _ = a.SetVMSSHUser(driverID, name, user) } if user == "" { user = endpointUser } target := sshHost if user != "" { target = user + "@" + sshHost } portStr := fmt.Sprintf("%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.emitVMLogForDriver(driverID, 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(driverID, name, user string) (string, error) { d, err := a.resolveVMInfo(driverID, name) if err != nil { return "", err } sshHost, sshPort, endpointUser, ok := sshTarget(d) if !ok { return "", fmt.Errorf("SSH port forwarding is not enabled for %s", name) } user = strings.TrimSpace(user) if user == "" { user = a.GetVMSSHUser(driverID, name) } else if !safeSSHUserRe.MatchString(user) { return "", fmt.Errorf("invalid SSH username %q", user) } else { _ = a.SetVMSSHUser(driverID, name, user) } if user == "" { user = endpointUser } 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(driverID, name) if err := upsertSSHConfigBlock(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil { return "", err } a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (%s:%d)", alias, sshHost, 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(driverID, name, user string) error { alias, err := a.WriteSSHConfig(driverID, 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.emitVMLogForDriver(driverID, name, fmt.Sprintf("Launched %s Remote-SSH for %s", filepath.Base(bin), alias)) return nil } func upsertSSHConfigBlock(cfgPath, vmName, alias, host 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) fmt.Fprintf(&block, " HostName %s\n", host) 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) }