สรุป: XSS คืออะไร และทำไมต้องจัดการใน AI Output?

XSS (Cross-Site Scripting) เป็นช่องโหว่ด้านความปลอดภัยที่พบได้บ่อยเมื่อนำผลลัพธ์จาก AI มาแสดงบนหน้าเว็บ เมื่อ AI สร้างเนื้อหาที่มีโค้ด HTML หรือ JavaScript แทรก และเราแสดงผลโดยไม่ sanitise อย่างเหมาะสม ผู้โจมตีสามารถใช้ช่องโหว่นี้ขโมย session, เปลี่ยนเส้นทางผู้ใช้ หรือดึงข้อมูลส่วนตัวได้ ในบทความนี้เราจะอธิบายวิธีป้องกันอย่างเป็นระบบ

วิธีการป้องกัน XSS ใน AI Output

มีหลายวิธีในการจัดการ XSS ขึ้นอยู่กับภาษาที่ใช้ วิธีที่นิยมใช้กันมากคือการใช้ฟังก์ชัน HTML escape และการใช้ Content Security Policy (CSP)

1. การใช้ HTML Entity Encoding

วิธีพื้นฐานที่สุดคือการแปลงอักขระพิเศษเป็น HTML entities ป้องกันไม่ให้โค้ดถูกตีความว่าเป็นโค้ด HTML จริง

// ตัวอย่างการใช้งานใน JavaScript (Node.js)
const escapeHtml = (text) => {
  const map = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": '''
  };
  return text.replace(/[&<>"']/g, (m) => map[m]);
};

// ตัวอย่างการใช้งานกับ AI response
const aiResponse = await fetch('https://api.holysheep.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': Bearer YOUR_HOLYSHEEP_API_KEY
  },
  body: JSON.stringify({
    model: 'gpt-4.1',
    messages: [{ role: 'user', content: 'อธิบายเรื่อง XSS' }]
  })
});

const data = await aiResponse.json();
const safeOutput = escapeHtml(data.choices[0].message.content);
document.getElementById('output').innerHTML = safeOutput;

2. การใช้ DOMPurify (แนะนำสำหรับ Frontend)

สำหรับการพัฒนาเว็บไซต์แบบ Frontend แนะนำให้ใช้ DOMPurify ซึ่งเป็นไลบรารีที่ได้รับการพิสูจน์แล้วว่าปลอดภัย

<!-- นำเข้า DOMPurify ผ่าน CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script>

<script>
  // ฟังก์ชันสำหรับ sanitize AI output
  const sanitizeAIOutput = (htmlContent) => {
    return DOMPurify.sanitize(htmlContent, {
      ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p', 'br', 'ul', 'li', 'ol', 'h1', 'h2', 'h3', 'code', 'pre'],
      ALLOWED_ATTR: ['class'],
      FORBID_TAGS: ['script', 'style', 'iframe', 'form', 'input'],
      FORBID_ATTR: ['onerror', 'onclick', 'onload', 'onmouseover']
    });
  };

  // ตัวอย่างการใช้งาน
  async function getAIResponse() {
    const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_HOLYSHEEP_API_KEY'
      },
      body: JSON.stringify({
        model: 'claude-sonnet-4.5',
        messages: [{ role: 'user', content: 'เขียนโค้ด JavaScript ให้หน่อย' }]
      })
    });
    
    const data = await response.json();
    const rawOutput = data.choices[0].message.content;
    const safeOutput = sanitizeAIOutput(rawOutput);
    
    document.getElementById('chat-container').innerHTML = safeOutput;
  }
</script>

3. การใช้ CSP (Content Security Policy)

เพิ่ม HTTP Header เพื่อบอกเบราว์เซอร์ว่าอนุญาตให้โหลด script ได้จากที่ไหน

// ตัวอย่างการตั้งค่า CSP ใน Express.js
app.use((req, res, next) => {
  res.setHeader(
    'Content-Security-Policy',
    "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline';"
  );
  next();
});

// หรือใน Nginx
// add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com;";

ตารางเปรียบเทียบบริการ AI API ยอดนิยม

