# Tempsession.sh client for Windows PowerShell 5.1 and PowerShell 7+. Protocol v1, client 1.2.0. # # Load it INTO the PowerShell session you want to share, so commands run in that very session: # irm https://tempsession.sh/connect/v1/ps | iex # # What it does: # 1. Registers this session with TempSession and prints an approval link. # Ctrl+C cancels while it waits. # 2. Once you approve it in the browser, the session is shared at once and # this window shows who approved it. # 3. In a Windows console window with PSReadLine (the default) you get your # prompt back and keep working. Remote commands run here whenever the # prompt is empty and you are not running a command yourself. Commands # you type yourself are shown in Tempsession.sh too, with their output. # Ctrl+C on an empty prompt stops sharing. Elsewhere (Linux, macOS, editors) the # window stays busy while shared: Ctrl+C stops a running remote command, # Ctrl+C while none runs stops sharing. # 4. Remote commands run dot-sourced in this session, each in its own # pipeline, so variables, functions, loaded modules and existing # connections (for example Connect-MgGraph) are shared. You see each one # and its output here. Output is sent back over HTTPS; nothing listens on # a port. When sharing stops, everything this script defined (named # __ts*) is removed. # Run again in the same window: stop the earlier TempSession first and clear # anything an earlier run left behind, so that two runs never mix. # (Get-Variable instead of $global:__tsShared: under Set-StrictMode an unset variable is an error.) $__tsEarlier = Get-Variable -Name __tsShared -Scope Global -ValueOnly -ErrorAction SilentlyContinue if ($null -ne $__tsEarlier -and -not $__tsEarlier.Done -and (Get-Command -Name __tsStop -ErrorAction SilentlyContinue)) { Write-Host '[Tempsession.sh] Stopping the earlier session in this window first.' -ForegroundColor Yellow . __tsStop } Get-EventSubscriber -ErrorAction SilentlyContinue | Where-Object SourceIdentifier -like 'TempSession.*' | Unregister-Event -ErrorAction SilentlyContinue Get-Job -ErrorAction SilentlyContinue | Where-Object Name -like 'TempSession.*' | Remove-Job -Force -ErrorAction SilentlyContinue function global:__tsSay([string] $Text, [string] $Color = 'Cyan') { Write-Host "[Tempsession.sh] $Text" -ForegroundColor $Color } # The current location as the prompt shows it. Sent along with each report, # so the web terminal can show the same "PS C:\path>" prompt. function global:__tsCwd { try { return [string] $ExecutionContext.SessionState.Path.CurrentLocation.Path } catch { return '' } } # Parses a "key=value" response body. function global:__tsFields([string] $Text) { $fields = @{} if ($Text) { foreach ($line in ($Text -split "`n")) { $index = $line.IndexOf('=') if ($index -gt 0) { $fields[$line.Substring(0, $index)] = $line.Substring($index + 1).TrimEnd("`r") } } } $fields } function global:__tsRequest([string] $Method, [string] $Path, $Body = $null, [string] $ContentType = $null) { $ProgressPreference = 'SilentlyContinue' $parameters = @{ Uri = $__tsShared.Api + $Path Method = $Method Headers = $__tsShared.Headers UseBasicParsing = $true TimeoutSec = 30 UserAgent = $__tsShared.UserAgent ErrorAction = 'Stop' } if ($null -ne $Body) { $parameters.Body = $Body } if ($ContentType) { $parameters.ContentType = $ContentType } try { $response = Invoke-WebRequest @parameters $content = $response.Content if ($content -is [byte[]]) { $content = [Text.Encoding]::UTF8.GetString($content) } return @{ Status = [int] $response.StatusCode; Headers = $response.Headers; Content = [string] $content; Fields = (__tsFields $content) } } catch { $status = 0 $errorResponse = $null if ($_.Exception.PSObject.Properties['Response']) { $errorResponse = $_.Exception.Response } if ($null -ne $errorResponse) { $status = [int] $errorResponse.StatusCode } $content = '' if ($null -ne $_.ErrorDetails -and $_.ErrorDetails.Message) { $content = $_.ErrorDetails.Message } elseif ($errorResponse -is [System.Net.WebResponse]) { # Windows PowerShell 5.1 does not put the body of an error response into ErrorDetails. try { $reader = New-Object System.IO.StreamReader($errorResponse.GetResponseStream()) $content = $reader.ReadToEnd() $reader.Dispose() } catch { } } return @{ Status = $status; Headers = @{}; Content = $content; Fields = (__tsFields $content) } } } function global:__tsHeader($Response, [string] $Name) { $value = $Response.Headers[$Name] if ($null -eq $value) { return '' } ($value | Select-Object -First 1) -as [string] } # Waits, but returns early (with $true) when Ctrl+C asked to stop. function global:__tsWait([int] $Milliseconds) { $until = [DateTime]::UtcNow.AddMilliseconds($Milliseconds) while ([DateTime]::UtcNow -lt $until) { if ($__tsShared.Quit) { return $true } Start-Sleep -Milliseconds 50 } $__tsShared.Quit } # Sends what the running command printed since the last upload. function global:__tsFlush { foreach ($stream in 'stdout', 'stderr') { $buffer = $__tsState.Buffers[$stream] if ($buffer.Length -eq 0) { continue } $bytes = [Text.Encoding]::UTF8.GetBytes($buffer.ToString()) [void] $buffer.Clear() $position = 0 $tries = 0 while ($position -lt $bytes.Length -and -not $__tsState.Ended) { $length = [Math]::Min(60000, $bytes.Length - $position) $chunk = New-Object byte[] $length [Array]::Copy($bytes, $position, $chunk, 0, $length) $response = __tsRequest 'POST' "/commands/$($__tsState.CommandId)/output?stream=$stream&offset=$($__tsState.Sent[$stream])" $chunk 'application/octet-stream' if ($response.Status -eq 200) { $__tsState.Sent[$stream] += $length $position += $length if ($response.Fields['cancel'] -eq '1') { $__tsState.Cancel = $true } } elseif ($response.Status -eq 409 -and $response.Fields['expected_offset'] -match '^\d+$') { $__tsState.Sent[$stream] = [long] $response.Fields['expected_offset'] } elseif ($response.Status -eq 410 -or $response.Status -eq 401) { $__tsState.Ended = $true } elseif (++$tries -ge 3) { break } else { Start-Sleep -Seconds 1 } } } $__tsState.LastFlush = [DateTime]::UtcNow } # The width PowerShell itself would format for: this window's width (a line # exactly as wide as the window would wrap), or 200 without a window. function global:__tsOutputWidth { try { $width = $Host.UI.RawUI.BufferSize.Width if ($width -ge 40) { return $width - 1 } } catch { } 200 } # Shows a line here, buffers it for upload, and stops the command when a # cancel was requested (by throwing, which stops its pipeline). function global:__tsEmit([string] $Stream, [string] $Text) { # Table lines come padded with spaces; they only make the window wrap. $Text = $Text.TrimEnd() # Blank lines before the first and after the last line of output are dropped # (PowerShell frames tables with them); several in a row in between become one. if ($Text.Length -eq 0) { $__tsState.BlankLines++ return } if ($__tsState.Emitted -and $__tsState.BlankLines -gt 0) { __tsEmitLine $Stream '' } $__tsState.BlankLines = 0 $__tsState.Emitted = $true __tsEmitLine $Stream $Text } function global:__tsEmitLine([string] $Stream, [string] $Text) { # Through this console's own interface, kept from before the command: while it runs, $Host.UI is the quiet one. if ($Stream -eq 'stderr') { $__tsConsoleUI.WriteLine([ConsoleColor]::Red, $__tsConsoleUI.RawUI.BackgroundColor, $Text) } else { $__tsConsoleUI.WriteLine($Text) } # Keep stdout and stderr in order: send what the other stream has before switching. if ($__tsState.LastStream -and $__tsState.LastStream -ne $Stream -and $__tsState.Buffers[$__tsState.LastStream].Length -gt 0) { __tsFlush } $__tsState.LastStream = $Stream [void] $__tsState.Buffers[$Stream].Append($Text).Append("`n") if (([DateTime]::UtcNow - $__tsState.LastFlush).TotalMilliseconds -ge 500 -or $__tsState.Buffers[$Stream].Length -ge 32000) { __tsFlush } if ($__tsState.Cancel -and -not $__tsState.Interrupted) { $__tsState.Interrupted = $true throw [System.OperationCanceledException]::new('Tempsession.sh: the command was cancelled remotely.') } } # Turns one object of the command's merged output streams into lines. function global:__tsHandle($Item) { if ($Item -is [System.Management.Automation.ErrorRecord]) { $__tsState.Failed = $true __tsEmit 'stderr' $Item.ToString() } elseif ($Item -is [System.Management.Automation.WarningRecord]) { __tsEmit 'stdout' ('WARNING: ' + $Item.Message) } elseif ($Item -is [System.Management.Automation.VerboseRecord]) { __tsEmit 'stdout' ('VERBOSE: ' + $Item.Message) } elseif ($Item -is [System.Management.Automation.DebugRecord]) { __tsEmit 'stdout' ('DEBUG: ' + $Item.Message) } elseif ($Item -is [System.Management.Automation.InformationRecord]) { __tsEmit 'stdout' ([string] $Item.MessageData) } else { foreach ($line in $__tsState.Formatter.Process($Item)) { __tsEmit 'stdout' $line } } } # Runs a command's text, dot-sourced. Called (dot-sourced) from the command's # own pipeline, so it runs in this session's global scope like typed at the prompt. function global:__tsExecute([string] $__tsText) { . ([scriptblock]::Create($__tsText)) *>&1 | ForEach-Object { __tsHandle $_ } } # Runs the command the helper thread claimed, reports its output and result. # Must be dot-sourced, so that it runs in the global scope. Whatever goes # wrong in here, the result is reported and the client is free again after. function global:__tsRunPending { # Busy until the result is reported, so the helper does not claim the next command before that. $__tsShared.Busy = $true $__tsCommand = $__tsShared.Pending $__tsShared.CommandId = $__tsCommand.Id $__tsReported = $false try { $__tsState = @{ CommandId = $__tsCommand.Id Buffers = @{ stdout = New-Object Text.StringBuilder; stderr = New-Object Text.StringBuilder } Sent = @{ stdout = [long] 0; stderr = [long] 0 } LastFlush = [DateTime]::UtcNow LastStream = $null BlankLines = 0 Emitted = $false Failed = $false Terminated = $false Cancel = $false Interrupted = $false Ended = $false Formatter = $null } Write-Host '' __tsSay "$($__tsCommand.Author) runs:" Write-Host (($__tsCommand.Text -split "`n" | ForEach-Object { ' > ' + $_.TrimEnd("`r") }) -join "`n") -ForegroundColor DarkGray # $LASTEXITCODE may not exist yet (and reading it would fail under Set-StrictMode). # Keep its value, not the variable: the variable itself is overwritten next. $__tsExitVariable = Get-Variable -Name LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue $__tsHadExitCode = $null -ne $__tsExitVariable $__tsExitBefore = $(if ($__tsHadExitCode) { $__tsExitVariable.Value } else { $null }) $global:LASTEXITCODE = $__tsExitSentinel $__tsWidth = __tsOutputWidth $__tsState.Formatter = { Out-String -Stream -Width $__tsWidth }.GetSteppablePipeline() $__tsState.Formatter.Begin($true) $__tsShared.Interrupted = $false $__tsShared.RemoteCancel = $false $__tsPipeline = [PowerShell]::Create('CurrentRunspace') [void] $__tsPipeline.AddScript('param($__tsText) . __tsExecute $__tsText', $false).AddArgument($__tsCommand.Text) $__tsShared.Pipeline = $__tsPipeline $__tsShared.Pending = $null # Programs must not ask at this console either: git (and its credential manager) and ssh fail at once instead. $__tsEnvBefore = @{} foreach ($__tsName in $__tsNoPromptEnvironment.Keys) { $__tsEnvBefore[$__tsName] = [Environment]::GetEnvironmentVariable($__tsName) [Environment]::SetEnvironmentVariable($__tsName, $__tsNoPromptEnvironment[$__tsName]) } try { if ($null -ne $__tsQuietSettings) { $null = $__tsPipeline.Invoke($null, $__tsQuietSettings) } else { $null = $__tsPipeline.Invoke() } foreach ($__tsLine in $__tsState.Formatter.End()) { __tsEmit 'stdout' $__tsLine } } catch { if (-not ($__tsState.Interrupted -or $__tsShared.Interrupted -or $__tsShared.RemoteCancel)) { $__tsState.Failed = $true $__tsState.Terminated = $true $__tsError = $_.Exception while ($null -ne $__tsError.InnerException) { $__tsError = $__tsError.InnerException } __tsEmit 'stderr' $__tsError.Message } } finally { $__tsShared.Pipeline = $null foreach ($__tsName in $__tsEnvBefore.Keys) { [Environment]::SetEnvironmentVariable($__tsName, $__tsEnvBefore[$__tsName]) } } if ($__tsPipeline.InvocationStateInfo.State -eq 'Stopped') { $__tsState.Interrupted = $true } # Errors outside the command's own output, e.g. a parse error of the command text. if (-not $__tsState.Interrupted) { foreach ($__tsErrorRecord in @($__tsPipeline.Streams.Error)) { $__tsState.Failed = $true __tsEmit 'stderr' $__tsErrorRecord.ToString() } } $__tsPipeline.Dispose() if ($__tsShared.Interrupted) { __tsSay 'Command stopped (Ctrl+C).' 'Yellow' } elseif ($__tsShared.RemoteCancel -or $__tsState.Interrupted) { __tsSay 'Cancelled remotely.' 'Yellow' } $__tsInterrupted = $__tsState.Interrupted -or $__tsShared.Interrupted -or $__tsShared.RemoteCancel __tsFlush if ($global:LASTEXITCODE -eq $__tsExitSentinel) { # No native program ran: leave $LASTEXITCODE as it was (or unset). if ($__tsHadExitCode) { $global:LASTEXITCODE = $__tsExitBefore } else { Remove-Variable -Name LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue } $__tsSucceeded = -not ($__tsState.Failed -or $__tsInterrupted) $__tsExitCode = $(if ($__tsSucceeded) { 0 } else { 1 }) } else { $__tsExitCode = $global:LASTEXITCODE $__tsSucceeded = ($__tsExitCode -eq 0) -and -not ($__tsState.Terminated -or $__tsInterrupted) } __tsSay "Exit code $__tsExitCode" 'DarkGray' for ($__tsTry = 0; $__tsTry -lt 5; $__tsTry++) { $__tsShared.Cwd = __tsCwd $__tsResponse = __tsRequest 'POST' "/commands/$($__tsState.CommandId)/finish" @{ exit_code = $__tsExitCode succeeded = [int] $__tsSucceeded interrupted = [int] $__tsInterrupted cwd = $__tsShared.Cwd } if ($__tsResponse.Status -eq 200) { break } if ($__tsResponse.Status -eq 410 -or $__tsResponse.Status -eq 401) { $__tsState.Ended = $true; break } Start-Sleep -Seconds 1 } $__tsReported = $true if ($__tsState.Ended) { $__tsShared.Ended = $true } } catch { __tsSay "Tempsession.sh client error: $($_.Exception.Message)" 'Red' } finally { # A problem of this client must not leave the command running forever or block the next one. if (-not $__tsReported) { $null = __tsRequest 'POST' "/commands/$($__tsCommand.Id)/finish" @{ succeeded = 0; interrupted = 0; cwd = (__tsCwd) } } $__tsShared.Pipeline = $null $__tsShared.Pending = $null $__tsShared.LastCommandEnd = [DateTime]::UtcNow $__tsShared.Busy = $false } } # Commands typed at the prompt while shared (prompt mode) are mirrored to # TempSession: the line when it is entered, PowerShell's output as it comes # (through the Out-Default proxy), and the result at the next prompt. The # helper thread uploads everything, so typing never waits for the network. function global:__tsLocalStart([string] $Line) { # The previous command's report should be done; give the helper a moment, then move on. for ($wait = 0; $null -ne $__tsShared.Local -and $wait -lt 150; $wait++) { Start-Sleep -Milliseconds 20 } if ($null -ne $__tsShared.Local) { $__tsShared.Local.Failed = $true $item = $null while ($__tsShared.LocalQueue.TryDequeue([ref] $item)) { } } $row = 0 try { $row = $Host.UI.RawUI.CursorPosition.Y } catch { } $exitVariable = Get-Variable -Name LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue $errors = $global:Error $__tsShared.Local = [hashtable]::Synchronized(@{ ErrorTop = $(if ($errors.Count -gt 0) { $errors[0] } else { $null }) Text = $Line Key = [guid]::NewGuid().ToString('N') Cwd = (__tsCwd) CwdAfter = '' Id = $null Failed = $false Ended = $false Captured = $false StartRow = $row ExitBefore = $(if ($exitVariable) { $exitVariable.Value } else { $null }) ExitCode = 0 Succeeded = $true Interrupted = $false Sent = @{ stdout = [long] 0; stderr = [long] 0 } Pending = @{ stdout = New-Object Text.StringBuilder; stderr = New-Object Text.StringBuilder } }) $__tsShared.LocalCapturing = $true } function global:__tsLocalAppend([string] $Stream, [string] $Text) { $local = $__tsShared.Local if ($null -eq $local) { return } $local.Captured = $true $__tsShared.LocalQueue.Enqueue(@{ Stream = $Stream; Text = $Text.TrimEnd() }) } function global:__tsLocalEnd { $__tsShared.LocalCapturing = $false $local = $__tsShared.Local if ($null -eq $local -or $local.Ended) { return } # Programs such as ipconfig write to the console directly, past PowerShell. When # nothing was captured, take what the command left on the screen (Windows console). if (-not $local.Captured) { try { $rawUi = $Host.UI.RawUI $endRow = $rawUi.CursorPosition.Y if ($endRow -gt $local.StartRow) { $width = $rawUi.BufferSize.Width $cells = $rawUi.GetBufferContents((New-Object System.Management.Automation.Host.Rectangle 0, $local.StartRow, ($width - 1), ($endRow - 1))) for ($r = 0; $r -lt $cells.GetLength(0); $r++) { $text = New-Object Text.StringBuilder for ($c = 0; $c -lt $cells.GetLength(1); $c++) { $cell = $cells.GetValue($r, $c) if ($cell.BufferCellType -ne [System.Management.Automation.Host.BufferCellType]::Trailing) { [void] $text.Append($cell.Character) } } __tsLocalAppend 'stdout' $text.ToString().TrimEnd() } } } catch { } } # How did the line end? $? cannot tell from here; these can: the history entry # (Stopped by Ctrl+C, Failed on a terminating error), a new entry in $Error, and # a changed $LASTEXITCODE of a native program. $historyStatus = '' try { $last = Get-History -Count 1 if ($null -ne $last -and $last.CommandLine -eq $local.Text) { $historyStatus = "$($last.ExecutionStatus)" } } catch { } $errors = $global:Error $newError = $errors.Count -gt 0 -and -not [object]::ReferenceEquals($errors[0], $local.ErrorTop) $exitVariable = Get-Variable -Name LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue $exitNow = $(if ($exitVariable) { $exitVariable.Value } else { $null }) $nativeRan = $null -ne $exitNow -and $exitNow -ne $local.ExitBefore $local.Interrupted = $historyStatus -eq 'Stopped' $succeeded = -not ($local.Interrupted -or $historyStatus -eq 'Failed' -or $newError -or ($nativeRan -and $exitNow -ne 0)) $local.Succeeded = $succeeded $local.ExitCode = $(if ($nativeRan) { $exitNow } elseif ($succeeded) { 0 } else { 1 }) $local.CwdAfter = __tsCwd $__tsShared.Cwd = $local.CwdAfter $local.Ended = $true } # Installs the hooks that mirror typed commands: wrappers around # PSConsoleHostReadLine (a line was entered) and prompt (it has ended), and an # Out-Default proxy that copies PowerShell's output. All are put back on stop. function global:__tsInstallLocalMirror { $readLine = Get-Command -Name PSConsoleHostReadLine -CommandType Function -ErrorAction SilentlyContinue | Select-Object -First 1 $promptFunction = Get-Command -Name prompt -CommandType Function -ErrorAction SilentlyContinue | Select-Object -First 1 if ($null -eq $readLine -or $null -eq $promptFunction) { return } $global:__tsReadLineOriginal = $readLine.ScriptBlock $global:__tsPromptOriginal = $promptFunction.ScriptBlock $global:__tsOutDefaultOriginal = $null $existingOutDefault = Get-Command -Name Out-Default -CommandType Function -ErrorAction SilentlyContinue | Select-Object -First 1 if ($null -ne $existingOutDefault) { $global:__tsOutDefaultOriginal = $existingOutDefault.ScriptBlock } $originalReadLine = $readLine.ScriptBlock Set-Item -Path Function:\global:PSConsoleHostReadLine -Value ({ $line = & $originalReadLine try { $shared = Get-Variable -Name __tsShared -Scope Global -ValueOnly -ErrorAction SilentlyContinue if ($null -ne $shared -and -not $shared.Done -and $line -and $line.Trim()) { __tsLocalStart $line } } catch { } $line }.GetNewClosure()) $originalPrompt = $promptFunction.ScriptBlock Set-Item -Path Function:\global:prompt -Value ({ try { $shared = Get-Variable -Name __tsShared -Scope Global -ValueOnly -ErrorAction SilentlyContinue if ($null -ne $shared -and $null -ne $shared.Local) { __tsLocalEnd } } catch { } & $originalPrompt }.GetNewClosure()) # The proxy is generated from the real cmdlet's parameters, so it fits every PowerShell version. $metadata = New-Object System.Management.Automation.CommandMetadata (Get-Command -Name Microsoft.PowerShell.Core\Out-Default -CommandType Cmdlet) $proxy = [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($metadata) + "`nparam(" + [System.Management.Automation.ProxyCommand]::GetParamBlock($metadata) + ")`n" + @' begin { $forwardCommand = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Core\Out-Default', [System.Management.Automation.CommandTypes]::Cmdlet) $forward = { & $forwardCommand @PSBoundParameters }.GetSteppablePipeline($MyInvocation.CommandOrigin) $forward.Begin($PSCmdlet) $formatter = $null $shared = Get-Variable -Name __tsShared -Scope Global -ValueOnly -ErrorAction SilentlyContinue if ($null -ne $shared -and $shared.LocalCapturing -and -not $PSBoundParameters.ContainsKey('Transcript')) { try { $width = __tsOutputWidth $formatter = { Out-String -Stream -Width $width }.GetSteppablePipeline() $formatter.Begin($true) } catch { $formatter = $null } } } process { $forward.Process($_) if ($null -ne $formatter) { try { if ($_ -is [System.Management.Automation.ErrorRecord]) { __tsLocalAppend 'stderr' $_.ToString() } else { foreach ($line in $formatter.Process($_)) { __tsLocalAppend 'stdout' $line } } } catch { } } } end { $forward.End() if ($null -ne $formatter) { try { foreach ($line in $formatter.End()) { __tsLocalAppend 'stdout' $line } } catch { } } } '@ Set-Item -Path Function:\global:Out-Default -Value ([scriptblock]::Create($proxy)) $global:__tsMirrorInstalled = $true } function global:__tsRemoveLocalMirror { if (-not (Get-Variable -Name __tsMirrorInstalled -Scope Global -ValueOnly -ErrorAction SilentlyContinue)) { return } try { Set-Item -Path Function:\global:PSConsoleHostReadLine -Value $__tsReadLineOriginal } catch { } try { Set-Item -Path Function:\global:prompt -Value $__tsPromptOriginal } catch { } try { if ($null -ne $__tsOutDefaultOriginal) { Set-Item -Path Function:\global:Out-Default -Value $__tsOutDefaultOriginal } else { Remove-Item -Path Function:\Out-Default -ErrorAction SilentlyContinue } } catch { } $global:__tsMirrorInstalled = $false } # Prompt mode: you keep the prompt. A timer event, which PSReadLine processes # while it waits for input, runs claimed commands when the line is empty. function global:__tsStartPromptMode { $global:__tsTimer = New-Object System.Timers.Timer 250 $__tsTimer.AutoReset = $false # A name of its own per run, so a leftover of an earlier run can never block this one. $global:__tsTickSource = "TempSession.Tick.$([guid]::NewGuid().ToString('N'))" $null = Register-ObjectEvent -InputObject $__tsTimer -EventName Elapsed -SourceIdentifier $__tsTickSource -Action { try { if ($__tsShared.Ended) { . __tsStop -EndedRemotely return } $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $line, [ref] $cursor) if ($line.Length -eq 0) { $__tsShared.ReadyAt = [DateTime]::UtcNow if ($null -ne $__tsShared.Pending) { . __tsRunPending } } } finally { if ($null -ne $__tsShared -and -not $__tsShared.Done) { $__tsTimer.Start() } } } $global:__tsCtrlCFunction = 'CopyOrCancelLine' try { $handler = Get-PSReadLineKeyHandler -Chord 'Ctrl+c' -ErrorAction Stop | Select-Object -First 1 if ($handler -and $handler.Function -and $handler.Function -ne 'CustomAction') { $global:__tsCtrlCFunction = $handler.Function } } catch { } Set-PSReadLineKeyHandler -Chord 'Ctrl+c' -ScriptBlock { $line = $null $cursor = $null [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $line, [ref] $cursor) if ($line.Length -gt 0) { [Microsoft.PowerShell.PSConsoleReadLine]::CopyOrCancelLine() return } # A Ctrl+C typed while a remote command ran can arrive here just after it ended; it must not stop sharing. if (([DateTime]::UtcNow - $__tsShared.LastCommandEnd).TotalMilliseconds -lt 1000) { return } Write-Host '' . __tsStop [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() } try { __tsInstallLocalMirror } catch { __tsSay "Commands typed here will not be shown in Tempsession.sh: $($_.Exception.Message)" 'Yellow' } $__tsTimer.Start() } # Stops sharing and removes everything this script added. Must be dot-sourced. function global:__tsStop([switch] $EndedRemotely) { if ($__tsShared.Done) { return } $__tsShared.Done = $true Get-EventSubscriber -ErrorAction SilentlyContinue | Where-Object SourceIdentifier -like 'TempSession.*' | Unregister-Event -ErrorAction SilentlyContinue Get-Job -ErrorAction SilentlyContinue | Where-Object Name -like 'TempSession.*' | Remove-Job -Force -ErrorAction SilentlyContinue $__tsTimerObject = Get-Variable -Name __tsTimer -Scope Global -ValueOnly -ErrorAction SilentlyContinue if ($null -ne $__tsTimerObject) { $__tsTimerObject.Dispose() } if ($__tsPromptMode) { try { Set-PSReadLineKeyHandler -Chord 'Ctrl+c' -Function $__tsCtrlCFunction } catch { } } try { __tsRemoveLocalMirror } catch { } if ($null -ne $__tsHelperHandle) { $null = $__tsHelperHandle.AsyncWaitHandle.WaitOne(2000) } $__tsHelper.Dispose() if ($null -ne $__tsQuietRunspace) { try { $__tsQuietRunspace.Dispose() } catch { } } if ($null -ne $__tsTreatControlC) { try { [Console]::TreatControlCAsInput = $__tsTreatControlC } catch { } } if ($EndedRemotely -or $__tsShared.Ended) { $__tsReason = $__tsShared.EndReason if (-not $__tsReason -and $__tsRegistered) { $__tsReason = (__tsRequest 'GET' '/session').Fields['reason'] } if ($__tsReason) { __tsSay "The session was ended in Tempsession.sh ($__tsReason)." 'Yellow' } else { __tsSay 'The session was ended in Tempsession.sh.' 'Yellow' } } elseif ($__tsRegistered) { $null = __tsRequest 'POST' '/session/end' } try { [Net.ServicePointManager]::SecurityProtocol = $__tsProtocols } catch { } __tsSay 'Session ended. This session is yours again.' 'Green' Get-ChildItem -Path Function:\ | Where-Object Name -like '__ts*' | Remove-Item -ErrorAction SilentlyContinue Get-Variable -Name '__ts*' -Scope Global -ErrorAction SilentlyContinue | Remove-Variable -Scope Global -ErrorAction SilentlyContinue } $__tsBase = 'https://tempsession.sh' $__tsVersion = '1.2.0' $__tsRegistered = $false $__tsActive = $false $__tsPromptMode = $false $__tsExitSentinel = -2147480000 # Remote commands run with a host that has no user interface, taken from a # runspace of its own: whatever would prompt (Read-Host, a confirmation, a # missing mandatory parameter, Get-Credential) fails at once instead of # waiting at this console for keys nobody presses from afar. While a command # runs, $Host.UI is that quiet interface, so its output is shown through the # console's own one, kept here. Without a quiet host commands run as before. $__tsConsoleUI = $Host.UI $__tsQuietSettings = $null $__tsQuietRunspace = $null try { $__tsQuietRunspace = [runspacefactory]::CreateRunspace() $__tsQuietRunspace.Open() $__tsQuietProbe = [PowerShell]::Create() $__tsQuietProbe.Runspace = $__tsQuietRunspace $__tsQuietSettings = New-Object System.Management.Automation.PSInvocationSettings $__tsQuietSettings.Host = @($__tsQuietProbe.AddScript('$Host').Invoke())[0] $__tsQuietProbe.Dispose() } catch { $__tsQuietSettings = $null } # Set while a remote command runs. ssh gets a password helper that always # fails (outside Windows, where ssh can use one). $__tsNoPromptEnvironment = @{ GIT_TERMINAL_PROMPT = '0'; GCM_INTERACTIVE = 'never' } if ($PSVersionTable['PSEdition'] -eq 'Core' -and -not (Get-Variable -Name IsWindows -ValueOnly -ErrorAction SilentlyContinue)) { $__tsNoPromptEnvironment['SSH_ASKPASS'] = 'false' $__tsNoPromptEnvironment['SSH_ASKPASS_REQUIRE'] = 'force' } $__tsProtocols = [Net.ServicePointManager]::SecurityProtocol try { [Net.ServicePointManager]::SecurityProtocol = $__tsProtocols -bor [Net.SecurityProtocolType]::Tls12 } catch { } # State shared with the helper thread. Synchronized, because both threads change it. $__tsShared = [hashtable]::Synchronized(@{ Api = "$__tsBase/api/agent/v1" Headers = @{} UserAgent = "TempSession-PowerShell/$__tsVersion" WatchKeys = $false PromptMode = $false Cwd = '' Local = $null LocalCapturing = $false LocalQueue = New-Object 'System.Collections.Concurrent.ConcurrentQueue[object]' ReadyAt = [DateTime]::MinValue Busy = $false Pending = $null Pipeline = $null CommandId = $null Interrupted = $false RemoteCancel = $false LastCommandEnd = [DateTime]::MinValue Quit = $false Ended = $false EndReason = '' Done = $false }) $__tsState = @{} # The helper thread: claims the next command whenever this session is ready # for one, asks about once a second whether a running command should be # cancelled, keeps the session alive, and (where this window is busy) turns # Ctrl+C into "stop the command" or "stop sharing". $__tsHelper = [PowerShell]::Create() [void] $__tsHelper.AddScript({ param($shared) $ProgressPreference = 'SilentlyContinue' function Send([string] $Method, [string] $Path, $Body) { $parameters = @{ Uri = $shared.Api + $Path; Method = $Method; Headers = $shared.Headers; UseBasicParsing = $true TimeoutSec = 30; UserAgent = $shared.UserAgent; ErrorAction = 'Stop' } if ($null -ne $Body) { $parameters.Body = $Body if ($Body -isnot [hashtable]) { $parameters.ContentType = 'application/octet-stream' } } try { $response = Invoke-WebRequest @parameters $content = $response.Content if ($content -is [byte[]]) { $content = [Text.Encoding]::UTF8.GetString($content) } return @{ Status = [int] $response.StatusCode; Headers = $response.Headers; Content = [string] $content } } catch { $status = 0 $errorResponse = $null if ($_.Exception.PSObject.Properties['Response']) { $errorResponse = $_.Exception.Response } if ($null -ne $errorResponse) { $status = [int] $errorResponse.StatusCode } $content = '' if ($null -ne $_.ErrorDetails -and $_.ErrorDetails.Message) { $content = $_.ErrorDetails.Message } elseif ($errorResponse -is [System.Net.WebResponse]) { try { $reader = New-Object System.IO.StreamReader($errorResponse.GetResponseStream()) $content = $reader.ReadToEnd() $reader.Dispose() } catch { } } return @{ Status = $status; Headers = @{}; Content = $content } } } function Header($Response, [string] $Name) { $value = $Response.Headers[$Name] if ($null -eq $value) { return '' } ($value | Select-Object -First 1) -as [string] } function Field($Response, [string] $Key) { if ($Response.Content -match "(?m)^$Key=(.*)$") { return $Matches[1].TrimEnd("`r") } '' } # Prompt mode: PSReadLine's key reader always waits for a key, so a Ctrl+C typed while a # remote command runs lands in PSReadLine's queue. It is looked for there, read only. $readLineType = 'Microsoft.PowerShell.PSConsoleReadLine' -as [type] $readLineSingleton = $null $readLineQueueField = $null $stoppedPipeline = $null # Uploads what a command typed at the prompt printed; keeps what could not be sent. function UploadLocal($local) { foreach ($stream in 'stdout', 'stderr') { $pending = $local.Pending[$stream] if ($pending.Length -eq 0) { continue } $bytes = [Text.Encoding]::UTF8.GetBytes($pending.ToString()) $position = 0 while ($position -lt $bytes.Length) { $length = [Math]::Min(60000, $bytes.Length - $position) $chunk = New-Object byte[] $length [Array]::Copy($bytes, $position, $chunk, 0, $length) $response = Send 'POST' "/commands/$($local.Id)/output?stream=$stream&offset=$($local.Sent[$stream])" $chunk if ($response.Status -eq 200) { $local.Sent[$stream] += $length $position += $length } elseif ($response.Status -eq 409 -and (Field $response 'expected_offset') -match '^\d+$') { $local.Sent[$stream] = [long] (Field $response 'expected_offset') } else { break } } $rest = $(if ($position -lt $bytes.Length) { [Text.Encoding]::UTF8.GetString($bytes, $position, $bytes.Length - $position) } else { '' }) [void] $pending.Clear() [void] $pending.Append($rest) } } $lastContact = [DateTime]::UtcNow $lastCancelCheck = [DateTime]::UtcNow $lastLocalUpload = [DateTime]::UtcNow $localRetryAt = [DateTime]::UtcNow $nextPoll = [DateTime]::UtcNow while (-not $shared.Done) { $pipeline = $shared.Pipeline if ($shared.PromptMode -and $null -ne $pipeline -and $null -ne $readLineType -and -not [object]::ReferenceEquals($pipeline, $stoppedPipeline)) { try { if ($null -eq $readLineQueueField) { $readLineSingleton = $readLineType.GetField('_singleton', [Reflection.BindingFlags] 'NonPublic, Static').GetValue($null) $readLineQueueField = $readLineType.GetField('_queuedKeys', [Reflection.BindingFlags] 'NonPublic, Instance') } foreach ($queuedKey in @($readLineQueueField.GetValue($readLineSingleton).ToArray())) { if ([string] $queuedKey -eq 'Ctrl+c') { $stoppedPipeline = $pipeline $shared.Interrupted = $true try { $pipeline.Stop() } catch { } break } } } catch { } } if ($shared.WatchKeys) { $isCtrlC = $false try { if ([Console]::KeyAvailable) { $key = [Console]::ReadKey($true) $isCtrlC = $key.Key -eq [ConsoleKey]::C -and ($key.Modifiers -band [ConsoleModifiers]::Control) } } catch { } if ($isCtrlC) { if ($null -ne $pipeline) { $shared.Interrupted = $true try { $pipeline.Stop() } catch { } } else { $shared.Quit = $true } } } $now = [DateTime]::UtcNow # A command typed at the prompt: record it, stream its output, report its result. $local = $shared.Local if ($null -ne $local) { try { $item = $null while ($shared.LocalQueue.TryDequeue([ref] $item)) { [void] $local.Pending[$item.Stream].Append($item.Text).Append("`n") } if ($null -eq $local.Id -and -not $local.Failed -and $now -ge $localRetryAt) { $lastContact = $now $response = Send 'POST' '/commands' @{ command = $local.Text; idempotency_key = $local.Key; cwd = $local.Cwd } if ($response.Status -eq 201) { $local.Id = Field $response 'command_id' } elseif ($response.Status -eq 410 -or $response.Status -eq 401) { $shared.EndReason = Field $response 'reason' $shared.Ended = $true $local.Failed = $true } elseif ($response.Status -eq 409 -or $response.Status -eq 422) { $local.Failed = $true } else { $localRetryAt = $now.AddSeconds(2) } } if ($local.Failed) { if ($local.Ended -and [object]::ReferenceEquals($shared.Local, $local)) { $shared.Local = $null } } elseif ($null -ne $local.Id -and ($local.Ended -or ($now - $lastLocalUpload).TotalMilliseconds -ge 300)) { $lastLocalUpload = $now $lastContact = $now UploadLocal $local if ($local.Ended -and $shared.LocalQueue.IsEmpty -and $local.Pending.stdout.Length -eq 0 -and $local.Pending.stderr.Length -eq 0) { $response = Send 'POST' "/commands/$($local.Id)/finish" @{ exit_code = $local.ExitCode; succeeded = [int] $local.Succeeded; interrupted = [int] $local.Interrupted; cwd = $local.CwdAfter } if ($response.Status -ne 0 -and [object]::ReferenceEquals($shared.Local, $local)) { $shared.Local = $null } } } } catch { } } if ($null -ne $pipeline) { if (($now - $lastCancelCheck).TotalMilliseconds -ge 1000) { $lastCancelCheck = $now $lastContact = $now $response = Send 'POST' "/commands/$($shared.CommandId)/output?stream=stdout&offset=0" ([byte[]] @()) if ((Field $response 'cancel') -eq '1') { $shared.RemoteCancel = $true try { $pipeline.Stop() } catch { } } } } elseif ($null -eq $shared.Pending -and $null -eq $shared.Local -and -not $shared.Busy -and -not $shared.Ended -and ($now - $shared.ReadyAt).TotalMilliseconds -lt 1000 -and $now -ge $nextPoll) { $lastContact = $now $response = Send 'POST' '/commands/next' $null $completionId = $(if ($response.Status -eq 200) { Header $response 'X-TempSession-Completion-Id' } else { '' }) if ($completionId) { # Tab in the web terminal: complete the line the way Tab in this console would, # in the shell's current location. This thread has its own runspace, so the # session's own functions and variables are not offered; paths, commands and # parameters are. $text = '' $query = '' try { $cursor = 0 [void] [int]::TryParse((Header $response 'X-TempSession-Completion-Cursor'), [ref] $cursor) if ($shared.Cwd) { Set-Location -LiteralPath $shared.Cwd -ErrorAction SilentlyContinue } $completion = TabExpansion2 -inputScript ([string] $response.Content) -cursorColumn $cursor $text = (@($completion.CompletionMatches) | Select-Object -First 200 | ForEach-Object { $_.CompletionText + "`t" + $_.ListItemText }) -join "`n" $query = "?start=$($completion.ReplacementIndex)&length=$($completion.ReplacementLength)" } catch { } $null = Send 'POST' "/completions/$completionId$query" ([Text.Encoding]::UTF8.GetBytes($text)) } elseif ($response.Status -eq 200) { $shared.Pending = @{ Id = (Header $response 'X-TempSession-Command-Id'); Author = (Header $response 'X-TempSession-Author'); Text = $response.Content } } elseif ($response.Status -eq 204) { $milliseconds = 1000 [void] [int]::TryParse((Header $response 'X-TempSession-Poll-Ms'), [ref] $milliseconds) $nextPoll = $now.AddMilliseconds($milliseconds) } elseif ($response.Status -eq 410 -or $response.Status -eq 401) { $shared.EndReason = Field $response 'reason' $shared.Ended = $true } else { $nextPoll = $now.AddSeconds(2) } } elseif (-not $shared.Ended -and ($now - $lastContact).TotalSeconds -ge 10) { $lastContact = $now $response = Send 'GET' '/session' $null if ($response.Status -eq 410 -or $response.Status -eq 401) { $shared.EndReason = Field $response 'reason' $shared.Ended = $true } } Start-Sleep -Milliseconds 50 } }).AddArgument($__tsShared) $__tsHelperHandle = $null # Ctrl+C as a key (watched by the helper thread) while this window is busy. $__tsTreatControlC = $null $__tsHasConsole = $false try { if (-not [Console]::IsInputRedirected) { $__tsTreatControlC = [Console]::TreatControlCAsInput [Console]::TreatControlCAsInput = $true $__tsHasConsole = $true $__tsShared.WatchKeys = $true } } catch { } $__tsHandedOver = $false try { $__tsShared.Cwd = __tsCwd $__tsResponse = __tsRequest 'POST' '/sessions' @{ shell = 'powershell' shell_version = $PSVersionTable.PSVersion.ToString() os = $(if ($PSVersionTable['OS']) { $PSVersionTable['OS'] } else { [Environment]::OSVersion.VersionString }) hostname = [Environment]::MachineName local_user = [Environment]::UserName cwd = $__tsShared.Cwd features = 'complete' client_version = $__tsVersion output_encoding = 'UTF-8' } if ($__tsResponse.Status -ne 201) { __tsSay "Could not register this session (HTTP $($__tsResponse.Status)). Is $__tsBase reachable?" 'Red' } else { $__tsRegistered = $true $__tsShared.Headers = @{ Authorization = 'Bearer ' + $__tsResponse.Fields['agent_token'] } $__tsHelperHandle = $__tsHelper.BeginInvoke() Write-Host '' __tsSay 'Approve this session in your browser:' Write-Host '' Write-Host " $($__tsResponse.Fields['pairing_url'])" Write-Host '' __tsSay "Code: $($__tsResponse.Fields['pairing_code']) (the browser must show the same code)" __tsSay 'Waiting for approval. Press Ctrl+C to cancel.' # Pairing: wait until the session is approved in the browser. while (-not $__tsActive) { if (__tsWait 1500) { break } $__tsResponse = __tsRequest 'GET' '/session' if ($__tsResponse.Status -eq 410 -or $__tsResponse.Status -eq 401) { $__tsShared.EndReason = $__tsResponse.Fields['reason'] $__tsShared.Ended = $true break } if ($__tsResponse.Status -eq 200 -and $__tsResponse.Fields['status'] -eq 'active') { $__tsActive = $true Write-Host '' __tsSay "Approved by $($__tsResponse.Fields['approved_by']), workspace: $($__tsResponse.Fields['workspace'])." 'Yellow' } } } if ($__tsActive) { # Windows only: elsewhere .NET reads the cursor position from the terminal's input, which # PSReadLine's key reader takes away, so event processing at the prompt stalls after output. $__tsOnWindows = $PSVersionTable['PSEdition'] -ne 'Core' -or (Get-Variable -Name IsWindows -ValueOnly -ErrorAction SilentlyContinue) $__tsPromptMode = $__tsOnWindows -and $__tsHasConsole -and $Host.Name -eq 'ConsoleHost' -and $null -ne (Get-Module PSReadLine) -and $null -ne ('Microsoft.PowerShell.PSConsoleReadLine' -as [type]) if ($__tsPromptMode) { # Hand the window back: PSReadLine owns the keys again. $__tsShared.WatchKeys = $false $__tsShared.PromptMode = $true try { [Console]::TreatControlCAsInput = $__tsTreatControlC } catch { } $__tsTreatControlC = $null __tsStartPromptMode $__tsHandedOver = $true __tsSay 'This session is now shared. Keep working here: remote commands run whenever the prompt is empty.' 'Green' __tsSay 'Ctrl+C on an empty prompt stops sharing.' 'Green' } else { __tsSay 'This session is now shared. Remote commands run here.' 'Green' __tsSay 'Ctrl+C stops a running command; Ctrl+C while none runs stops sharing.' 'Green' while (-not ($__tsShared.Quit -or $__tsShared.Ended)) { $__tsShared.ReadyAt = [DateTime]::UtcNow if ($null -ne $__tsShared.Pending) { . __tsRunPending } else { Start-Sleep -Milliseconds 50 } } } } } finally { # Unless the prompt took over, every way out ends here: stop sharing and clean up. if (-not $__tsHandedOver) { . __tsStop } }