# Outpost starter. Public and generic: it contains nothing private. # # On a new Windows machine, open Terminal (Admin) and type: # # irm https://o.jclay.dev | iex # # It installs Tailscale, joins your tailnet with a QR code you scan on your # phone, then asks your other machines (same Tailscale user only) for a setup # package and runs it. Everything machine-specific arrives over the tailnet. # # Written for Windows PowerShell 5.1. Keep this file ASCII-only. $global:Outpost = @{ StarterVersion = 1 Origin = 'https://o.jclay.dev' OfferPort = 47801 WorkDir = (Join-Path $env:LOCALAPPDATA 'Outpost\bootstrap') Log = $null Tailscale = (Join-Path $env:ProgramFiles 'Tailscale\tailscale.exe') Curl = (Join-Path $env:SystemRoot 'System32\curl.exe') Ui = $null Closed = $false Facts = @{} Offer = $null BaseUrl = $null Result = $null } # ---------------------------------------------------------------- logging function Write-OutpostLog { param([string]$Text) $line = '{0} {1}' -f (Get-Date -Format 'HH:mm:ss'), $Text Write-Host $line if ($global:Outpost.Log) { try { Add-Content -LiteralPath $global:Outpost.Log -Value $line -Encoding UTF8 } catch { } } } # ---------------------------------------------------------------- window function New-OutpostUi { Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing [System.Windows.Forms.Application]::EnableVisualStyles() $ui = @{ Blue = [System.Drawing.Color]::FromArgb(0, 90, 170) Green = [System.Drawing.Color]::FromArgb(0, 120, 60) Red = [System.Drawing.Color]::FromArgb(180, 30, 30) Amber = [System.Drawing.Color]::FromArgb(150, 95, 0) Gray = [System.Drawing.Color]::FromArgb(90, 90, 90) Tick = [string][char]0x2713 Cross = [string][char]0x2717 Current = $null } $form = New-Object System.Windows.Forms.Form $form.Text = 'Outpost setup' # Must fit the work area (taskbar excluded) of a 1280x720 logical desktop. $wa = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea $form.Size = New-Object System.Drawing.Size(([Math]::Min(1000, $wa.Width - 24)), ([Math]::Min(640, $wa.Height - 24))) $form.StartPosition = 'CenterScreen' $form.TopMost = $true $form.BackColor = [System.Drawing.Color]::White $form.Font = New-Object System.Drawing.Font('Segoe UI', 12) $form.Add_FormClosing({ $global:Outpost.Closed = $true }) $title = New-Object System.Windows.Forms.Label $title.Dock = 'Top' $title.Height = 64 $title.Padding = New-Object System.Windows.Forms.Padding(16, 14, 16, 0) $title.Font = New-Object System.Drawing.Font('Segoe UI', 20, [System.Drawing.FontStyle]::Bold) $title.Text = 'Setting up this machine' $bottom = New-Object System.Windows.Forms.Panel $bottom.Dock = 'Bottom' $bottom.Height = 150 $bottom.BackColor = [System.Drawing.Color]::FromArgb(240, 240, 240) $buttons = New-Object System.Windows.Forms.FlowLayoutPanel $buttons.Dock = 'Right' $buttons.Width = 290 $buttons.FlowDirection = 'TopDown' $buttons.WrapContents = $false $buttons.Padding = New-Object System.Windows.Forms.Padding(10, 10, 10, 4) $security = New-Object System.Windows.Forms.Button $security.Text = 'Open Windows Security' $security.Size = New-Object System.Drawing.Size(260, 56) $security.Font = New-Object System.Drawing.Font('Segoe UI', 12) $security.Visible = $false $security.Add_Click({ try { Start-Process 'windowsdefender://appbrowser/' } catch { } }) $close = New-Object System.Windows.Forms.Button $close.Text = 'Close' $close.Size = New-Object System.Drawing.Size(260, 56) $close.Font = New-Object System.Drawing.Font('Segoe UI', 12) $close.Enabled = $false $close.Add_Click({ $global:Outpost.Ui.Form.Close() }) $buttons.Controls.Add($security) $buttons.Controls.Add($close) $banner = New-Object System.Windows.Forms.Label $banner.Dock = 'Fill' $banner.Padding = New-Object System.Windows.Forms.Padding(16, 10, 10, 10) $banner.Font = New-Object System.Drawing.Font('Segoe UI', 13) $banner.TextAlign = 'MiddleLeft' $banner.ForeColor = $ui.Gray $banner.Text = 'Starting...' $bottom.Controls.Add($banner) $bottom.Controls.Add($buttons) $right = New-Object System.Windows.Forms.Panel $right.Dock = 'Right' $right.Width = 380 # The QR sits on top (hidden when there is none); the caption fills the rest. $qr = New-Object System.Windows.Forms.PictureBox $qr.Dock = 'Top' $qr.Height = 260 $qr.SizeMode = 'CenterImage' $qr.Visible = $false $caption = New-Object System.Windows.Forms.Label $caption.Dock = 'Fill' $caption.Padding = New-Object System.Windows.Forms.Padding(14, 8, 10, 0) $caption.Font = New-Object System.Drawing.Font('Segoe UI', 12) $caption.TextAlign = 'TopLeft' $caption.ForeColor = $ui.Gray $right.Controls.Add($caption) $right.Controls.Add($qr) $caption.BringToFront() $steps = New-Object System.Windows.Forms.FlowLayoutPanel $steps.Dock = 'Fill' $steps.FlowDirection = 'TopDown' $steps.WrapContents = $false $steps.AutoScroll = $true $steps.Padding = New-Object System.Windows.Forms.Padding(16, 4, 4, 4) $form.Controls.Add($steps) $form.Controls.Add($right) $form.Controls.Add($bottom) $form.Controls.Add($title) $steps.BringToFront() $ui.Form = $form $ui.Steps = $steps $ui.Banner = $banner $ui.Bottom = $bottom $ui.Qr = $qr $ui.Caption = $caption $ui.Close = $close $ui.Security = $security return $ui } # Keeps the window responsive while the script waits. Throws if the window # was closed, which ends setup. function Wait-OutpostUi { param([int]$Milliseconds = 50) $until = [DateTime]::UtcNow.AddMilliseconds($Milliseconds) do { if ($global:Outpost.Ui) { [System.Windows.Forms.Application]::DoEvents() if ($global:Outpost.Closed) { throw 'The setup window was closed.' } } Start-Sleep -Milliseconds 30 } while ([DateTime]::UtcNow -lt $until) } function Start-OutpostStep { param([string]$Text) Write-OutpostLog "STEP $Text" $ui = $global:Outpost.Ui if (-not $ui) { return } $label = New-Object System.Windows.Forms.Label $label.AutoSize = $true $label.MaximumSize = New-Object System.Drawing.Size(([Math]::Max(200, $ui.Steps.ClientSize.Width - 60)), 0) $label.Margin = New-Object System.Windows.Forms.Padding(4, 6, 4, 6) $label.ForeColor = $ui.Blue $label.Tag = $Text $label.Text = "... $Text" $ui.Steps.Controls.Add($label) $ui.Steps.ScrollControlIntoView($label) $ui.Current = $label Set-OutpostBanner -Text "$Text..." } function Complete-OutpostStep { param([string]$Detail) Write-OutpostLog "OK $Detail" $ui = $global:Outpost.Ui if (-not $ui -or -not $ui.Current) { return } $text = [string]$ui.Current.Tag if ($Detail) { $text = "$text - $Detail" } $ui.Current.ForeColor = $ui.Green $ui.Current.Text = "$($ui.Tick) $text" $ui.Steps.ScrollControlIntoView($ui.Current) Wait-OutpostUi 1 } # Marks the current step failed. It does not throw; the caller decides. function Stop-OutpostStep { param([string]$Detail) Write-OutpostLog "FAIL $Detail" $ui = $global:Outpost.Ui if (-not $ui -or -not $ui.Current) { return } $text = [string]$ui.Current.Tag if ($Detail) { $text = "$text - $Detail" } $ui.Current.ForeColor = $ui.Red $ui.Current.Text = "$($ui.Cross) $text" $ui.Steps.ScrollControlIntoView($ui.Current) Wait-OutpostUi 1 } # Kind: info, ok, warn or fail. function Set-OutpostBanner { param([string]$Text, [string]$Kind = 'info') $ui = $global:Outpost.Ui if (-not $ui) { return } $ui.Banner.Text = $Text switch ($Kind) { 'ok' { $ui.Banner.ForeColor = $ui.Green } 'warn' { $ui.Banner.ForeColor = $ui.Amber } 'fail' { $ui.Banner.ForeColor = $ui.Red } default { $ui.Banner.ForeColor = $ui.Gray } } [System.Windows.Forms.Application]::DoEvents() } function Show-OutpostQr { param([string]$Base64Png, [string]$Caption) $ui = $global:Outpost.Ui if (-not $ui) { return } $shown = $null if ($Base64Png) { # Draw at a whole-number scale with no smoothing so the modules stay sharp. try { $size = 260 $bytes = [Convert]::FromBase64String($Base64Png) $stream = New-Object System.IO.MemoryStream(, $bytes) $image = [System.Drawing.Image]::FromStream($stream) $dim = [Math]::Max($image.Width, $image.Height) if ($dim -ge $size) { $dw = $size $dh = $size } else { $k = [int][Math]::Floor($size / $dim) $dw = $image.Width * $k $dh = $image.Height * $k } $shown = New-Object System.Drawing.Bitmap($size, $size) $g = [System.Drawing.Graphics]::FromImage($shown) $g.Clear([System.Drawing.Color]::White) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::NearestNeighbor $g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half $g.DrawImage($image, [int](($size - $dw) / 2), [int](($size - $dh) / 2), $dw, $dh) $g.Dispose() $image.Dispose() $stream.Dispose() } catch { Write-OutpostLog "QR image could not be drawn: $($_.Exception.Message)" $shown = $null } } $old = $ui.Qr.Image $ui.Qr.Image = $shown $ui.Qr.Visible = [bool]$shown if ($old) { $old.Dispose() } $ui.Caption.Text = $Caption [System.Windows.Forms.Application]::DoEvents() } # ---------------------------------------------------------------- tools function ConvertTo-OutpostArgLine { param([string[]]$Arguments) $parts = foreach ($a in $Arguments) { if ($a -match '[\s"]' -or $a -eq '') { '"' + ($a -replace '"', '\"') + '"' } else { $a } } return ($parts -join ' ') } # Runs a program hidden, keeps the window responsive, returns Code/Out/Err. function Invoke-OutpostTool { param([string]$File, [string[]]$Arguments = @(), [int]$TimeoutSec = 600, [switch]$Quiet) $id = [Guid]::NewGuid().ToString('N') $outFile = Join-Path $global:Outpost.WorkDir "$id.out" $errFile = Join-Path $global:Outpost.WorkDir "$id.err" $argLine = ConvertTo-OutpostArgLine $Arguments if (-not $Quiet) { Write-OutpostLog "RUN $File $argLine" } $start = @{ FilePath = $File PassThru = $true WindowStyle = 'Hidden' RedirectStandardOutput = $outFile RedirectStandardError = $errFile } if ($argLine) { $start.ArgumentList = $argLine } $p = Start-Process @start $null = $p.Handle $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSec) try { while (-not $p.HasExited) { if ([DateTime]::UtcNow -gt $deadline) { try { $p.Kill() } catch { } throw "$File did not finish within $TimeoutSec seconds." } Wait-OutpostUi 100 } $p.WaitForExit() $out = '' $err = '' if (Test-Path -LiteralPath $outFile) { $out = [IO.File]::ReadAllText($outFile) } if (Test-Path -LiteralPath $errFile) { $err = [IO.File]::ReadAllText($errFile) } if (-not $Quiet) { Write-OutpostLog "EXIT $($p.ExitCode)" if ($out.Trim()) { Write-OutpostLog "OUT $($out.Trim())" } if ($err.Trim()) { Write-OutpostLog "ERR $($err.Trim())" } } return [pscustomobject]@{ Code = $p.ExitCode; Out = $out; Err = $err } } finally { Remove-Item -LiteralPath $outFile, $errFile -Force -ErrorAction SilentlyContinue } } function Get-OutpostFile { param([string]$Url, [string]$Path, [string]$Sha256) if (Test-Path -LiteralPath $global:Outpost.Curl) { $r = Invoke-OutpostTool $global:Outpost.Curl @('-fsSL', '--retry', '3', '--connect-timeout', '15', '-o', $Path, $Url) -TimeoutSec 1800 if ($r.Code -ne 0) { throw "Download failed: $Url ($($r.Err.Trim()))" } } else { $ProgressPreference = 'SilentlyContinue' Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Path } if ($Sha256) { $actual = (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLower() if ($actual -ne $Sha256.ToLower()) { Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue throw "Checksum mismatch for $Url" } } } # GET a small JSON document. Returns $null on any failure. function Get-OutpostJson { param([string]$Url, [int]$TimeoutSec = 5) try { if (Test-Path -LiteralPath $global:Outpost.Curl) { $r = Invoke-OutpostTool $global:Outpost.Curl @('-fsS', '--max-time', "$TimeoutSec", $Url) -TimeoutSec ($TimeoutSec + 5) -Quiet if ($r.Code -ne 0 -or -not $r.Out.Trim()) { return $null } return ($r.Out | ConvertFrom-Json) } $ProgressPreference = 'SilentlyContinue' return (Invoke-RestMethod -Uri $Url -TimeoutSec $TimeoutSec) } catch { return $null } } # POST a small JSON document. Never throws. function Send-OutpostJson { param([string]$Url, $Body, [int]$TimeoutSec = 8) try { $json = $Body | ConvertTo-Json -Compress -Depth 6 if (Test-Path -LiteralPath $global:Outpost.Curl) { $file = Join-Path $global:Outpost.WorkDir ([Guid]::NewGuid().ToString('N') + '.json') [IO.File]::WriteAllText($file, $json, (New-Object System.Text.UTF8Encoding($false))) try { $null = Invoke-OutpostTool $global:Outpost.Curl @('-fsS', '--max-time', "$TimeoutSec", '-X', 'POST', '-H', 'Content-Type: application/json', '-H', 'X-Outpost: 1', '--data-binary', "@$file", $Url) -TimeoutSec ($TimeoutSec + 5) -Quiet } finally { Remove-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue } } else { $ProgressPreference = 'SilentlyContinue' $null = Invoke-RestMethod -Method Post -Uri $Url -ContentType 'application/json' -Headers @{ 'X-Outpost' = '1' } -Body $json -TimeoutSec $TimeoutSec } } catch { } } # The local Tailscale daemon's status, or $null if it is not answering. function Get-OutpostTailscale { if (-not (Test-Path -LiteralPath $global:Outpost.Tailscale)) { return $null } try { $r = Invoke-OutpostTool $global:Outpost.Tailscale @('status', '--json') -TimeoutSec 20 -Quiet $text = $r.Out.Trim() if (-not $text.StartsWith('{')) { return $null } return ($text | ConvertFrom-Json) } catch { if ($global:Outpost.Closed) { throw } return $null } } # Online machines owned by the same Tailscale user as this one, untagged. function Get-OutpostOwnPeers { param($Status) $peers = @() if (-not $Status -or -not $Status.Self -or -not $Status.Peer) { return $peers } foreach ($entry in $Status.Peer.PSObject.Properties) { $peer = $entry.Value if (-not $peer.Online) { continue } if ($peer.UserID -ne $Status.Self.UserID) { continue } if ($peer.Tags) { continue } $ip = $peer.TailscaleIPs | Where-Object { $_ -match '^\d+\.\d+\.\d+\.\d+$' } | Select-Object -First 1 if ($ip) { $peers += [pscustomobject]@{ Name = $peer.HostName; IP = $ip } } } return $peers } # ---------------------------------------------------------------- stages function Invoke-OutpostCheck { Start-OutpostStep 'Checking this PC' $facts = $global:Outpost.Facts $cv = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' $productName = [string]$cv.ProductName # Windows 11 still reports "Windows 10 ..." in ProductName. if ([int]$cv.CurrentBuild -ge 22000) { $productName = $productName -replace '^Windows 10', 'Windows 11' } $facts.os = "$productName $($cv.DisplayVersion) build $($cv.CurrentBuild).$($cv.UBR)" $facts.edition = [string]$cv.EditionID $facts.arch = [string]$env:PROCESSOR_ARCHITECTURE $facts.user = [Security.Principal.WindowsIdentity]::GetCurrent().Name $facts.profile = [string]$env:USERPROFILE $facts.computer = [string]$env:COMPUTERNAME $facts.powershell = $PSVersionTable.PSVersion.ToString() try { $facts.consoleUser = [string](Get-CimInstance Win32_ComputerSystem).UserName } catch { $facts.consoleUser = '' } $sac = $null try { $sac = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\CI\Policy' -Name VerifiedAndReputablePolicyState -ErrorAction Stop).VerifiedAndReputablePolicyState } catch { } switch ($sac) { 0 { $facts.smartAppControl = 'off' } 1 { $facts.smartAppControl = 'on' } 2 { $facts.smartAppControl = 'evaluation' } default { $facts.smartAppControl = 'unknown' } } foreach ($k in ($facts.Keys | Sort-Object)) { Write-OutpostLog "FACT $k = $($facts[$k])" } if ($facts.arch -ne 'AMD64' -and $facts.arch -ne 'ARM64') { throw "Unsupported processor: $($facts.arch)" } if ($facts.consoleUser -and ($facts.consoleUser -ne $facts.user)) { Write-OutpostLog "WARN elevated as $($facts.user) but the desktop belongs to $($facts.consoleUser)" } Complete-OutpostStep "$($cv.DisplayVersion) $($facts.edition), signed in as $($facts.user)" } function Invoke-OutpostTailscaleInstall { Start-OutpostStep 'Installing Tailscale' if (Test-Path -LiteralPath $global:Outpost.Tailscale) { Complete-OutpostStep 'already installed' } else { $arch = 'amd64' if ($global:Outpost.Facts.arch -eq 'ARM64') { $arch = 'arm64' } $index = Get-OutpostJson 'https://pkgs.tailscale.com/stable/?mode=json&os=windows' 30 if (-not $index -or -not $index.MSIs.$arch) { throw 'Could not read the Tailscale download list. Is this PC online?' } $name = [string]$index.MSIs.$arch if ($name -notmatch '^tailscale-setup-[0-9.]+-(amd64|arm64)\.msi$') { throw "Unexpected Tailscale installer name: $name" } $msi = Join-Path $global:Outpost.WorkDir $name Get-OutpostFile "https://pkgs.tailscale.com/stable/$name" $msi $sig = Get-AuthenticodeSignature -LiteralPath $msi if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Subject -notmatch '(^|,\s*)O=Tailscale Inc\.(,|$)') { throw "The Tailscale installer is not signed by Tailscale Inc. (status $($sig.Status)). Stopping." } Write-OutpostLog "SIGN $($sig.SignerCertificate.Subject)" $msiLog = Join-Path $global:Outpost.WorkDir 'tailscale-msi.log' $r = Invoke-OutpostTool (Join-Path $env:SystemRoot 'System32\msiexec.exe') @('/i', $msi, '/qn', '/norestart', 'TS_NOLAUNCH=true', '/l*v', $msiLog) -TimeoutSec 900 if ($r.Code -ne 0 -and $r.Code -ne 3010) { throw "The Tailscale installer failed with code $($r.Code). See $msiLog" } if (-not (Test-Path -LiteralPath $global:Outpost.Tailscale)) { throw 'Tailscale installed but tailscale.exe was not found.' } Complete-OutpostStep ($name -replace '^tailscale-setup-|\.msi$', '') } # The service takes a moment to answer after install or boot. $deadline = [DateTime]::UtcNow.AddSeconds(90) while (-not (Get-OutpostTailscale)) { if ([DateTime]::UtcNow -gt $deadline) { throw 'The Tailscale service did not start.' } Wait-OutpostUi 1500 } } function Invoke-OutpostTailscaleJoin { Start-OutpostStep 'Joining your tailnet' $st = Get-OutpostTailscale if ($st -and $st.BackendState -eq 'Running') { $null = Invoke-OutpostTool $global:Outpost.Tailscale @('set', '--unattended=true') -TimeoutSec 30 Complete-OutpostStep "already joined as $($st.Self.HostName)" return } $outFile = Join-Path $global:Outpost.WorkDir 'tailscale-up.out' $errFile = Join-Path $global:Outpost.WorkDir 'tailscale-up.err' Remove-Item -LiteralPath $outFile, $errFile -Force -ErrorAction SilentlyContinue Write-OutpostLog 'RUN tailscale up --json --unattended --timeout=1800s' $p = Start-Process -FilePath $global:Outpost.Tailscale -ArgumentList 'up --json --unattended --timeout=1800s' -PassThru -WindowStyle Hidden -RedirectStandardOutput $outFile -RedirectStandardError $errFile $null = $p.Handle $shownUrl = '' $approvalShown = $false $deadline = [DateTime]::UtcNow.AddSeconds(1800) try { while ($true) { if ([DateTime]::UtcNow -gt $deadline) { throw 'Timed out waiting for the Tailscale sign-in.' } $text = '' try { $fs = New-Object System.IO.FileStream($outFile, 'Open', 'Read', 'ReadWrite') $reader = New-Object System.IO.StreamReader($fs) $text = $reader.ReadToEnd() $reader.Dispose() } catch { } $urls = [regex]::Matches($text, '"AuthURL":\s*"([^"]+)"') if ($urls.Count -gt 0) { $url = $urls[$urls.Count - 1].Groups[1].Value -replace '\\u0026', '&' if ($url -ne $shownUrl) { $shownUrl = $url $png = '' $qrs = [regex]::Matches($text, '"QR":\s*"data:image/png;base64,([A-Za-z0-9+/=]+)"') if ($qrs.Count -gt 0) { $png = $qrs[$qrs.Count - 1].Groups[1].Value } Write-OutpostLog "AUTH $url" Show-OutpostQr $png "Scan with your phone and approve this machine.`r`nOr open: $url" Set-OutpostBanner -Text 'Scan the code with your phone to add this machine to your tailnet.' } } $st = Get-OutpostTailscale if ($st -and $st.BackendState -eq 'Running') { break } if ($st -and $st.BackendState -eq 'NeedsMachineAuth' -and -not $approvalShown) { $approvalShown = $true Show-OutpostQr '' 'Signed in. This machine is waiting for approval in the Tailscale admin console.' Set-OutpostBanner -Text 'Approve this machine in the Tailscale admin console.' -Kind 'warn' } if ($p.HasExited -and $p.ExitCode -ne 0) { $err = '' try { $err = [IO.File]::ReadAllText($errFile).Trim() } catch { } throw "tailscale up failed: $err $text" } Wait-OutpostUi 700 } } finally { if (-not $p.HasExited) { try { $p.Kill() } catch { } } } Show-OutpostQr '' '' $ip = $st.TailscaleIPs | Select-Object -First 1 $global:Outpost.Facts.tailscaleIP = [string]$ip Complete-OutpostStep "joined as $($st.Self.HostName) ($ip)" } # Asks every given peer for a setup offer at the same time. Returns the first # valid answer as an object with Offer, Base and Peer, or $null. function Find-OutpostOffer { param($Peers) $port = $global:Outpost.OfferPort if (-not (Test-Path -LiteralPath $global:Outpost.Curl)) { foreach ($peer in $Peers) { $base = "http://$($peer.IP):$port" $offer = Get-OutpostJson "$base/bootstrap/v1/offer" 3 if ($offer -and $offer.kind -eq 'outpost-offer') { return [pscustomobject]@{ Offer = $offer; Base = $base; Peer = $peer } } } return $null } $probes = @() try { foreach ($peer in $Peers) { $base = "http://$($peer.IP):$port" $out = Join-Path $global:Outpost.WorkDir ([Guid]::NewGuid().ToString('N') + '.probe') $proc = Start-Process -FilePath $global:Outpost.Curl -ArgumentList "-fsS --max-time 3 $base/bootstrap/v1/offer" -PassThru -WindowStyle Hidden -RedirectStandardOutput $out -RedirectStandardError "$out.err" $null = $proc.Handle $probes += [pscustomobject]@{ Peer = $peer; Base = $base; Out = $out; Proc = $proc } } $deadline = [DateTime]::UtcNow.AddSeconds(6) while ([DateTime]::UtcNow -lt $deadline) { if (-not ($probes | Where-Object { -not $_.Proc.HasExited })) { break } Wait-OutpostUi 100 } foreach ($probe in $probes) { if (-not $probe.Proc.HasExited) { continue } $text = '' try { $text = [IO.File]::ReadAllText($probe.Out).Trim() } catch { } if (-not $text.StartsWith('{')) { continue } $offer = $null try { $offer = $text | ConvertFrom-Json } catch { } if ($offer -and $offer.kind -eq 'outpost-offer') { return [pscustomobject]@{ Offer = $offer; Base = $probe.Base; Peer = $probe.Peer } } } return $null } finally { foreach ($probe in $probes) { if (-not $probe.Proc.HasExited) { try { $probe.Proc.Kill() } catch { } } Remove-Item -LiteralPath $probe.Out, "$($probe.Out).err" -Force -ErrorAction SilentlyContinue } } } function Invoke-OutpostFindOffer { Start-OutpostStep 'Finding your other machine' Show-OutpostQr '' "On your Mac or another machine of yours, run:`r`n`r`n outpost bootstrap " Set-OutpostBanner -Text 'Waiting for one of your machines to offer setup. Run "outpost bootstrap " there.' $deadline = [DateTime]::UtcNow.AddMinutes(30) while ($true) { if ([DateTime]::UtcNow -gt $deadline) { throw 'No machine on your tailnet offered setup within 30 minutes.' } $found = Find-OutpostOffer (Get-OutpostOwnPeers (Get-OutpostTailscale)) if ($found) { if ([int]$found.Offer.minStarter -gt $global:Outpost.StarterVersion) { throw "$($found.Peer.Name) needs a newer starter (version $($found.Offer.minStarter))." } $global:Outpost.Offer = $found.Offer $global:Outpost.BaseUrl = $found.Base Show-OutpostQr '' '' Complete-OutpostStep "$($found.Peer.Name) is setting this machine up as $($found.Offer.name)" return } Wait-OutpostUi 2000 } } function Invoke-OutpostSetup { $offer = $global:Outpost.Offer if (-not $offer -or -not $offer.setup -or -not $offer.setup.path) { throw 'The setup offer did not name a setup script.' } if ([string]$offer.setup.sha256 -notmatch '^[0-9a-fA-F]{64}$') { throw 'The setup offer did not include a checksum for its script.' } $path = Join-Path $global:Outpost.WorkDir 'setup.ps1' Get-OutpostFile ($global:Outpost.BaseUrl + $offer.setup.path) $path $offer.setup.sha256 $text = [IO.File]::ReadAllText($path) & ([scriptblock]::Create($text)) } function Start-OutpostStarter { $o = $global:Outpost $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $admin) { Write-Host 'Asking for administrator rights...' $command = "irm $($o.Origin) | iex" if ($PSCommandPath) { $command = "& '$PSCommandPath'" } Start-Process powershell.exe -Verb RunAs -ArgumentList "-NoProfile -NoExit -ExecutionPolicy Bypass -Command `"$command`"" return } New-Item -ItemType Directory -Force -Path $o.WorkDir | Out-Null $o.Log = Join-Path $o.WorkDir 'bootstrap.log' [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 Write-OutpostLog "Outpost starter $($o.StarterVersion) from $($o.Origin)" try { $o.Ui = New-OutpostUi $o.Ui.Form.Show() [System.Windows.Forms.Application]::DoEvents() } catch { $o.Ui = $null Write-OutpostLog "No window available ($($_.Exception.Message)); continuing in this console." } try { Invoke-OutpostCheck Invoke-OutpostTailscaleInstall Invoke-OutpostTailscaleJoin Invoke-OutpostFindOffer Invoke-OutpostSetup $result = $o.Result if (-not $result) { $result = @{ Kind = 'warn'; Text = 'Setup finished without reporting a result.' } } Write-OutpostLog "RESULT $($result.Kind): $($result.Text)" Set-OutpostBanner -Text $result.Text -Kind $result.Kind } catch { $message = $_.Exception.Message if (-not $o.Closed) { Stop-OutpostStep $message Set-OutpostBanner -Text "Setup stopped: $message`r`nLog: $($o.Log)" -Kind 'fail' } Write-OutpostLog "STOPPED $message" } if ($o.Ui -and -not $o.Closed) { if ($o.Facts.smartAppControl -eq 'on' -or $o.Facts.smartAppControl -eq 'evaluation') { $o.Ui.Security.Visible = $true } $o.Ui.Close.Enabled = $true while (-not $o.Closed) { [System.Windows.Forms.Application]::DoEvents() Start-Sleep -Milliseconds 50 } } if ($o.Ui) { try { $o.Ui.Form.Dispose() } catch { } } Write-Host "Log: $($o.Log)" } if (-not $env:OUTPOST_STARTER_NORUN) { Start-OutpostStarter }