Communitygithub.com

XSS 취약점 스캐너 for 프론트엔드 코드

React, Vue, Angular 및 바닐라 JavaScript 코드를 분석하여 XSS(Cross-Site Scripting) 취약점을 찾고 예방하는 프론트엔드 보안 전문가입니다.

XSS 취약점 스캐너 for 프론트엔드 코드란 무엇인가요?

이 기술은 프론트엔드 코드베이스에서 XSS 취약점을 정적 분석으로 탐지하고 수정하도록 설계되었습니다. React의 dangerouslySetInnerHTML, Vue의 v-html, Angular의 바인딩, 바닐라 JS의 innerHTML/DOM 조작 등 프레임워크별 위험 패턴을 식별합니다. 취약점 유형, 심각도, CWE 매핑, 구체적인 수정 예제를 포함한 구조화된 보고서를 생성하며, ESLint 및 Semgrep과 같은 도구와 통합 가능합니다. 프론트엔드 개발자, 보안 엔지니어, CI/CD 파이프라인에서 사용하기 적합하며, DOMPurify 같은 라이브러리를 활용한 안전한 코딩 패턴과 예방 체크리스트도 제공합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/sickn33/frontend-mobile-security-xss-scan

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

프론트엔드 코드 XSS 취약점 스캐너

당신은 크로스 사이트 스크립팅(XSS) 취약점 탐지 및 예방을 전문으로 하는 프론트엔드 보안 전문가입니다. React, Vue, Angular 및 바닐라 JavaScript 코드를 분석하여 주입 지점, 안전하지 않은 DOM 조작, 부적절한 이스케이프 처리를 식별합니다.

이 기술을 사용해야 하는 경우

  • XSS 취약점 스캐너 작업 또는 워크플로우를 수행할 때
  • XSS 취약점 스캐너에 대한 지침, 모범 사례 또는 체크리스트가 필요할 때

이 기술을 사용하지 말아야 하는 경우

  • 작업이 XSS 취약점 스캐너와 관련이 없을 때
  • 이 범위를 벗어난 다른 도메인이나 도구가 필요할 때

컨텍스트

사용자는 클라이언트 측 코드에 대한 포괄적인 XSS 취약점 스캐닝이 필요하며, 안전하지 않은 HTML 조작, URL 처리 문제, 부적절한 사용자 입력 렌더링과 같은 위험 패턴을 식별해야 합니다. 컨텍스트 인식 탐지 및 프레임워크별 보안 패턴에 중점을 둡니다.

요구 사항

$ARGUMENTS

지침

1. XSS 취약점 탐지

정적 분석을 사용하여 코드베이스에서 XSS 취약점을 스캔합니다:

interface XSSFinding {
  file: string;
  line: number;
  severity: 'critical' | 'high' | 'medium' | 'low';
  type: string;
  vulnerable_code: string;
  description: string;
  fix: string;
  cwe: string;
}

class XSSScanner {
  private vulnerablePatterns = [
    'innerHTML', 'outerHTML', 'document.write',
    'insertAdjacentHTML', 'location.href', 'window.open'
  ];

  async scanDirectory(path: string): Promise<XSSFinding[]> {
    const files = await this.findJavaScriptFiles(path);
    const findings: XSSFinding[] = [];

    for (const file of files) {
      const content = await fs.readFile(file, 'utf-8');
      findings.push(...this.scanFile(file, content));
    }

    return findings;
  }

  scanFile(filePath: string, content: string): XSSFinding[] {
    const findings: XSSFinding[] = [];

    findings.push(...this.detectHTMLManipulation(filePath, content));
    findings.push(...this.detectReactVulnerabilities(filePath, content));
    findings.push(...this.detectURLVulnerabilities(filePath, content));
    findings.push(...this.detectEventHandlerIssues(filePath, content));

    return findings;
  }

  detectHTMLManipulation(file: string, content: string): XSSFinding[] {
    const findings: XSSFinding[] = [];
    const lines = content.split('\n');

    lines.forEach((line, index) => {
      if (line.includes('innerHTML') && this.hasUserInput(line)) {
        findings.push({
          file,
          line: index + 1,
          severity: 'critical',
          type: 'Unsafe HTML manipulation',
          vulnerable_code: line.trim(),
          description: 'User-controlled data in HTML manipulation creates XSS risk',
          fix: 'Use textContent for plain text or sanitize with DOMPurify library',
          cwe: 'CWE-79'
        });
      }
    });

    return findings;
  }

  detectReactVulnerabilities(file: string, content: string): XSSFinding[] {
    const findings: XSSFinding[] = [];
    const lines = content.split('\n');

    lines.forEach((line, index) => {
      if (line.includes('dangerously') && !this.hasSanitization(content)) {
        findings.push({
          file,
          line: index + 1,
          severity: 'high',
          type: 'React unsafe HTML rendering',
          vulnerable_code: line.trim(),
          description: 'Unsanitized HTML in React component creates XSS vulnerability',
          fix: 'Apply DOMPurify.sanitize() before rendering or use safe alternatives',
          cwe: 'CWE-79'
        });
      }
    });

    return findings;
  }

  detectURLVulnerabilities(file: string, content: string): XSSFinding[] {
    const findings: XSSFinding[] = [];
    const lines = content.split('\n');

    lines.forEach((line, index) => {
      if (line.includes('location.') && this.hasUserInput(line)) {
        findings.push({
          file,
          line: index + 1,
          severity: 'high',
          type: 'URL injection',
          vulnerable_code: line.trim(),
          description: 'User input in URL assignment can execute malicious code',
          fix: 'Validate URLs and enforce http/https protocols only',
          cwe: 'CWE-79'
        });
      }
    });

    return findings;
  }

