Now.js Framework Documentation

Now.js Framework Documentation

SecurityManager

TH 13 Nov 2026 06:18

SecurityManager

ภาพรวม

SecurityManager คือระบบจัดการความปลอดภัยใน Now.js Framework รองรับ CSRF, JWT, Rate Limiting และ Content Security Policy

ใช้เมื่อ:

  • ต้องการป้องกัน CSRF attacks
  • ต้องการจัดการ JWT tokens
  • ต้องการ rate limiting
  • ต้องการ input sanitization
  • ต้องการ CSP management

ทำไมต้องใช้:

  • ✅ CSRF protection (token-based)
  • ✅ JWT management (validate, refresh)
  • ✅ Rate limiting (per endpoint)
  • ✅ Input sanitization (XSS prevention)
  • ✅ Content Security Policy
  • ✅ HTTP interceptors
  • ✅ Form protection

การใช้งานพื้นฐาน

Initialization

await SecurityManager.init({
  csrf: {
    enabled: true,
    tokenName: '_token',
    headerName: 'X-CSRF-Token'
  },
  jwt: {
    enabled: true,
    storageName: 'auth_token',
    autoRefresh: true
  },
  rateLimit: {
    enabled: true,
    globalLimit: 100,
    windowMs: 15 * 60 * 1000 // 15 minutes
  }
});

CSRF Protection

Auto-inject in Forms

<form action="/api/submit" method="POST">
  <!-- CSRF token จะถูก inject อัตโนมัติ -->
  <input type="text" name="email">
  <button type="submit">Submit</button>
</form>

Get CSRF Token

const token = SecurityManager.getCSRFToken();
console.log(token); // 'abc123...'

Manual CSRF in Requests

// SecurityManager จะ inject อัตโนมัติใน ApiService
await ApiService.post('/api/data', {
  name: 'John'
});
// Request จะมี X-CSRF-Token header อัตโนมัติ

token ไปกับคำขอ POST/PUT/PATCH/DELETE ที่ไป origin ของหน้านี้ หรือ origin ใน config.trustedOrigins เท่านั้น · GET ไม่มี token และคำขอที่ไป origin อื่นไม่มีทั้ง header และ _token · token ใหม่ใน response รับมาเฉพาะจาก origin เหล่านั้น · กฎเดียวกันใช้กับ HttpClient, simpleFetch, ApiService (CSRF, Bearer, Basic), AuthManager และการอัปโหลดของ FormManager:

await Now.init({security: {trustedOrigins: ['https://api.example.com']}});
SecurityManager.isTrustedOrigin('https://api.example.com/x'); // true
SecurityManager.isTrustedOrigin('https://other.example/x');   // false

Refresh CSRF Token

await SecurityManager.refreshCSRFToken();

ยกเว้นบาง path จาก CSRF

csrf.excludePaths (ค่าเริ่มต้น ['api/public/*', '/auth/verify']) คือ path ที่ไม่แนบ CSRF token
* ท้ายรายการทำให้เทียบแบบ prefix ทั้ง URL ของคำขอและรายการถูก resolve แบบที่เบราว์เซอร์ resolve
(เทียบกับหน้าปัจจุบัน ตัด ./.. ออก) แล้วเทียบเฉพาะ pathname:

SecurityManager.isPathExcluded('api/public/list');          // true
SecurityManager.isPathExcluded('api/public/../index/save'); // false — ไม่อยู่ใต้ api/public/
SecurityManager.isPathExcluded('/auth/verify?id=1');        // true — query ไม่นับ
SecurityManager.isPathExcluded(location.origin + '/auth/verify'); // true
SecurityManager.isPathExcluded('https://other.example/auth/verify'); // false — คนละ origin

SecurityManager.getCookie(name) คืนค่า cookie ที่ decode แล้ว (a%2Bb → a+b) ถ้าชื่อเดียวกันถูกตั้งไว้
หลาย path จะได้ค่าของ path ที่เจาะจงที่สุด (ตัวที่เบราว์เซอร์ส่งมาก่อน)

ถ้า SecurityManager.init() ล้มระหว่าง Now.init() จะมี console.error บอกว่า CSRF และการกรอง HTML
อาจยังไม่พร้อม (manager อื่นที่ล้มก็ถูก log พร้อมชื่อ) และถ้าเปิด strictMode error จะถูกโยนต่อ

JWT Management

Get JWT Token

const token = SecurityManager.getJWTToken();

Validate Token

const isValid = SecurityManager.validateJWTToken(token);
if (!isValid) {
  // Token expired or invalid
  redirectToLogin();
}

Refresh Token

await SecurityManager.refreshJWTToken();

Clear Token (Logout)

SecurityManager.clearJWTToken();

Auto-refresh Token

SecurityManager.init({
  jwt: {
    enabled: true,
    autoRefresh: true,
    refreshThreshold: 5 * 60 * 1000 // Refresh 5 mins before expiry
  }
});

Rate Limiting

Check Rate Limit

const result = SecurityManager.checkRateLimit('/api/login');

if (!result.allowed) {
  console.log(`Rate limited. Retry after ${result.retryAfter}ms`);
}

Per-Endpoint Limits

SecurityManager.init({
  rateLimit: {
    enabled: true,
    globalLimit: 100,
    perEndpoint: {
      '/api/login': { limit: 5, windowMs: 60000 },    // 5 per minute
      '/api/register': { limit: 3, windowMs: 60000 }, // 3 per minute
      '/api/upload': { limit: 10, windowMs: 300000 }  // 10 per 5 minutes
    }
  }
});

แสดง HTML อย่างปลอดภัย

ทุกจุดของเฟรมเวิร์กที่ใส่ markup ใช้ sanitizer ตัวเดียว: sanitizeHtml() / sanitizeTree() markup ถูก parse ใน <template> จึงไม่มีอะไรในนั้นโหลดหรือทำงานระหว่างทำความสะอาด มี 2 ระดับ

ระดับ ใช้กับ คงไว้
untrusted (ค่าเริ่มต้น) ข้อมูล, action จาก response ของ server, เซลล์ตาราง {html}, data-html, ข้อความของ DialogManager/Modal, รายการ html ของ MediaViewer tag, attribute และ style property ใน config.html · iframe เฉพาะจาก config.html.iframeHosts
trusted ({trusted: true}) template ที่โหลดจาก origin ของตัวเอง (TemplateManager) tag ใน config.html.templateTags และทุก attribute ยกเว้น on*, srcdoc, http-equiv, URL ที่ไม่ปลอดภัย และ style ที่มีสคริปต์
  • tag นอก templateTags ถูกลบพร้อมเนื้อหา · รายการรวมแท็กวาดรูปของ SVG (g, path, circle, rect, line, polyline, polygon, ellipse, text, tspan, defs, linearGradient, radialGradient, stop, use, symbol, clipPath, mask, title — ชื่อในรายการเป็นตัวเล็ก) และ optgroup, del, ins, q, address, dfn, bdi, bdo, data, hgroup, search · script, foreignObject, animate, set, animateTransform ไม่อยู่ในรายการ · <use> ชี้ได้เฉพาะ #id ในเอกสาร
  • ระดับ untrusted คงเฉพาะ element กับ text (ไม่มี comment, processing instruction, CDATA) · template คง comment ไว้
  • data:image/... เป็น URL ที่โหลดได้เฉพาะบนแท็กรูป (img, source, video, input, picture — SecurityManager.isImageTag()) ทั้งสองระดับ ทั้งจาก binding และจาก response · iframe, embed, object ไม่รับ เพราะ SVG ข้างในรันสคริปต์ได้
// ข้อมูลจาก server หรือผู้ใช้
SecurityManager.setSafeHtml(element, row.detail);
element.innerHTML = SecurityManager.sanitizeHtml(row.detail);

// '<span style="color:red;position:fixed" onclick="x()">a</span>'
//   => '<span style="color: red">a</span>'

// URL: http, https, mailto, tel และ URL ที่ไม่มี scheme ผ่านทั้งหมด
SecurityManager.sanitizeUrl('../api/export?id=1'); // '../api/export?id=1'
SecurityManager.sanitizeUrl('java\tscript:alert(1)'); // ''

