Private/Server.ps1

# Local web UI host. Listens on 127.0.0.1 only (TcpListener: no admin rights or URL reservation needed), requires a one-time key,
# checks Host and Origin against DNS rebinding and cross-site calls, and serves one self-contained page (no CDN, no telemetry).
# Single-threaded on purpose: the page drives long work in small steps (one object type, one device page, one batch of 20 writes).

function New-STMSecret {
    $b = New-Object byte[] 32
    $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
    try { $rng.GetBytes($b) } finally { $rng.Dispose() }
    return ([Convert]::ToBase64String($b)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}

function ConvertTo-STMRowsJson {
    # Compact rows for the browser: [key,type,id,name,platform,tags,modified,supported,note,tagsKnown,odata,serial,upn,os,owner,agent]
    # Arrays are built with ::new() and filled in place so no PowerShell wrapper objects reach the serializer.
    param([object[]]$Rows)
    $out = [object[]]::new(@($Rows).Count)
    $i = 0
    foreach ($Row in $Rows) {
        $a = [object[]]::new(16)
        $tl = @($Row.TagIds)
        $tags = [string[]]::new($tl.Count)
        for ($j = 0; $j -lt $tl.Count; $j++) { $tags[$j] = [string]$tl[$j] }
        $a[0] = [string]$Row.Key; $a[1] = [string]$Row.Type; $a[2] = [string]$Row.Id; $a[3] = [string]$Row.Name; $a[4] = [string]$Row.Platform
        $a[5] = $tags; $a[6] = [string]$Row.Modified; $a[7] = [bool]$Row.Supported; $a[8] = [string]$Row.Note; $a[9] = [bool]$Row.TagsKnown
        $a[10] = ([string]$Row.ODataType).Replace('#microsoft.graph.', '')
        $x = $Row.Extra
        if ($x) { $a[11] = [string]$x.serial; $a[12] = [string]$x.upn; $a[13] = [string]$x.os; $a[14] = [string]$x.owner; $a[15] = [string]$x.agent }
        else { for ($k = 11; $k -le 15; $k++) { $a[$k] = '' } }
        $out[$i] = $a; $i++
    }
    return ConvertTo-STMFastJson -Value $out
}

function Get-STMStateView {
    $reg = @(Get-STMTypeRegistry | ForEach-Object {
        [ordered]@{ key = $_.key; label = $_.label; category = $_.category; status = $_.status; onDemand = [bool]($_.PSObject.Properties['onDemand'] -and $_.onDemand); notes = [string]$_.notes; optional = [bool]($_.PSObject.Properties['optional'] -and $_.optional) }
    })
    $prot = if ($script:STM.Tags) { Get-STMProtectedTagIds } else { @{ Ids = @(); Missing = @(); Ambiguous = @() } }
    $dl = $script:STM.DeviceLoad
    [ordered]@{
        version = $script:STM.Version; backend = $script:STM.Backend; mode = $script:STM.Mode; tenant = $script:STM.TenantId; account = $script:STM.Account
        profile = $script:STM.Profile; roleInfo = $script:STM.RoleInfo; dataRoot = (Get-STMDataRoot)
        settings = [ordered]@{ maxChangesPerRun = [int]$script:STM.Settings.MaxChangesPerRun; maxWritesPer20Seconds = [int]$script:STM.Settings.MaxWritesPer20Seconds; protectedTagNames = @($script:STM.Settings.ProtectedScopeTagNames); protectedTagMissingBehavior = [string]$script:STM.Settings.ProtectedTagMissingBehavior }
        protected = [ordered]@{ ids = @($prot.Ids); missing = @($prot.Missing); ambiguous = @($prot.Ambiguous) }
        registry = $reg
        typeStatus = @($script:STM.TypeStatus.Values)
        tags = if ($script:STM.Tags) { @($script:STM.Tags) } else { @() }
        tagsLoadedAt = if ($script:STM.TagsLoadedAt) { $script:STM.TagsLoadedAt.ToString('o') } else { $null }
        roleAssignments = if ($script:STM.RoleAssignments) { @($script:STM.RoleAssignments) } else { @() }
        groupNames = $script:STM.GroupNames; groupNameStatus = $script:STM.GroupNameStatus
        stats = $script:STM.Stats
        deviceLoad = if ($dl) { [ordered]@{ loaded = $dl.Loaded; done = $dl.Done; filter = $dl.Filter; tagsMissing = $dl.TagsMissing } } else { $null }
        activeRun = $script:STM.ActiveRun
        signedIn = [bool]$script:STM.Backend; appOnly = [bool]$script:STM.AppOnly; appCanWrite = [bool](Test-STMAppCanWrite); appWritePermissions = @(Get-STMAppWritePermissions); lastSignIn = (Get-STMLastSignIn); launcher = [bool]$script:STM.Launcher
        tokenCheck = (Get-STMTokenCheckView); missingScopes = @($script:STM.MissingScopes)
        isWindows = [bool](Test-STMIsWindows); psVersion = [string]$PSVersionTable.PSVersion; graphModule = (Get-STMGraphModuleInfo)
        profiles = (Get-STMProfilesView); profileNames = @(Get-STMProfileNames); edition = (Get-STMEdition)
        labRuns = @($script:STM.LabRuns.Keys | Sort-Object -Descending)
    }
}

function Get-STMPlanView {
    param($Plan)
    return $Plan
}

function Get-STMRunViewSince {
    param($View, [int]$Since = 0)
    $all = @($View.Results)
    $new = if ($Since -lt $all.Count) { @($all[$Since..($all.Count - 1)]) } else { @() }
    $o = [ordered]@{}
    foreach ($p in $View.PSObject.Properties) { if ($p.Name -ne 'Results') { $o[$p.Name] = $p.Value } }
    $o.ResultCount = $all.Count; $o.NewResults = $new
    return $o
}

# Routes that work before anyone signs in. Every other route needs a sign-in (or the sample tenant).
$script:STMOpenRoutes = @('GET /api/state', 'POST /api/connect', 'POST /api/signout', 'POST /api/settings/save', 'POST /api/install-graph',
    'POST /api/labtest/start', 'POST /api/labtest/status', 'POST /api/folder/open', 'POST /api/shortcut', 'POST /api/ping', 'POST /api/shutdown', 'POST /api/diagnostics')

function Invoke-STMApiRoute {
    param([string]$Method, [string]$Path, [hashtable]$Query, $Body)
    if (-not $script:STM.Backend -and $script:STMOpenRoutes -notcontains "$Method $Path") { throw 'Sign in first.' }
    switch -Regex ("$Method $Path") {
        '^GET /api/state$' { return Get-STMStateView }
        '^POST /api/ping$' { return @{ ok = $true } }
        '^POST /api/connect$' {
            if ($script:STM.ActiveRun) { throw 'A change run is in progress. Let it finish before signing in again.' }
            Connect-STMFromPage -Body $Body
            return Get-STMStateView
        }
        '^POST /api/signout$' {
            if ($script:STM.ActiveRun) { throw 'A change run is in progress. Let it finish before signing out.' }
            Disconnect-STMTenant; return Get-STMStateView
        }
        '^POST /api/settings/save$' {
            [void](Save-STMUserProfile -Profile ([string]$Body.profile) -TenantId ([string]$Body.tenantId).Trim() -ClientId ([string]$Body.clientId).Trim() -CertificateThumbprint ([string]$Body.thumbprint).Trim() -AccessCheckFolder ([string]$Body.accessCheckFolder).Trim())
            return Get-STMStateView
        }
        '^POST /api/install-graph$' { $r = Install-STMGraphModule; return @{ module = $r; state = (Get-STMStateView) } }
        '^POST /api/access$' { return Start-STMAccessCheckFromPage -Body $Body }
        '^POST /api/labtest/start$' { return Start-STMLabTestFromPage -Body $Body }
        '^POST /api/labtest/status$' { return Get-STMLabTestStatus -Id ([string]$Body.id) }
        '^POST /api/folder/open$' {
            $key = [string]$Body.which
            $path = switch ($key) {
                'data' { Get-STMDataRoot }
                'diag' { $d = Join-Path (Get-STMDataRoot) 'Diagnostics'; if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null }; $d }
                'access' { if ($script:STM.LastAccessCheck) { $script:STM.LastAccessCheck.OutputDirectory } }
                'lab' { $r = $script:STM.LabRuns[[string]$Body.id]; if ($r) { $r.Dir } }
                default { $null }
            }
            if (-not $path) { throw 'Nothing to open yet.' }
            return Open-STMFolder -Path $path
        }
        '^POST /api/diagnostics$' { return Get-STMDiagnosticsReport }
        '^POST /api/shortcut$' { return New-STMDesktopShortcut }
        '^POST /api/refresh/meta$' { [void](Update-STMScopeTags); [void](Update-STMRoleAssignments); return Get-STMStateView }
        '^POST /api/refresh/type$' {
            $st = Update-STMTypeInventory -TypeKey ([string]$Body.type)
            $rows = @($script:STM.Inventory.Values | Where-Object Type -eq $Body.type)
            return @{ __raw = "{`"status`":$($st | ConvertTo-Json -Compress -Depth 4),`"rows`":$(ConvertTo-STMRowsJson -Rows $rows)}" }
        }
        '^GET /api/inventory$' {
            $rows = @($script:STM.Inventory.Values)
            return @{ __raw = "{`"rows`":$(ConvertTo-STMRowsJson -Rows $rows)}" }
        }
        '^POST /api/devices/start$' { $d = Start-STMDeviceLoad -OperatingSystem ([string]$Body.os) -NameStartsWith ([string]$Body.name); return @{ loaded = 0; done = $false; filter = $d.Filter } }
        '^POST /api/devices/page$' {
            $d = Step-STMDeviceLoad
            $st = $script:STM.TypeStatus['ManagedDevice']
            $rows = @($d.LastPage)
            return @{ __raw = "{`"loaded`":$([int]$d.Loaded),`"done`":$(([bool]$d.Done).ToString().ToLower()),`"tagsMissing`":$([int]$d.TagsMissing),`"state`":$($st.State | ConvertTo-Json -Compress),`"error`":$([string]$st.Error | ConvertTo-Json -Compress),`"rows`":$(ConvertTo-STMRowsJson -Rows $rows)}" }
        }
        '^POST /api/devices/tags$' {
            $ids = @($Body.ids | ForEach-Object { [string]$_ })
            [void](Update-STMDeviceTags -DeviceIds $ids)
            $rows = @($ids | ForEach-Object { $script:STM.Inventory["ManagedDevice|$_"] } | Where-Object { $_ })
            return @{ __raw = "{`"rows`":$(ConvertTo-STMRowsJson -Rows $rows)}" }
        }
        '^POST /api/import/csv$' {
            if (-not $script:STM.Tags) { [void](Update-STMScopeTags) }
            $text = [string]$Body.text
            if ($text.Length -gt 0 -and [int][char]$text[0] -eq 0xFEFF) { $text = $text.Substring(1) }
            $rows = @($text | ConvertFrom-Csv)
            $res = ConvertFrom-STMCsvRows -Rows $rows -SourceName ([string]$Body.name)
            Write-STMAudit -Event 'CsvImported' -Data @{ name = [string]$Body.name; rows = $res.Rows; operations = @($res.Operations).Count; errors = @($res.Errors).Count }
            # Rows for objects that were read live (not loaded yet) come back too, so the grid can show them.
            $keys = @($res.Operations | ForEach-Object { "$($_.Type)|$($_.Id)" } | Sort-Object -Unique)
            $missing = @($keys | Where-Object { -not $script:STM.Inventory.ContainsKey($_) } | ForEach-Object { $p = $_.Split('|', 2); @{ Type = $p[0]; Id = $p[1] } })
            if ($missing.Count) {
                $live = Get-STMLiveObject -Refs $missing
                foreach ($k in $live.Keys) { if ($live[$k].Row) { $script:STM.Inventory[$k] = $live[$k].Row } }
            }
            $rowsOut = @($keys | ForEach-Object { $script:STM.Inventory[$_] } | Where-Object { $_ })
            $resJson = [ordered]@{ operations = @($res.Operations); errors = @($res.Errors); skipped = $res.Skipped; rows = $res.Rows } | ConvertTo-Json -Depth 6 -Compress
            return @{ __raw = "{`"result`":$resJson,`"objects`":$(ConvertTo-STMRowsJson -Rows $rowsOut)}" }
        }
        '^POST /api/plan$' {
            $ops = @($Body.operations | ForEach-Object { [pscustomobject]@{ Type = [string]$_.type; Id = [string]$_.id; Mode = [string]$_.mode; Tags = @($_.tags | ForEach-Object { [string]$_ }); Note = [string]$_.note; Source = [string]$_.source } })
            if (-not $ops.Count) { throw 'No changes staged.' }
            $plan = New-STMPlan -Operations $ops -AllowNoExplicitTags:([bool]$Body.allowNoTags) -OverrideCap:([bool]$Body.overrideCap) -OverrideReason ([string]$Body.overrideReason) -Title ([string]$Body.title)
            Write-STMAudit -Event 'PlanCreated' -Data @{ planId = $plan.PlanId; hash = $plan.Hash; summary = $plan.Summary }
            return $plan
        }
        '^POST /api/plan/export$' {
            $plan = $script:STM.Plans[[string]$Body.planId]
            if (-not $plan) { throw 'Plan not found; build it again.' }
            $out = Export-STMPlan -Plan $plan -Directory (Join-Path (Get-STMDataRoot) 'Plans')
            return @{ json = $out.Json; csv = $out.Csv; hash = $out.Hash; csvText = (Get-Content -LiteralPath $out.Csv -Raw); jsonText = (Get-Content -LiteralPath $out.Json -Raw) }
        }
        '^POST /api/plan/import$' {
            $tmp = Join-Path (Get-STMDataRoot) ("import-{0}.json" -f [guid]::NewGuid().ToString('N'))
            Set-Content -LiteralPath $tmp -Value ([string]$Body.text) -Encoding utf8
            try { $plan = Import-STMPlanFile -Path $tmp } finally { Remove-Item -LiteralPath $tmp -ErrorAction SilentlyContinue }
            Write-STMAudit -Event 'PlanImported' -Data @{ planId = $plan.PlanId; hash = $plan.Hash }
            return $plan
        }
        '^POST /api/mode$' { [void](Set-STMMode -Mode ([string]$Body.mode)); return Get-STMStateView }
        '^POST /api/apply/start$' {
            $plan = $script:STM.Plans[[string]$Body.planId]
            if (-not $plan) { throw 'Plan not found; build it again.' }
            return Get-STMRunViewSince -View (Start-STMRun -Plan $plan -Confirmation ([string]$Body.confirmation)) -Since 0
        }
        '^POST /api/apply/next$' { return Get-STMRunViewSince -View (Step-STMRun -RunId ([string]$Body.runId)) -Since ([int]$Body.since) }
        '^POST /api/apply/cancel$' { return Get-STMRunViewSince -View (Stop-STMRun -RunId ([string]$Body.runId)) -Since ([int]$Body.since) }
        '^GET /api/runs$' { return @{ runs = @(Get-STMRunHistory) } }
        '^POST /api/runs/rollback$' {
            $ops = @(New-STMRollbackOperations -RunId ([string]$Body.runId))
            if (-not $ops.Count) { throw 'That run changed nothing, so there is nothing to roll back.' }
            return New-STMPlan -Operations $ops -AllowNoExplicitTags -OverrideCap -OverrideReason "Rollback of run $($Body.runId)" -Title "Rollback of run $($Body.runId)"
        }
        '^POST /api/runs/open$' {
            $dir = Join-Path (Join-Path (Get-STMDataRoot) 'Runs') ([string]$Body.runId)
            if (-not (Test-Path -LiteralPath $dir) -or ([string]$Body.runId) -match '[\\/]|\.\.') { throw 'Run folder not found.' }
            if (Test-STMIsWindows) { Invoke-Item -LiteralPath $dir }
            return @{ folder = $dir }
        }
        '^GET /api/rbac/changes$' { return @{ changes = @(Get-STMRbacChanges) } }
        '^POST /api/rbac/tag/create$' { $c = Invoke-STMTagCreate -Name ([string]$Body.name) -Description ([string]$Body.description); return @{ change = $c; state = (Get-STMStateView) } }
        '^POST /api/rbac/tag/update$' { $c = Invoke-STMTagUpdate -Id ([string]$Body.id) -Name ([string]$Body.name) -Description ([string]$Body.description); return @{ change = $c; state = (Get-STMStateView) } }
        '^POST /api/rbac/tag/delete$' { $c = Invoke-STMTagDelete -Id ([string]$Body.id) -ConfirmName ([string]$Body.confirmName); return @{ change = $c; state = (Get-STMStateView) } }
        '^POST /api/rbac/assignment/tags$' { $c = Invoke-STMAssignmentTags -Id ([string]$Body.id) -TagIds @($Body.tagIds | ForEach-Object { [string]$_ }) -ExpectedTagIds @($Body.expectedTagIds | ForEach-Object { [string]$_ }); return @{ change = $c; state = (Get-STMStateView) } }
        '^POST /api/rbac/undo$' { $c = Invoke-STMRbacUndo -ChangeId ([string]$Body.changeId); return @{ change = $c; state = (Get-STMStateView) } }
        '^POST /api/shutdown$' { $script:STMServerStop = $true; return @{ ok = $true } }
        default { throw [System.Collections.Generic.KeyNotFoundException]::new("No route for $Method $Path") }
    }
}

