IntuneScopeTagManager.psm1

# Intune Scope Tag Manager
# View, search, filter and change Intune scope tags across policies, apps, scripts, profiles and devices, with a dry-run plan,
# backup, verification and one-click rollback. Runs locally; nothing leaves the admin's machine except calls to Microsoft Graph.

$script:STM = @{
    Version = '1.4.1'
    ModuleRoot = $PSScriptRoot
    Backend = $null          # 'Graph' or 'Mock'
    Mode = 'ReadOnly'        # 'ReadOnly' or 'ReadWrite'
    TenantId = $null; Account = $null; ClientId = $null; Profile = $null
    Settings = $null; Registry = $null
    Inventory = @{}; TypeStatus = @{}; Tags = $null; TagsLoadedAt = $null; RoleAssignments = @(); RoleAssignmentsLoadedAt = $null; GroupNames = @{}; GroupNameStatus = ''
    DeviceLoad = $null; Plans = @{}; Runs = @{}; ActiveRun = $null
    WriteLog = [System.Collections.Generic.Queue[datetime]]::new()
    Stats = @{ Retries = 0 }
    MockHandler = $null; MockRoleInfo = $null; MockGrantedScopes = $null; RoleInfo = $null; AppOnly = $false; HeldSecret = $null; Errors = $null; TokenCheck = $null; MissingScopes = @(); AppRoles = @()
    PreferBrowserSignIn = $false; Launcher = $false; LabRuns = @{}; LastAccessCheck = $null
}

foreach ($f in 'Compat', 'Graph', 'Inventory', 'Plan', 'Apply', 'Diagnostics', 'Rbac', 'Csv', 'Mock', 'Access', 'Tools', 'Server') {
    . (Join-Path $PSScriptRoot "Private/$f.ps1")
}

$script:STMReadScopes = @(
    'DeviceManagementConfiguration.Read.All', 'DeviceManagementApps.Read.All', 'DeviceManagementManagedDevices.Read.All',
    'DeviceManagementServiceConfig.Read.All', 'DeviceManagementRBAC.Read.All', 'DeviceManagementScripts.Read.All'
)
$script:STMWriteScopes = @(
    'DeviceManagementConfiguration.ReadWrite.All', 'DeviceManagementApps.ReadWrite.All', 'DeviceManagementManagedDevices.ReadWrite.All',
    'DeviceManagementServiceConfig.ReadWrite.All', 'DeviceManagementScripts.ReadWrite.All', 'DeviceManagementRBAC.Read.All'
)

# Per-user sign-in details (tenant id, client id, certificate thumbprint, report folder) kept outside the module folder,
# so the shipped profiles stay as approved and an update of the module keeps them. Never holds a secret.
$script:STMUserProfileKeys = @('TenantId', 'ClientId', 'CertificateThumbprint', 'AccessCheckFolder')

function Get-STMUserConfigRoot {
    if ($env:STM_USERCONFIG) { $root = $env:STM_USERCONFIG }
    else {
        $base = if ($env:LOCALAPPDATA) { $env:LOCALAPPDATA } else { Join-Path $HOME '.local/share' }
        $root = Join-Path $base 'IntuneScopeTagManager'
    }
    return $root
}

function Get-STMProfileNames {
    @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'Config/Profiles') -Filter '*.json' | ForEach-Object { $_.BaseName } | Sort-Object)
}

function Get-STMUserProfile {
    param([Parameter(Mandatory)][string]$Profile)
    $o = @{}
    if ($Profile -notmatch '^[A-Za-z0-9_-]+$') { return $o }
    $f = Join-Path (Join-Path (Get-STMUserConfigRoot) 'Profiles') "$Profile.json"
    if (Test-Path -LiteralPath $f) {
        try {
            $j = Get-Content -LiteralPath $f -Raw | ConvertFrom-STMJson
            foreach ($k in $script:STMUserProfileKeys) { if ($j.PSObject.Properties[$k] -and "$($j.$k)") { $o[$k] = [string]$j.$k } }
        } catch { Write-Verbose "Ignoring unreadable $f" }
    }
    return $o
}

function Save-STMUserProfile {
    <# Saves sign-in details for a profile for the current Windows user. Only tenant id, client id, certificate thumbprint and report folder. #>
    param([Parameter(Mandatory)][string]$Profile, [string]$TenantId, [string]$ClientId, [string]$CertificateThumbprint, [string]$AccessCheckFolder)
    if ((Get-STMProfileNames) -notcontains $Profile) { throw "Unknown profile '$Profile'." }
    $guid = '^[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}$'
    if ($TenantId -and $TenantId -notmatch $guid -and $TenantId -notmatch '^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$') { throw 'Tenant must be a tenant id (GUID) or a domain such as contoso.onmicrosoft.com.' }
    if ($ClientId -and $ClientId -notmatch $guid) { throw 'Client id must be a GUID (the Application (client) ID of the app registration).' }
    if ($CertificateThumbprint -and $CertificateThumbprint -notmatch '^[0-9a-fA-F]{40}$') { throw 'Certificate thumbprint must be 40 hexadecimal characters.' }
    $dir = Join-Path (Get-STMUserConfigRoot) 'Profiles'
    if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
    $o = [ordered]@{ TenantId = [string]$TenantId; ClientId = [string]$ClientId; CertificateThumbprint = [string]$CertificateThumbprint; AccessCheckFolder = [string]$AccessCheckFolder; SavedAtUtc = [DateTime]::UtcNow.ToString('o') }
    $o | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $dir "$Profile.json") -Encoding utf8
    Write-STMAudit -Event 'ProfileSaved' -Data @{ profile = $Profile; tenantId = $TenantId; clientId = $ClientId; certificate = [bool]$CertificateThumbprint }
    return (Get-STMSettings -Profile $Profile)
}

function Get-STMEdition {
    # 'Customer' hides the sample tenant and the lab test; anything else is the full edition.
    try { $e = [string](Get-STMSettings).Edition } catch { $e = '' }
    if ($e -eq 'Customer') { 'Customer' } else { 'Full' }
}

function Get-STMSettings {
    param([string]$Profile)
    $s = @{}
    $base = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'Config/Settings.json') -Raw | ConvertFrom-STMJson
    foreach ($p in $base.PSObject.Properties) { if ($p.Name -notlike '_*') { $s[$p.Name] = $p.Value } }
    if ($Profile) {
        if ($Profile -notmatch '^[A-Za-z0-9_-]+$') { throw "Profile '$Profile' is not a valid name." }
        $pf = Join-Path $PSScriptRoot "Config/Profiles/$Profile.json"
        if (-not (Test-Path -LiteralPath $pf)) { throw "Profile '$Profile' not found ($pf)" }
        $po = Get-Content -LiteralPath $pf -Raw | ConvertFrom-STMJson
        foreach ($p in $po.PSObject.Properties) { if ($p.Name -notlike '_*') { $s[$p.Name] = $p.Value } }
        # Sign-in details saved by this user fill in only what the shipped profile leaves empty; guardrails never come from here.
        $u = Get-STMUserProfile -Profile $Profile
        foreach ($k in $u.Keys) { if (-not "$($s[$k])") { $s[$k] = $u[$k] } }
    }
    $s.ProtectedScopeTagNames = @($s.ProtectedScopeTagNames | Where-Object { $_ })
    return $s
}

function Reset-STMSession {
    $script:STM.Inventory = @{}; $script:STM.TypeStatus = @{}; $script:STM.Tags = $null; $script:STM.RoleAssignments = @(); $script:STM.RoleAssignmentsLoadedAt = $null
    $script:STM.GroupNames = @{}; $script:STM.GroupNameStatus = ''; $script:STM.DeviceLoad = $null; $script:STM.Plans = @{}; $script:STM.Runs = @{}
    $script:STM.ActiveRun = $null; $script:STM.Stats = @{ Retries = 0 }; $script:STM.WriteLog.Clear(); $script:STM.Registry = $null
}

function Get-STMScopes {
    param([ValidateSet('ReadOnly', 'ReadWrite')][string]$Mode)
    $scopes = if ($Mode -eq 'ReadWrite') { $script:STMWriteScopes } else { $script:STMReadScopes }
    if ($script:STM.Settings.ResolveGroupNames) { $scopes += 'Group.Read.All' }
    return $scopes
}

