Private/Application/CredentialStore.ps1

$script:credentialStoreNativeType = 'PSExchangeClock.Native.WindowsCredentialStore'

function Initialize-WindowsCredentialStoreType {
    [CmdletBinding()]
    param()

    if (-not $IsWindows) {
        throw 'Windows Credential Manager and DPAPI-protected CLIXML are available only on Windows.'
    }

    if ($null -ne ($script:credentialStoreNativeType -as [type])) {
        return
    }

    $definition = @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;
 
namespace PSExchangeClock.Native
{
    public static class WindowsCredentialStore
    {
        private const int CredentialTypeGeneric = 1;
        private const int CredentialPersistLocalMachine = 2;
        private const int ErrorNotFound = 1168;
        private const int MaximumBlobBytes = 2560;
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct Credential
        {
            public int Flags;
            public int Type;
            public string TargetName;
            public string Comment;
            public long LastWritten;
            public int CredentialBlobSize;
            public IntPtr CredentialBlob;
            public int Persist;
            public int AttributeCount;
            public IntPtr Attributes;
            public string TargetAlias;
            public string UserName;
        }
 
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool CredReadW(string target, int type, int flags, out IntPtr credential);
 
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool CredWriteW(ref Credential credential, int flags);
 
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool CredDeleteW(string target, int type, int flags);
 
        [DllImport("advapi32.dll")]
        private static extern void CredFree(IntPtr buffer);
 
        private static void Clear(IntPtr buffer, int length)
        {
            if (buffer == IntPtr.Zero || length <= 0) return;
            for (int index = 0; index < length; index++)
            {
                Marshal.WriteByte(buffer, index, 0);
            }
        }
 
        public static SecureString Read(string target)
        {
            IntPtr credentialPointer;
            if (!CredReadW(target, CredentialTypeGeneric, 0, out credentialPointer))
            {
                int error = Marshal.GetLastWin32Error();
                if (error == ErrorNotFound) return null;
                throw new Win32Exception(error, "Credential Manager read failed.");
            }
 
            try
            {
                Credential credential = Marshal.PtrToStructure<Credential>(credentialPointer);
                if (credential.CredentialBlobSize < 0 ||
                    credential.CredentialBlobSize > MaximumBlobBytes ||
                    credential.CredentialBlobSize % 2 != 0)
                {
                    throw new InvalidOperationException("Credential Manager returned an invalid credential size.");
                }
 
                SecureString value = new SecureString();
                for (int offset = 0; offset < credential.CredentialBlobSize; offset += 2)
                {
                    value.AppendChar((char)Marshal.ReadInt16(credential.CredentialBlob, offset));
                }
 
                value.MakeReadOnly();
                return value;
            }
            finally
            {
                CredFree(credentialPointer);
            }
        }
 
        public static void Write(string target, SecureString secret, string userName)
        {
            if (secret == null || secret.Length == 0)
            {
                throw new ArgumentException("Credential must not be empty.", "secret");
            }
 
            int byteCount = checked(secret.Length * 2);
            if (byteCount > MaximumBlobBytes)
            {
                throw new ArgumentOutOfRangeException("secret", "Credential exceeds the Windows Credential Manager blob limit.");
            }
 
            IntPtr secretPointer = IntPtr.Zero;
            IntPtr blobPointer = IntPtr.Zero;
            try
            {
                secretPointer = Marshal.SecureStringToGlobalAllocUnicode(secret);
                blobPointer = Marshal.AllocHGlobal(byteCount);
                for (int offset = 0; offset < byteCount; offset++)
                {
                    Marshal.WriteByte(blobPointer, offset, Marshal.ReadByte(secretPointer, offset));
                }
 
                Credential credential = new Credential();
                credential.Type = CredentialTypeGeneric;
                credential.TargetName = target;
                credential.CredentialBlobSize = byteCount;
                credential.CredentialBlob = blobPointer;
                credential.Persist = CredentialPersistLocalMachine;
                credential.UserName = userName;
                if (!CredWriteW(ref credential, 0))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Credential Manager write failed.");
                }
            }
            finally
            {
                Clear(blobPointer, byteCount);
                if (blobPointer != IntPtr.Zero) Marshal.FreeHGlobal(blobPointer);
                if (secretPointer != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(secretPointer);
            }
        }
 
        public static bool Delete(string target)
        {
            if (CredDeleteW(target, CredentialTypeGeneric, 0)) return true;
            int error = Marshal.GetLastWin32Error();
            if (error == ErrorNotFound) return false;
            throw new Win32Exception(error, "Credential Manager removal failed.");
        }
    }
}
'@


    Add-Type -TypeDefinition $definition -ErrorAction Stop
}

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

    "CountdownDashboard_$CredentialName"
}