function Send-STMHttpResponse {
    param($Stream, [int]$Status, [string]$ContentType, [byte[]]$Bytes, [bool]$Gzip, [hashtable]$Headers)
    $reason = @{ 200 = 'OK'; 204 = 'No Content'; 400 = 'Bad Request'; 403 = 'Forbidden'; 404 = 'Not Found'; 405 = 'Method Not Allowed'; 413 = 'Payload Too Large'; 500 = 'Internal Server Error' }[$Status]
    if (-not $Bytes) { $Bytes = New-Object byte[] 0 }
    if ($Gzip -and $Bytes.Length -gt 1024) {
        $ms = New-Object System.IO.MemoryStream
        $gz = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionLevel]::Fastest)
        $gz.Write($Bytes, 0, $Bytes.Length); $gz.Dispose()
        $Bytes = $ms.ToArray()
    } else { $Gzip = $false }
    $sb = New-Object System.Text.StringBuilder
    [void]$sb.Append("HTTP/1.1 $Status $reason`r`n")
    [void]$sb.Append("Content-Type: $ContentType`r`nContent-Length: $($Bytes.Length)`r`nConnection: close`r`nCache-Control: no-store`r`n")
    [void]$sb.Append("X-Content-Type-Options: nosniff`r`nReferrer-Policy: no-referrer`r`nX-Frame-Options: DENY`r`nCross-Origin-Opener-Policy: same-origin`r`nCross-Origin-Resource-Policy: same-origin`r`n")
    if ($Gzip) { [void]$sb.Append("Content-Encoding: gzip`r`n") }
    if ($Headers) { foreach ($k in $Headers.Keys) { [void]$sb.Append("${k}: $($Headers[$k])`r`n") } }
    [void]$sb.Append("`r`n")
    $head = [Text.Encoding]::ASCII.GetBytes($sb.ToString())
    $Stream.Write($head, 0, $head.Length)
    if ($Bytes.Length) { $Stream.Write($Bytes, 0, $Bytes.Length) }
    $Stream.Flush()
}

