# output-exfiltration-scanner.ps1 -- PostToolUse hook
#
# Detects potential data exfiltration attempts in tool outputs:
#   - Encoded data (base64 blobs, hex dumps)
#   - Sensitive patterns in outputs (credentials, tokens)
#   - Suspicious URL patterns in outputs
#
# T-048: Output exfiltration scanning.
#
# @connexum/ai-governance

$rawInput = [Console]::In.ReadToEnd()

if ([string]::IsNullOrWhiteSpace($rawInput)) { exit 0 }

try { $input_obj = $rawInput | ConvertFrom-Json } catch { exit 0 }

$toolName = if ($input_obj.tool_name) { $input_obj.tool_name } else { '' }
$toolOutput = if ($input_obj.tool_output) { $input_obj.tool_output.ToString() }
               elseif ($input_obj.output) { $input_obj.output.ToString() }
               else { '' }

if (-not $toolOutput) { exit 0 }

$violations = @()

# 1. Large base64 blobs (>500 chars of continuous base64)
if ($toolOutput -match '[A-Za-z0-9+/]{500,}={0,2}') {
    $violations += 'Large base64 blob detected in output (potential encoded data exfiltration)'
}

# 2. Long hex dumps (>200 chars of continuous hex)
if ($toolOutput -match '([0-9a-fA-F]{2}\s?){100,}') {
    $violations += 'Large hex dump in output (potential binary data exfiltration)'
}

# 3. Credential patterns in output
if ($toolOutput -match '(?i)(api[_-]?key|secret[_-]?key|access[_-]?token|bearer|authorization)\s*[:=]\s*[A-Za-z0-9+/_.=-]{20,}') {
    $violations += 'Credential/token pattern detected in output'
}

# 4. AWS-style keys in output
if ($toolOutput -match 'AKIA[0-9A-Z]{16}') {
    $violations += 'AWS access key detected in output'
}

# 5. Private key material
if ($toolOutput -match '-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----') {
    $violations += 'Private key material detected in output'
}

# 6. Connection strings with credentials
if ($toolOutput -match '(?i)(postgres|mysql|mongodb|redis)://[^:]+:[^@]+@') {
    $violations += 'Database connection string with credentials in output'
}

# 7. JWT tokens
if ($toolOutput -match 'eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}') {
    $violations += 'JWT token detected in output'
}

# Report violations
$logDir = if ($env:GOVERNANCE_LOG_DIR) { $env:GOVERNANCE_LOG_DIR } else { Join-Path $env:TEMP 'governance/logs' }
try { New-Item -ItemType Directory -Path $logDir -Force | Out-Null } catch { }
$logFile = Join-Path $logDir 'exfiltration-scan.jsonl'

if ($violations.Count -gt 0) {
    $timestamp = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')

    foreach ($violation in $violations) {
        $entry = @{
            timestamp = $timestamp
            tool = $toolName
            violation = $violation
            action = 'WARN'
        } | ConvertTo-Json -Compress

        try { Add-Content -Path $logFile -Value $entry -ErrorAction SilentlyContinue } catch { }
        [Console]::Error.WriteLine("EXFILTRATION WARNING: $violation (tool: $toolName)")
    }

    exit 0
}

exit 0
