Private/Tools.ps1

# Everything the page needs so nobody has to run a script: sign-in from the page, the Microsoft Graph module install,
# saved sign-in details, the read-only access check, the lab test (run as its own process), folders and a desktop shortcut.

$script:STMGuidPattern = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
$script:STMMinGraphVersion = [version]'2.35.1'

function Get-STMGraphModuleInfo {
    $m = @(Get-Module -ListAvailable -Name Microsoft.Graph.Authentication | Sort-Object Version -Descending)
    if (-not $m.Count) { return [ordered]@{ installed = $false; version = ''; recommended = [string]$script:STMMinGraphVersion; upToDate = $false } }
    return [ordered]@{ installed = $true; version = [string]$m[0].Version; recommended = [string]$script:STMMinGraphVersion; upToDate = ($m[0].Version -ge $script:STMMinGraphVersion) }
}

function Install-STMGraphModule {
    # Installs or updates Microsoft.Graph.Authentication for the current user only (no admin rights).
    $before = Get-STMGraphModuleInfo
    if ($PSVersionTable.PSEdition -eq 'Desktop') {
        [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
        if (-not (Get-PackageProvider -ListAvailable -Name NuGet -ErrorAction SilentlyContinue | Where-Object { $_.Version -ge [version]'2.8.5.201' })) {
            Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force -ErrorAction Stop | Out-Null
        }
    }
    try { Install-Module -Name Microsoft.Graph.Authentication -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop }
    catch { throw "Could not install Microsoft.Graph.Authentication from the PowerShell Gallery: $($_.Exception.Message). If this computer cannot reach the Gallery, ask your desktop team to install it." }
    $after = Get-STMGraphModuleInfo
    Write-STMAudit -Event 'GraphModuleInstalled' -Data @{ before = $before.version; after = $after.version }
    if ($before.installed -and $before.version -ne $after.version -and (Get-Module Microsoft.Graph.Authentication)) {
        $after.restartNeeded = $true   # an older copy is already loaded in this process
    }
    return $after
}

function Connect-STMFromPage {
    # Sign-in from the page. The secret, if any, only lives in memory as a SecureString until sign-out.
    param($Body)
    $kind = [string]$Body.kind
    $profile = [string]$Body.profile
    if ($profile -and (Get-STMProfileNames) -notcontains $profile) { throw "Unknown profile '$profile'." }
    if ($kind -eq 'demo') {
        if ((Get-STMEdition) -eq 'Customer') { throw 'Sample data is not part of this edition.' }
        [void](Connect-STMDemo -Profile $profile)
        return
    }
    if ($kind -notin 'delegated', 'appCert', 'appSecret') { throw "Unknown sign-in kind '$kind'." }
    if (-not (Get-STMGraphModuleInfo).installed) {
        $e = [System.Exception]::new('The Microsoft Graph sign-in module is not installed on this computer.'); $e.Data['Kind'] = 'GraphModuleMissing'; throw $e
    }
    $tenant = ([string]$Body.tenantId).Trim(); $client = ([string]$Body.clientId).Trim()
    if ($Body.remember -and $profile) {
        $keep = Get-STMUserProfile -Profile $profile
        [void](Save-STMUserProfile -Profile $profile -TenantId $tenant -ClientId $client -CertificateThumbprint $(if ($kind -eq 'appCert') { ([string]$Body.thumbprint).Trim() } else { $keep.CertificateThumbprint }) -AccessCheckFolder $keep.AccessCheckFolder)
    }
    $p = @{ TenantId = $tenant; ClientId = $client; Profile = $profile }
    switch ($kind) {
        'delegated' { [void](Connect-STMTenant @p -Mode ReadOnly) }
        'appCert' {
            $tp = ([string]$Body.thumbprint).Trim()
            if ($tp -notmatch '^[0-9a-fA-F]{40}$') { throw 'Certificate thumbprint must be 40 hexadecimal characters.' }
            [void](Connect-STMTenant @p -CertificateThumbprint $tp)
        }
        'appSecret' {
            $plain = [string]$Body.secret
            if (-not $plain) { throw 'Paste the client secret value.' }
            $sec = ConvertTo-SecureString -String $plain -AsPlainText -Force
            $plain = $null; $Body.secret = $null
            # Kept in memory for the session (Graph renews the token with it); disposed on sign-out or the next sign-in.
            try { [void](Connect-STMTenant @p -ClientSecret $sec) } catch { $sec.Dispose(); throw }
        }
        default { throw "Unknown sign-in kind '$kind'." }
    }
    if ($Body.remember) { try { Save-STMLastSignIn -How $kind -Profile $profile -TenantId $tenant -ClientId $client -CertificateThumbprint $(if ($kind -eq 'appCert') { ([string]$Body.thumbprint).Trim() } else { '' }) } catch { } }
}

function Get-STMProfilesView {
    $o = [ordered]@{}
    foreach ($n in Get-STMProfileNames) {
        $s = Get-STMSettings -Profile $n
        $u = Get-STMUserProfile -Profile $n
        $o[$n] = [ordered]@{
            tenantId = [string]$s.TenantId; clientId = [string]$s.ClientId; certificateThumbprint = [string]$s.CertificateThumbprint
            accessCheckFolder = [string]$s.AccessCheckFolder; saved = [bool]$u.Count
            protectedTagNames = @($s.ProtectedScopeTagNames); protectedTagMissingBehavior = [string]$s.ProtectedTagMissingBehavior
        }
    }
    return $o
}

function Get-STMProductionTenantIds {
    # Every tenant id the Production profile knows (shipped or saved by this user). The lab test refuses all of them.
    $ids = @()
    if ((Get-STMProfileNames) -contains 'Production') { $ids += [string](Get-STMSettings -Profile 'Production').TenantId }
    if ($script:STM.Profile -eq 'Production' -and $script:STM.TenantId) { $ids += [string]$script:STM.TenantId }
    return @($ids | Where-Object { $_ } | ForEach-Object { $_.ToLowerInvariant() } | Sort-Object -Unique)
}

function Start-STMAccessCheckFromPage {
    param($Body)
    Assert-STMConnected
    $folder = ([string]$Body.folder).Trim()
    if ($folder) {
        if ($folder -match '[<>"|?*]' -or $folder -match '(^|[\\/])\.\.([\\/]|$)') { throw 'That folder path is not valid.' }
        $folder = Join-Path $folder ('ScopeTag_AccessCheck_' + [DateTime]::UtcNow.ToString('yyyyMMdd-HHmmss'))
    }
    if ($Body.rememberFolder -and $script:STM.Profile) {
        $u = Get-STMUserProfile -Profile $script:STM.Profile
        [void](Save-STMUserProfile -Profile $script:STM.Profile -TenantId $u.TenantId -ClientId $u.ClientId -CertificateThumbprint $u.CertificateThumbprint -AccessCheckFolder ([string]$Body.folder).Trim())
    }
    $size = 100; if ($Body.deviceSample) { $size = [math]::Max(1, [math]::Min(999, [int]$Body.deviceSample)) }
    $r = Invoke-STMAccessCheck -OutputDirectory $folder -SkipDeviceSample:([bool]$Body.skipDevices) -DeviceSampleSize $size -IncludeInventoryCsv:([bool]$Body.includeInventory)
    $script:STM.LastAccessCheck = $r
    return $r
}

function Get-STMPowerShellExe {
    $p = (Get-Process -Id $PID).Path
    if ($p -and ([IO.Path]::GetFileNameWithoutExtension($p) -match '^(pwsh|powershell)$')) { return $p }
    if (Test-STMIsWindows) { $c = Get-Command pwsh.exe -ErrorAction SilentlyContinue; if ($c) { return $c.Source }; return (Join-Path $PSHOME 'powershell.exe') }
    $c = Get-Command pwsh -ErrorAction SilentlyContinue
    if ($c) { return $c.Source }
    throw 'Could not find PowerShell to start the lab test.'
}

function Start-STMLabTestFromPage {
    # Starts LabTest/Invoke-STMLabTest.ps1 as its own process so the page stays responsive; the page follows its log.
    param($Body)
    if ((Get-STMEdition) -eq 'Customer') { throw 'The lab test is not part of this edition.' }
    $demo = [bool]$Body.demo
    $args2 = [System.Collections.Generic.List[string]]::new()
    if ($demo) {
        if ($script:STM.Backend -ne 'Mock') { throw 'The sample run of the lab test is only offered while the sample tenant is open.' }
        $args2.Add('-Demo')
    }
    else {
        $t = ([string]$Body.tenantId).Trim().ToLowerInvariant(); $c = ([string]$Body.confirmTenantId).Trim().ToLowerInvariant(); $cl = ([string]$Body.clientId).Trim()
        if ($t -notmatch $script:STMGuidPattern) { throw 'Type the lab tenant id (a GUID). A domain name is not accepted here, so there is no doubt which tenant this is.' }
        if ($t -ne $c) { throw 'The two lab tenant ids differ. Type the lab tenant id in both boxes.' }
        if ($cl -notmatch $script:STMGuidPattern) { throw 'Type the client id of the LAB app registration.' }
        if ((Get-STMProductionTenantIds) -contains $t) { throw 'This tenant id belongs to the Production profile. The lab test never runs there.' }
        if (-not (Get-STMGraphModuleInfo).installed) { throw 'Install the Microsoft Graph sign-in module first (Sign-in screen).' }
        if ($Body.remember) {
            $u = Get-STMUserProfile -Profile 'Lab'
            [void](Save-STMUserProfile -Profile 'Lab' -TenantId $t -ClientId $cl -CertificateThumbprint $u.CertificateThumbprint -AccessCheckFolder $u.AccessCheckFolder)
        }
        foreach ($a in '-TenantId', $t, '-ConfirmLabTenant', $c, '-ClientId', $cl, '-BrowserSignIn') { $args2.Add($a) }
    }
    if ($Body.includeDevice) { $args2.Add('-IncludeDevice') }
    if ($Body.keepObjects) { $args2.Add('-KeepTestObjects') }
    if ($Body.noTestObjects) { $args2.Add('-NoTestObjects') }
    $id = [DateTime]::UtcNow.ToString('yyyyMMdd-HHmmss')
    $dir = Join-Path (Join-Path (Get-STMDataRoot) 'LabTests') $id
    New-Item -ItemType Directory -Path $dir -Force | Out-Null
    foreach ($a in '-OutputDirectory', $dir, '-NoPrompt') { $args2.Add($a) }
    $script = Join-Path $script:STM.ModuleRoot 'LabTest/Invoke-STMLabTest.ps1'
    $all = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', $script) + @($args2)
    $quoted = @($all | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } })
    $sp = @{ FilePath = (Get-STMPowerShellExe); ArgumentList = $quoted; PassThru = $true; RedirectStandardOutput = (Join-Path $dir 'console.txt'); RedirectStandardError = (Join-Path $dir 'errors.txt') }
    if (Test-STMIsWindows) { $sp.WindowStyle = 'Hidden' }
    $proc = Start-Process @sp
    $script:STM.LabRuns[$id] = @{ Process = $proc; Dir = $dir; Demo = $demo; Started = [DateTime]::UtcNow }
    Write-STMAudit -Event 'LabTestStarted' -Data @{ id = $id; demo = $demo; tenant = [string]$Body.tenantId; folder = $dir }
    return Get-STMLabTestStatus -Id $id
}

function Get-STMLabTestStatus {
    param([Parameter(Mandatory)][string]$Id)
    $r = $script:STM.LabRuns[$Id]
    if (-not $r) { throw 'That lab test is not known to this window. Its results are in the LabTests folder.' }
    $p = $r.Process
    $exited = $false; $code = $null
    try { $p.Refresh(); $exited = $p.HasExited; if ($exited) { $code = $p.ExitCode } } catch { $exited = $true }
    $read = { param($n) $f = Join-Path $r.Dir $n; if (Test-Path -LiteralPath $f) { [IO.File]::ReadAllText($f) } else { '' } }
    $logLines = @(((& $read 'lab-test.log') -split "`r?`n") | Where-Object { $_ })
    $results = $null
    $rj = Join-Path $r.Dir 'lab-results.json'
    if (Test-Path -LiteralPath $rj) { try { $results = @(Get-Content -LiteralPath $rj -Raw | ConvertFrom-STMJson) } catch { } }
    $err = ''
    if ($exited) { $err = ((& $read 'errors.txt') -split "`r?`n" | Where-Object { $_ } | Select-Object -Last 15) -join "`n" }
    $state = if (-not $exited) { 'Running' } elseif ($results) { 'Finished' } else { 'Stopped' }
    return [ordered]@{
        id = $Id; state = $state; exitCode = $code; folder = $r.Dir; demo = $r.Demo; startedAt = $r.Started.ToString('o')
        log = @($logLines | Select-Object -Last 200); logCount = $logLines.Count; results = $results; errors = $err
    }
}