function Connect-STMTenant {
    <#
    .SYNOPSIS
      Signs in to Microsoft Graph. Delegated sign-in (default) applies your own Intune role and scope tags to everything shown and changed.
    .PARAMETER Mode
      ReadOnly (default) asks only for read permissions. ReadWrite adds write permissions and is needed to apply a plan.
    .PARAMETER ClientId
      App registration created for this tool (recommended). Without it the Microsoft Graph Command Line Tools app is used.
    .PARAMETER UseDeviceCode
      Sign in with a code on another device (for sessions without a browser).
    .PARAMETER CertificateThumbprint
      App-only, read-only inventory with a certificate in the current user's store. Intune RBAC does not apply to app-only access,
      so the app sees every object; writes always need a delegated sign-in so they run under a named admin's Intune role.
    .PARAMETER ClientSecret
      App-only, read-only inventory with a client secret passed as a SecureString (for example from Get-Secret or Azure Key Vault).
      The secret is never written to disk, settings or logs.
    .PARAMETER ExtraScopes
      Additional delegated permissions to request (the lab test adds DeviceManagementRBAC.ReadWrite.All for its own test tags).
    .PARAMETER BrowserSignIn
      Sign in through the default web browser instead of the Windows sign-in broker (WAM). Used when the tool runs without a
      console window. Needs your own app registration (-ClientId) with the http://localhost redirect; the previous setting is restored.
    #>

    [CmdletBinding(DefaultParameterSetName = 'Delegated')]
    param(
        [Parameter(ParameterSetName = 'Delegated')][ValidateSet('ReadOnly', 'ReadWrite')][string]$Mode = 'ReadOnly',
        [string]$TenantId, [string]$ClientId, [string]$Profile,
        [Parameter(ParameterSetName = 'Delegated')][switch]$UseDeviceCode,
        [Parameter(Mandatory, ParameterSetName = 'AppCert')][string]$CertificateThumbprint,
        [Parameter(Mandatory, ParameterSetName = 'AppSecret')][securestring]$ClientSecret,
        [Parameter(ParameterSetName = 'Delegated')][string[]]$ExtraScopes,
        [Parameter(ParameterSetName = 'Delegated')][switch]$BrowserSignIn
    )
    if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
        throw 'Microsoft.Graph.Authentication is not installed. Run: Install-Module Microsoft.Graph.Authentication -Scope CurrentUser'
    }
    Import-Module Microsoft.Graph.Authentication -ErrorAction Stop
    if ($Profile -or -not $script:STM.Settings) { $script:STM.Settings = Get-STMSettings -Profile $Profile; $script:STM.Profile = $Profile }
    if (-not $TenantId) { $TenantId = $script:STM.Settings.TenantId }
    if (-not $ClientId) { $ClientId = $script:STM.Settings.ClientId }
    $appOnly = $PSCmdlet.ParameterSetName -ne 'Delegated'
    if ($appOnly) {
        if (-not $TenantId -or -not $ClientId) { throw 'App-only sign-in needs -TenantId and -ClientId.' }
        $Mode = 'ReadOnly'
        $p = @{ TenantId = $TenantId; NoWelcome = $true; ErrorAction = 'Stop'; ContextScope = 'Process' }
        if ($CertificateThumbprint) { $p.ClientId = $ClientId; $p.CertificateThumbprint = $CertificateThumbprint }
        else { $p.ClientSecretCredential = New-Object System.Management.Automation.PSCredential($ClientId, $ClientSecret) }
    }
    else {
        $p = @{ Scopes = @(@(Get-STMScopes -Mode $Mode) + @($ExtraScopes | Where-Object { $_ }) | Sort-Object -Unique); NoWelcome = $true; ErrorAction = 'Stop'; ContextScope = 'Process' }
        if ($TenantId) { $p.TenantId = $TenantId }
        if ($ClientId) { $p.ClientId = $ClientId }
        if ($UseDeviceCode) { $p.UseDeviceCode = $true }
    }
    $useBrowser = (-not $appOnly) -and (-not $UseDeviceCode) -and ($BrowserSignIn -or $script:STM.PreferBrowserSignIn) -and $ClientId
    Invoke-STMGraphSignIn -Parameters $p -BrowserSignIn:$useBrowser
    # Microsoft Graph reads the secret again each time it renews the token, so the SecureString is kept in memory
    # (never on disk) until sign-out or the next sign-in, then disposed.
    $old = $script:STM.HeldSecret
    $script:STM.HeldSecret = if ($PSCmdlet.ParameterSetName -eq 'AppSecret') { $ClientSecret } else { $null }
    if ($old -and -not [object]::ReferenceEquals($old, $script:STM.HeldSecret)) { try { $old.Dispose() } catch { } }
    $ctx = Get-MgContext
    if ($script:STM.TenantId -and $script:STM.TenantId -ne $ctx.TenantId) { Reset-STMSession }
    $script:STM.Backend = 'Graph'; $script:STM.Mode = $Mode; $script:STM.AppOnly = $appOnly
    $script:STM.TenantId = $ctx.TenantId; $script:STM.ClientId = $ctx.ClientId
    $script:STM.Account = if ($appOnly) { "app:$($ctx.AppName) ($($ctx.ClientId))" } else { $ctx.Account }
    $missing = @()
    if ($appOnly) {
        $script:STM.RoleInfo = [pscustomobject]@{ Detected = $true; IsTenantWideAdmin = $true; Roles = @('App-only (Intune RBAC not applied)') }
        $need = @('DeviceManagementConfiguration.Read.All', 'DeviceManagementApps.Read.All', 'DeviceManagementRBAC.Read.All')
        $missing = @($need | Where-Object { @($ctx.Scopes) -notcontains $_ -and @($ctx.Scopes) -notcontains ($_ -replace 'Read\.All$', 'ReadWrite.All') })
    }
    else {
        $missing = @(Get-STMScopes -Mode $Mode | Where-Object { $ctx.Scopes -notcontains $_ -and $_ -ne 'Group.Read.All' })
        $script:STM.RoleInfo = Get-STMSignedInRoleInfo
    }
    $script:STM.MissingScopes = @($missing)
    # Prove the sign-in with one small read and record what the token carries, so a refused sign-in shows up now, with the reason.
    $script:STM.TokenCheck = $null
    try { $script:STM.TokenCheck = Get-STMTokenCheck } catch { }
    # Application permissions the app holds: from the token when it could be read, else from the Graph SDK context.
    $script:STM.AppRoles = @()
    if ($appOnly) {
        $r = @($ctx.Scopes)
        if ($script:STM.TokenCheck -and $script:STM.TokenCheck.claims) { $r += @($script:STM.TokenCheck.claims.applicationPermissions) }
        $script:STM.AppRoles = @($r | Where-Object { $_ } | ForEach-Object { [string]$_ } | Sort-Object -Unique)
    }
    if ($script:STM.TokenCheck -and -not $script:STM.TokenCheck.ok) {
        $te = [System.Exception]::new("Sign-in test read failed: HTTP $($script:STM.TokenCheck.status) $($script:STM.TokenCheck.graphCode): $($script:STM.TokenCheck.error)")
        $te.Data['Status'] = $script:STM.TokenCheck.status; $te.Data['GraphCode'] = $script:STM.TokenCheck.graphCode; $te.Data['RequestId'] = $script:STM.TokenCheck.requestId
        try { [void](Write-STMErrorLog -Exception $te -Source 'SignInCheck') } catch { }
    }
    Write-STMAudit -Event 'SignedIn' -Data @{ mode = $Mode; appOnly = $appOnly; clientId = $ctx.ClientId; missingScopes = $missing; testRead = $(if ($script:STM.TokenCheck) { $script:STM.TokenCheck.status } else { $null }) }
    [pscustomobject]@{ TenantId = $ctx.TenantId; Account = $script:STM.Account; Mode = $Mode; AppOnly = $appOnly; MissingScopes = $missing; TenantWideAdmin = $script:STM.RoleInfo.IsTenantWideAdmin }
}