อนุญาต host อื่นสำหรับเนื้อหาที่ฝัง (เช่น Google Maps) ใน Now.init():

Now.init({
  security: {html: {iframeHosts: ['www.google.com/maps/embed']}} // เพิ่มจากค่าเริ่มต้น
});

config.html ตั้งได้ครั้งเดียวที่ init() ครั้งแรก (ครั้งที่ Now.init() เรียกด้วยส่วน security) หลังจากนั้นถูก freeze — init() ครั้งต่อไปไม่เปลี่ยน config.html (ส่วนอื่นยังเปลี่ยนได้) และการแก้ในที่ เช่น config.html.iframeHosts.push(...) จะ throw TypeError จึงไม่มีโค้ดใดที่ถูกเรียกทีหลังขยายสิ่งที่ sanitizer ยอมได้

sanitizer ทำงานที่เบราว์เซอร์ HTML ที่บันทึกเก็บยังต้องกรองที่ server ตอนบันทึก

Input Sanitization

การทำความสะอาด body ของคำขอฝั่ง client ปิดเป็นค่าเริ่มต้น (config.sanitization.enabled: false) server เป็นที่เดียวที่กรอง input เพราะอะไรที่เบราว์เซอร์ทำ ใครก็ข้ามได้ด้วยการยิงคำขอเอง เมื่อปิดอยู่ สิ่งที่ผู้เรียกส่งคือสิ่งที่ server ได้ — ทั้งผ่าน window.http, การส่งฟอร์มแบบแนบไฟล์ (XMLHttpRequest) และการ submit ปกติ

เปิดเฉพาะเมื่อต้องการเป็นชั้นเสริม:

await Now.init({security: {sanitization: {enabled: true}}});

เมื่อเปิด prepareRequestBody() — จุดเดียวที่ทำความสะอาด body ใช้โดย interceptor ของ window.http และทางอัปโหลดของ FormManager — คืน สำเนา ที่ทำความสะอาดแล้ว:

  • ทำความสะอาดเฉพาะ string ที่มี HTML · ข้อความธรรมดา, URL (รวม javascript:void(0)) และตัวเลขส่งตามเดิม
  • array ยังเป็น array, object ซ้อนถูกทำความสะอาดด้วย, Date, File, Blob คงไว้ตามเดิม
  • คำขอที่มี X-Skip-Sanitize: true — FormManager ตั้งให้ฟอร์มที่มี data-sanitize-input="false" — ส่งตามที่ได้รับ

Sanitize Input

SecurityManager.config.sanitization.enabled = true;
SecurityManager.sanitizeInput('a<script>alert("xss")</script>b'); // 'ab'
SecurityManager.sanitizeInput('<b onclick="x()">y</b>');         // '<b>y</b>'
SecurityManager.sanitizeInput('javascript:void(0)');             // ไม่เปลี่ยน เพราะไม่ใช่ HTML

ใน string ที่เป็น HTML จะลบ 3 อย่างนี้ และไม่จำกัดความยาว (การกำหนดความยาวเป็นหน้าที่ของ server)

  • <script>...</script>
  • แอตทริบิวต์ event handler ในแท็ก เช่น onclick="..."
  • javascript: ที่ขึ้นต้นค่าของแอตทริบิวต์

อ่านแท็กแบบเดียวกับเบราว์เซอร์ จึงไม่แตะข้อความนอกแท็กและค่าของแอตทริบิวต์อื่น: ?month=12, href="report?month=12" และประโยคที่มีคำว่า javascript: อยู่กลางข้อความคงเดิม · เมื่อปิดอยู่ sanitizeInput() คืนค่าเดิม

Sanitize Object

SecurityManager.sanitizeRequestData({
  ids: [1, 2],
  when: new Date(0),
  html: '<b onclick="x()">y</b>'
});
// { ids: [1, 2], when: Date, html: '<b>y</b>' }  (เป็นสำเนา input ไม่ถูกแก้)

Content Security Policy

ส่ง CSP เป็น header จาก server (แนะนำ)

ให้ server ส่ง Content-Security-Policy เป็น header ของหน้า HTML นโยบายจาก header มีผลตั้งแต่ไบต์แรกของหน้า
ส่วน <meta> ที่ SecurityManager ใส่ตอน init() มีผลเฉพาะสิ่งที่โหลดหลังจากนั้น และตั้ง frame-ancestors
ไม่ได้ ถ้ามีทั้งสองแบบ เบราว์เซอร์บังคับทั้งสองชุดพร้อมกัน (ต้องผ่านทั้งคู่)

Now.js ไม่สร้าง inline event handler ใน markup ของตัวเอง (หน้า 404 ของ router, error modal ของ
ResponseHandler, หน้าข้อผิดพลาดของ AuthErrorHandler และ ErrorRenderer ใช้ addEventListener) และ template
ถูกตัด on* ทิ้งอยู่แล้ว script จึงไม่ต้องใช้ 'unsafe-inline' ค่าที่ adminframework/index.php ส่ง
(ตรวจ 21 หน้าของแอป ไม่มี violation):

header('Content-Security-Policy: '.implode('; ', [
    "default-src 'self'",
    "script-src 'self' https://accounts.google.com https://apis.google.com https://connect.facebook.net https://telegram.org https://*.telegram.org",
    "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://accounts.google.com",
    "font-src 'self' data: https://fonts.gstatic.com",
    "img-src 'self' data: blob: https:",
    "media-src 'self' blob:",
    "connect-src 'self' https://accounts.google.com https://www.googleapis.com https://graph.facebook.com https://www.facebook.com",
    "frame-src 'self' https://accounts.google.com https://www.google.com https://maps.google.com https://www.facebook.com https://web.facebook.com https://access.line.me https://oauth.line.me https://oauth.telegram.org https://t.me https://www.youtube.com https://www.youtube-nocookie.com https://player.vimeo.com",
    "worker-src 'self' blob:",
    "frame-ancestors 'self'",
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'"
]));
ต้องการ เพิ่ม
โหลดสคริปต์จาก CDN host นั้นใน script-src
ResponseHandler ที่ตั้ง allowEval: true (action eval, <script> ใน HTML จาก server) 'unsafe-eval' ใน script-src
หน้า/theme ที่มี <script> inline (เช่น theme ของเว็บ GCMS) ย้ายไปเป็นไฟล์ หรือใช้ nonce/hash — 'unsafe-inline' เป็นทางสุดท้าย
iframe จาก host อื่น (เช่น Google Maps embed) host ใน frame-src และใน html.iframeHosts

style ยังต้องมี 'unsafe-inline' เพราะ template และ editor ใช้ attribute style · blob: ใน img-src/media-src
ใช้กับพรีวิวไฟล์ที่เลือกและการ export กราฟ

CSP จาก SecurityManager (meta)

Now.init({
  security: {
    csp: {
      enabled: true,          // Now.init ปิดไว้เป็นค่าเริ่มต้น
      directives: {
        'script-src': ['https://cdn.example.com']   // ต่อจากค่าเริ่มต้น ไม่ซ้ำ
      }
    }
  }
});

enabled: true ใส่ <meta http-equiv="Content-Security-Policy"> จาก csp.directives เมื่อหน้ายังไม่มี meta ตัวนี้
ค่าเริ่มต้นของ script-src ไม่มี 'unsafe-inline' และ 'unsafe-eval' · array ใน config ที่ส่งมาถูกต่อกับค่าเริ่มต้น
โดยไม่ซ้ำ เรียก init() ซ้ำด้วยค่าเดิมได้ config ไม่โต

รายงานการละเมิด CSP

Now.init({
  security: {
    csp: {
      enabled: true,
      reportUri: 'api/csp-report',  // ค่าเริ่มต้น '' = ไม่ส่ง
      maxViolations: 50,            // จำนวนการละเมิดที่ไม่ซ้ำที่เก็บไว้
      maxReports: 10                // จำนวนที่ส่งไป server ต่อหน้า
    }
  }
});

