websh

package
v1.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var WebshCmd = &cobra.Command{
	Use:   "websh [flags] [USER@]SERVER [COMMAND...]",
	Short: "Open a Websh terminal or run a command",
	Long: `Open a Websh terminal for interacting with a server or execute a command directly on the server.
Supports SSH-like user@host syntax for specifying the username inline.
For executing commands, it is highly recommended to wrap the entire command string in quotes
to ensure it is interpreted correctly on the remote server.

Shell metacharacters (;, |, &, $) pass through unquoted to the remote shell.
To send a literal metacharacter, wrap the argument in quotes:
  alpacon websh server 'echo hello;world'

Executing a command (SERVER followed by COMMAND) runs through the same executor
as 'alpacon exec'—identical output, exit codes, and sudo-approval handling.
Command execution does not accept exec-only flags such as --detach, --wait, or --wait-approval.

Exit code 3 indicates a WorkSession gate denial; run with --output json to
parse a machine-readable diagnostic on stderr.
Exit code 4 indicates the sudo command is pending human approval; approve it in
the Alpacon console (web), then re-run—or use 'alpacon exec --wait' to block.
Exit code 7 indicates the verification gate held the command and is asking what
it is for. websh command mode has no --purpose, so it cannot state one up front:
answer with 'alpacon exec purpose JOB_ID "..."', or submit through
'alpacon exec --purpose' when the command is expected to be held.
When websh runs a command, the server rejects it before it runs if its command
line carries a credential—a -p/--password flag, a KEY=VALUE secret such as
PGPASSWORD=..., or a user:pass@host connection string—with exit code 1. Pass
the secret with --env="KEY" instead; --output json emits an error envelope on
stderr with error_code command_inline_credential.
A command whose line carries a script body—a heredoc, a multi-line -c or -e
body, or a decoded payload piped into a shell—can be refused when the
workspace approval policy blocks script bodies, with exit code 6 and the code
use_file_execution. Save the script to a file and run it with
'alpacon exec --file', as the printed commands show; --output json carries them
in next_actions.
Requires an active WorkSession when using Browser login (Auth0). Token auth (API
token or Service token) bypasses this requirement for 'websh SERVER COMMAND',
but cannot open an interactive terminal or watch, join, or invite to a session—those
need 'alpacon login' without -t (on a machine without a browser, open the printed URL on another device).`,
	Example: `  # Open a websh terminal
  alpacon websh my-server

  # Open as root using SSH-like syntax
  alpacon websh root@my-server

  # Open with specific user and group
  alpacon websh admin@my-server
  alpacon websh -u admin -g developers my-server

  # Execute a command on a server
  alpacon websh my-server "ls -la /var/log"
  alpacon websh root@my-server "systemctl status nginx"

  # Pass a secret via the shell env; the value stays off the alpacon command line.
  # Read it in rather than typing it inline, so it stays out of shell history too.
  # psql reads PGPASSWORD directly from the env.
  printf 'PGPASSWORD: ' && read -rs PGPASSWORD && export PGPASSWORD
  alpacon websh --env="PGPASSWORD" my-server 'psql -h localhost -U app -c "SELECT 1"'

  # Share terminal session
  alpacon websh --share my-server
  alpacon websh --share --read-only=true my-server

  # Join an existing shared session
  alpacon websh join --url https://myws.us1.alpacon.io/websh/shared/abcd1234?channel=default --password my-session-pass

  # Session management
  alpacon websh ls                          # List active sessions
  alpacon websh describe SESSION_ID         # Show session details
  alpacon websh watch SESSION_ID            # Watch a session (read-only, staff/superuser only)
  alpacon websh invite SESSION_ID --email user@example.com
  alpacon websh close SESSION_ID            # Close a session
  alpacon websh force-close SESSION_ID      # Force close (Superuser only)

Flags:
  -u, --username [USER_NAME]         Specify the username for command execution.
  -g, --groupname [GROUP_NAME]       Specify the group name for command execution.
  --env="KEY"                        Pass an environment variable, reading its value
                                     from the current shell. This keeps the value off
                                     your local alpacon command line—use it for
                                     secrets such as passwords or tokens.
  --env="KEY=VALUE"                  Set 'KEY' to a literal value. Discouraged: the
                                     value stays on your local alpacon command line,
                                     so it lands in shell history, ps output, and CI
                                     job logs. Never pass credentials this way.
  -s, --share                        Share the terminal via a temporary link.
  --read-only=[true|false]           Set shared session to read-only (default: false).
  --work-session [UUID]              Attach this session to a work-session.
                                     Overrides the workspace's active session
                                     set via 'alpacon work-session use'.

Note: All flags must be placed before the server name.
      Everything after the server name is treated as the remote command.`,

	DisableFlagParsing: true,
	Run: func(cmd *cobra.Command, args []string) {
		parsed, err := ParseWebshArgs(args)
		if errors.Is(err, errHelpRequested) {
			_ = cmd.Help()
			return
		}
		if err != nil {
			utils.CliParseErrorWithExit(cmd, parsed.OutputFormat, err.Error())
		}
		if parsed.OutputFormat != "" {
			if err := utils.SetOutputFormat(parsed.OutputFormat); err != nil {
				utils.CliUsageErrorWithExit("%s", err)
			}
		}

		username := parsed.Username
		groupname := parsed.Groupname
		serverName := parsed.ServerName
		commandArgs := parsed.CommandArgs
		share := parsed.Share
		readOnly := parsed.ReadOnly
		env := parsed.Env

		if serverName == "" {
			utils.CliUsageErrorWithExit("Server name is required.")
		}

		if share && len(commandArgs) > 0 {
			utils.CliUsageErrorWithExit("The --share flag cannot be used with remote commands. Use --share for interactive sessions only.")
		}

		if strings.Contains(serverName, "@") && !strings.Contains(serverName, ":") {
			sshTarget := utils.ParseSSHTarget(serverName)
			if username == "" && sshTarget.User != "" {
				username = sshTarget.User
			}
			serverName = sshTarget.Host
		}

		if len(commandArgs) > 0 {
			execCmd.RunRemoteExec(buildRemoteExecArgs(parsed, username, serverName))
			return
		}

		if len(env) > 0 {
			utils.CliWarning("--env has no effect on an interactive websh session; it applies only when running a command")
		}

		authMethod := config.ResolveAuthMethod()

		alpaconClient, err := client.NewAlpaconAPIClient()
		if err != nil {
			utils.CliErrorWithExit("Connection to Alpacon API failed: %s. Consider re-logging.", err)
		}

		workSessionID := worksession.ResolveOrExit(alpaconClient, parsed.WorkSessionID)

		session, err := websh.CreateWebshSession(alpaconClient, serverName, username, groupname, share, readOnly, workSessionID)

		if err != nil {
			err = utils.HandleCommonErrors(err, serverName, mfa.ErrorCallbacks(alpaconClient, func() error {
				session, err = websh.CreateWebshSession(alpaconClient, serverName, username, groupname, share, readOnly, workSessionID)
				return err
			}))

			if err != nil {
				utils.HandleWorkSessionError(err, utils.OperationWebsh, serverName, authMethod, workSessionID)
				utils.CliErrorWithExit("Failed to create websh session for '%s' server: %s.", serverName, utils.InteractiveOnly(err, "open an interactive Websh terminal"))
			}
		}

		listenerDone := make(chan *event.SudoListener, 1)
		go func() {
			listenerDone <- setupSudoListener(alpaconClient, serverName, session.ID)
		}()
		defer func() {
			select {
			case sl := <-listenerDone:
				if sl != nil {
					sl.Stop()
				}
			case <-time.After(3 * time.Second):

			}
		}()

		if err = websh.OpenNewTerminal(alpaconClient, session); err != nil {

			switch {
			case errors.Is(err, websh.ErrReconnectFailed):
				utils.CliErrorWithExitCode(utils.ExitCodeGeneralError, "Could not reconnect to the session.")
			case errors.Is(err, websh.ErrSessionGone):
				utils.CliErrorWithExitCode(utils.ExitCodeGeneralError, "The session is no longer open.")
			default:
				utils.CliErrorWithExitCode(utils.ExitCodeGeneralError, "Websh session ended with error: %s.", err)
			}
		}
	},
}

Functions

This section is empty.

Types

type WebshArgs added in v1.4.6

type WebshArgs struct {
	Username      string
	Groupname     string
	ServerName    string
	CommandArgs   []string
	Share         bool
	ReadOnly      bool
	WorkSessionID string
	OutputFormat  string
	Env           map[string]string
}

func ParseWebshArgs added in v1.4.6

func ParseWebshArgs(args []string) (WebshArgs, error)

ParseWebshArgs parses raw CLI args for `alpacon websh` (DisableFlagParsing mode), returning errHelpRequested when -h/--help is seen.

NOTE: every named flag must be matched before the unknown-flag case.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL