#!/bin/bash
set -euo pipefail

ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
WORKDIR="/tmp/haraka_verify_fix"
LOGFILE="$ROOT/coding/verify_fix.log"
PATCH_FILE="$ROOT/coding/proposed_fix.diff"

mkdir -p "$ROOT/coding"
: > "$LOGFILE"

log() {
    echo "$1" | tee -a "$LOGFILE"
}

log "[+] Starting verification for CVE-2026-34752 fix"
log "[+] Using patch: $PATCH_FILE"

if [ ! -f "$PATCH_FILE" ]; then
    log "[-] Patch file not found"
    exit 1
fi

rm -rf "$WORKDIR"
mkdir -p "$WORKDIR"
cd "$WORKDIR"

cat > package.json << 'EOF'
{
  "name": "haraka-verify-fix",
  "version": "1.0.0",
  "private": true
}
EOF

log "[+] Installing vulnerable baseline package haraka-email-message@1.2.0"
npm install haraka-email-message@1.2.0 >> "$LOGFILE" 2>&1

cat > verify_harness.js << 'EOF'
const mode = process.argv[2]
const EmailMessage = require('haraka-email-message')
const Header = EmailMessage.Header

function parseLines(lines) {
  const h = new Header()
  h.parse(lines)
  return h
}

function expectNoCrash(payload, label) {
  try {
    parseLines([
      'From: attacker@evil.com',
      `${payload}: crash`,
    ])
    return true
  } catch (e) {
    console.error(`[-] ${label} crashed: ${e.message}`)
    return false
  }
}

let crashErr = null
try {
  parseLines([
    'From: attacker@evil.com',
    '__proto__: crash',
  ])
} catch (e) {
  crashErr = e
}

if (mode === 'vuln') {
  if (!crashErr) {
    console.error('[-] Expected vulnerable crash but parse succeeded')
    process.exit(1)
  }
  console.log(`[+] Vulnerable behavior confirmed: ${crashErr.message}`)
  process.exit(0)
}

if (mode === 'fixed') {
  if (crashErr) {
    console.error(`[-] Patched code still crashes on __proto__: ${crashErr.message}`)
    process.exit(1)
  }

  // Ensure normal behavior still works
  const normal = parseLines([
    'From: test@example.com',
    'Subject: Hello',
  ])
  if (!normal.get('from').includes('test@example.com')) {
    console.error('[-] Regression: normal headers no longer parse correctly')
    process.exit(1)
  }

  // Variant hardening checks
  if (!expectNoCrash('__PROTO__', 'uppercase __PROTO__')) process.exit(1)
  if (!expectNoCrash('constructor', 'constructor')) process.exit(1)
  if (!expectNoCrash('prototype', 'prototype')) process.exit(1)

  console.log('[+] Patched behavior confirmed: no crash and normal parsing preserved')
  process.exit(0)
}

console.error('Usage: node verify_harness.js <vuln|fixed>')
process.exit(2)
EOF

log "[+] Verifying baseline is vulnerable"
node verify_harness.js vuln | tee -a "$LOGFILE"

log "[+] Applying proposed patch"
patch -p1 -d "$WORKDIR/node_modules/haraka-email-message" < "$PATCH_FILE" >> "$LOGFILE" 2>&1

log "[+] Verifying patched package is not vulnerable"
node verify_harness.js fixed | tee -a "$LOGFILE"

log "[+] Verification successful"