function Assert-SecretManagementCommands {
    [CmdletBinding()]
    param()

    $module = Get-Module -ListAvailable -Name Microsoft.PowerShell.SecretManagement |
        Sort-Object Version -Descending | Select-Object -First 1
    if ($null -eq $module) {
        throw 'The selected SecretManagement backend is unavailable.'
    }

    if ($null -eq (Get-Command Get-Secret -ErrorAction SilentlyContinue)) {
        Import-Module -Name $module.Path -ErrorAction Stop
    }
}

function New-CredentialStore {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('CredentialManager', 'SecretManagement', 'CliXml')]
        [string]$Backend,

        [Parameter()]
        [string]$VaultName,

        [Parameter()]
        [string]$CliXmlPath
    )

    if ($Backend -in @('CredentialManager', 'CliXml')) {
        Initialize-WindowsCredentialStoreType
    }

    if ($Backend -eq 'SecretManagement') {
        $module = Get-Module -ListAvailable -Name Microsoft.PowerShell.SecretManagement |
            Sort-Object Version -Descending | Select-Object -First 1
        if ($null -eq $module) {
            throw 'The selected SecretManagement backend is unavailable. Install Microsoft.PowerShell.SecretManagement or select another backend explicitly.'
        }

        Import-Module -Name $module.Path -ErrorAction Stop
    }

    if ($Backend -eq 'CliXml' -and [string]::IsNullOrWhiteSpace($CliXmlPath)) {
        $appData = [Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData)
        if ([string]::IsNullOrWhiteSpace($appData)) {
            throw 'The current user application-data directory is unavailable.'
        }

        $CliXmlPath = Join-Path $appData 'CountdownDashboard\api-keys.clixml'
    }

    [pscustomobject]@{
        Backend = $Backend
        VaultName = $VaultName
        CliXmlPath = if ([string]::IsNullOrWhiteSpace($CliXmlPath)) { $null } else { [System.IO.Path]::GetFullPath($CliXmlPath) }
        SyncRoot = [object]::new()
    }
}

function Import-CredentialMap {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Store
    )

    if (-not (Test-Path -LiteralPath $Store.CliXmlPath -PathType Leaf)) {
        return @{}
    }

    $map = Import-Clixml -LiteralPath $Store.CliXmlPath -ErrorAction Stop
    if ($map -isnot [System.Collections.IDictionary]) {
        throw 'The DPAPI credential file is corrupt or has an unsupported format.'
    }

    foreach ($entry in $map.GetEnumerator()) {
        if ($entry.Value -isnot [System.Security.SecureString]) {
            throw 'The DPAPI credential file contains a non-SecureString value.'
        }
    }

    return $map
}

function Export-CredentialMap {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Store,

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

    $directory = Split-Path -Parent $Store.CliXmlPath
    [void][System.IO.Directory]::CreateDirectory($directory)
    $temporaryPath = "$($Store.CliXmlPath).$([guid]::NewGuid().ToString('N')).tmp"
    try {
        Export-Clixml -InputObject $Map -LiteralPath $temporaryPath -ErrorAction Stop
        $verifiedMap = Import-Clixml -LiteralPath $temporaryPath -ErrorAction Stop
        if ($verifiedMap -isnot [System.Collections.IDictionary] -or
            $verifiedMap.Count -ne $Map.Count) {
            throw 'DPAPI credential-store verification failed.'
        }

        foreach ($entry in $verifiedMap.GetEnumerator()) {
            if ($entry.Value -isnot [System.Security.SecureString]) {
                throw 'DPAPI credential-store verification found an invalid value.'
            }
        }

        Move-Item -LiteralPath $temporaryPath -Destination $Store.CliXmlPath -Force
    }
    finally {
        if (Test-Path -LiteralPath $temporaryPath) {
            Remove-Item -LiteralPath $temporaryPath -Force
        }
    }
}