EventManager.on('csp:violation', (violation) => {
  console.log('CSP Violation:', violation);  // {directive, uri, source, line, timestamp, count}
});

การละเมิดที่ซ้ำ (directive, blocked URI, ไฟล์ และบรรทัดเดียวกัน) ถูกเก็บและรายงานครั้งเดียว ครั้งถัดไปแค่เพิ่ม
count · csp:violation ส่งเฉพาะครั้งแรกของแต่ละแบบ · listener ผูกครั้งเดียวแม้ init() หลายรอบ
ต้องมี endpoint ที่รับ POST JSON ตาม reportUri เอง (Kotchasan/Gcms ไม่มีให้)

ก่อนแก้ไข ทุกการละเมิดถูกเก็บไม่จำกัดและ POST ทุกครั้ง (ซ้ำ 200 ครั้ง = 200 คำขอ) และ init() รอบที่สองทำให้รายงานซ้อนเป็นสองเท่า

การตั้งค่า

await SecurityManager.init({
  // CSRF
  csrf: {
    enabled: true,
    tokenName: '_token',
    headerName: 'X-CSRF-Token',
    cookieName: 'XSRF-TOKEN',
    tokenUrl: '/api/auth/csrf-token',
    autoRefresh: true,
    refreshInterval: 30 * 60 * 1000 // 30 minutes
  },

  // JWT
  jwt: {
    enabled: true,
    cookieName: 'auth_token',
    refreshCookieName: 'refresh_token',
    storageKey: 'auth_jwt',              // ดูหมายเหตุด้านล่าง
    storage: 'memory',                   // 'memory' | 'localStorage' — ที่เก็บ token ที่ JS ได้รับ
    autoRefresh: true,
    refreshBeforeExpiry: 5 * 60 * 1000,  // 5 นาที
    refreshEndpoint: 'api/auth/refresh',
    validateSignature: true,
    algorithm: 'HS256',
    issuer: window.location.hostname,
    audience: window.location.hostname
  },

  // Rate Limiting
  rateLimit: {
    enabled: true,
    storage: 'memory',
    globalLimit: 100,
    windowMs: 15 * 60 * 1000,
    perEndpoint: {}
  },

  // CSP (ดูหัวข้อ Content Security Policy)
  csp: {
    enabled: false,                      // ผ่าน Now.init (เรียก SecurityManager.init ตรง ๆ = true)
    directives: {/* script-src ไม่มี 'unsafe-inline' 'unsafe-eval' */},
    reportUri: '',                       // '' = ไม่รายงาน
    maxViolations: 50,
    maxReports: 10
  },

  // origin อื่นนอกจากหน้านี้ที่ได้รับ CSRF token / Authorization header
  trustedOrigins: [],

  // ทำความสะอาด body ของคำขอฝั่ง client — ปิดเป็นค่าเริ่มต้น server เป็นผู้กรอง
  sanitization: {
    enabled: false
  },

  // HTML sanitizer (sanitizeHtml / sanitizeTree)
  html: {
    urlSchemes: ['http:', 'https:', 'mailto:', 'tel:'],
    iframeHosts: ['www.youtube.com/embed/', 'www.youtube-nocookie.com/embed/', 'player.vimeo.com/video/'],
    iframeSandbox: 'allow-scripts allow-same-origin allow-presentation allow-popups',
    tags: [/* tag ระดับ untrusted */],
    dataAttributes: [],  // data-* ที่ untrusted คงไว้ (ค่าเริ่มต้นไม่มี)
    attributes: {'*': [/* ทุก tag */], a: ['href', 'target', 'rel', 'hreflang'] /* … */},
    styleProperties: [/* style property ระดับ untrusted */],
    templateTags: [/* tag ของ template ระดับ trusted */]
  }
});

init() รวม array ด้วยการต่อท้าย จึงเพิ่มรายการด้วย push แทนการส่งรายการใหม่ให้ init()

