Private/Presentation/CredentialSettings.ps1

function Test-SecureStringEqual {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Security.SecureString]$First,

        [Parameter(Mandatory)]
        [System.Security.SecureString]$Second
    )

    if ($First.Length -ne $Second.Length) {
        return $false
    }

    $firstPointer = [IntPtr]::Zero
    $secondPointer = [IntPtr]::Zero
    try {
        $firstPointer = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($First)
        $secondPointer = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Second)
        for ($offset = 0; $offset -lt ($First.Length * 2); $offset += 2) {
            if ([System.Runtime.InteropServices.Marshal]::ReadInt16($firstPointer, $offset) -ne
                [System.Runtime.InteropServices.Marshal]::ReadInt16($secondPointer, $offset)) {
                return $false
            }
        }

        return $true
    }
    finally {
        if ($firstPointer -ne [IntPtr]::Zero) {
            [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($firstPointer)
        }
        if ($secondPointer -ne [IntPtr]::Zero) {
            [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($secondPointer)
        }
    }
}

function Get-PendingLegacyApiKeyPreferences {
    [CmdletBinding()]
    param(
        [Parameter()]
        [AllowNull()]
        [object]$Preferences
    )

    $pending = @{}
    if ($null -eq $Preferences) {
        return $pending
    }

    foreach ($field in @('TwelveDataApiKey', 'AlphaVantageApiKey')) {
        if ($Preferences -is [System.Collections.IDictionary]) {
            if (-not $Preferences.Contains($field)) {
                continue
            }
            $value = [string]$Preferences[$field]
        }
        else {
            $property = $Preferences.PSObject.Properties[$field]
            if ($null -eq $property) {
                continue
            }
            $value = [string]$property.Value
        }

        if (-not [string]::IsNullOrWhiteSpace($value)) {
            $pending[$field] = $value
        }
    }

    $pending
}

function Move-LegacyApiKeysToCredentialStore {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [object]$Preferences,

        [Parameter(Mandatory)]
        [pscustomobject]$CredentialStore,

        [Parameter(Mandatory)]
        [System.Collections.IDictionary]$Mappings
    )

    $verifiedFields = [System.Collections.Generic.List[string]]::new()
    foreach ($legacyField in $Mappings.Keys) {
        if ($Preferences -is [System.Collections.IDictionary]) {
            if (-not $Preferences.Contains($legacyField)) {
                continue
            }
            $legacyValue = [string]$Preferences[$legacyField]
        }
        else {
            $legacyProperty = $Preferences.PSObject.Properties[$legacyField]
            if ($null -eq $legacyProperty) {
                continue
            }
            $legacyValue = [string]$legacyProperty.Value
        }

        if ([string]::IsNullOrWhiteSpace($legacyValue)) {
            continue
        }

        $legacySecret = ConvertTo-SecureString -String $legacyValue -AsPlainText -Force
        $storedSecret = $null
        $readBackSecret = $null
        try {
            $credentialName = [string]$Mappings[$legacyField]
            $storedSecret = Get-CredentialSecret -Store $CredentialStore -CredentialName $credentialName
            if ($null -ne $storedSecret) {
                if (-not (Test-SecureStringEqual -First $legacySecret -Second $storedSecret)) {
                    throw "Existing secure credential '$credentialName' does not match its legacy preference."
                }
            }
            else {
                if (-not (Set-CredentialSecret -Store $CredentialStore -CredentialName $credentialName -Secret $legacySecret)) {
                    throw "Secure credential migration failed for '$credentialName'."
                }

                $readBackSecret = Get-CredentialSecret -Store $CredentialStore -CredentialName $credentialName
                if ($null -eq $readBackSecret -or
                    -not (Test-SecureStringEqual -First $legacySecret -Second $readBackSecret)) {
                    throw "Secure credential read-back verification failed for '$credentialName'."
                }
            }

            $verifiedFields.Add($legacyField)
        }
        finally {
            $legacySecret.Dispose()
            if ($null -ne $storedSecret) {
                $storedSecret.Dispose()
            }
            if ($null -ne $readBackSecret) {
                $readBackSecret.Dispose()
            }
        }
    }

    foreach ($legacyField in $verifiedFields) {
        if ($Preferences -is [System.Collections.IDictionary]) {
            [void]$Preferences.Remove($legacyField)
        }
        else {
            $Preferences.PSObject.Properties.Remove($legacyField)
        }
    }

    [pscustomobject]@{
        Migrated = @($verifiedFields)
    }
}