function Invoke-STMGraphSignIn {
    # Connect-MgGraph, optionally through the browser instead of WAM. WAM needs a visible parent window, which the double-click
    # launcher does not have. Set-MgGraphOption persists for the user, so the previous value is put back afterwards.
    param([hashtable]$Parameters, [switch]$BrowserSignIn)
    $restore = $null
    $opt = Get-Command Set-MgGraphOption -ErrorAction SilentlyContinue
    if ($BrowserSignIn -and $opt -and $opt.Parameters.ContainsKey('DisableLoginByWAM')) {
        $restore = $false
        try {
            $cur = Get-MgGraphOption -ErrorAction Stop
            $prop = @($cur.PSObject.Properties | Where-Object { $_.Name -match 'WAM' }) | Select-Object -First 1
            if ($prop -and $prop.Name -match 'Disable') { $restore = [bool]$prop.Value }
            elseif ($prop -and $prop.Name -match 'Enable') { $restore = -not [bool]$prop.Value }
        } catch { }
        Set-MgGraphOption -DisableLoginByWAM $true
    }
    try { Connect-MgGraph @Parameters | Out-Null }
    finally { if ($null -ne $restore -and -not $restore) { try { Set-MgGraphOption -DisableLoginByWAM $false } catch { } } }
}

function Disconnect-STMTenant {
    <# Signs out and clears everything loaded in this session (staged changes in the browser are kept). #>
    if ($script:STM.Backend -eq 'Graph') { try { Disconnect-MgGraph -ErrorAction Stop | Out-Null } catch { } }
    if ($script:STM.HeldSecret) { try { $script:STM.HeldSecret.Dispose() } catch { } ; $script:STM.HeldSecret = $null }
    Write-STMAudit -Event 'SignedOut' -Data @{ tenant = $script:STM.TenantId }
    Reset-STMSession
    $script:STM.Backend = $null; $script:STM.Mode = 'ReadOnly'; $script:STM.AppOnly = $false; $script:STM.TenantId = $null
    $script:STM.Account = $null; $script:STM.ClientId = $null; $script:STM.RoleInfo = $null; $script:STM.LastAccessCheck = $null
    $script:STM.TokenCheck = $null; $script:STM.MissingScopes = @(); $script:STM.AppRoles = @()
}