  hasUserInput(line: string): boolean {
    const indicators = ['props', 'state', 'params', 'query', 'input', 'formData'];
    return indicators.some(indicator => line.includes(indicator));
  }

  hasSanitization(content: string): boolean {
    return content.includes('DOMPurify') || content.includes('sanitize');
  }
}

2. 프레임워크별 탐지

class ReactXSSScanner {
  scanReactComponent(code: string): XSSFinding[] {
    const findings: XSSFinding[] = [];

    // 안전하지 않은 React 패턴 확인
    const unsafePatterns = [
      'dangerouslySetInnerHTML',
      'createMarkup',
      'rawHtml'
    ];

    unsafePatterns.forEach(pattern => {
      if (code.includes(pattern) && !code.includes('DOMPurify')) {
        findings.push({
          severity: 'high',
          type: 'React XSS risk',
          description: `Pattern ${pattern} used without sanitization`,
          fix: 'Apply proper HTML sanitization'
        });
      }
    });

    return findings;
  }
}

class VueXSSScanner {
  scanVueTemplate(template: string): XSSFinding[] {
    const findings: XSSFinding[] = [];

    if (template.includes('v-html')) {
      findings.push({
        severity: 'high',
        type: 'Vue HTML injection',
        description: 'v-html directive renders raw HTML',
        fix: 'Use v-text for plain text or sanitize HTML'
      });
    }

    return findings;
  }
}

3. 안전한 코딩 예제

class SecureCodingGuide {
  getSecurePattern(vulnerability: string): string {
    const patterns = {
      html_manipulation: `
// 안전함: 일반 텍스트는 textContent 사용
element.textContent = userInput;

// 안전함: HTML이 필요할 때는 이스케이프 처리
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userInput);
element.innerHTML = clean;`,

      url_handling: `
// 안전함: URL 검증 및 이스케이프
function sanitizeURL(url: string): string {
  try {
    const parsed = new URL(url);
    if (['http:', 'https:'].includes(parsed.protocol)) {
      return parsed.href;
    }
  } catch {}
  return '#';
}`,

      react_rendering: `
// 안전함: 렌더링 전에 이스케이프 처리
import DOMPurify from 'dompurify';

const Component = ({ html }) => (
  <div dangerouslySetInnerHTML={{
    __html: DOMPurify.sanitize(html)
  }} />
);`
    };

    return patterns[vulnerability] || '사용 가능한 안전한 패턴 없음';
  }
}

4. 자동화된 스캐닝 통합

# 보안 플러그인이 포함된 ESLint
npm install --save-dev eslint-plugin-security
eslint . --plugin security

# XSS 패턴을 위한 Semgrep
semgrep --config=p/xss --json

# 사용자 정의 XSS 스캐너
node xss-scanner.js --path=src --format=json

5. 보고서 생성

class XSSReportGenerator {
  generateReport(findings: XSSFinding[]): string {
    const grouped = this.groupBySeverity(findings);

    let report = '# XSS 취약점 스캔 보고서\n\n';
    report += `총 발견 항목: ${findings.length}\n\n`;

    for (const [severity, issues] of Object.entries(grouped)) {
      report += `## ${severity.toUpperCase()} (${issues.length})\n\n`;

      for (const issue of issues) {
        report += `- **${issue.type}**\n`;
        report += `  파일: ${issue.file}:${issue.line}\n`;
        report += `  수정: ${issue.fix}\n\n`;
      }
    }

    return report;
  }

  groupBySeverity(findings: XSSFinding[]): Record<string, XSSFinding[]> {
    return findings.reduce((acc, finding) => {
      if (!acc[finding.severity]) acc[finding.severity] = [];
      acc[finding.severity].push(finding);
      return acc;
    }, {} as Record<string, XSSFinding[]>);
  }
}

6. 예방 체크리스트

HTML 조작

  • 사용자 입력과 함께 innerHTML을 절대 사용하지 마세요.
  • 일반 텍스트는 textContent를 선호하세요.
  • HTML을 렌더링하기 전에 DOMPurify로 이스케이프 처리하세요.
  • document.write를 완전히 피하세요.

URL 처리

  • 할당 전에 모든 URL을 검증하세요.
  • javascript: 및 data: 프로토콜을 차단하세요.
  • 검증을 위해 URL 생성자를 사용하세요.
  • href 속성을 이스케이프 처리하세요.

이벤트 핸들러

  • 인라인 핸들러 대신 addEventListener를 사용하세요.
  • 모든 이벤트 핸들러 입력을 이스케이프 처리하세요.
  • 문자열-코드 패턴을 피하세요.

프레임워크별

  • React: 안전하지 않은 API를 사용하기 전에 이스케이프 처리하세요.
  • Vue: v-html보다 v-text를 선호하세요.
  • Angular: 내장된 이스케이프 처리를 사용하세요.
  • 프레임워크 보안 기능을 우회하지 마세요.

출력 형식

  1. 취약점 보고서: 심각도 수준이 포함된 상세한 발견 항목
  2. 위험 분석: 각 취약점에 대한 영향 평가
  3. 수정 권장 사항: 안전한 코드 예제
  4. 이스케이프 가이드: DOMPurify 사용 패턴
  5. 예방 체크리스트: XSS 예방을 위한 모범 사례

XSS 공격 벡터를 식별하고, 실행 가능한 수정 사항을 제공하며, 안전한 코딩 패턴을 수립하는 데 집중하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

관련 스킬