function Set-CredentialSecretVerified {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$CredentialStore,

        [Parameter(Mandatory)]
        [ValidatePattern('^[A-Za-z0-9._-]{1,128}$')]
        [string]$CredentialName,

        [Parameter(Mandatory)]
        [System.Security.SecureString]$Secret
    )

    $readBack = $null
    try {
        if ($Secret.Length -eq 0) {
            throw 'Credential must not be empty.'
        }

        if (-not (Set-CredentialSecret -Store $CredentialStore -CredentialName $CredentialName -Secret $Secret)) {
            throw "Secure credential write failed for '$CredentialName'."
        }

        $readBack = Get-CredentialSecret -Store $CredentialStore -CredentialName $CredentialName
        if ($null -eq $readBack -or -not (Test-SecureStringEqual -First $Secret -Second $readBack)) {
            throw "Secure credential read-back verification failed for '$CredentialName'."
        }

        return $true
    }
    finally {
        if ($null -ne $readBack) {
            $readBack.Dispose()
        }
    }
}

function Get-PlainTextCredentialForRequest {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$CredentialStore,

        [Parameter(Mandatory)]
        [ValidatePattern('^[A-Za-z0-9._-]{1,128}$')]
        [string]$CredentialName
    )

    $secret = Get-CredentialSecret -Store $CredentialStore -CredentialName $CredentialName
    if ($null -eq $secret) {
        return $null
    }

    try {
        return ConvertFrom-CredentialSecretForRequest -Secret $secret
    }
    finally {
        $secret.Dispose()
    }
}

function Test-CredentialConfigured {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$CredentialStore,

        [Parameter(Mandatory)]
        [ValidatePattern('^[A-Za-z0-9._-]{1,128}$')]
        [string]$CredentialName
    )

    $secret = Get-CredentialSecret -Store $CredentialStore -CredentialName $CredentialName
    if ($null -eq $secret) {
        return $false
    }

    $secret.Dispose()
    return $true
}

function ConvertFrom-CredentialSecretForRequest {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Security.SecureString]$Secret
    )

    $pointer = [IntPtr]::Zero
    try {
        $pointer = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Secret)
        [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer)
    }
    finally {
        if ($pointer -ne [IntPtr]::Zero) {
            [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer)
        }
    }
}

function Set-CredentialControlState {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Windows.Controls.PasswordBox]$PasswordBox,

        [Parameter(Mandatory)]
        [System.Windows.Controls.TextBlock]$StatusText,

        [Parameter()]
        [switch]$IsConfigured,

        [Parameter()]
        [string]$UnavailableMessage
    )

    $PasswordBox.Password = ''
    if (-not [string]::IsNullOrWhiteSpace($UnavailableMessage)) {
        $StatusText.Text = $UnavailableMessage
        return
    }

    $StatusText.Text = if ($IsConfigured.IsPresent) {
        'Configured; saved value is not displayed.'
    }
    else {
        'Not configured.'
    }
}

function Register-CredentialProviderLinks {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Windows.FrameworkElement]$View,

        [Parameter(Mandatory)]
        [System.Windows.Controls.TextBlock]$StatusText
    )

    $openCommand = Get-Command Open-DashboardLink -CommandType Function -ErrorAction Stop
    $handler = [System.Windows.Navigation.RequestNavigateEventHandler]{
        param($sender, $eventArgs)
        & $openCommand -Uri ([string]$eventArgs.Uri.AbsoluteUri) -Metadata $StatusText -LinkType 'provider sign-up page'
        $eventArgs.Handled = $true
    }.GetNewClosure()
    $View.AddHandler([System.Windows.Documents.Hyperlink]::RequestNavigateEvent, $handler)
}