function Read-STMHttpRequest {
    param($Client, [int]$MaxBody = 64MB)
    $stream = $Client.GetStream()
    $stream.ReadTimeout = 15000
    $buf = New-Object byte[] 65536
    $ms = New-Object System.IO.MemoryStream
    $headerEnd = -1
    while ($headerEnd -lt 0) {
        $n = $stream.Read($buf, 0, $buf.Length)
        if ($n -le 0) { return $null }
        $ms.Write($buf, 0, $n)
        $all = $ms.ToArray()
        for ($i = [math]::Max(0, $all.Length - $n - 3); $i -le $all.Length - 4; $i++) {
            if ($all[$i] -eq 13 -and $all[$i + 1] -eq 10 -and $all[$i + 2] -eq 13 -and $all[$i + 3] -eq 10) { $headerEnd = $i; break }
        }
        if ($ms.Length -gt 65536 -and $headerEnd -lt 0) { return @{ Error = 413 } }
    }
    $all = $ms.ToArray()
    $headText = [Text.Encoding]::ASCII.GetString($all, 0, $headerEnd)
    $lines = $headText -split "`r`n"
    $first = $lines[0].Split(' ')
    $headers = @{}
    foreach ($l in $lines[1..($lines.Count - 1)]) { $c = $l.IndexOf(':'); if ($c -gt 0) { $headers[$l.Substring(0, $c).Trim().ToLowerInvariant()] = $l.Substring($c + 1).Trim() } }
    $len = 0
    if ($headers.ContainsKey('content-length')) { $len = [int]$headers['content-length'] }
    if ($len -gt $MaxBody) { return @{ Error = 413 } }
    $bodyStart = $headerEnd + 4
    $have = $all.Length - $bodyStart
    $bodyMs = New-Object System.IO.MemoryStream
    if ($have -gt 0) { $bodyMs.Write($all, $bodyStart, $have) }
    while ($bodyMs.Length -lt $len) {
        $n = $stream.Read($buf, 0, [math]::Min($buf.Length, $len - $bodyMs.Length))
        if ($n -le 0) { break }
        $bodyMs.Write($buf, 0, $n)
    }
    $target = $first[1]
    $q = @{}
    $path = $target
    $qi = $target.IndexOf('?')
    if ($qi -ge 0) {
        $path = $target.Substring(0, $qi)
        foreach ($pair in $target.Substring($qi + 1).Split('&')) { $kv = $pair.Split('=', 2); if ($kv[0]) { $q[[uri]::UnescapeDataString($kv[0])] = if ($kv.Count -gt 1) { [uri]::UnescapeDataString($kv[1]) } else { '' } } }
    }
    return @{ Method = $first[0].ToUpperInvariant(); Path = $path; Query = $q; Headers = $headers; Body = [Text.Encoding]::UTF8.GetString($bodyMs.ToArray()); Stream = $stream }
}

