Files
pipelines/internal/server/terminal_login.go
T
alan 3d739c3bfc Copy and paste: the desktop's universal copy key works; Ctrl+C at the terminal login keeps the terminal
Omarchy's Super+C sends Ctrl+C by setting the modifier state with no Ctrl key
event while Super is held. Flutter's web engine only presses a modifier on its
own key event, so the app saw a plain "c": the chat selection was not copied
and the terminal typed the letter. A key modifier sync in front of the
framework's key handler now presses the modifiers the browser event's flags
hold (and outside Apple platforms lets go of a held Meta for Ctrl+C/V/X/A/
Insert), installed by the app's binding.

The terminal copies a selection on Ctrl+C without sending ^C, treats the
injected copy key as copy only, and pastes on Shift+Insert. A refused
clipboard write or read now shows a message instead of failing silently.

Server: before the login completes, Ctrl+C and Ctrl+\ erase the typed
password (Ctrl+U) and Ctrl+Z is dropped, so su is not killed and the terminal
no longer ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:57:28 +00:00

190 lines
6.7 KiB
Go

package server
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strings"
"time"
)
// A machine terminal starts at the operating system's login prompt for the
// server's own account (`su -l <user>`): the operator types that account's
// password into the terminal (the PTY hides it) before getting a shell. A
// terminal is refused rather than opened unauthenticated when su is missing,
// the server runs as root (su would not ask), or su opens a shell without
// asking.
const (
// terminalPromptWait bounds how long Open waits for su's password prompt.
terminalPromptWait = 5 * time.Second
// terminalLoginScan bounds the pre-login output searched for the prompt.
terminalLoginScan = 4 << 10
)
// terminalLoginMarker is printed by the logged-in account's shell before it
// starts the interactive shell: an OSC sequence emulators ignore. Seeing it
// means the login succeeded; seeing it before a password prompt means su
// did not ask for one.
var terminalLoginMarker = []byte("\x1b]6973;pipelines-login\x07")
const (
terminalLoginFailedReason = "The login did not complete (wrong password, or the prompt was cancelled). Close this tab and open a new terminal to try again."
terminalRestartReason = "The Pipelines server restarted and this terminal ended with it. Terminals end with the server; run tmux inside a terminal to keep work across restarts."
terminalStopReason = "The Pipelines server stopped and this terminal ended with it. Run tmux inside a terminal to keep work across restarts."
)
// terminalSuDirs are where su is looked for after PATH, per OS (a service's
// PATH may lack them). Tests replace them.
var terminalSuDirs = map[string][]string{
"darwin": {"/usr/bin"},
"linux": {"/bin", "/usr/bin"},
}
// findTerminalSu is su on PATH or in goos's usual directories; empty when
// none is installed.
func findTerminalSu(goos string) string {
if program, err := exec.LookPath("su"); err == nil {
if abs, absErr := filepath.Abs(program); absErr == nil {
return abs
}
}
for _, dir := range terminalSuDirs[goos] {
candidate := filepath.Join(dir, "su")
if info, err := os.Stat(candidate); err == nil && !info.IsDir() && info.Mode()&0o111 != 0 {
return candidate
}
}
return ""
}
// terminalLoginArgs is the login command of a terminal starting in dir on
// goos: su for username, whose shell then cds to dir and starts the account's
// login shell. It refuses whatever could not ask for the password.
func terminalLoginArgs(goos string, euid int, su, username, dir string) ([]string, error) {
switch goos {
case "darwin", "linux":
default:
return nil, fmt.Errorf("terminals start at the login prompt (su), which Pipelines does not support on %s", goos)
}
switch {
case euid == 0:
return nil, errors.New("the Pipelines server runs as root, so su would not ask for a password; terminals are refused")
case su == "":
return nil, errors.New("su is not installed on this machine, so a terminal cannot ask for the account password; terminals are refused")
case username == "":
return nil, errors.New("the server's account has no user name to log in as; terminals are refused")
}
// Both macOS su and util-linux su take `-l <user> -c <command>` (macOS
// passes the arguments after the login name to the shell).
return []string{su, "-l", username, "-c", terminalLoginScript(dir)}, nil
}
// terminalLoginScript runs in the account's shell after a successful login:
// it marks the login, enters dir (home when that fails) and becomes the
// account's interactive login shell.
func terminalLoginScript(dir string) string {
return `printf '\033]6973;pipelines-login\007'; cd ` + terminalShellQuote(dir) + ` || cd; exec "$SHELL" -l`
}
// terminalShellQuote single-quotes s for sh (and fish).
func terminalShellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// terminalLoginCommand is the server's own login command for dir, or why a
// terminal is refused.
func terminalLoginCommand(dir string) (*exec.Cmd, error) {
account, err := user.Current()
name := ""
if err == nil {
name = account.Username
}
args, err := terminalLoginArgs(runtime.GOOS, os.Geteuid(), findTerminalSu(runtime.GOOS), name, dir)
if err != nil {
return nil, err
}
cmd := exec.Command(args[0], args[1:]...)
// su -l discards the environment but TERM; LC_ALL=C keeps its prompt
// English, so it is recognised.
cmd.Env = append(terminalEnv(os.Environ(), dir), "LC_ALL=C")
cmd.Dir = dir
return cmd, nil
}
// terminalLoginInput is input typed before the login completes. At su's
// password prompt the terminal's signal keys would end su, and the terminal
// with it (Ctrl-C there is a habit, not a request to close the tab): Ctrl-C
// and Ctrl-\ erase the line typed so far instead (Ctrl-U, the kill
// character), and Ctrl-Z, which would stop su, is dropped.
func terminalLoginInput(data []byte) []byte {
if bytes.IndexAny(data, "\x03\x1c\x1a") < 0 {
return data
}
out := make([]byte, 0, len(data))
for _, b := range data {
switch b {
case 0x03, 0x1c:
out = append(out, 0x15)
case 0x1a:
default:
out = append(out, b)
}
}
return out
}
// terminalLoginWatch follows a terminal's output until its login completes.
type terminalLoginWatch struct {
seen []byte
// prompted: a password prompt appeared; loggedIn: the marker appeared;
// unprompted: the marker appeared before any prompt.
prompted, loggedIn, unprompted bool
}
// feed scans more output and reports whether the state changed.
func (w *terminalLoginWatch) feed(data []byte) bool {
if w.loggedIn {
return false
}
w.seen = append(w.seen, bytes.ToLower(data)...)
if len(w.seen) > terminalLoginScan {
w.seen = w.seen[len(w.seen)-terminalLoginScan:]
}
prompt := bytes.Index(w.seen, []byte("password"))
marker := bytes.Index(w.seen, terminalLoginMarker)
changed := false
if !w.prompted && prompt >= 0 && (marker < 0 || prompt < marker) {
w.prompted, changed = true, true
}
if marker >= 0 {
w.loggedIn, w.unprompted, changed = true, !w.prompted, true
w.seen = nil
}
return changed
}
// terminalEnv is env for a terminal's process: TERM names the emulator the
// clients draw, PWD the start directory (when set), and no TMUX variables
// leak in from a tmux the server runs inside.
func terminalEnv(env []string, cwd string) []string {
out := make([]string, 0, len(env)+2)
for _, entry := range env {
if strings.HasPrefix(entry, "TERM=") || strings.HasPrefix(entry, "TMUX=") || strings.HasPrefix(entry, "TMUX_PANE=") ||
strings.HasPrefix(entry, "LC_ALL=") || (cwd != "" && strings.HasPrefix(entry, "PWD=")) {
continue
}
out = append(out, entry)
}
out = append(out, "TERM=xterm-256color")
if cwd != "" {
out = append(out, "PWD="+cwd)
}
return out
}