# Tempsession.sh client for bash and POSIX sh. Protocol v1, client 1.2.0. # # Load it INTO the shell you want to share, so commands run in that very shell: # bash: source <(curl -fsSL https://tempsession.sh/connect/v1/sh) # sh: eval "$(curl -fsSL https://tempsession.sh/connect/v1/sh)" # # What it does: # 1. Registers this shell with TempSession and prints an approval link. # 2. Once you approve it in the browser, the shell is shared at once and # shows who approved it. No remote command runs before that. # 3. Runs approved commands one at a time in this shell with `eval`, so # variables, functions, aliases and the working directory are shared. # You see each command and its output here. Output is sent back over # HTTPS; nothing listens on a port. The shell stays busy while shared. # 4. Ctrl+C while a command runs stops that command (later parts of the # same command line still run). Ctrl+C while none runs ends the session: # its helpers (__ts_*), its traps and its temporary files are removed # and your prompt comes back. # # Commands run without a terminal on stdin (&2; } # Ctrl+C reaches a running command anyway (same process group), so it stops # just that command; while no command runs it ends the session. __ts_on_int() { if [ "$__ts_running" = 1 ]; then __ts_local_interrupt=1 else __ts_stop=1 fi } trap '__ts_on_int' INT # Usage: __ts_http METHOD PATH [curl options...] # Body and headers go to files, the HTTP status to $__ts_code. Succeeds on 2xx. # The token is read from a file (curl -H @file), so it never shows in `ps`. __ts_http() { __ts_method=$1 __ts_path=$2 shift 2 __ts_code=$(curl -sS -X "$__ts_method" -o "$__ts_dir/$__ts_io.body" -D "$__ts_dir/$__ts_io.headers" \ -w '%{http_code}' -H "@$__ts_dir/auth" -H "User-Agent: TempSession-sh/$__ts_version" \ --connect-timeout 10 --max-time 60 "$@" "$__ts_api$__ts_path" 2>/dev/null) || __ts_code=000 case $__ts_code in 2??) return 0 ;; esac return 1 } # A "key=value" field of the last response body. __ts_field() { awk -v key="$1" 'index($0, key "=") == 1 { print substr($0, length(key) + 2); exit }' "$__ts_dir/$__ts_io.body" 2>/dev/null } # A header of the last response, matched without regard to case. __ts_header() { awk -v name="$1" 'BEGIN { name = tolower(name) } { sub(/\r$/, ""); i = index($0, ":") } i > 0 && tolower(substr($0, 1, i - 1)) == name { value = substr($0, i + 1); sub(/^[ \t]+/, "", value) } END { print value }' "$__ts_dir/$__ts_io.headers" 2>/dev/null } __ts_sleep_ms() { case $1 in '' | *[!0-9]*) sleep 1 ;; *) if [ "$1" -lt 1000 ]; then sleep "0.$(printf '%03d' "$1")" 2>/dev/null || sleep 1; else sleep $(($1 / 1000)); fi ;; esac } # Tab in the web terminal: prints what completes word $2 of kind $1 (command, # directory, file or variable), one per line, folders with a trailing /. # Runs here in the shell, so it sees its directory, PATH and functions. __ts_complete() { case $1 in variable) [ -n "${BASH_VERSION:-}" ] && compgen -v -- "${2#\$}" | sed 's/^/$/' ;; command) if [ -n "${BASH_VERSION:-}" ]; then compgen -c -- "$2" else __ts_ifs=$IFS IFS=: for __ts_d in $PATH; do for __ts_f in "${__ts_d:-.}/$2"*; do [ -f "$__ts_f" ] && [ -x "$__ts_f" ] && printf '%s\n' "${__ts_f##*/}" done done IFS=$__ts_ifs fi | sort -u | head -n 200 ;; *) __ts_glob=$2 case $2 in "~") __ts_glob=$HOME ;; "~/"*) __ts_glob="$HOME/${2#"~/"}" ;; esac __ts_noglob=0 case $- in *f*) __ts_noglob=1; set +f ;; esac for __ts_f in "$__ts_glob"*; do [ -e "$__ts_f" ] || continue __ts_slash= [ -d "$__ts_f" ] && __ts_slash=/ [ "$1" = directory ] && [ -z "$__ts_slash" ] && continue case $2 in "~" | "~/"*) __ts_f="~${__ts_f#"$HOME"}" ;; esac printf '%s%s\n' "$__ts_f" "$__ts_slash" done | head -n 200 [ "$__ts_noglob" = 1 ] && set -f ;; esac } # Uploads what a stream's file has gained since the last upload, and shows # it here. Offsets make a retried upload harmless on the server. __ts_send() { eval "__ts_offset=\$__ts_off_$1" __ts_size=$(wc -c <"$2" 2>/dev/null | tr -d ' ') __ts_tries=0 while [ -n "$__ts_size" ] && [ "$__ts_offset" -lt "$__ts_size" ]; do __ts_n=$((__ts_size - __ts_offset)) [ "$__ts_n" -gt 60000 ] && __ts_n=60000 tail -c +$((__ts_offset + 1)) "$2" | head -c "$__ts_n" >|"$__ts_dir/chunk" if __ts_http POST "/commands/$__ts_cmd_id/output?stream=$1&offset=$__ts_offset" \ -H 'Content-Type: application/octet-stream' --data-binary "@$__ts_dir/chunk"; then if [ "$1" = stderr ]; then cat "$__ts_dir/chunk" >&2; else cat "$__ts_dir/chunk"; fi __ts_offset=$((__ts_offset + __ts_n)) __ts_sent=1 [ "$(__ts_field cancel)" = 1 ] && __ts_interrupt elif [ "$__ts_code" = 409 ]; then __ts_expected=$(__ts_field expected_offset) case $__ts_expected in '' | *[!0-9]*) break ;; esac __ts_offset=$__ts_expected else __ts_tries=$((__ts_tries + 1)) [ "$__ts_tries" -ge 3 ] && break sleep 1 fi done eval "__ts_off_$1=\$__ts_offset" } # Interrupts the programs the remote command started (children of this # shell). Commands that run inside the shell itself (builtins, loops) # cannot be interrupted this way; then the command just runs to its end. __ts_interrupt() { [ "$__ts_cancelled" = 1 ] && return 0 __ts_cancelled=1 __ts_kids=$(ps -A -o pid= -o ppid= 2>/dev/null | awk -v parent="$__ts_shell_pid" -v self="$__ts_self" '$2 == parent && $1 != self { print $1 }') if [ -z "$__ts_kids" ]; then __ts_say 'Cancel requested, but the command runs inside the shell and cannot be interrupted.' return 0 fi __ts_say 'Cancel requested remotely. Interrupting the command.' : >|"$__ts_dir/interrupted" # shellcheck disable=SC2086 kill -INT $__ts_kids 2>/dev/null } # Runs in the background while a command runs: streams its output, and # about once a second without output asks whether a cancel was requested. __ts_stream() { __ts_io=stream __ts_self=$(exec sh -c 'echo $PPID') __ts_off_stdout=0 __ts_off_stderr=0 __ts_cancelled=0 __ts_quiet=0 while :; do __ts_last=0 [ -f "$__ts_dir/done" ] && __ts_last=1 __ts_sent=0 __ts_send stdout "$__ts_dir/out" __ts_send stderr "$__ts_dir/err" [ "$__ts_last" = 1 ] && break if [ "$__ts_sent" = 1 ]; then __ts_quiet=0 else __ts_quiet=$((__ts_quiet + 1)) if [ "$__ts_quiet" -ge 2 ]; then __ts_quiet=0 __ts_http POST "/commands/$__ts_cmd_id/output?stream=stdout&offset=$__ts_off_stdout" --data-binary '' \ && [ "$(__ts_field cancel)" = 1 ] && __ts_interrupt fi fi sleep 0.5 2>/dev/null || sleep 1 done } __ts_dir=$(mktemp -d 2>/dev/null || mktemp -d -t tempsession 2>/dev/null) __ts_shell_pid=$$ if [ -n "${ZSH_VERSION:-}" ]; then __ts_say 'zsh is not supported yet. Start bash (or sh) and run the command there.' __ts_stop=1 elif [ -z "$__ts_dir" ] || ! command -v curl >/dev/null 2>&1; then __ts_say 'TempSession needs curl and a writable temporary folder.' __ts_stop=1 else chmod 700 "$__ts_dir" : >|"$__ts_dir/auth" chmod 600 "$__ts_dir/auth" __ts_shell=sh [ -n "${BASH_VERSION:-}" ] && __ts_shell=bash if __ts_http POST /sessions \ --data-urlencode "shell=$__ts_shell" \ --data-urlencode "shell_version=${BASH_VERSION:-}" \ --data-urlencode "os=$(uname -srm 2>/dev/null)" \ --data-urlencode "hostname=$(uname -n 2>/dev/null)" \ --data-urlencode "local_user=$(id -un 2>/dev/null)" \ --data-urlencode "cwd=$PWD" \ --data-urlencode "home=${HOME:-}" \ --data-urlencode 'features=complete' \ --data-urlencode "client_version=$__ts_version" \ --data-urlencode 'output_encoding=UTF-8'; then __ts_registered=1 printf 'Authorization: Bearer %s\n' "$(__ts_field agent_token)" >|"$__ts_dir/auth" printf '\n' >&2 __ts_say 'Approve this shell in your browser:' printf '\n %s\n\n' "$(__ts_field pairing_url)" >&2 __ts_say "Code: $(__ts_field pairing_code) (the browser must show the same code)" __ts_say 'Waiting for approval. Press Ctrl+C to cancel.' else __ts_say "Could not register this shell (HTTP $__ts_code). Is $__ts_base reachable?" __ts_stop=1 fi fi # Pairing: wait until the session is approved in the browser. __ts_active=0 while [ "$__ts_stop" = 0 ] && [ "$__ts_active" = 0 ]; do sleep 1.5 2>/dev/null || sleep 2 [ "$__ts_stop" = 1 ] && break if ! __ts_http GET /session; then case $__ts_code in 401 | 404 | 410) __ts_ended_remotely=1 __ts_say "The session was not approved ($(__ts_field reason))." break ;; esac continue fi if [ "$(__ts_field status)" = active ]; then __ts_active=1 printf '\n' >&2 __ts_say "Approved by $(__ts_field approved_by), workspace: $(__ts_field workspace)." __ts_say 'This shell is now shared. Remote commands run here.' __ts_say 'Ctrl+C stops a running command; Ctrl+C while none runs stops sharing.' fi done # While shared, nothing may ask at this terminal, where nobody remote can # answer: git and ssh fail at once instead of asking for a password or about # a host key. The earlier values are put back when sharing ends. for __ts_name in GIT_TERMINAL_PROMPT GCM_INTERACTIVE SSH_ASKPASS SSH_ASKPASS_REQUIRE; do eval "__ts_had_$__ts_name=\${$__ts_name+1}; __ts_old_$__ts_name=\${$__ts_name-}" done GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never SSH_ASKPASS=false SSH_ASKPASS_REQUIRE=force export GIT_TERMINAL_PROMPT GCM_INTERACTIVE SSH_ASKPASS SSH_ASKPASS_REQUIRE # Work: ask for the next command, run it here, report the result. __ts_fails=0 while [ "$__ts_stop" = 0 ] && [ "$__ts_active" = 1 ]; do if ! __ts_http POST /commands/next; then case $__ts_code in 401 | 404 | 410) __ts_ended_remotely=1 __ts_say "The session was ended in Tempsession.sh ($(__ts_field reason))." break ;; esac __ts_fails=$((__ts_fails + 1)) [ "$__ts_fails" = 1 ] && __ts_say "Connection problem (HTTP $__ts_code). Retrying..." sleep 2 continue fi __ts_fails=0 # A Tab completion request from the web terminal instead of a command. __ts_cmp_id=$(__ts_header X-TempSession-Completion-Id) if [ -n "$__ts_cmp_id" ]; then __ts_complete "$(__ts_header X-TempSession-Completion-Mode)" "$(cat "$__ts_dir/main.body")" >|"$__ts_dir/completion" 2>/dev/null __ts_http POST "/completions/$__ts_cmp_id" -H 'Content-Type: text/plain' --data-binary "@$__ts_dir/completion" continue fi if [ "$__ts_code" = 204 ]; then __ts_sleep_ms "$(__ts_header X-TempSession-Poll-Ms)" continue fi __ts_cmd_id=$(__ts_header X-TempSession-Command-Id) __ts_author=$(__ts_header X-TempSession-Author) mv "$__ts_dir/main.body" "$__ts_dir/command" : >|"$__ts_dir/out" : >|"$__ts_dir/err" rm -f "$__ts_dir/done" "$__ts_dir/interrupted" printf '\n[Tempsession.sh] %s runs:\n' "${__ts_author:-Someone}" >&2 sed 's/^/ > /' "$__ts_dir/command" >&2 printf '\n' >&2 (__ts_stream) & __ts_spid=$! __ts_local_interrupt=0 __ts_running=1 # In a condition, so that a failing command cannot end this shell after a remote "set -e"; # -e and -u are switched off again right after, before this script goes on. if eval "$(cat "$__ts_dir/command")" >|"$__ts_dir/out" 2>|"$__ts_dir/err" |"$__ts_dir/done" wait "$__ts_spid" 2>/dev/null __ts_interrupted=0 if [ "$__ts_rc" -ge 128 ] && { [ "$__ts_local_interrupt" = 1 ] || [ -f "$__ts_dir/interrupted" ]; }; then __ts_interrupted=1 fi [ "$__ts_local_interrupt" = 1 ] && __ts_say 'Command stopped (Ctrl+C). Ctrl+C while no command runs stops sharing.' __ts_succeeded=0 [ "$__ts_rc" = 0 ] && __ts_succeeded=1 __ts_say "Exit code $__ts_rc" __ts_tries=0 until __ts_http POST "/commands/$__ts_cmd_id/finish" \ -d "exit_code=$__ts_rc" -d "succeeded=$__ts_succeeded" -d "interrupted=$__ts_interrupted" \ --data-urlencode "cwd=$PWD"; do case $__ts_code in 401 | 404 | 410) break ;; esac __ts_tries=$((__ts_tries + 1)) [ "$__ts_tries" -ge 5 ] && break sleep 1 done done # Cleanup: end the session (unless TempSession already did), then remove # everything this script added to the shell. if [ "$__ts_registered" = 1 ] && [ "$__ts_ended_remotely" = 0 ]; then __ts_http POST /session/end fi for __ts_name in GIT_TERMINAL_PROMPT GCM_INTERACTIVE SSH_ASKPASS SSH_ASKPASS_REQUIRE; do if eval "[ -n \"\${__ts_had_$__ts_name-}\" ]"; then eval "$__ts_name=\$__ts_old_$__ts_name" else unset "$__ts_name" fi done [ -n "$__ts_dir" ] && rm -rf "$__ts_dir" __ts_say 'Session ended. This shell is yours again.' trap - INT eval "$__ts_traps" case $__ts_flags in *m*) set -m ;; esac case $__ts_flags in *e*) set -e ;; esac case $__ts_flags in *u*) set -u ;; esac case $__ts_flags in *C*) set -C ;; esac unset -f __ts_say __ts_on_int __ts_http __ts_field __ts_header __ts_sleep_ms __ts_send __ts_interrupt __ts_stream __ts_complete # shellcheck disable=SC2046 unset $(set | awk -F= '/^__ts_[A-Za-z0-9_]*=/ { print $1 }')