function Get-STMAppWritePermissions {
    # Intune write permissions an app-only sign-in holds as application permissions (empty for user sign-ins).
    if (-not $script:STM.AppOnly) { return @() }
    return @(@($script:STM.AppRoles) | Where-Object { $_ -match '^DeviceManagement\w+\.ReadWrite\.All$' } | Sort-Object -Unique)
}

function Test-STMAppCanWrite {
    # An app sign-in may save once it holds at least one Intune ReadWrite application permission. Each change is
    # still checked against the permission its object type needs (Start-STMRun, Rbac.ps1).
    return [bool]($script:STM.AppOnly -and @(Get-STMAppWritePermissions).Count)
}

function Test-STMAppHasWrite {
    # True when the session may write with this permission: user sign-ins get it from consent at sign-in; app sign-ins
    # need the application permission itself.
    param([Parameter(Mandatory)][string]$Permission)
    if (-not $script:STM.AppOnly) { return $true }
    return @(Get-STMAppWritePermissions) -contains $Permission
}

function Assert-STMRbacWrite {
    # Scope tag and role assignment changes need DeviceManagementRBAC.ReadWrite.All. App sign-ins must hold it as an
    # application permission. User sign-ins ask for it only when first needed (a browser sign-in), so everyday write
    # mode keeps working where it has not been consented.
    if ($script:STM.Backend -ne 'Graph') { return }
    $perm = 'DeviceManagementRBAC.ReadWrite.All'
    if ($script:STM.AppOnly) {
        if (-not (Test-STMAppHasWrite -Permission $perm)) {
            $e = [System.Exception]::new("The app registration lacks the $perm application permission, which scope tag and role assignment changes need. An Entra admin adds it with admin consent; then sign out and sign in again.")
            $e.Data['Kind'] = 'AppReadOnly'; throw $e
        }
        return
    }
    if (@((Get-MgContext).Scopes) -contains $perm) { return }
    [void](Connect-STMTenant -Mode ReadWrite -TenantId $script:STM.TenantId -ClientId $script:STM.ClientId -ExtraScopes $perm)
    if (@((Get-MgContext).Scopes) -notcontains $perm) {
        $e = [System.Exception]::new("The sign-in did not get $perm, which scope tag and role assignment changes need. The app registration needs it as a delegated permission with admin consent.")
        $e.Data['Kind'] = 'Forbidden'; throw $e
    }
}

function Get-STMLastSignIn {
    # Last tenant, client and sign-in kind used on this computer (never a secret), so the page can fill them in.
    $f = Join-Path (Get-STMUserConfigRoot) 'last-signin.json'
    if (-not (Test-Path -LiteralPath $f)) { return $null }
    try {
        $j = Get-Content -LiteralPath $f -Raw | ConvertFrom-STMJson
        return [ordered]@{ how = [string]$j.how; profile = [string]$j.profile; tenantId = [string]$j.tenantId; clientId = [string]$j.clientId; certificateThumbprint = [string]$j.certificateThumbprint }
    } catch { return $null }
}

function Save-STMLastSignIn {
    param([string]$How, [string]$Profile, [string]$TenantId, [string]$ClientId, [string]$CertificateThumbprint)
    $dir = Get-STMUserConfigRoot
    if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
    [ordered]@{ how = $How; profile = $Profile; tenantId = $TenantId; clientId = $ClientId; certificateThumbprint = $CertificateThumbprint; savedAtUtc = [DateTime]::UtcNow.ToString('o') } |
        ConvertTo-Json | Set-Content -LiteralPath (Join-Path $dir 'last-signin.json') -Encoding utf8
}

function Connect-STMDemo {
    <# Uses a built-in sample tenant (invented data) so the tool can be tried and demonstrated without signing in. #>
    param([int]$DeviceCount = 3000, [string]$Profile, [ValidateSet('ReadOnly', 'ReadWrite')][string]$Mode = 'ReadOnly', [string]$DataRoot)
    Reset-STMSession
    $script:STM.Settings = Get-STMSettings -Profile $Profile
    if (-not $Profile) { $script:STM.Settings.ProtectedScopeTagNames = @('PAW-Protected') }
    if ($DataRoot) { $script:STM.Settings.DataRoot = $DataRoot }
    elseif (-not $script:STM.Settings.DataRoot) { $script:STM.Settings.DataRoot = Join-Path (Get-STMDataRoot) 'Demo' }
    $script:STM.Backend = 'Mock'; $script:STM.Mode = $Mode; $script:STM.Profile = $Profile
    $script:STM.TenantId = '11111111-2222-4333-8444-000000000de0'; $script:STM.Account = 'demo.admin@contoso.example'
    [void](New-STMMockTenant -DeviceCount $DeviceCount)
    $script:STM.MockHandler = { param($m, $u, $b) Invoke-STMMockRequest -Method $m -Uri $u -Body $b }
    $script:STM.MockRoleInfo = { [ordered]@{ Detected = $true; IsTenantWideAdmin = $true; Roles = @('Intune Administrator') } }
    $script:STM.RoleInfo = Get-STMSignedInRoleInfo
    [pscustomobject]@{ TenantId = $script:STM.TenantId; Account = $script:STM.Account; Mode = $Mode; Demo = $true }
}