jwt.storageKey ต้องไม่ชนกับ token.storageKey ของ AuthManager
ค่าเริ่มต้นคือ 'auth_jwt' เก็บ สตริง JWT ส่วน AuthManager เก็บ
โปรไฟล์ผู้ใช้ (ออบเจ็กต์ JSON) ไว้ที่ 'auth_user' เดิมทั้งคู่ตั้งค่า
เริ่มต้นเป็น 'auth_user' เหมือนกัน ทำให้ initJWT() อ่านโปรไฟล์ขึ้นมา
ตรวจว่าไม่ใช่ JWT แล้ว clearJWTToken() ก็ลบทิ้งทุกครั้งที่โหลดหน้า
โปรไฟล์ที่แคชไว้จึงไม่เคยอยู่รอด และแอปเปิดตอนออฟไลน์ไม่ได้
ถ้าแอปของคุณเขียน JWT ลง 'auth_user' เอง ให้ย้ายไป 'auth_jwt'
(หรือกำหนด storageKey เป็นคีย์อื่นของคุณเอง) ตอนอัปเกรด
ทั้งนี้ในการใช้งานปกติ token จริงอยู่ใน httpOnly cookie คีย์นี้จึงแทบไม่ถูกใช้

API อ้างอิง

CSRF Methods

SecurityManager.getCSRFToken()

รับ CSRF token ปัจจุบัน

Returns: string|null

SecurityManager.refreshCSRFToken()

Refresh CSRF token จาก server

Returns: Promise<string>

SecurityManager.injectCSRFIntoForm(form, token?)

Inject CSRF token ใน form

Parameter Type Description
form HTMLFormElement Form element

JWT Methods

SecurityManager.getJWTToken()

รับ JWT token

Returns: string|null

SecurityManager.validateJWTToken(token)

Validate JWT token

Parameter Type Description
token string JWT token

Returns: boolean

SecurityManager.refreshJWTToken()

Refresh JWT token

Returns: Promise<string>

SecurityManager.clearJWTToken()

Clear JWT token (logout)

Rate Limit Methods

SecurityManager.checkRateLimit(endpoint, identifier?)

ตรวจสอบ rate limit

Parameter Type Description
endpoint string API endpoint
identifier string User identifier (optional)

Returns: Object:

{
  allowed: boolean,
  remaining: number,
  resetTime: number,
  retryAfter: number
}

Sanitization Methods

SecurityManager.sanitizeHtml(html, options?)

คืน markup ที่ใส่ innerHTML ได้อย่างปลอดภัย parse แบบเฉื่อยใน <template>

Parameter Type Description
html string markup ที่จะทำความสะอาด
options.trusted boolean true สำหรับ template จาก origin ของตัวเอง ค่าเริ่มต้นคือ untrusted

Returns: string - markup ที่สะอาดแล้ว

SecurityManager.sanitizeTree(root, options?)

ทำความสะอาด element หรือ fragment ในที่เดิมด้วยระดับเดียวกัน root ยังอยู่แต่ attribute ของมันถูกทำความสะอาด markup ที่ parse ในหน้าจริงแล้วอาจโหลดรูปไปแล้ว ถ้ายังไม่ได้ใส่ลงหน้าให้ใช้ sanitizeHtml()

Returns: root ตัวเดิม

SecurityManager.setSafeHtml(element, html)

element.innerHTML = sanitizeHtml(html) (untrusted) Returns: element

SecurityManager.sanitizeUrl(url, options?)

