Private/Authentication/Acronis/Get-AcronisO365SessionCookie.ps1

function Get-AcronisO365SessionCookie {
    <#
    .SYNOPSIS
        Returns the cached, decrypted jlhosting.dk AAD session cookie used to mint
        OAuth codes for Acronis M365 onboarding, or $null if missing/expired.
    #>

    [CmdletBinding()]
    param(
        [Parameter()]
        [switch]$Force
    )

    if (-not $script:TokenCacheConfig.ContainsKey('CookieTtlDays')) {
        $script:TokenCacheConfig.CookieTtlDays = 90
    }

    $cacheKey = 'AcronisO365Session'
    $now = Get-Date

    if ($Force -or -not $script:TokenCache.ContainsKey($cacheKey)) {
        return $null
    }

    $entry = $script:TokenCache[$cacheKey]

    # Expired (or pruned-on-load by Initialize-TokenCache) -> needs re-seed
    if (-not $entry.ExpirationDateTime -or $entry.ExpirationDateTime -le $now) {
        return $null
    }

    # Inside the refresh window -> treat as needing re-seed
    $refreshThreshold = $now.AddMinutes($script:TokenCacheConfig.RefreshBuffer)
    if ($entry.ExpirationDateTime -le $refreshThreshold) {
        Write-ModuleLog -Message "Acronis O365 session cookie is inside the refresh window - re-seed with Save-AcronisO365Session" -Level Verbose -Component 'AcronisO365Session'
        return $null
    }

    # Decrypt the SecureString cookie back to a plaintext Cookie header value
    if ($entry.Cookies -is [System.Security.SecureString]) {
        $cookie = [System.Net.NetworkCredential]::new('', $entry.Cookies).Password
    }
    elseif ($entry.Cookies -is [string] -and $entry.Cookies) {
        $cookie = $entry.Cookies
    }
    else {
        return $null
    }

    Write-ModuleLog -Message ("Using cached Acronis O365 session cookie (expires {0})" -f $entry.ExpirationDateTime) -Level Verbose -Component 'AcronisO365Session'
    return $cookie
}