function Set-STMMode {
    <# Switches between read-only and write mode. Write mode signs in again with write permissions. #>
    param([Parameter(Mandatory)][ValidateSet('ReadOnly', 'ReadWrite')][string]$Mode)
    if ($script:STM.AppOnly -and $Mode -eq 'ReadWrite') {
        if (-not (Test-STMAppCanWrite)) {
            $e = [System.Exception]::new('This app registration can only read: its token holds no Intune write permission. An Entra admin adds the ReadWrite.All application permissions it needs (DeviceManagementRBAC.ReadWrite.All for scope tags and roles; DeviceManagementConfiguration, DeviceManagementApps and DeviceManagementManagedDevices ReadWrite.All for objects), grants admin consent, then you sign out and sign in again. Or sign in as yourself.')
            $e.Data['Kind'] = 'AppReadOnly'; throw $e
        }
        $script:STM.Mode = 'ReadWrite'
        Write-STMAudit -Event 'AppWriteEnabled' -Data @{ appWritePermissions = @(Get-STMAppWritePermissions) }
    }
    elseif ($script:STM.Backend -eq 'Mock') { $script:STM.Mode = $Mode }
    elseif ($Mode -eq 'ReadWrite') { [void](Connect-STMTenant -Mode ReadWrite -TenantId $script:STM.TenantId -ClientId $script:STM.ClientId) }
    else { $script:STM.Mode = 'ReadOnly' }
    Write-STMAudit -Event 'ModeChanged' -Data @{ mode = $script:STM.Mode }
    return $script:STM.Mode
}

function Assert-STMConnected { if (-not $script:STM.Backend) { throw 'Not connected. Run Connect-STMTenant (or Connect-STMDemo) first.' } }

function Update-STMInventory {
    <# Loads scope tags, role assignments and every supported object type (devices only with -IncludeDevices). #>
    param([string[]]$Type, [switch]$IncludeDevices, [string]$DeviceOperatingSystem)
    Assert-STMConnected
    [void](Update-STMScopeTags); [void](Update-STMRoleAssignments)
    $types = @(Get-STMTypeRegistry | Where-Object { -not ($_.PSObject.Properties['onDemand'] -and $_.onDemand) } | Where-Object { -not $Type -or $Type -contains $_.key })
    $i = 0
    foreach ($t in $types) {
        $i++
        Write-Progress -Activity 'Loading Intune objects' -Status $t.label -PercentComplete (100 * $i / [math]::Max(1, $types.Count))
        $st = Update-STMTypeInventory -TypeKey $t.key
        if ($st.State -notin 'Loaded', 'NotAvailable', 'AppSignInNotSupported') { Write-Warning "$($t.label): $($st.State) $($st.Error)" }
    }
    if ($IncludeDevices) {
        [void](Start-STMDeviceLoad -OperatingSystem $DeviceOperatingSystem)
        do { $d = Step-STMDeviceLoad; Write-Progress -Activity 'Loading managed devices' -Status "$($d.Loaded) loaded" } while (-not $d.Done)
    }
    Write-Progress -Activity 'Loading Intune objects' -Completed
    return @($script:STM.TypeStatus.Values | Sort-Object Category, Label)
}