คง URL ที่ไม่มี scheme (/path, ../path, ?t=12:30, #id, //host) และ URL ที่ scheme อยู่ใน config.html.urlSchemes อ่าน scheme แบบเดียวกับเบราว์เซอร์ (ไม่สนอักขระควบคุมและช่องว่างหัวท้าย ตัด tab/CR/LF ทิ้ง) java\tscript: จึงนับเป็น javascript:

Parameter Type Description
url string URL ที่จะตรวจ
options.image boolean คง data:image/... แบบ raster ด้วย
options.svg boolean ใช้คู่กับ image เพื่อคง data:image/svg+xml

Returns: string - URL ที่ตัดช่องว่างแล้ว หรือ '' เมื่อถูกปฏิเสธ

SecurityManager.sanitizeStyle(style)

คง declaration ของค่า style ที่ property อยู่ใน config.html.styleProperties และค่าไม่มี url(), expression(), scheme ของสคริปต์, @import, backslash, <, > หรือ comment

Returns: string|null - declaration ที่เหลือ หรือ null เมื่อไม่เหลือเลย

SecurityManager.cssUrl(url)

url("...") ของ CSS สำหรับ URL: ใส่เครื่องหมายคำพูดและ escape อักขระที่มีความหมายใน CSS (CSS.escape) ทำให้ ), เครื่องหมายคำพูด หรือ backslash ใน URL ยังเป็นส่วนของ URL · ไม่ได้ตรวจ URL — ส่ง URL ที่ผ่าน sanitizeUrl() แล้ว · FileElementFactory (ภาพตัวอย่าง), TemplateManager (data-style ที่เป็นรูป) และ AppConfigManager ใช้ตัวนี้

Returns: string

SecurityManager.isForbiddenAttribute(name)

attribute ที่ค่าจากข้อมูล (response ของ server, binding ใน template) ห้ามเขียนไม่ว่าค่าเป็นอะไร: on*, srcdoc, http-equiv และ directive ที่ทำให้ markup มีพฤติกรรม (directiveAttributes: data-on, data-action, data-script, data-on-load, data-html, data-component, data-attr, data-if, data-for, data-model, data-bind และ data-api-*) · ResponseHandler (update attr/attrs, action attribute) และ TemplateManager.safeAttributeValue() ใช้ตัวนี้ตัวเดียว

Returns: boolean

SecurityManager.isUrlAttribute(name)

attribute ที่ค่าเป็น URL (href, src, action, formaction, poster, cite, background, xlink:href, data, codebase, ping, manifest) — รายการเดียวกับที่ sanitizer ตรวจ ทุกที่ที่เขียน URL จากข้อมูลใช้รายการนี้ · srcset เป็นรายการ URL ดู sanitizeSrcset()

Returns: boolean

SecurityManager.isAllowedDataAttribute(name)

เนื้อหาระดับ untrusted มี attribute data-* ชื่อนี้ได้หรือไม่: เฉพาะชื่อใน config.html.dataAttributes (ลงท้าย * = prefix) ค่าเริ่มต้นว่าง directive ทุกตัวเป็น data-* จึงไม่ผ่าน · sanitizer และ MenuManager (item.data) ใช้กฎนี้

Returns: boolean

SecurityManager.isAllowedIframe(src)

<iframe> ระดับ untrusted โหลด src ได้หรือไม่: ต้องเป็น http(s) และ host + path ขึ้นต้นด้วยรายการใน config.html.iframeHosts

Returns: boolean

SecurityManager.escapeHtml(value)

แปลง & < > " ' เป็น entity สำหรับใส่ค่าเป็นข้อความ Returns: string

SecurityManager.isTrustedOrigin(url)

คำขอที่ไป url แนบ CSRF token และ Authorization header ได้หรือไม่ และรับ token ใหม่จาก response ของมันได้หรือไม่: origin ของหน้านี้หรือ origin ใน config.trustedOrigins · ไม่ระบุ URL หมายถึงหน้านี้เอง

Returns: boolean

SecurityManager.prepareRequestBody(body, headers)

body ที่ใช้ส่งคำขอ: body ตามที่ได้รับเมื่อ config.sanitization.enabled ปิดอยู่ (ค่าเริ่มต้น) หรือเมื่อ headers มี X-Skip-Sanitize: true · ไม่งั้นเป็นสำเนาที่ทำความสะอาดแล้ว (sanitizeRequestData)

Returns: body ที่จะส่ง

SecurityManager.sanitizeInput(value)

Sanitize input string

Parameter Type Description
value string Input value

Returns: string - Sanitized value

SecurityManager.sanitizeRequestData(data)

Sanitize object/array recursively

Parameter Type Description
data object/array Data to sanitize

Returns: object/array - Sanitized data

Data Attributes