function Open-STMFolder {
    # Opens a folder in File Explorer. Folders only, so nothing can be launched this way.
    param([Parameter(Mandatory)][string]$Path)
    if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw 'Folder not found.' }
    $full = (Resolve-Path -LiteralPath $Path).ProviderPath
    if (Test-STMIsWindows) { Start-Process -FilePath (Join-Path $env:WINDIR 'explorer.exe') -ArgumentList ('"' + $full + '"') }
    return @{ folder = $full }
}

function New-STMDesktopShortcut {
    # Desktop and Start menu shortcuts to the double-click launcher (per user; no admin rights).
    if (-not (Test-STMIsWindows)) { throw 'Shortcuts are created on Windows only.' }
    $target = Join-Path $script:STM.ModuleRoot 'Start Scope Tag Manager.cmd'
    if (-not (Test-Path -LiteralPath $target)) { throw "Launcher not found: $target" }
    $shell = New-Object -ComObject WScript.Shell
    $made = @()
    foreach ($dir in @([Environment]::GetFolderPath('Desktop'), (Join-Path ([Environment]::GetFolderPath('Programs')) ''))) {
        if (-not $dir) { continue }
        $lnk = $shell.CreateShortcut((Join-Path $dir 'Intune Scope Tag Manager.lnk'))
        $lnk.TargetPath = $target
        $lnk.WorkingDirectory = $script:STM.ModuleRoot
        $lnk.WindowStyle = 7
        $lnk.Description = 'Intune Scope Tag Manager'
        $lnk.IconLocation = (Join-Path $env:WINDIR 'System32\imageres.dll') + ',109'
        $lnk.Save()
        $made += $lnk.FullName
    }
    Write-STMAudit -Event 'ShortcutCreated' -Data @{ paths = $made }
    return @{ shortcuts = $made }
}