function Test-STMAccess {
    <#
    .SYNOPSIS
      Read-only access check. Reports which permissions this sign-in or app has, and whether scope tags can be read for every object type.
    .DESCRIPTION
      Sends GET requests only. The session is held read-only while the check runs, so any other request is refused before it is sent.
      Writes access-check.md, access-check.json and access-check-types.csv. The report holds counts, not object names, unless
      -IncludeInventoryCsv is used.
    .EXAMPLE
      # Existing app registration, secret kept in a vault (never typed into a script or saved to disk):
      $s = Get-Secret -Name IntuneScopeTagReader # or (Get-AzKeyVaultSecret -VaultName <vault> -Name <name>).SecretValue
      Connect-STMTenant -TenantId <tenant id> -ClientId <client id> -ClientSecret $s -Profile Production
      Test-STMAccess -OutputDirectory <client folder>\AccessCheck
    #>

    param([string]$OutputDirectory, [switch]$SkipDeviceSample, [ValidateRange(1, 999)][int]$DeviceSampleSize = 100, [switch]$IncludeInventoryCsv)
    Assert-STMConnected
    $r = Invoke-STMAccessCheck -OutputDirectory $OutputDirectory -SkipDeviceSample:$SkipDeviceSample -DeviceSampleSize $DeviceSampleSize -IncludeInventoryCsv:$IncludeInventoryCsv
    Write-Host "Access check: $(if ($r.Verdict -eq 'ReadyForReadOnlyUse') { 'ready for read-only use' } else { 'incomplete' }). $($r.Summary.ObjectTypesReadable) of $($r.Summary.ObjectTypesTotal) object types readable. Report: $($r.OutputDirectory)"
    return $r
}

function Get-STMInventory {
    <# Returns loaded objects with their scope tags (names resolved). Loads first if nothing is loaded yet. #>
    param([string[]]$Type, [string]$Tag, [switch]$Refresh, [switch]$IncludeDevices)
    Assert-STMConnected
    if ($Refresh -or -not $script:STM.Inventory.Count) { [void](Update-STMInventory -IncludeDevices:$IncludeDevices) }
    $tagId = $null
    if ($Tag) { $r = Resolve-STMTagTokens -Tokens @($Tag); if ($r.Errors) { throw ($r.Errors -join '; ') }; $tagId = $r.Ids[0] }
    $script:STM.Inventory.Values | Where-Object {
        (-not $Type -or $Type -contains $_.Type) -and (-not $tagId -or (@($_.TagIds) -contains $tagId) -or ($tagId -eq '0' -and -not @($_.TagIds).Count))
    } | Sort-Object Category, TypeLabel, Name | ForEach-Object {
        $_ | Select-Object Type, TypeLabel, Category, Id, Name, Platform, @{ n = 'ScopeTags'; e = { (@($_.TagIds) | ForEach-Object { Get-STMTagName $_ }) -join '; ' } }, @{ n = 'ScopeTagIds'; e = { @($_.TagIds) -join ';' } }, Modified, Supported, Note
    }
}

function New-STMChangePlan {
    <#
    .SYNOPSIS
      Builds a dry-run plan from a CSV or from operations. Nothing is written to Intune.
    .EXAMPLE
      New-STMChangePlan -CsvPath .\changes.csv -OutputDirectory .\plans
    #>

    [CmdletBinding(DefaultParameterSetName = 'Csv')]
    param(
        [Parameter(Mandatory, ParameterSetName = 'Csv')][string]$CsvPath,
        [Parameter(Mandatory, ParameterSetName = 'Ops')][object[]]$Operations,
        [string]$Title, [switch]$AllowNoExplicitTags, [switch]$OverrideCap, [string]$OverrideReason, [string]$OutputDirectory
    )
    Assert-STMConnected
    if ($PSCmdlet.ParameterSetName -eq 'Csv') {
        $imp = Import-STMCsv -Path $CsvPath
        foreach ($e in $imp.Errors) { Write-Warning "Row $($e.Row) ($($e.Object)): $($e.Message)" }
        if ($imp.Errors.Count) { throw "$($imp.Errors.Count) row(s) in the CSV have errors. Fix them and try again." }
        $Operations = $imp.Operations
        if (-not $Title) { $Title = "Import of $(Split-Path -Leaf $CsvPath)" }
    }
    if (-not @($Operations).Count) { throw 'Nothing to change: no rows have a Mode.' }
    $plan = New-STMPlan -Operations $Operations -AllowNoExplicitTags:$AllowNoExplicitTags -OverrideCap:$OverrideCap -OverrideReason $OverrideReason -Title $Title
    if ($OutputDirectory) { [void](Export-STMPlan -Plan $plan -Directory $OutputDirectory) }
    Write-STMAudit -Event 'PlanCreated' -Data @{ planId = $plan.PlanId; hash = $plan.Hash; summary = $plan.Summary }
    return $plan
}

function Export-STMChangePlan { param([Parameter(Mandatory)]$Plan, [Parameter(Mandatory)][string]$Directory) Export-STMPlan -Plan $Plan -Directory $Directory }
function Import-STMChangePlan { param([Parameter(Mandatory)][string]$Path) Assert-STMConnected; Import-STMPlanFile -Path $Path }

