桃花源记手游vivo版
599.15MB · 2025-12-04
随着前端应用复杂度不断提升,保护JavaScript源代码和核心业务逻辑变得越来越重要。本文将介绍多种前端代码安全防护策略,构建多层次的安全防护体系。
JavaScript代码混淆是最基础也是最重要的防护手段。通过变量重命名、控制流平展、字符串加密等技术,让代码难以阅读和分析。
详细的混淆配置和使用方法请参考:
// 检测开发者工具function detectDevTools() { const threshold = 160; setInterval(() => { if (window.outerHeight - window.innerHeight > threshold || window.outerWidth - window.innerWidth > threshold) { // 检测到开发者工具打开 document.body.innerHTML = '检测到调试工具,页面已停止运行'; } }, 500);}// 禁用右键菜单document.addEventListener('contextmenu', e => e.preventDefault());// 禁用F12等快捷键document.addEventListener('keydown', e => { if (e.key === 'F12' || (e.ctrlKey && e.shiftKey && e.key === 'I') || (e.ctrlKey && e.shiftKey && e.key === 'C')) { e.preventDefault(); }});
// 域名白名单检查function checkDomain() { const allowedDomains = ['yourdomain.com', 'www.yourdomain.com']; const currentDomain = window.location.hostname; if (!allowedDomains.includes(currentDomain)) { window.location.href = 'https://yo**u*rdomain.com'; }}// 检测运行环境function detectEnvironment() { // 检测是否在iframe中运行 if (window.self !== window.top) { throw new Error('不允许在iframe中运行'); } // 检测User-Agent const ua = navigator.userAgent; if (ua.includes('HeadlessChrome') || ua.includes('PhantomJS')) { throw new Error('检测到自动化工具'); }}
// 请求签名验证function generateSignature(params, timestamp, nonce) { const sortedParams = Object.keys(params) .sort() .map(key => `${key}=${params[key]}`) .join('&'); const signString = `${sortedParams}×tamp=${timestamp}&nonce=${nonce}`; return CryptoJS.SHA256(signString + SECRET_KEY).toString();}// 请求频率限制class RateLimiter { constructor(maxRequests = 100, timeWindow = 60000) { this.requests = []; this.maxRequests = maxRequests; this.timeWindow = timeWindow; } canMakeRequest() { const now = Date.now(); this.requests = this.requests.filter(time => now - time < this.timeWindow); if (this.requests.length >= this.maxRequests) { return false; } this.requests.push(now); return true; }}
<!-- 使用SRI确保资源完整性 --><script src="app.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" crossorigin="anonymous"></script><!-- CSP内容安全策略 --><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline';">
const JavaScriptObfuscator = require('webpack-obfuscator');module.exports = { // 生产环境配置 mode: 'production', plugins: [ // 代码混淆插件 new JavaScriptObfuscator({ rotateStringArray: true, stringArray: true, stringArrayThreshold: 0.8, transformObjectKeys: true, unicodeEscapeSequence: false }, ['excluded_bundle.js']) ], optimization: { // 移除console语句 minimizer: [ new TerserPlugin({ terserOptions: { compress: { drop_console: true, drop_debugger: true } } }) ] }};
前端安全防护是一个持续的过程,需要根据业务特点选择合适的防护策略。通过代码混淆、反调试、环境检测等多种手段的组合使用,可以大大提高攻击者的成本,有效保护前端应用的安全。
记住:没有绝对的安全,只有相对的安全。关键是要让攻击成本远高于攻击收益。