Files
Reims-Go/internal/app/ssh_flow.go
T
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI

# Conflicts:
#	frontend/src/i18n.ts
#	internal/cli/cli.go
#	internal/i18n/i18n.go
2026-11-30 14:56:19 +08:00

206 lines
6.0 KiB
Go

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)
}