grianggrai.n
เมื่อต้องการเพิ่มคะแนนของ HTTP Observatory Report เลื่อนไปๆ จะเจอว่าคะแนนของ Subresource integrity (SRI) ยังเป็น -5 ทำไงได้บ้างสำหรับ WordPress
SRI หรือ Subresource Integrity คือฟีเจอร์ด้านความปลอดภัยที่ช่วยให้ Browser ตรวจสอบว่าไฟล์ที่ถูกดึงมาจากภายนอก (เช่น JS หรือ CSS จาก CDN) ไม่ถูกแก้ไขหรือแอบฝังมัลแวร์มาโดยผู้ไม่หวังดี
สิ่งที่ต้องมี
// 1. Hook เพื่อแทรก SRI ให้ Script และ Style add_filter( 'script_loader_tag', 'auto_add_sri', 10, 2 ); add_filter( 'style_loader_tag', 'auto_add_sri', 10, 2 ); function auto_add_sri( $tag, $handle ) { if ( ! preg_match( '/\s(src|href)=[\x27\x22]([^\x27\x22]+)[\x27\x22]/i', $tag, $matches ) ) { return $tag; } $attr = $matches[1]; $url = $matches[2]; $site_url = site_url(); if ( strpos( $url, 'http' ) !== 0 || strpos( $url, $site_url ) === 0 ) { return $tag; } $hash_key = 'sri_hash_' . md5( $url ); $hash = get_transient( $hash_key ); if ( false === $hash ) { $response = wp_remote_get( $url, array( 'timeout' => 5 ) ); if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) != 200 ) { set_transient( $hash_key, 'failed', HOUR_IN_SECONDS ); return $tag; } $content = wp_remote_retrieve_body( $response ); $hash = 'sha384-' . base64_encode( hash( 'sha384', $content, true ) ); set_transient( $hash_key, $hash, 12 * HOUR_IN_SECONDS ); } if ( $hash && $hash !== 'failed' ) { $replace_target = ' ' . $attr . '='; $replace_with = ' integrity="' . $hash . '" crossorigin="anonymous" ' . $attr . '='; return str_replace( $replace_target, $replace_with, $tag ); } return $tag; }