function Invoke-STMChangePlan {
    <#
    .SYNOPSIS
      Applies a plan: backup and rollback files first, then per batch a drift check, the write, and a read-back to verify.
    .EXAMPLE
      Invoke-STMChangePlan -Plan $plan -WhatIf
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param([Parameter(Mandatory)]$Plan)
    Assert-STMConnected
    $ready = @($Plan.Items | Where-Object State -eq 'Ready')
    foreach ($i in $ready) { Write-Verbose ("{0} {1}: [{2}] -> [{3}]" -f $i.TypeLabel, $i.Name, ($i.BeforeNames -join ', '), ($i.AfterNames -join ', ')) }
    if (-not $PSCmdlet.ShouldProcess("$($ready.Count) Intune objects in tenant $($script:STM.TenantId)", 'Change scope tags')) {
        return [pscustomobject]@{ WhatIf = $true; Ready = $ready.Count; Blocked = $Plan.Summary.Blocked; PlanIssues = $Plan.PlanIssues; Items = $ready }
    }
    $run = Start-STMRun -Plan $Plan -Confirmation "APPLY $($ready.Count)"
    while (-not $run.Done) {
        $run = Step-STMRun -RunId $run.RunId
        Write-Progress -Activity 'Applying scope tag changes' -Status "$($run.Processed) of $($run.Total)" -PercentComplete (100 * $run.Processed / [math]::Max(1, $run.Total))
    }
    Write-Progress -Activity 'Applying scope tag changes' -Completed
    return $run
}

function Get-STMRun { param([string]$RunId) if ($RunId) { Get-STMRunHistory | Where-Object RunId -eq $RunId } else { Get-STMRunHistory } }

function Undo-STMRun {
    <# Builds a plan that puts every object a run changed back to its previous tags. Review it, then Invoke-STMChangePlan. #>
    param([Parameter(Mandatory)][string]$RunId)
    Assert-STMConnected
    $ops = @(New-STMRollbackOperations -RunId $RunId)
    if (-not $ops.Count) { throw "Run $RunId changed nothing, so there is nothing to roll back." }
    return New-STMPlan -Operations $ops -AllowNoExplicitTags -OverrideCap -OverrideReason "Rollback of run $RunId" -Title "Rollback of run $RunId"
}

function Start-ScopeTagManager {
    <#
    .SYNOPSIS
      Opens the Scope Tag Manager in your browser. The page is served only to this computer (127.0.0.1) and needs a one-time key in its address.
    .DESCRIPTION
      With no sign-in parameters the page opens on its sign-in screen, where you pick the profile and sign in (or try the sample data).
      -Profile, -TenantId or -ClientId sign in first from PowerShell, as in earlier versions.
    .EXAMPLE
      Start-ScopeTagManager
    .EXAMPLE
      Start-ScopeTagManager -Profile Production -TenantId <tenant id> -ClientId <client id>
    .EXAMPLE
      Start-ScopeTagManager -Demo
    #>

    param(
        [switch]$Demo, [string]$Profile, [string]$TenantId, [string]$ClientId, [switch]$UseDeviceCode,
        [int]$Port = 0, [switch]$NoBrowser, [int]$DemoDeviceCount = 3000, [int]$MaxRequests = 0,
        # Set by the double-click launcher: no console, so sign-in goes through the browser and the server stops when the page is gone.
        [switch]$Launcher, [int]$IdleMinutes = 0
    )
    if ($Launcher) { $script:STM.Launcher = $true; $script:STM.PreferBrowserSignIn = $true; if (-not $IdleMinutes) { $IdleMinutes = 20 } }
    if ($Demo) { [void](Connect-STMDemo -DeviceCount $DemoDeviceCount -Profile $Profile) }
    elseif (-not $Launcher -and ($TenantId -or $ClientId -or $UseDeviceCode -or ($Profile -and "$((Get-STMSettings -Profile $Profile).TenantId)"))) {
        if (-not $script:STM.Backend -or $script:STM.Backend -eq 'Mock') { [void](Connect-STMTenant -Mode ReadOnly -TenantId $TenantId -ClientId $ClientId -Profile $Profile -UseDeviceCode:$UseDeviceCode) }
    }
    if ($Profile -and -not $script:STM.Profile) { $script:STM.Profile = $Profile }
    Start-STMServer -Port $Port -NoBrowser:$NoBrowser -MaxRequests $MaxRequests -IdleMinutes $IdleMinutes
}

Export-ModuleMember -Function Connect-STMTenant, Disconnect-STMTenant, Connect-STMDemo, Set-STMMode, Update-STMInventory, Get-STMInventory, Export-STMInventoryCsv, Import-STMCsv,
    New-STMChangePlan, Export-STMChangePlan, Import-STMChangePlan, Invoke-STMChangePlan, Get-STMRun, Undo-STMRun, Test-STMAccess, Start-ScopeTagManager