Attribute คำอธิบาย
data-csrf ใส่บน <form> ตั้ง false หรือ disabled เพื่อไม่ให้แนบ CSRF token กับฟอร์มนั้น

เหตุการณ์

Event เมื่อเกิด Detail
security:initialized init() เสร็จ {csrf, jwt}
csrf:refreshed ได้ CSRF token ใหม่ {token}
csrf:retry เจอ CSRF ไม่ผ่าน (419) กำลังให้โอกาสส่งซ้ำ {token}
jwt:refreshed ได้ JWT ใหม่ {token}
jwt:cleared ลบ JWT ที่เก็บไว้ ไม่มี
csp:violation เบราว์เซอร์รายงานการละเมิด CSP (ครั้งแรกของแต่ละแบบ) {directive, uri, source, line, timestamp, count} (ส่งตรง ไม่ห่อ)
security:error เกิดข้อผิดพลาดด้านความปลอดภัย {message, error}
security:destroyed destroy() เสร็จ ไม่มี

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

Protected API Calls

// SecurityManager จะ inject headers อัตโนมัติ
async function saveProfile(data) {
  try {
    // CSRF และ JWT headers จะถูกเพิ่มอัตโนมัติ
    await ApiService.put('/api/profile', data);
    NotificationManager.success('บันทึกแล้ว');
  } catch (error) {
    if (error.status === 419) {
      // CSRF token expired
      await SecurityManager.refreshCSRFToken();
      // Retry
      return saveProfile(data);
    }
    throw error;
  }
}

Login with Rate Limiting

async function login(email, password) {
  // Check rate limit
  const limit = SecurityManager.checkRateLimit('/api/login');
  if (!limit.allowed) {
    throw new Error(`ลองอีกครั้งใน ${Math.ceil(limit.retryAfter / 1000)} วินาที`);
  }

  const response = await ApiService.post('/api/login', {
    email: SecurityManager.sanitizeInput(email),
    password
  });

  return response;
}

Form with CSRF Protection

<form id="contact-form" action="/api/contact" method="POST" data-security>
  <input type="text" name="name" required>
  <input type="email" name="email" required>
  <textarea name="message" required></textarea>
  <button type="submit">ส่งข้อความ</button>
</form>

<script>
// SecurityManager จะ:
// 1. Inject CSRF token
// 2. Sanitize inputs
// 3. Check rate limit
// ... อัตโนมัติ
</script>

ข้อควรระวัง

⚠️ 1. Enable CSRF สำหรับ Production

// ❌ CSRF disabled in production
SecurityManager.init({ csrf: { enabled: false } });

// ✅ Enable CSRF
SecurityManager.init({ csrf: { enabled: true } });

⚠️ 2. JWT Token ใน Memory

Kotchasan/Gcms ส่ง access token เป็น httpOnly cookie เท่านั้น JavaScript อ่านไม่ได้และไม่ต้องเก็บอะไร
ถ้า backend อื่นส่ง token มาใน body ของ refresh jwt.storage เลือกที่เก็บ:

// ✅ ค่าเริ่มต้น: อยู่ใน state เท่านั้น หายเมื่อ reload แล้วได้ใหม่จาก refresh (cookie)
jwt: { storage: 'memory' }

// ⚠️ อยู่รอด reload แต่สคริปต์ที่ถูกฉีด (XSS) อ่านจาก localStorage ได้
jwt: { storage: 'localStorage' }

โหมด memory ลบ token ที่รุ่นก่อนเคยเขียนไว้ใต้ storageKey ใน localStorage ตอน init

ก่อนแก้ไข token จาก refresh ถูกเขียนลง localStorage เสมอ และคู่มือเคยอ้าง storageType ซึ่งไม่มีอยู่จริง

⚠️ 3. Sanitize User Input

// ❌ ใช้ user input โดยตรง
element.innerHTML = userInput;

// ✅ Sanitize ก่อน (sanitizeInput ใช้กับ body ของคำขอ ไม่ใช่การแสดงผล)
SecurityManager.setSafeHtml(element, userInput);

// หรือใช้ textContent
element.textContent = userInput;

เอกสารที่เกี่ยวข้อง