// check-rsc-vuln.js
const fs = require('fs');
const path = require('path');

const vulnerableRanges = [
  { name: 'react-server-dom-webpack', versions: ['19.0.0', '19.1.0', '19.1.1', '19.2.0'] },
  { name: 'react-server-dom-parcel', versions: ['19.0.0', '19.1.0', '19.1.1', '19.2.0'] },
  { name: 'react-server-dom-turbopack', versions: ['19.0.0', '19.1.0', '19.1.1', '19.2.0'] },
];

function checkPackageJson(dir) {
  const packagePath = path.join(dir, 'package.json');
  if (!fs.existsSync(packagePath)) {
    console.log('❌ package.json tidak ditemukan di folder ini.');
    return;
  }

  const pkg = JSON.parse(fs.readFileSync(packagePath));

  console.log('🔍 Mengecek dependency...');

  let foundVulnerability = false;

  vulnerableRanges.forEach(({ name, versions }) => {
    const version =
      (pkg.dependencies && pkg.dependencies[name]) ||
      (pkg.devDependencies && pkg.devDependencies[name]);

    if (version) {
      const cleaned = version.replace(/^[^\d]*/, ''); // Remove ^ ~ etc
      if (versions.includes(cleaned)) {
        foundVulnerability = true;
        console.log(`❌ RENTAN: ${name}@${cleaned} — mengandung celah CVE-2025-55182`);
      } else {
        console.log(`✔ Aman: ${name}@${cleaned}`);
      }
    }
  });

  if (!foundVulnerability) {
    console.log('\n✅ Tidak ditemukan versi yang rentan. Proyek kamu AMAN.');
  } else {
    console.log(
      '\n⚠ ACTION: Segera jalankan update:\n  npm install react-server-dom-webpack@latest'
    );
  }
}

checkPackageJson(process.cwd());