function Invoke-STMHttpConnection {
    param($Client, [int]$Port, [string]$Token)
    $req = Read-STMHttpRequest -Client $Client
    if (-not $req) { return }
    $stream = $Client.GetStream()
    if ($req.Error) { Send-STMHttpResponse -Stream $stream -Status $req.Error -ContentType 'text/plain' -Bytes ([Text.Encoding]::UTF8.GetBytes('Too large')); return }
    $gzip = ([string]$req.Headers['accept-encoding']) -match 'gzip'
    $json = 'application/json; charset=utf-8'
    $deny = { param($s, $msg) Send-STMHttpResponse -Stream $stream -Status $s -ContentType $json -Bytes ([Text.Encoding]::UTF8.GetBytes((@{ error = $msg } | ConvertTo-Json -Compress))) }

    # DNS rebinding and cross-site protection.
    $allowedHosts = @("127.0.0.1:$Port", "localhost:$Port")
    if ($allowedHosts -notcontains ([string]$req.Headers['host']).ToLowerInvariant()) { & $deny 403 'Host not allowed'; return }
    $origin = [string]$req.Headers['origin']
    if ($origin -and @("http://127.0.0.1:$Port", "http://localhost:$Port") -notcontains $origin.ToLowerInvariant()) { & $deny 403 'Origin not allowed'; return }

    if ($req.Method -eq 'GET' -and $req.Path -eq '/') {
        if ($req.Query['t'] -cne $Token) {
            Send-STMHttpResponse -Stream $stream -Status 403 -ContentType 'text/html; charset=utf-8' -Bytes ([Text.Encoding]::UTF8.GetBytes('<!doctype html><meta charset="utf-8"><title>Scope Tag Manager</title><p style="font-family:sans-serif">Open the full address shown in the PowerShell window. It contains a one-time key.</p>'))
            return
        }
        $nonce = New-STMSecret
        $html = [IO.File]::ReadAllText((Join-Path $script:STM.ModuleRoot 'UI/index.html'))
        $html = $html.Replace('__STM_TOKEN__', $Token).Replace('__STM_NONCE__', $nonce)
        $csp = "default-src 'none'; script-src 'nonce-$nonce'; style-src 'nonce-$nonce'; style-src-attr 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
        Send-STMHttpResponse -Stream $stream -Status 200 -ContentType 'text/html; charset=utf-8' -Bytes ([Text.Encoding]::UTF8.GetBytes($html)) -Gzip $gzip -Headers @{ 'Content-Security-Policy' = $csp }
        return
    }
    if ($req.Path -eq '/favicon.ico') { Send-STMHttpResponse -Stream $stream -Status 204 -ContentType 'text/plain'; return }
    if (-not $req.Path.StartsWith('/api/')) { & $deny 404 'Not found'; return }
    if ([string]$req.Headers['x-stm-token'] -cne $Token) { & $deny 403 'Missing or wrong session key'; return }
    if ($req.Method -notin 'GET', 'POST') { & $deny 405 'Method not allowed'; return }
    if ($req.Method -eq 'POST' -and ([string]$req.Headers['content-type']) -notmatch '^application/json') { & $deny 400 'Content-Type must be application/json'; return }

    $status = 200
    try {
        $body = if ($req.Body) { $req.Body | ConvertFrom-STMJson } else { $null }
        $result = Invoke-STMApiRoute -Method $req.Method -Path $req.Path -Query $req.Query -Body $body
        if ($result -is [hashtable] -and $result.ContainsKey('__raw')) { $out = $result.__raw }
        else { $out = $result | ConvertTo-Json -Depth 12 -Compress }
        if (-not $out) { $out = 'null' }
    }
    catch {
        $status = if ($_.Exception -is [System.Collections.Generic.KeyNotFoundException]) { 404 } else { 400 }
        $kind = $_.Exception.Data['Kind']
        $errId = $null
        try { $errId = Write-STMErrorLog -Exception $_.Exception -Source 'Page' -Route "$($req.Method) $($req.Path)" -Stack $_.ScriptStackTrace } catch { }
        $out = @{ error = (Protect-STMDiagText $_.Exception.Message); kind = $kind; errorId = $errId } | ConvertTo-Json -Compress
        try { Write-STMAudit -Event 'ApiError' -Data @{ path = $req.Path; error = (Protect-STMDiagText $_.Exception.Message); errorId = $errId } } catch { }
    }
    Send-STMHttpResponse -Stream $stream -Status $status -ContentType $json -Bytes ([Text.Encoding]::UTF8.GetBytes($out)) -Gzip $gzip
}