บริการ ราคา ($/MTok) ความหน่วง (Latency) วิธีชำระเงิน โมเดลที่รองรับ กลุ่มเป้าหมาย
HolySheep AI สมัครที่นี่ GPT-4.1: $8, Claude 4.5: $15, Gemini 2.5: $2.50, DeepSeek V3.2: $0.42 <50ms WeChat, Alipay, บัตรเครดิต GPT-4.1, Claude Sonnet 4.5, Gemini 2.5 Flash, DeepSeek V3.2 นักพัฒนาทั่วโลก, ผู้ใช้ในจีน, สตาร์ทอัพ
OpenAI API GPT-4o: $15, GPT-4o-mini: $0.60 100-500ms บัตรเครดิตเท่านั้น GPT-4o, GPT-4o-mini, o1 องค์กรใหญ่, นักพัฒนาตะวันตก
Anthropic API Claude 3.5 Sonnet: $15, Claude 3.5 Haiku: $0.80 150-600ms บัตรเครดิตเท่านั้น Claude 3.5 Sonnet, Claude 3.5 Haiku, Claude 3 Opus องค์กรที่ต้องการ AI ที่ปลอดภัยสูง
Google Gemini API Gemini 1.5 Pro: $7, Gemini 1.5 Flash: $0.70 80-400ms บัตรเครดิต, Google Pay Gemini 1.5 Pro, Gemini 1.5 Flash, Gemini 2.0 นักพัฒนา Google Ecosystem
DeepSeek API DeepSeek V3: $0.27, DeepSeek Coder: $0.14 60-200ms WeChat, Alipay DeepSeek V3, DeepSeek Coder V2 นักพัฒนาในจีน, งานเขียนโค้ด

วิเคราะห์ความคุ้มค่า

จากตารางจะเห็นได้ว่า HolySheep AI มีความได้เปรียบด้านราคาอย่างมาก โดยเฉพาะอัตราแลกเปลี่ยนที่ ¥1=$1 ทำให้ประหยัดได้ถึง 85% เมื่อเทียบกับการซื้อผ่านช่องทางอื่น นอกจากนี้ยังรองรับ WeChat และ Alipay ทำให้สะดวกสำหรับผู้ใช้ในประเทศจีน และมีความหน่วงต่ำกว่าค่าเฉลี่ยที่ <50ms

ตัวอย่างการนำไปใช้งานจริง

ต่อไปนี้คือตัวอย่างการสร้างแอปพลิเคชัน Chat ที่ปลอดภัยจาก XSS โดยใช้ HolySheep AI

