# Owner-owned Windows connect helper (PowerShell 5.1, normal user). # Fixed production gateway: https://k.shinick.dev # -LocalTest allows only http://127.0.0.1:8799 or http://localhost:8799. # Request secrets stay in memory and POST bodies. Remote mode additionally puts # an ephemeral encryption key in the owner invitation URL fragment (never HTTP). # Child gh/codex/claude processes drop inherited API-key variables for that # child only. Values are restored in finally via EnvironmentVariableTarget # Process. User and Machine environment scopes are never written. # An inherited API key would otherwise select API billing over the official # user credential store. Existing logins are not logged out or overwritten. # Official status commands use exit 0 when credentials are present, exit 1 # when authentication is needed. Their output is never sent to the server. # Exit codes: 0 ready or check-only inventory, 2 bad arguments, 3 tool mismatch, # 4 cancelled, 5 expired or approval timeout, 6 tool not ready, 7 request error. [CmdletBinding()] param( [string[]]$Tools, [string]$DeviceName, [switch]$CheckOnly, [switch]$Remote, [switch]$LocalTest, [string]$Gateway, [switch]$NoBrowser, [switch]$NoTerminal ) $script:ConnectProductionOrigin = 'https://k.shinick.dev' $script:ConnectLocalOrigins = @('http://127.0.0.1:8799', 'http://localhost:8799') $script:ConnectAllowedTools = @('github', 'codex', 'claude') function Write-ConnectLine { param([string]$Message) if ($null -eq $Message) { $Message = '' } if ($script:ConnectSecret -and $Message.Contains($script:ConnectSecret)) { $Message = $Message.Replace($script:ConnectSecret, '[redacted]') } if ($script:ConnectWriteOverride) { & $script:ConnectWriteOverride $Message return } Write-Host $Message } function ConvertTo-ConnectJson { param($Value) if ($null -eq $Value) { return 'null' } if ($Value -is [bool]) { if ($Value) { return 'true' } return 'false' } if ($Value -is [byte] -or $Value -is [int16] -or $Value -is [int32] -or $Value -is [int64]) { return ([string][int64]$Value) } if ($Value -is [string]) { $escaped = $Value.Replace('\', '\\').Replace('"', '\"').Replace("`r", '\r').Replace("`n", '\n') return '"' + $escaped + '"' } if ($Value -is [System.Collections.IDictionary]) { $props = New-Object System.Collections.Generic.List[string] foreach ($key in @($Value.Keys)) { $props.Add((ConvertTo-ConnectJson ([string]$key)) + ':' + (ConvertTo-ConnectJson $Value[$key])) } return '{' + ($props -join ',') + '}' } if ($Value -is [System.Collections.IEnumerable]) { $items = New-Object System.Collections.Generic.List[string] foreach ($item in $Value) { $items.Add((ConvertTo-ConnectJson $item)) } return '[' + ($items -join ',') + ']' } return (ConvertTo-ConnectJson ([string]$Value)) } function Get-ConnectField { param($Object, [string]$Name) if ($null -eq $Object) { return $null } if ($Object -is [System.Collections.IDictionary]) { return $Object[$Name] } $prop = $Object.PSObject.Properties[$Name] if ($prop) { return $prop.Value } return $null } function ConvertTo-ConnectToolSelection { param([string[]]$Tools) $ids = New-Object System.Collections.Generic.List[string] foreach ($entry in @($Tools)) { if ($null -eq $entry) { continue } $parts = ([string]$entry).Split(',') foreach ($part in $parts) { $token = $part.Trim().ToLowerInvariant() if ($token.Length -eq 0) { continue } $ids.Add($token) } } if ($ids.Count -lt 1) { return @{ Ok = $false; Error = 'Select at least one tool: github, codex, claude.' } } if ($ids.Count -gt 3) { return @{ Ok = $false; Error = 'Select at most three tools.' } } $seen = @{} foreach ($id in $ids) { if ($script:ConnectAllowedTools -notcontains $id) { $shown = $id if ($shown.Length -gt 40) { $shown = $shown.Substring(0, 40) } return @{ Ok = $false; Error = "Unknown tool: $shown" } } if ($seen.ContainsKey($id)) { return @{ Ok = $false; Error = "Duplicate tool selection: $id" } } $seen[$id] = $true } return @{ Ok = $true; Ids = @($ids.ToArray()) } } function Resolve-ConnectGateway { param([string]$Gateway, [switch]$LocalTest) $value = $Gateway if ([string]::IsNullOrWhiteSpace($value)) { if ($LocalTest) { $value = 'http://127.0.0.1:8799' } else { $value = $script:ConnectProductionOrigin } } $value = $value.Trim().TrimEnd('/') if ($LocalTest) { if ($script:ConnectLocalOrigins -notcontains $value) { return @{ Ok = $false; Error = 'Local test gateway must be http://127.0.0.1:8799 or http://localhost:8799.' } } } elseif ($value -ne $script:ConnectProductionOrigin) { return @{ Ok = $false; Error = 'Gateway must be https://k.shinick.dev unless -LocalTest is set.' } } return @{ Ok = $true; Origin = $value } } function Get-ConnectToolSpec { param([string]$Tool) switch ($Tool) { 'github' { return @{ Command = 'gh' StatusArgs = @('auth', 'status', '--hostname', 'github.com') LoginArgs = @('auth', 'login', '--hostname', 'github.com', '--git-protocol', 'https', '--web') ClearEnv = @('GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN') Install = 'GitHub CLI is not installed. Official install: https://cli.github.com/' StatusMode = 'gh-exit' } } 'codex' { return @{ Command = 'codex' StatusArgs = @('login', 'status') LoginArgs = @('login', '--device-auth') ClearEnv = @('OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_ACCESS_TOKEN') Install = 'Codex CLI is not installed. Official install: https://github.com/openai/codex' StatusMode = 'official-exit' } } 'claude' { return @{ Command = 'claude' StatusArgs = @('auth', 'status', '--json') LoginArgs = @('auth', 'login') ClearEnv = @('ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN') Install = 'Claude Code is not installed. Official install: https://code.claude.com/docs/en/setup' StatusMode = 'official-exit' } } } return $null } function Format-ConnectArguments { param([string[]]$ArgumentList) $parts = New-Object System.Collections.Generic.List[string] foreach ($arg in @($ArgumentList)) { if ($null -eq $arg) { continue } $text = [string]$arg if ($text -match '[\s"]') { $parts.Add('"' + $text.Replace('"', '\"') + '"') } else { $parts.Add($text) } } return ($parts -join ' ') } function Find-ConnectCommand { param([string]$Name) if ($script:ConnectCommandOverride) { return (& $script:ConnectCommandOverride $Name) } $cmd = Get-Command -Name $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($cmd) { return [string]$cmd.Source } return $null } function Invoke-ConnectProcess { param( [string]$FilePath, [string[]]$ArgumentList, [string[]]$ClearEnv, [switch]$Stream ) $saved = @{} foreach ($name in @($ClearEnv)) { if ([string]::IsNullOrWhiteSpace($name)) { continue } $saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') [Environment]::SetEnvironmentVariable($name, $null, 'Process') } try { if ($script:ConnectRunOverride) { $ran = & $script:ConnectRunOverride $FilePath (@($ArgumentList)) $code = 1 if ($null -ne $ran -and $null -ne (Get-ConnectField $ran 'ExitCode')) { $code = [int](Get-ConnectField $ran 'ExitCode') } return @{ ExitCode = $code; Output = [string](Get-ConnectField $ran 'Output') } } $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $FilePath $psi.Arguments = (Format-ConnectArguments -ArgumentList $ArgumentList) if ([IO.Path]::GetExtension($FilePath) -in @('.cmd', '.bat')) { # Windows CreateProcess cannot launch a batch shim directly. # Only the resolved local tool and its fixed argument list enter it. if ($FilePath.Contains('"')) { throw 'Invalid local tool path.' } $psi.FileName = Join-Path $env:SystemRoot 'System32\cmd.exe' $psi.Arguments = '/d /s /c ""' + $FilePath + '" ' + (Format-ConnectArguments -ArgumentList $ArgumentList) + '"' } $psi.UseShellExecute = $false $psi.CreateNoWindow = (-not $Stream) $psi.RedirectStandardOutput = (-not $Stream) $psi.RedirectStandardError = (-not $Stream) $process = New-Object System.Diagnostics.Process $process.StartInfo = $psi [void]$process.Start() if (-not $Stream) { $stdoutTask = $process.StandardOutput.ReadToEndAsync() $stderrTask = $process.StandardError.ReadToEndAsync() $process.WaitForExit() $statusStdout = [string]$stdoutTask.Result $statusOutput = $statusStdout + [string]$stderrTask.Result if ($statusOutput.Length -gt 65536) { $statusOutput = ''; $statusStdout = '' } } else { $process.WaitForExit() } return @{ ExitCode = [int]$process.ExitCode; Output = [string]$statusOutput; Stdout = [string]$statusStdout } } finally { foreach ($name in @($saved.Keys)) { [Environment]::SetEnvironmentVariable($name, $saved[$name], 'Process') } } } function Get-ConnectObservation { param([string]$Tool) $spec = Get-ConnectToolSpec -Tool $Tool $path = Find-ConnectCommand -Name $spec.Command if ([string]::IsNullOrWhiteSpace($path)) { return @{ Kind = 'missing'; ExitCode = $null; Spec = $spec } } $ran = Invoke-ConnectProcess -FilePath $path -ArgumentList @($spec.StatusArgs) -ClearEnv @($spec.ClearEnv) if ($spec.StatusMode -in @('gh-exit', 'official-exit')) { if ($ran.ExitCode -eq 0) { # Only inspect local status metadata. Never publish this output. # Existing API/third-party modes are preserved and never relabeled # as a subscription login or silently replaced by another account. $subscription = $true if ($Tool -eq 'codex') { $subscription = [string]$ran.Output -match '(?i)logged in using ChatGPT' } if ($Tool -eq 'claude') { $subscription = $false try { $json = [string](Get-ConnectField $ran 'Stdout') if ([string]::IsNullOrWhiteSpace($json)) { $json = [string]$ran.Output } $auth = $json | ConvertFrom-Json -ErrorAction Stop $subscription = ($auth.loggedIn -eq $true -and $auth.authMethod -in @('claude.ai', 'oauth_token')) } catch { } } if ($subscription) { return @{ Kind = 'ready'; ExitCode = 0; Spec = $spec; CommandPath = $path } } Write-ConnectLine ($Tool + ': Existing authentication mode was preserved. Verify subscription authentication in the official CLI; no account settings were replaced.') return @{ Kind = 'check-failed'; ExitCode = 0; Spec = $spec; CommandPath = $path } } if ($ran.ExitCode -eq 1) { return @{ Kind = 'login-required'; ExitCode = 1; Spec = $spec; CommandPath = $path } } } return @{ Kind = 'check-failed'; ExitCode = $ran.ExitCode; Spec = $spec; CommandPath = $path } } function Get-ConnectNowMs { if ($script:ConnectNowOverride) { return [int64](& $script:ConnectNowOverride) } $epoch = New-Object DateTimeOffset (1970, 1, 1, 0, 0, 0, [TimeSpan]::Zero) return [int64](([DateTimeOffset]::UtcNow - $epoch).TotalMilliseconds) } function Start-ConnectWait { param([int]$Seconds) if ($script:ConnectSleepOverride) { & $script:ConnectSleepOverride $Seconds return } if ($Seconds -gt 0) { Start-Sleep -Seconds $Seconds } } function Invoke-ConnectHttp { param([string]$Path, $Body) if ($script:ConnectHttpOverride) { return (& $script:ConnectHttpOverride $Path $Body) } if ($Path -notmatch '^/api/connect/(create|[A-Za-z0-9_-]{22}/(poll|progress|cancel|relay-publish|relay-pull|relay-clear))$') { throw 'Connect request failed.' } if ([string]::IsNullOrWhiteSpace([string]$script:ConnectOrigin)) { throw 'Connect request failed.' } $json = ConvertTo-ConnectJson $Body try { $bytes = [System.Text.Encoding]::UTF8.GetBytes($json) return Invoke-RestMethod -Method Post -Uri ($script:ConnectOrigin + $Path) -Body $bytes -ContentType 'application/json; charset=utf-8' -TimeoutSec 30 -MaximumRedirection 0 -ErrorAction Stop } catch { throw 'Connect request failed.' } } function ConvertTo-ConnectToolArray { param($Value) $items = New-Object System.Collections.Generic.List[string] if ($null -eq $Value) { return @() } foreach ($item in $Value) { if ($null -eq $item) { continue } $items.Add([string]$item) } return @($items.ToArray()) } function Test-SameToolSet { param($Left, $Right) $a = @(ConvertTo-ConnectToolArray $Left) $b = @(ConvertTo-ConnectToolArray $Right) if ($a.Count -ne $b.Count) { return $false } $sa = @($a | Sort-Object) $sb = @($b | Sort-Object) for ($i = 0; $i -lt $sa.Count; $i++) { if ([string]$sa[$i] -cne [string]$sb[$i]) { return $false } } return $true } function New-ConnectResult { param([string]$Tool, [string]$State, [string]$Detail) $row = New-Object System.Collections.Specialized.OrderedDictionary $row['tool'] = $Tool $row['state'] = $State $row['detail'] = $Detail return $row } function Read-ConnectStatus { param($Response) $status = [string](Get-ConnectField $Response 'status') if ($null -eq $status) { $status = '' } return @{ Status = $status.Trim().ToLowerInvariant() Tools = @(ConvertTo-ConnectToolArray (Get-ConnectField $Response 'tools')) Code = [string](Get-ConnectField $Response 'code') ExpiresAt = (Get-ConnectField $Response 'expiresAt') } } function Invoke-ConnectPoll { param([string]$Id, [string]$Secret) $body = New-Object System.Collections.Specialized.OrderedDictionary $body['secret'] = $Secret $response = Invoke-ConnectHttp -Path ("/api/connect/$Id/poll") -Body $body return (Read-ConnectStatus $response) } function Send-ConnectProgress { param([string]$Id, [string]$Secret, $Rows) $script:ConnectProgressSeq = [int]$script:ConnectProgressSeq + 1 $seq = [int]$script:ConnectProgressSeq $list = New-Object System.Collections.Generic.List[object] foreach ($row in $Rows) { $list.Add($row) } $body = New-Object System.Collections.Specialized.OrderedDictionary $body['secret'] = $Secret $body['seq'] = $seq $body['results'] = $list $response = Invoke-ConnectHttp -Path ("/api/connect/$Id/progress") -Body $body $ok = Get-ConnectField $response 'ok' $got = Get-ConnectField $response 'seq' $okTrue = ($ok -eq $true -or [string]$ok -eq 'true') $seqOk = ($null -ne $got -and ([int64]$got -eq [int64]$seq)) if (-not $okTrue -or -not $seqOk) { return $false } return $true } function Invoke-ConnectCancel { param([string]$Id, [string]$Secret) $body = New-Object System.Collections.Specialized.OrderedDictionary $body['secret'] = $Secret [void](Invoke-ConnectHttp -Path ("/api/connect/$Id/cancel") -Body $body) } function Wait-ConnectApproval { param( [string]$Id, [string]$Secret, [string]$ExpectedCode, [int]$PollTimeoutSec, [int]$PollIntervalSec ) $start = Get-ConnectNowMs $deadline = $start + ([int64]$PollTimeoutSec * 1000) $guard = 0 $interval = $PollIntervalSec if ($interval -lt 1) { $interval = 1 } $maxGuard = [int]($PollTimeoutSec / $interval) + 3 if ($maxGuard -lt 3) { $maxGuard = 3 } while ($guard -lt $maxGuard) { $guard++ $snap = Invoke-ConnectPoll -Id $Id -Secret $Secret if ($snap.Code -cne $ExpectedCode) { return @{ Outcome = 'error'; Error = 'Approval code did not match.'; ExitCode = 7 } } if ($snap.Status -eq 'approved') { return @{ Outcome = 'approved'; Tools = @($snap.Tools) } } if ($snap.Status -eq 'cancelled') { return @{ Outcome = 'cancelled'; ExitCode = 4 } } if ($snap.Status -eq 'expired') { return @{ Outcome = 'expired'; ExitCode = 5 } } if ($snap.Status -eq 'completed') { return @{ Outcome = 'completed'; ExitCode = 7 } } $pending = @('pending', 'created', 'awaiting', 'awaiting-approval', 'open', 'approval-required') if ($pending -notcontains $snap.Status) { return @{ Outcome = 'error'; Error = 'Connect status was not recognized.'; ExitCode = 7 } } $now = Get-ConnectNowMs $expiredAt = $false if ($null -ne $snap.ExpiresAt -and [string]$snap.ExpiresAt -match '^\d+$') { if ($now -ge [int64]$snap.ExpiresAt) { $expiredAt = $true } } if ($now -ge $deadline -or $expiredAt) { return @{ Outcome = 'expired'; ExitCode = 5 } } Start-ConnectWait -Seconds $PollIntervalSec } return @{ Outcome = 'expired'; ExitCode = 5 } } function Confirm-ConnectSession { param([string]$Id, [string]$Secret, [string[]]$ExpectedTools) $snap = Invoke-ConnectPoll -Id $Id -Secret $Secret if ($snap.Status -eq 'cancelled') { return @{ Ok = $false; Terminal = $true; ExitCode = 4; Error = 'Connect request was cancelled.' } } if ($snap.Status -eq 'expired') { return @{ Ok = $false; Terminal = $true; ExitCode = 5; Error = 'Connect request expired.' } } if ($snap.Status -eq 'completed') { return @{ Ok = $false; Terminal = $true; ExitCode = 7; Error = 'Connect request is already completed.' } } if ($snap.Status -ne 'approved') { return @{ Ok = $false; Terminal = $false; ExitCode = 7; Error = 'Connect request is not approved.' } } if ($null -eq $snap.ExpiresAt -or [string]$snap.ExpiresAt -notmatch '^\d+$' -or (Get-ConnectNowMs) -ge [int64]$snap.ExpiresAt) { return @{ Ok = $false; Terminal = $true; ExitCode = 5; Error = 'Connect request expired.' } } if (-not (Test-SameToolSet -Left $snap.Tools -Right $ExpectedTools)) { return @{ Ok = $false; Terminal = $false; ExitCode = 3; Error = 'Server tool list does not match the local selection.' } } return @{ Ok = $true; Terminal = $false } } function Start-ConnectTerminal { param([string[]]$Tools) $saved = @{} foreach ($tool in $Tools) { $spec = Get-ConnectToolSpec -Tool $tool foreach ($name in $spec.ClearEnv) { if (-not $saved.ContainsKey($name)) { $saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') [Environment]::SetEnvironmentVariable($name, $null, 'Process') } } } try { if ($script:ConnectTerminalOverride) { & $script:ConnectTerminalOverride $Tools; return } $shell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' $clearNames = (@($saved.Keys | ForEach-Object { "'" + $_ + "'" }) -join ',') $command = 'foreach($name in @(' + $clearNames + ')){[Environment]::SetEnvironmentVariable($name,$null,''Process'')}; Set-Location -LiteralPath $env:USERPROFILE; Write-Host "Connected CLI terminal. API environment overrides are excluded for the selected tools."' $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) Start-Process -FilePath $shell -ArgumentList @('-NoLogo', '-NoProfile', '-NoExit', '-EncodedCommand', $encoded) | Out-Null } finally { foreach ($name in $saved.Keys) { [Environment]::SetEnvironmentVariable($name, $saved[$name], 'Process') } } } function ConvertTo-Relay64 { param([byte[]]$Bytes) return [Convert]::ToBase64String($Bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_') } function ConvertFrom-Relay64 { param([string]$Value) if ($Value -notmatch '^[A-Za-z0-9_-]+$' -or $Value.Length % 4 -eq 1) { throw 'Invalid remote envelope.' } return ,([Convert]::FromBase64String($Value.Replace('-', '+').Replace('_', '/') + ('=' * ((4 - $Value.Length % 4) % 4)))) } function New-RelayRandom { param([int]$Size = 32) $bytes = New-Object byte[] $Size $rng = [Security.Cryptography.RandomNumberGenerator]::Create() try { $rng.GetBytes($bytes) } finally { $rng.Dispose() } return (ConvertTo-Relay64 $bytes) } function Get-RelayKey { param([string]$Key, [string]$Purpose) if ($Key -notmatch '^[A-Za-z0-9_-]{43}$' -or $Purpose -notin @('enc', 'mac')) { throw 'Invalid remote key.' } $sha = [Security.Cryptography.SHA256]::Create() try { return ,($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes('connect-remote-v1|' + $Purpose + '|' + $Key))) } finally { $sha.Dispose() } } function Get-RelayMac { param([string]$Key, [string]$Id, [string]$Nonce, [string]$Direction, [string]$IV, [string]$Ciphertext) $hmac = [Security.Cryptography.HMACSHA256]::new([byte[]](Get-RelayKey $Key 'mac')) try { return (ConvertTo-Relay64 ($hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes(('connect-remote-v1', $Id, $Nonce, $Direction, $IV, $Ciphertext) -join '|')))) } finally { $hmac.Dispose() } } function Protect-RelayValue { param([string]$Key, [string]$Id, [string]$Nonce, [string]$Direction, $Value) $aes = [Security.Cryptography.Aes]::Create() try { $aes.Key = [byte[]](Get-RelayKey $Key 'enc'); $aes.GenerateIV() $aes.Mode = [Security.Cryptography.CipherMode]::CBC; $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7 $plain = [Text.Encoding]::UTF8.GetBytes((ConvertTo-ConnectJson $Value)) $transform = $aes.CreateEncryptor() try { $ct = ConvertTo-Relay64 ($transform.TransformFinalBlock($plain, 0, $plain.Length)) } finally { $transform.Dispose() } $iv = ConvertTo-Relay64 $aes.IV return @{iv = $iv; ct = $ct; mac = (Get-RelayMac $Key $Id $Nonce $Direction $iv $ct)} } finally { $aes.Dispose() } } function Unprotect-RelayValue { param([string]$Key, [string]$Id, [string]$Nonce, [string]$Direction, $Box) $iv = [string](Get-ConnectField $Box 'iv'); $ct = [string](Get-ConnectField $Box 'ct'); $mac = [string](Get-ConnectField $Box 'mac') if ($iv -notmatch '^[A-Za-z0-9_-]{22}$' -or $ct -notmatch '^[A-Za-z0-9_-]{22,8192}$' -or $mac -notmatch '^[A-Za-z0-9_-]{43}$') { throw 'Invalid remote envelope.' } $want = Get-RelayMac $Key $Id $Nonce $Direction $iv $ct $diff = 0 for ($i = 0; $i -lt 43; $i++) { $diff = $diff -bor ([int][char]$want[$i] -bxor [int][char]$mac[$i]) } if ($diff -ne 0) { throw 'Remote envelope authentication failed.' } $aes = [Security.Cryptography.Aes]::Create() try { $aes.Key = [byte[]](Get-RelayKey $Key 'enc'); $aes.IV = ConvertFrom-Relay64 $iv $aes.Mode = [Security.Cryptography.CipherMode]::CBC; $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7 $bytes = ConvertFrom-Relay64 $ct $transform = $aes.CreateDecryptor() try { $plain = $transform.TransformFinalBlock($bytes, 0, $bytes.Length) } finally { $transform.Dispose() } return ([Text.Encoding]::UTF8.GetString($plain) | ConvertFrom-Json -ErrorAction Stop) } finally { $aes.Dispose() } } function Find-RelayChallenge { param([string]$Tool, [string]$Output) # Parse only documented login artifacts, never status dumps or credentials. $clean = [regex]::Replace($Output, '\x1B\[[0-?]*[ -/]*[@-~]', '') $clean = [regex]::Replace($clean, '\x1B\][^\x07]*(?:\x07|\x1B\\)', '') if ($Tool -eq 'github') { $m = [regex]::Match($clean, '\b[A-Z0-9]{4}-[A-Z0-9]{4}\b') if ($m.Success -and $clean.Contains('https://github.com/login/device')) { return @{tool = $Tool; kind = 'device'; url = 'https://github.com/login/device'; code = $m.Value} } } if ($Tool -eq 'codex') { $m = [regex]::Match($clean, '(?m)^\s*([A-Z0-9]{4}-[A-Z0-9]{4,8})\s*$') if ($m.Success -and $clean.Contains('https://auth.openai.com/codex/device')) { return @{tool = $Tool; kind = 'device'; url = 'https://auth.openai.com/codex/device'; code = $m.Groups[1].Value} } } if ($Tool -eq 'claude') { foreach ($m in [regex]::Matches($clean, 'https://[^\s<>"'']+')) { $uri = $null if (-not [Uri]::TryCreate($m.Value, [UriKind]::Absolute, [ref]$uri)) { continue } if ($uri.Scheme -ne 'https' -or $uri.Host -cne 'claude.ai' -or $uri.Port -ne 443 -or $uri.UserInfo -or $uri.Fragment -or $uri.AbsolutePath -cne '/oauth/authorize') { continue } $cbMatch = [regex]::Match($uri.Query, '(?:^\?|&)redirect_uri=([^&]+)') if (-not $cbMatch.Success) { continue } $cb = $null if (-not [Uri]::TryCreate([Uri]::UnescapeDataString($cbMatch.Groups[1].Value), [UriKind]::Absolute, [ref]$cb)) { continue } $local = $cb.Scheme -eq 'http' -and $cb.Host -in @('localhost', '127.0.0.1') -and $cb.AbsolutePath -ceq '/callback' $oob = $cb.Scheme -eq 'https' -and $cb.Host -in @('platform.claude.com', 'console.anthropic.com') -and $cb.Port -eq 443 -and $cb.AbsolutePath -ceq '/oauth/code/callback' if (($local -or $oob) -and -not $cb.UserInfo -and -not $cb.Fragment) { return @{tool = $Tool; kind = 'oauth'; url = $uri.AbsoluteUri; code = ''} } } } return $null } function Invoke-RemoteConnectLogin { param([string]$Tool, $Observation, [string]$Id, [string]$Secret, [string[]]$ExpectedTools, [string]$Key, [int]$TimeoutSec = 600) $spec = $Observation.Spec $psi = New-Object Diagnostics.ProcessStartInfo $psi.FileName = $Observation.CommandPath $loginArgs = @($spec.LoginArgs) if ($Tool -eq 'claude') { $loginArgs = @('auth', 'login', '--claudeai') } $psi.Arguments = Format-ConnectArguments $loginArgs if ([IO.Path]::GetExtension($psi.FileName) -in @('.cmd', '.bat')) { if ($psi.FileName.Contains('"')) { throw 'Invalid local tool path.' } $psi.Arguments = '/d /s /c ""' + $psi.FileName + '" ' + (Format-ConnectArguments $loginArgs) + '"' $psi.FileName = Join-Path $env:SystemRoot 'System32\cmd.exe' } $psi.UseShellExecute = $false; $psi.CreateNoWindow = $true $psi.RedirectStandardOutput = $true; $psi.RedirectStandardError = $true; $psi.RedirectStandardInput = $true foreach ($name in $spec.ClearEnv) { [void]$psi.EnvironmentVariables.Remove($name) } # Suppress color without altering User/Machine environment or browser settings. $psi.EnvironmentVariables['NO_COLOR'] = '1'; $psi.EnvironmentVariables['TERM'] = 'dumb' $process = New-Object Diagnostics.Process $process.StartInfo = $psi $nonce = New-RelayRandom 16 $started = $false; $published = $false; $sentAnswer = $false $text = ''; $nextCheck = 0L $deadline = (Get-ConnectNowMs) + [int64]$TimeoutSec * 1000 try { $gate = Confirm-ConnectSession $Id $Secret $ExpectedTools if (-not $gate.Ok) { return @{ExitCode = 1} } [void]$process.Start(); $started = $true $readers = @($process.StandardOutput, $process.StandardError) $buffers = @((New-Object char[] 1024), (New-Object char[] 1024)) $pending = @($readers[0].ReadAsync($buffers[0], 0, 1024), $readers[1].ReadAsync($buffers[1], 0, 1024)) while ($true) { for ($i = 0; $i -lt 2; $i++) { if ($null -ne $pending[$i] -and $pending[$i].IsCompleted) { $count = $pending[$i].GetAwaiter().GetResult() if ($count -eq 0) { $pending[$i] = $null } else { $text += [string]::new([char[]]$buffers[$i], 0, $count); $pending[$i] = $readers[$i].ReadAsync($buffers[$i], 0, 1024) } } } if ($text.Length -gt 65536) { throw 'Unsupported login output.' } if (-not $published) { $challenge = Find-RelayChallenge $Tool $text if ($challenge) { $script:ConnectRelaySeq++ $box = Protect-RelayValue $Key $Id $nonce 'challenge' $challenge [void](Invoke-ConnectHttp -Path "/api/connect/$Id/relay-publish" -Body @{secret = $Secret; seq = $script:ConnectRelaySeq; nonce = $nonce; tool = $Tool; box = $box}) $published = $true Write-ConnectLine ($Tool + ': Continue the official login on your approval device.') if ($Tool -eq 'github') { $process.StandardInput.WriteLine(''); $process.StandardInput.Flush() } } } $now = Get-ConnectNowMs if ($now -ge $deadline) { throw 'Remote login timed out.' } if ($now -ge $nextCheck) { $gate = Confirm-ConnectSession $Id $Secret $ExpectedTools if (-not $gate.Ok) { throw 'Remote connection ended.' } if ($published -and $Tool -eq 'claude' -and -not $sentAnswer) { $answer = Invoke-ConnectHttp -Path "/api/connect/$Id/relay-pull" -Body @{secret = $Secret; nonce = $nonce} $answerBox = Get-ConnectField $answer 'box' if ($answerBox) { $value = [string](Get-ConnectField (Unprotect-RelayValue $Key $Id $nonce 'answer' $answerBox) 'value') if ($value -notmatch '^[A-Za-z0-9._~#-]{16,2048}$') { throw 'Invalid login response.' } $process.StandardInput.WriteLine($value); $process.StandardInput.Flush() $value = $null; $sentAnswer = $true } } $nextCheck = $now + 2000 } if ($process.HasExited -and $null -eq $pending[0] -and $null -eq $pending[1]) { break } Start-Sleep -Milliseconds 50 } if (-not $published) { Write-ConnectLine ($Tool + ': Login output was not recognized. Use local mode or inspect this PC through your existing Tailscale/Sunshine connection.') } return @{ExitCode = [int]$process.ExitCode} } finally { if ($started -and -not $process.HasExited) { # Kill only the process tree this helper started, including .cmd shims. & (Join-Path $env:SystemRoot 'System32\taskkill.exe') /PID ([string]$process.Id) /T /F 2>&1 | Out-Null } if ($published) { try { [void](Invoke-ConnectHttp -Path "/api/connect/$Id/relay-clear" -Body @{secret = $Secret; nonce = $nonce}) } catch {} } $text = $null; $Key = $null; $process.Dispose() } } function Invoke-ConnectMain { param( [string[]]$Tools, [string]$DeviceName, [switch]$CheckOnly, [switch]$Remote, [switch]$LocalTest, [string]$Gateway, [switch]$NoBrowser, [switch]$NoTerminal, [int]$PollTimeoutSec = 600, [int]$PollIntervalSec = 2 ) $previousPreference = $ErrorActionPreference $ErrorActionPreference = 'Stop' $selection = ConvertTo-ConnectToolSelection -Tools $Tools if (-not $selection.Ok) { Write-ConnectLine $selection.Error return 2 } $toolIds = @(ConvertTo-ConnectToolArray $selection.Ids) if ($CheckOnly) { foreach ($toolId in $toolIds) { $obs = Get-ConnectObservation -Tool $toolId $state = 'failed' $detail = 'check-failed' if ($obs.Kind -eq 'missing') { $state = 'missing'; $detail = 'not-installed' } elseif ($obs.Kind -eq 'ready') { $state = 'ready'; $detail = 'already-authenticated' } elseif ($obs.Kind -eq 'login-required') { $state = 'login-required'; $detail = 'authentication-required' } Write-ConnectLine ("{0} {1} {2}" -f $toolId, $state, $detail) if ($detail -eq 'not-installed') { Write-ConnectLine $obs.Spec.Install } } return 0 } $name = [string]$DeviceName if ([string]::IsNullOrWhiteSpace($name)) { $name = [string][Environment]::MachineName } $name = $name.Trim() if ($name.Length -lt 1 -or $name.Length -gt 80 -or $name -match '[\x00-\x1F\x7F]') { Write-ConnectLine 'DeviceName must be 1..80 characters.' return 2 } $gatewayResolution = Resolve-ConnectGateway -Gateway $Gateway -LocalTest:$LocalTest if (-not $gatewayResolution.Ok) { Write-ConnectLine $gatewayResolution.Error return 2 } $script:ConnectOrigin = $gatewayResolution.Origin $script:ConnectSecret = $null $script:CancelArmed = $false $script:ConnectProgressSeq = 0 $script:ConnectRelaySeq = 0 $remoteKey = $null if ($Remote) { $remoteKey = New-RelayRandom } $exitCode = 0 $requestId = $null try { $createBody = New-Object System.Collections.Specialized.OrderedDictionary $createTools = New-Object System.Collections.Generic.List[object] foreach ($toolId in $toolIds) { $createTools.Add([string]$toolId) } $createBody['deviceName'] = $name $createBody['tools'] = $createTools $created = Invoke-ConnectHttp -Path '/api/connect/create' -Body $createBody $requestId = [string](Get-ConnectField $created 'id') $secret = [string](Get-ConnectField $created 'secret') $code = [string](Get-ConnectField $created 'code') $approveUrl = [string](Get-ConnectField $created 'approveUrl') if ($requestId -notmatch '^[A-Za-z0-9_-]{22}$' -or $secret -notmatch '^[A-Za-z0-9_-]{43}$' -or $code -notmatch '^\d{6}$') { Write-ConnectLine 'Connect create response was rejected.' $exitCode = 7 return $exitCode } $script:ConnectSecret = $secret $script:CancelArmed = $true $expectedUrl = $script:ConnectOrigin + '/connect/approve/' + $requestId Write-ConnectLine ("Approval code: {0}" -f $code) if ($approveUrl -ne $expectedUrl -or $approveUrl.Contains($secret)) { Write-ConnectLine 'Approval URL was rejected.' $exitCode = 7 return $exitCode } if ($Remote) { $approveUrl += '#key=' + $remoteKey } $statusUrl = $script:ConnectOrigin + '/connect#request=' + $requestId Write-ConnectLine ("Approve: {0}" -f $approveUrl) Write-ConnectLine ("Status: {0}" -f $statusUrl) $openUrl = $approveUrl if ($Remote) { $openUrl = $statusUrl + '&key=' + $remoteKey Write-ConnectLine ("QR: {0}" -f $openUrl) } if (-not $NoBrowser) { if ($script:ConnectOpenOverride) { & $script:ConnectOpenOverride $openUrl } else { Start-Process -FilePath $openUrl } } $wait = Wait-ConnectApproval -Id $requestId -Secret $secret -ExpectedCode $code -PollTimeoutSec $PollTimeoutSec -PollIntervalSec $PollIntervalSec if ($wait.Outcome -eq 'cancelled') { $script:CancelArmed = $false Write-ConnectLine 'Connect request was cancelled.' $exitCode = 4 return $exitCode } if ($wait.Outcome -eq 'expired') { Write-ConnectLine 'Connect request expired.' $exitCode = 5 return $exitCode } if ($wait.Outcome -eq 'completed') { $script:CancelArmed = $false Write-ConnectLine 'Connect request is already completed.' $exitCode = 7 return $exitCode } if ($wait.Outcome -ne 'approved') { Write-ConnectLine $(if ($wait.Error) { $wait.Error } else { 'Connect request failed.' }) $exitCode = 7 return $exitCode } if (-not (Test-SameToolSet -Left $wait.Tools -Right $toolIds)) { Write-ConnectLine 'Server tool list does not match the local selection.' $exitCode = 3 return $exitCode } $rows = New-Object System.Collections.Generic.List[object] $anyNotReady = $false foreach ($toolId in $toolIds) { $gate = Confirm-ConnectSession -Id $requestId -Secret $secret -ExpectedTools $toolIds if (-not $gate.Ok) { if ($gate.Terminal) { $script:CancelArmed = $false } Write-ConnectLine $gate.Error $exitCode = [int]$gate.ExitCode return $exitCode } $obs = Get-ConnectObservation -Tool $toolId if ($obs.Kind -eq 'missing') { $rows.Add((New-ConnectResult -Tool $toolId -State 'missing' -Detail 'not-installed')) if (-not (Send-ConnectProgress -Id $requestId -Secret $secret -Rows $rows)) { Write-ConnectLine 'Progress was rejected.' $exitCode = 7 return $exitCode } Write-ConnectLine $obs.Spec.Install $anyNotReady = $true continue } if ($obs.Kind -eq 'check-failed') { $rows.Add((New-ConnectResult -Tool $toolId -State 'failed' -Detail 'check-failed')) if (-not (Send-ConnectProgress -Id $requestId -Secret $secret -Rows $rows)) { Write-ConnectLine 'Progress was rejected.' $exitCode = 7 return $exitCode } Write-ConnectLine ("{0} status could not be verified." -f $toolId) $anyNotReady = $true continue } if ($obs.Kind -eq 'ready') { $rows.Add((New-ConnectResult -Tool $toolId -State 'ready' -Detail 'already-authenticated')) if (-not (Send-ConnectProgress -Id $requestId -Secret $secret -Rows $rows)) { Write-ConnectLine 'Progress was rejected.' $exitCode = 7 return $exitCode } Write-ConnectLine ("{0} ready already-authenticated" -f $toolId) continue } $rows.Add((New-ConnectResult -Tool $toolId -State 'login-required' -Detail 'authentication-required')) if (-not (Send-ConnectProgress -Id $requestId -Secret $secret -Rows $rows)) { Write-ConnectLine 'Progress was rejected.' $exitCode = 7 return $exitCode } $running = New-Object System.Collections.Generic.List[object] foreach ($existing in $rows) { if ([string]$existing['tool'] -eq $toolId) { $running.Add((New-ConnectResult -Tool $toolId -State 'running' -Detail 'login-started')) } else { $running.Add($existing) } } $rows = $running if (-not (Send-ConnectProgress -Id $requestId -Secret $secret -Rows $rows)) { Write-ConnectLine 'Progress was rejected.' $exitCode = 7 return $exitCode } $beforeLogin = Confirm-ConnectSession -Id $requestId -Secret $secret -ExpectedTools $toolIds if (-not $beforeLogin.Ok) { if ($beforeLogin.Terminal) { $script:CancelArmed = $false } Write-ConnectLine $beforeLogin.Error $exitCode = [int]$beforeLogin.ExitCode return $exitCode } if ($Remote) { $login = Invoke-RemoteConnectLogin -Tool $toolId -Observation $obs -Id $requestId -Secret $secret -ExpectedTools $toolIds -Key $remoteKey } else { $login = Invoke-ConnectProcess -FilePath $obs.CommandPath -ArgumentList @($obs.Spec.LoginArgs) -ClearEnv @($obs.Spec.ClearEnv) -Stream } Write-ConnectLine ("{0} login exited with code {1}" -f $toolId, $login.ExitCode) $afterLogin = Confirm-ConnectSession -Id $requestId -Secret $secret -ExpectedTools $toolIds if (-not $afterLogin.Ok) { if ($afterLogin.Terminal) { $script:CancelArmed = $false } Write-ConnectLine $afterLogin.Error $exitCode = [int]$afterLogin.ExitCode return $exitCode } $again = Get-ConnectObservation -Tool $toolId $authed = ($login.ExitCode -eq 0 -and $again.Kind -eq 'ready') $finalRows = New-Object System.Collections.Generic.List[object] foreach ($existing in $rows) { if ([string]$existing['tool'] -eq $toolId) { if ($authed) { $finalRows.Add((New-ConnectResult -Tool $toolId -State 'ready' -Detail 'authenticated')) } else { $finalRows.Add((New-ConnectResult -Tool $toolId -State 'failed' -Detail 'login-failed')) } } else { $finalRows.Add($existing) } } $rows = $finalRows if (-not (Send-ConnectProgress -Id $requestId -Secret $secret -Rows $rows)) { Write-ConnectLine 'Progress was rejected.' $exitCode = 7 return $exitCode } if (-not $authed) { $anyNotReady = $true continue } Write-ConnectLine ("{0} ready authenticated" -f $toolId) } $script:CancelArmed = $false if ($anyNotReady) { $exitCode = 6 } else { $exitCode = 0 } if ($exitCode -eq 0 -and -not $NoTerminal) { try { Start-ConnectTerminal -Tools $toolIds } catch { Write-ConnectLine 'Authentication is ready, but the development terminal could not be opened. Run the helper again or use a terminal without API overrides.' } } return $exitCode } catch { Write-ConnectLine 'Connect request failed.' $exitCode = 7 return $exitCode } finally { $ErrorActionPreference = $previousPreference if ($script:CancelArmed -and $requestId -and $script:ConnectSecret) { try { Invoke-ConnectCancel -Id $requestId -Secret $script:ConnectSecret } catch { Write-ConnectLine 'Cancellation attempt failed.' } } } } if ($MyInvocation.InvocationName -ne '.') { $code = Invoke-ConnectMain -Tools $Tools -DeviceName $DeviceName -CheckOnly:$CheckOnly -Remote:$Remote -LocalTest:$LocalTest -Gateway $Gateway -NoBrowser:$NoBrowser -NoTerminal:$NoTerminal exit $code }