Private/Application/Diagnostics.ps1

$script:diagnosticSecretFieldPattern = '(?i)(credential|api.?key|password|token|secret|authorization|auth.?header)'
$script:diagnosticPrivateFieldPattern = '(?i)(portfolio|transaction|holding|position|ledger|cost.?basis|account.?balance|share.?count|quantity|trade)'

function ConvertTo-SanitizedDiagnosticText {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Text,

        [Parameter()]
        [string[]]$SensitiveValues = @()
    )

    $safeText = [regex]::Replace(
        $Text,
        '(?i)([?&](?:api[-_]?key|key|token|secret|password|access[-_]?token|authorization)=)[^&\s#]+',
        '$1[REDACTED]'
    )
    $safeText = [regex]::Replace(
        $safeText,
        '(?i)\b(api[-_\s]?key|password|token|secret|access[-_\s]?token)\s*[:=]\s*[^,;\s]+',
        '$1=[REDACTED]'
    )
    $safeText = [regex]::Replace(
        $safeText,
        '(?i)\b(authorization|auth[\s_-]?header)\s*[:=]\s*(?:Bearer\s+)?[^,;\s]+(?:\s+[^,;\s]+)?',
        '$1=[REDACTED]'
    )
    $safeText = [regex]::Replace($safeText, '(?i)\bBearer\s+[^\s,;]+', 'Bearer [REDACTED]')
    $safeText = [regex]::Replace($safeText, '(?i)(https?://)[^:/@\s]+:[^/@\s]+@', '$1[REDACTED]@')
    $safeText = [regex]::Replace(
        $safeText,
        '(?i)\b(portfolio(?:[\s_-]?(?:value|balance|amount))?|transaction(?:[\s_-]?(?:value|amount))?|cost[\s_-]?basis|account[\s_-]balance|holding[\s_-]value)\s*[:=]\s*[^;\s]+',
        '$1=[REDACTED]'
    )

    foreach ($sensitiveValue in $SensitiveValues) {
        if (-not [string]::IsNullOrEmpty($sensitiveValue)) {
            $safeText = $safeText.Replace($sensitiveValue, '[REDACTED]', [System.StringComparison]::Ordinal)
        }
    }

    $safeText
}

function ConvertTo-SanitizedDiagnosticValue {
    [CmdletBinding()]
    param(
        [Parameter()]
        [AllowNull()]
        [object]$Value,

        [Parameter()]
        [string[]]$SensitiveValues = @()
    )

    if ($null -eq $Value) {
        return $null
    }
    if ($Value -is [string]) {
        return ConvertTo-SanitizedDiagnosticText -Text $Value -SensitiveValues $SensitiveValues
    }
    if ($Value -is [System.Security.SecureString]) {
        throw 'SecureString values are not allowed in diagnostics.'
    }
    if ($Value -is [System.Collections.IDictionary]) {
        $sanitized = [ordered]@{}
        foreach ($entry in $Value.GetEnumerator()) {
            $fieldName = [string]$entry.Key
            if ($fieldName -match $script:diagnosticSecretFieldPattern -or
                $fieldName -match $script:diagnosticPrivateFieldPattern) {
                throw "Diagnostic context contains a forbidden field name '$fieldName'."
            }

            $sanitized[$fieldName] = ConvertTo-SanitizedDiagnosticValue `
                -Value $entry.Value -SensitiveValues $SensitiveValues
        }
        return $sanitized
    }
    if ($Value -is [pscustomobject]) {
        $properties = [ordered]@{}
        foreach ($property in $Value.PSObject.Properties) {
            $properties[$property.Name] = $property.Value
        }
        return ConvertTo-SanitizedDiagnosticValue -Value $properties -SensitiveValues $SensitiveValues
    }
    if ($Value -is [datetime]) {
        return $Value.ToUniversalTime().ToString('o', [System.Globalization.CultureInfo]::InvariantCulture)
    }
    if ($Value -is [bool] -or
        $Value -is [byte] -or $Value -is [sbyte] -or
        $Value -is [int16] -or $Value -is [uint16] -or
        $Value -is [int32] -or $Value -is [uint32] -or
        $Value -is [int64] -or $Value -is [uint64] -or
        $Value -is [single] -or $Value -is [double] -or $Value -is [decimal]) {
        return $Value
    }
    if ($Value -is [System.Collections.IEnumerable]) {
        $items = [System.Collections.Generic.List[object]]::new()
        foreach ($item in $Value) {
            $items.Add((ConvertTo-SanitizedDiagnosticValue -Value $item -SensitiveValues $SensitiveValues))
        }
        return ,@($items)
    }

    throw "Unsupported diagnostic value type '$($Value.GetType().FullName)'."
}

function New-DiagnosticRecord {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('Debug', 'Information', 'Warning', 'Error', 'Critical')]
        [string]$Severity,

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

        [Parameter(Mandatory)]
        [string]$Message,

        [Parameter()]
        [System.Collections.IDictionary]$Context = @{},

        [Parameter()]
        [string[]]$SensitiveValues = @()
    )

    [pscustomobject]@{
        TimestampUtc = [datetime]::UtcNow.ToString('o', [System.Globalization.CultureInfo]::InvariantCulture)
        Severity = $Severity
        Category = $Category
        Message = ConvertTo-SanitizedDiagnosticText -Text $Message -SensitiveValues $SensitiveValues
        Context = ConvertTo-SanitizedDiagnosticValue -Value $Context -SensitiveValues $SensitiveValues
    }
}

function Write-DiagnosticRecord {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string]$Path,

        [Parameter(Mandatory)]
        [ValidateSet('Debug', 'Information', 'Warning', 'Error', 'Critical')]
        [string]$Severity,

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

        [Parameter(Mandatory)]
        [string]$Message,

        [Parameter()]
        [System.Collections.IDictionary]$Context = @{},

        [Parameter()]
        [string[]]$SensitiveValues = @()
    )

    if ([string]::IsNullOrWhiteSpace($Path)) {
        $appData = [Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData)
        if ([string]::IsNullOrWhiteSpace($appData)) {
            throw 'The current user application-data directory is unavailable for diagnostics.'
        }
        $Path = Join-Path $appData 'PSExchangeClock\Logs\diagnostics.jsonl'
    }

    $record = New-DiagnosticRecord -Severity $Severity -Category $Category `
        -Message $Message -Context $Context -SensitiveValues $SensitiveValues
    $directory = Split-Path -Parent $Path
    if (-not [string]::IsNullOrWhiteSpace($directory)) {
        [void][System.IO.Directory]::CreateDirectory($directory)
    }
    $json = ConvertTo-Json -InputObject $record -Depth 10 -Compress
    Add-Content -LiteralPath $Path -Value $json -Encoding utf8 -ErrorAction Stop
    $record
}