<!-- index.html -->
<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI Chat - XSS Safe Demo</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script>
  <style>
    #chat-box { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: auto; }
    .user-msg { color: blue; }
    .ai-msg { color: green; background: #f9f9f9; padding: 5px; }
    pre { background: #eee; padding: 10px; overflow-x: auto; }
  </style>
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com;">
</head>
<body>
  <h1>AI Chat ที่ปลอดภัยจาก XSS</h1>
  <div id="chat-box"></div>
  <textarea id="user-input" rows="3" style="width:100%; margin-top:10px;" placeholder="พิมพ์ข้อความ..."></textarea>
  <button onclick="sendMessage()" style="margin-top:10px; padding:10px 20px;">ส่ง</button>

  <script>
    const API_KEY = 'YOUR_HOLYSHEEP_API_KEY';
    const API_URL = 'https://api.holysheep.ai/v1/chat/completions';
    
    const sanitizeAndDisplay = (content, isUser) => {
      const chatBox = document.getElementById('chat-box');
      const div = document.createElement('div');
      div.className = isUser ? 'user-msg' : 'ai-msg';
      // Sanitize ทุกข้อความก่อนแสดง
      div.textContent = content;
      chatBox.appendChild(div);
      chatBox.scrollTop = chatBox.scrollHeight;
    };

    const sendMessage = async () => {
      const input = document.getElementById('user-input');
      const message = input.value.trim();
      if (!message) return;

      sanitizeAndDisplay('คุณ: ' + message, true);
      input.value = '';

      try {
        const response = await fetch(API_URL, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': \Bearer \${API_KEY}\
          },
          body: JSON.stringify({
            model: 'deepseek-v3.2',
            messages: [{ role: 'user', content: message }],
            max_tokens: 1000
          })
        });

        const data = await response.json();
        const aiReply = data.choices[0].message.content;
        sanitizeAndDisplay('AI: ' + aiReply, false);
      } catch (error) {
        sanitizeAndDisplay('เกิดข้อผิดพลาด: ' + error.message, false);
      }
    };
  </script>
</body>
</html>

ข้อผิดพลาดที่พบบ่อยและวิธีแก้ไข

1. ข้อผิดพลาด: innerHTML โดยตรงกับ AI Output

ปัญหา: การใช้ innerHTML กับข้อความจาก AI โดยตรงทำให้โค้ด JavaScript ถูก execute ได้

// ❌ วิธีที่ไม่ถูกต้อง
document.getElementById('output').innerHTML = aiResponse.content;

// ✅ วิธีที่ถูกต้อง
document.getElementById('output').textContent = aiResponse.content;
// หรือ
document.getElementById('output').innerHTML = DOMPurify.sanitize(aiResponse.content);

2. ข้อผิดพลาด: ลืม Sanitize กรณีที่ผู้ใช้ Copy-Paste

ปัญหา: เมื่อผู้ใช้ copy ข้อความจาก AI output แล้ววางที่อื่น อาจมีโค้ด XSS ติดมาด้วย

// ❌ ปัญหา: clipboard อาจมี HTML ที่เป็นอันตราย
const text = await navigator.clipboard.readText();

// ✅ วิธีแก้ไข: สร้าง temporary element เพื่อ sanitize
const sanitizeClipboard = async () => {
  const text = await navigator.clipboard.readText();
  const temp = document.createElement('div');
  temp.textContent = text; // ป้องกัน HTML ทั้งหมด
  return temp.innerHTML;
};

3. ข้อผิดพลาด: การใช้ eval() กับ AI Code Output

ปัญหา: AI อาจสร้างโค้ดที่มี XSS payload และถ้าเรา eval ก็จะถูก execute

// ❌ อันตรายมาก!
const aiGeneratedCode = getAIResponse();
eval(aiGeneratedCode); // หรือ Function(aiGeneratedCode)()

// ✅ วิธีที่ถูกต้อง: แสดงผลเป็น code block ไม่ใช่ execute
const displayCode = (code) => {
  const sanitized = DOMPurify.sanitize(code, { ALLOWED_TAGS: ['code', 'pre'] });
  const pre = document.createElement('pre');
  const codeEl = document.createElement('code');
  codeEl.textContent = code; // ใช้ textContent ไม่ใช่ innerHTML
  pre.appendChild(codeEl);
  document.body.appendChild(pre);
};

4. ข้อผิดพลาด: ไม่ตั้งค่า CSP อย่างเข้มงวด

ปัญหา: CSP ที่ไม่เข้มงวดพอสามารถถูก bypass ได้

// ❌ CSP ที่ไม่ปลอดภัย
// Content-Security-Policy: default-src 'self'; script-src 'unsafe-inline';

// ✅ CSP ที่ปลอดภัยกว่า
// Content-Security-Policy: 
//   default-src 'self';
//   script-src 'self' 'nonce-{random}';
//   style-src 'self' 'unsafe-inline';
//   img-src 'self' data: https:;
//   connect-src https://api.holysheep.ai/v1;
//   frame-ancestors 'none';

สรุปแนวทางปฏิบัติที่ดีที่สุด

XSS เป็นภัยคุกคามที่ร้ายแรงแต่ป้องกันได้ไม่ยาก ถ้าทำตามแนวทางในบทความนี้ แอปพลิเคชัน AI ของคุณจะปลอดภัยจากการโจมตีแบบ Cross-Site Scripting

👉 สมัคร HolySheep AI — รับเครดิตฟรีเมื่อลงทะเบียน