function Start-STMServer {
    param([int]$Port = 0, [switch]$NoBrowser, [int]$MaxRequests = 0, [int]$IdleMinutes = 0)
    $listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, $Port)
    $listener.Start()
    $Port = $listener.LocalEndpoint.Port
    $token = New-STMSecret
    $url = "http://127.0.0.1:$Port/?t=$token"
    $script:STMServerStop = $false
    Write-STMAudit -Event 'UiStarted' -Data @{ port = $Port; backend = $script:STM.Backend }
    Write-Host ''
    $who = if ($script:STM.Backend) { "for $($script:STM.Account) ($($script:STM.Backend), $($script:STM.Mode))" } else { '(sign in on the page)' }
    Write-Host "Intune Scope Tag Manager $($script:STM.Version) is running $who." -ForegroundColor Cyan
    Write-Host "Open: $url"
    Write-Host 'Press Ctrl+C here, or use Quit in the page, to stop.'
    Write-Output "STM_URL=$url"
    if (-not $NoBrowser) {
        try {
            if (Test-STMIsWindows) { Start-Process $url }
            elseif (Get-Command xdg-open -ErrorAction SilentlyContinue) { Start-Process xdg-open $url }
            elseif (Get-Command open -ErrorAction SilentlyContinue) { Start-Process open $url }
        } catch { Write-Warning "Could not open a browser. Open the address above yourself." }
    }
    # Browsers open spare connections that may never send a request; keep them aside so they never block real requests.
    $idle = New-Object 'System.Collections.Generic.List[object]'
    $handled = 0
    $lastRequest = [DateTime]::UtcNow
    try {
        while (-not $script:STMServerStop) {
            $busy = $false
            while ($listener.Pending()) { $idle.Add(@{ Client = $listener.AcceptTcpClient(); Since = [DateTime]::UtcNow }); $busy = $true }
            for ($i = $idle.Count - 1; $i -ge 0; $i--) {
                $c = $idle[$i]
                $ready = $false
                try { $ready = $c.Client.Available -gt 0 } catch { }
                if ($ready) {
                    $idle.RemoveAt($i); $busy = $true
                    try { Invoke-STMHttpConnection -Client $c.Client -Port $Port -Token $token } catch { Write-Verbose "Request failed: $($_.Exception.Message)" }
                    finally { $c.Client.Close() }
                    $handled++; $lastRequest = [DateTime]::UtcNow
                    if ($MaxRequests -gt 0 -and $handled -ge $MaxRequests) { $script:STMServerStop = $true }
                }
                elseif (([DateTime]::UtcNow - $c.Since).TotalSeconds -gt 30 -or -not $c.Client.Connected) { $idle.RemoveAt($i); $c.Client.Close() }
            }
            if (-not $busy) {
                # The page checks in every minute; with no page open for IdleMinutes (and no run in progress) the server stops.
                if ($IdleMinutes -gt 0 -and -not $script:STM.ActiveRun -and ([DateTime]::UtcNow - $lastRequest).TotalMinutes -ge $IdleMinutes) {
                    Write-STMAudit -Event 'UiIdleStop' -Data @{ minutes = $IdleMinutes }; $script:STMServerStop = $true
                }
                Start-Sleep -Milliseconds 15
            }
        }
    }
    finally {
        foreach ($c in $idle) { try { $c.Client.Close() } catch { } }
        $listener.Stop()
        Write-STMAudit -Event 'UiStopped' -Data @{ requests = $handled }
        Write-Host 'Scope Tag Manager stopped.'
    }
}