function Get-CredentialSecret {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Store,

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

    $target = Get-CredentialTargetName -CredentialName $CredentialName
    switch ($Store.Backend) {
        'CredentialManager' {
            return [PSExchangeClock.Native.WindowsCredentialStore]::Read($target)
        }
        'SecretManagement' {
            Assert-SecretManagementCommands
            $secretInfoParameters = @{ Name = $target; ErrorAction = 'Stop' }
            $secretParameters = @{ Name = $target; ErrorAction = 'Stop' }
            if (-not [string]::IsNullOrWhiteSpace($Store.VaultName)) {
                $secretInfoParameters.Vault = $Store.VaultName
                $secretParameters.Vault = $Store.VaultName
            }

            $secretInfo = @(Get-SecretInfo @secretInfoParameters)
            if ($secretInfo.Count -eq 0) {
                return $null
            }

            $secret = Get-Secret @secretParameters
            if ($secret -is [System.Security.SecureString]) {
                return $secret
            }
            if ($secret -is [string]) {
                return ConvertTo-SecureString -String $secret -AsPlainText -Force
            }

            throw 'The selected vault returned a credential in an unsupported format.'
        }
        'CliXml' {
            [System.Threading.Monitor]::Enter($Store.SyncRoot)
            try {
                $map = Import-CredentialMap -Store $Store
                if (-not $map.Contains($target)) {
                    return $null
                }

                return $map[$target]
            }
            finally {
                [System.Threading.Monitor]::Exit($Store.SyncRoot)
            }
        }
        default {
            throw "Unsupported credential backend '$($Store.Backend)'."
        }
    }
}

function Set-CredentialSecret {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Store,

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

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

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

    $target = Get-CredentialTargetName -CredentialName $CredentialName
    switch ($Store.Backend) {
        'CredentialManager' {
            [PSExchangeClock.Native.WindowsCredentialStore]::Write($target, $Secret, $CredentialName)
            return $true
        }
        'SecretManagement' {
            Assert-SecretManagementCommands
            $parameters = @{ Name = $target; Secret = $Secret; ErrorAction = 'Stop' }
            if (-not [string]::IsNullOrWhiteSpace($Store.VaultName)) {
                $parameters.Vault = $Store.VaultName
            }

            Set-Secret @parameters
            return $true
        }
        'CliXml' {
            [System.Threading.Monitor]::Enter($Store.SyncRoot)
            try {
                $map = Import-CredentialMap -Store $Store
                $map[$target] = $Secret
                Export-CredentialMap -Store $Store -Map $map
                $verified = $null
                try {
                    $verified = Get-CredentialSecret -Store $Store -CredentialName $CredentialName
                    if ($null -eq $verified) {
                        throw 'DPAPI credential-store read-back verification failed.'
                    }

                    return $true
                }
                finally {
                    if ($null -ne $verified) {
                        $verified.Dispose()
                    }
                }
            }
            finally {
                [System.Threading.Monitor]::Exit($Store.SyncRoot)
            }
        }
        default {
            throw "Unsupported credential backend '$($Store.Backend)'."
        }
    }
}

function Remove-CredentialSecret {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Store,

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

    $target = Get-CredentialTargetName -CredentialName $CredentialName
    switch ($Store.Backend) {
        'CredentialManager' {
            return [PSExchangeClock.Native.WindowsCredentialStore]::Delete($target)
        }
        'SecretManagement' {
            Assert-SecretManagementCommands
            $infoParameters = @{ Name = $target; ErrorAction = 'Stop' }
            $removeParameters = @{ Name = $target; ErrorAction = 'Stop' }
            if (-not [string]::IsNullOrWhiteSpace($Store.VaultName)) {
                $infoParameters.Vault = $Store.VaultName
                $removeParameters.Vault = $Store.VaultName
            }

            if (@(Get-SecretInfo @infoParameters).Count -eq 0) {
                return $false
            }

            Remove-Secret @removeParameters
            return $true
        }
        'CliXml' {
            [System.Threading.Monitor]::Enter($Store.SyncRoot)
            try {
                $map = Import-CredentialMap -Store $Store
                if (-not $map.Contains($target)) {
                    return $false
                }

                [void]$map.Remove($target)
                Export-CredentialMap -Store $Store -Map $map
                return $true
            }
            finally {
                [System.Threading.Monitor]::Exit($Store.SyncRoot)
            }
        }
        default {
            throw "Unsupported credential backend '$($Store.Backend)'."
        }
    }
}