网站安全助手(油猴脚本,AI制作,可做参考,仅供个人学习使用)
网站安全助手第2版已更新,点击查看
https://blog.csdn.net/csdnsxs/article/details/159793721?spm=1011.2415.3001.5331
此脚本使用AI制作,可以使用Tampermonkey安装使用,仅供个人学习使用。
免责声明
1.使用风险自担
本脚本使用AI制作,本脚本(网站安全助手)仅供个人学习和研究网络安全技术使用。用户通过本脚本进行的任何操作(包括但不限于风险评估、下载拦截等)均需自行承担风险。开发者不对因使用本脚本导致的任何直接或间接损失(包括但不限于数据丢失、系统故障、法律纠纷等)承担责任。本脚本仅提供技术研究参考,不保证其安全性、完整性和适用性。用户需自行承担使用风险。
2. 功能局限性说明
本脚本的所有检测功能无法保证100%的准确性。
本脚本的AI风险评估模型基于规则和特征工程的模拟机制,无法保证100%的准确性。用户应结合其他安全工具或专业建议进行综合判断。
假冒域名检测功能可能存在误报或漏报,尤其针对新型钓鱼攻击或高度仿冒的网站。
下载保护功能仅能拦截已知高风险文件类型,无法识别所有恶意软件或变种病毒。
下载保护功能仅拦截已知恶意文件类型,无法识别零日漏洞攻击。
3. 隐私保护声明
本脚本仅在用户本地浏览器环境中运行,不会收集、传输或存储任何用户敏感信息(如浏览历史、密码、Cookie等)。
所有风险评估和检测过程均在本地完成,数据不会上传至第三方服务器。
用户可随时通过浏览器扩展管理页面查看或删除脚本缓存数据。
4. 合法合规使用
用户需确保使用本脚本的行为符合当地法律法规,禁止用于非法扫描、攻击或侵犯他人权益。
开发者不承担因用户违规使用导致的法律责任,包括但不限于侵犯隐私等行为。
• 禁止非法用途包括但不限于:
• 不得用于网络攻击、数据窃取、侵犯隐私等违法行为。
• 不得绕过安全检测或用于破解受保护系统。
• 法律责任:因用户违规使用导致的法律纠纷,开发者不承担任何责任。
5.更新
此脚本使用AI制作,不会更新,不保证兼容所有浏览器版本或未来网络环境变化。用户需自行测试兼容性。
6. 修改
此脚本使用AI制作开源,允许用户自由使用、修改和分发,本脚本仅提供技术研究参考,不保证其安全性、完整性和适用性。用户需自行承担使用风险,包括但不限于:
• 因脚本漏洞导致的系统损坏、数据泄露或法律纠纷。
• 开发者不承担任何直接或间接损失,包括因使用本脚本导致的财产损失、业务中断或法律责任。
衍生作品声明:基于本脚本修改的衍生作品需开源,并注明修改内容,对于衍生作品用户需自行承担使用风险。
二次开发:允许用户修改代码,并注明修改来源。二次开发后的脚本用户需自行承担使用风险。
7.终止使用
用户可随时禁用或卸载本脚本。若因脚本缺陷导致浏览器异常,建议通过浏览器扩展管理页面关闭脚本或恢复默认设置。
开发者声明:
本脚本旨在提升用户网络安全意识,不替代专业安全软件。请用户结合实际情况谨慎使用,并保持对新兴网络威胁的警惕性。
脚本源码如下:
// ==UserScript==
// @name 网站安全助手
// @namespace http://tampermonkey.net/
// @version 2.2
// @description AI驱动的智能安全检测与主动防护系统 - 完整功能版
// @author AI优化
// @match *://*/*
// @grant GM_notification
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_xmlhttpRequest
// @grant GM_openInTab
// @run-at document-start
// @connect *
// @license MIT
// ==/UserScript==
(function() {
'use strict';
// 调试模式 - 设置为true会在控制台显示详细日志
const DEBUG_MODE = true;
function debugLog(...args) {
if (DEBUG_MODE) {
console.log('🔒 [安全助手]', ...args);
}
}
debugLog('脚本开始加载...');
// 增强配置区
const CONFIG = {
strictness: 'medium',
autoCloseSafe: 5000,
enableBehaviorMonitor: true,
trustDomainExpire: 30 * 24 * 60 * 60 * 1000,
safePage: "https://www.baidu.com",
// AI增强检测
aiEnhanced: {
enable: true,
localML: true,
confidenceThreshold: 0.75
},
highRiskBlock: {
enable: true,
immediateBlock: true,
allowTemporaryBypass: true,
bypassExpire: 15 * 60 * 1000,
blockUnencryptedPassword: true,
blockMixedContent: true
},
// 增强的假冒域名检测
fakeDomainCheck: {
enable: true,
sensitivity: 'medium',
useHomographDetection: true,
knownBrands: [
// 银行金融类
{ name: "工商银行", domain: "icbc.com.cn", threshold: 0.8, weight: 1.3 },
{ name: "建设银行", domain: "ccb.com", threshold: 0.8, weight: 1.3 },
{ name: "农业银行", domain: "abchina.com", threshold: 0.8, weight: 1.3 },
{ name: "中国银行", domain: "bankofchina.com", threshold: 0.8, weight: 1.3 },
{ name: "招商银行", domain: "cmbchina.com", threshold: 0.8, weight: 1.3 },
{ name: "交通银行", domain: "bankcomm.com", threshold: 0.8, weight: 1.3 },
{ name: "邮政储蓄银行", domain: "psbc.com", threshold: 0.8, weight: 1.3 },
{ name: "浦发银行", domain: "spdb.com.cn", threshold: 0.8, weight: 1.3 },
// 支付类
{ name: "支付宝", domain: "alipay.com", threshold: 0.85, weight: 1.4 },
{ name: "微信支付", domain: "pay.weixin.qq.com", threshold: 0.85, weight: 1.4 },
{ name: "银联", domain: "unionpay.com", threshold: 0.8, weight: 1.3 },
{ name: "云闪付", domain: "95516.com", threshold: 0.8, weight: 1.3 },
// 电商平台
{ name: "淘宝", domain: "taobao.com", threshold: 0.75, weight: 1.2 },
{ name: "天猫", domain: "tmall.com", threshold: 0.75, weight: 1.2 },
{ name: "京东", domain: "jd.com", threshold: 0.75, weight: 1.2 },
{ name: "拼多多", domain: "pinduoduo.com", threshold: 0.75, weight: 1.2 },
{ name: "苏宁易购", domain: "suning.com", threshold: 0.75, weight: 1.2 },
{ name: "国美", domain: "gome.com.cn", threshold: 0.75, weight: 1.2 },
{ name: "唯品会", domain: "vip.com", threshold: 0.75, weight: 1.2 },
// 社交娱乐
{ name: "微信", domain: "weixin.qq.com", threshold: 0.8, weight: 1.3 },
{ name: "QQ", domain: "qq.com", threshold: 0.75, weight: 1.2 },
{ name: "微博", domain: "weibo.com", threshold: 0.75, weight: 1.2 },
{ name: "抖音", domain: "douyin.com", threshold: 0.75, weight: 1.2 },
{ name: "快手", domain: "kuaishou.com", threshold: 0.75, weight: 1.2 },
{ name: "B站", domain: "bilibili.com", threshold: 0.75, weight: 1.2 },
{ name: "小红书", domain: "xiaohongshu.com", threshold: 0.75, weight: 1.2 },
// 科技互联网
{ name: "百度", domain: "baidu.com", threshold: 0.7, weight: 1.1 },
{ name: "腾讯", domain: "tencent.com", threshold: 0.75, weight: 1.2 },
{ name: "阿里巴巴", domain: "alibaba.com", threshold: 0.75, weight: 1.2 },
{ name: "字节跳动", domain: "bytedance.com", threshold: 0.75, weight: 1.2 },
{ name: "网易", domain: "163.com", threshold: 0.75, weight: 1.2 },
{ name: "搜狐", domain: "sohu.com", threshold: 0.75, weight: 1.2 },
{ name: "新浪", domain: "sina.com.cn", threshold: 0.75, weight: 1.2 },
// 政府机构
{ name: "中国政府网", domain: "gov.cn", threshold: 0.9, weight: 1.5 },
{ name: "国家税务总局", domain: "chinatax.gov.cn", threshold: 0.9, weight: 1.5 },
{ name: "公安部", domain: "mps.gov.cn", threshold: 0.9, weight: 1.5 },
{ name: "人社部", domain: "mohrss.gov.cn", threshold: 0.9, weight: 1.5 },
// 生活服务
{ name: "美团", domain: "meituan.com", threshold: 0.75, weight: 1.2 },
{ name: "饿了么", domain: "ele.me", threshold: 0.75, weight: 1.2 },
{ name: "滴滴出行", domain: "didiglobal.com", threshold: 0.75, weight: 1.2 },
{ name: "携程", domain: "ctrip.com", threshold: 0.75, weight: 1.2 },
{ name: "12306", domain: "12306.cn", threshold: 0.85, weight: 1.4 },
// 游戏平台
{ name: "腾讯游戏", domain: "qqgames.com", threshold: 0.75, weight: 1.2 },
{ name: "网易游戏", domain: "163.com", threshold: 0.75, weight: 1.2 },
{ name: "完美世界", domain: "wanmei.com", threshold: 0.75, weight: 1.2 },
{ name: "Steam中国", domain: "steamchina.com", threshold: 0.75, weight: 1.2 },
// 教育机构
{ name: "学信网", domain: "chsi.com.cn", threshold: 0.85, weight: 1.4 },
{ name: "中国教育在线", domain: "eol.cn", threshold: 0.8, weight: 1.3 },
{ name: "新东方", domain: "xdf.cn", threshold: 0.75, weight: 1.2 },
{ name: "好未来", domain: "100tal.com", threshold: 0.75, weight: 1.2 },
// 其他重要平台
{ name: "中国移动", domain: "10086.cn", threshold: 0.8, weight: 1.3 },
{ name: "中国联通", domain: "10010.com", threshold: 0.8, weight: 1.3 },
{ name: "中国电信", domain: "189.cn", threshold: 0.8, weight: 1.3 },
{ name: "国家电网", domain: "sgcc.com.cn", threshold: 0.8, weight: 1.3 },
{ name: "中石化", domain: "sinopec.com", threshold: 0.8, weight: 1.3 }
]
},
// 增强下载监控
downloadMonitor: {
enable: true,
safeExtensions: ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'txt', 'zip', 'rar', '7z', 'docx', 'xlsx', 'pptx', 'doc', 'xls', 'ppt'],
riskyExtensions: ['exe', 'msi', 'dll', 'bat', 'cmd', 'ps1', 'vbs', 'js', 'jar', 'apk', 'app', 'dmg', 'iso', 'scr', 'pif', 'com', 'hta'],
suspiciousPatterns: ['setup', 'install', 'crack', 'keygen', 'patch', 'serial', 'nulled', 'free_download']
},
// 行为监控
behaviorMonitor: {
enable: true,
detectKeylogger: true,
detectFormHijack: true,
detectCryptoMiner: true
},
whitelist: {
maxDomains: 100,
showExpiry: true,
allowPermanent: true,
autoCleanup: true
},
// 隐私保护
privacy: {
blockTrackers: false,
preventWebRTCLeak: false
}
};
// 全局状态管理
let securityState = {
isBlocked: false,
riskScore: 0,
detectedThreats: [],
monitoredDownloads: new Set(),
behaviorPatterns: [],
resourceUsage: {
cpu: 0,
memory: 0,
requests: 0
},
aiConfidence: 0,
pageLoadTime: Date.now()
};
// 数据存储初始化
let trustedDomains = GM_getValue('trustedDomains', {});
let temporaryBypasses = GM_getValue('temporaryBypasses', {});
let securityLogs = GM_getValue('securityLogs', []);
debugLog('数据存储初始化完成');
// 当前网站信息
const currentHost = window.location.hostname;
const currentProtocol = window.location.protocol;
const currentURL = window.location.href;
debugLog('当前网站:', currentHost, '协议:', currentProtocol);
// 检测结果对象
let detectionResult = {
safe: true,
message: "该网站未检测到已知风险",
level: "safe",
details: [],
safetyIndicators: [],
aiAnalysis: null,
threatLevel: "low"
};
// 完整样式定义
GM_addStyle(`
/* 基础重置与隔离 */
.sec-helper-reset {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
/* 阻断页面 - 极简风格 */
.sec-helper-block-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
z-index: 2147483647;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 20px;
color: #fff;
text-align: center;
}
.sec-helper-block-icon {
font-size: 80px;
margin-bottom: 24px;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
.sec-helper-block-title {
font-size: 28px;
font-weight: 700;
margin-bottom: 16px;
text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}
.sec-helper-block-desc {
font-size: 16px;
line-height: 1.6;
max-width: 600px;
margin-bottom: 8px;
opacity: 0.9;
}
.sec-helper-block-domain {
font-family: 'Courier New', monospace;
background: rgba(255,255,255,0.15);
padding: 12px 20px;
border-radius: 8px;
margin: 20px 0;
border: 1px solid rgba(255,255,255,0.2);
font-size: 16px;
font-weight: 600;
}
.sec-helper-block-risks {
max-width: 600px;
width: 100%;
background: rgba(255,255,255,0.1);
border-radius: 12px;
padding: 20px;
margin: 20px 0;
border: 1px solid rgba(255,255,255,0.2);
}
.sec-helper-block-risks-title {
font-size: 16px;
font-weight: 600;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.sec-helper-block-risks-list {
list-style: none;
padding: 0;
font-size: 14px;
line-height: 1.6;
}
.sec-helper-block-risks-item {
margin-bottom: 8px;
padding-left: 20px;
position: relative;
text-align: left;
}
.sec-helper-block-risks-item::before {
content: "⚠️";
position: absolute;
left: 0;
top: 2px;
}
/* 阻断页面按钮区 */
.sec-helper-block-btns {
display: flex;
gap: 12px;
margin-top: 30px;
flex-wrap: wrap;
justify-content: center;
max-width: 600px;
width: 100%;
}
.sec-helper-block-btn {
padding: 12px 28px;
border-radius: 8px;
border: none;
font-size: 15px;
font-weight: 600;
cursor: pointer;
flex: 1;
min-width: 160px;
transition: all 0.3s ease;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
.sec-helper-block-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(0,0,0,0.3);
}
.sec-helper-btn-safe {
background: #fff;
color: #dc2626;
}
.sec-helper-btn-bypass {
background: rgba(255,255,255,0.2);
color: #fff;
border: 2px solid rgba(255,255,255,0.3);
}
.sec-helper-btn-trust {
background: rgba(255,255,255,0.15);
color: #fff;
border: 2px solid rgba(255,255,255,0.3);
}
/* 底部信息 */
.sec-helper-block-footer {
position: absolute;
bottom: 20px;
font-size: 12px;
color: rgba(255,255,255,0.7);
text-align: center;
}
/* AI分析样式 */
.sec-helper-ai-analysis {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 16px;
padding: 24px;
margin: 24px 0;
color: white;
box-shadow: 0 8px 32px rgba(0,0,0,0.2);
border: 1px solid rgba(255,255,255,0.2);
}
.sec-helper-ai-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
font-size: 20px;
font-weight: 700;
}
.sec-helper-ai-confidence {
background: rgba(255,255,255,0.2);
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
backdrop-filter: blur(10px);
font-weight: 600;
}
.sec-helper-ai-details {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
margin-top: 16px;
}
.sec-helper-ai-feature {
background: rgba(255,255,255,0.1);
padding: 16px;
border-radius: 12px;
backdrop-filter: blur(10px);
border: 1px solid rgba(255,255,255,0.2);
}
.sec-helper-ai-feature-name {
font-size: 12px;
opacity: 0.8;
margin-bottom: 6px;
font-weight: 500;
}
.sec-helper-ai-feature-value {
font-size: 16px;
font-weight: 700;
}
.sec-helper-threat-level {
display: inline-block;
padding: 6px 14px;
border-radius: 20px;
font-size: 12px;
font-weight: 700;
margin-left: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.sec-helper-level-low { background: #10b981; }
.sec-helper-level-medium { background: #f59e0b; }
.sec-helper-level-high { background: #ef4444; }
.sec-helper-level-critical { background: #7c3aed; }
/* 实时监控面板 */
.sec-helper-monitor-panel {
position: fixed;
top: 20px;
left: 20px;
background: rgba(255,255,255,0.95);
backdrop-filter: blur(20px);
border-radius: 16px;
padding: 20px;
box-shadow: 0 8px 32px rgba(0,0,0,0.15);
border: 1px solid rgba(255,255,255,0.2);
z-index: 2147483646;
max-width: 320px;
font-family: system-ui, -apple-system, sans-serif;
transition: all 0.3s ease;
}
.sec-helper-monitor-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.sec-helper-monitor-title {
font-weight: 700;
color: #1f2937;
font-size: 16px;
}
.sec-helper-monitor-close {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #6b7280;
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.2s;
}
.sec-helper-monitor-close:hover {
background: #f3f4f6;
}
.sec-helper-monitor-metrics {
display: flex;
gap: 12px;
margin-bottom: 16px;
}
.sec-helper-metric {
flex: 1;
text-align: center;
padding: 12px;
background: #f8fafc;
border-radius: 12px;
border: 1px solid #e5e7eb;
}
.sec-helper-metric-value {
font-size: 18px;
font-weight: 700;
color: #3b82f6;
margin-bottom: 4px;
}
.sec-helper-metric-label {
font-size: 11px;
color: #6b7280;
font-weight: 500;
}
/* 增强的通知系统 */
.sec-helper-smart-notification {
position: fixed;
top: 20px;
right: 20px;
background: #fff;
border-radius: 16px;
box-shadow: 0 10px 40px rgba(0,0,0,0.15);
padding: 0;
z-index: 2147483647;
max-width: 420px;
border-left: 6px solid #10b981;
transform: translateX(100%);
transition: transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
overflow: hidden;
}
.sec-helper-smart-notification.show {
transform: translateX(0);
}
.sec-helper-notification-header {
padding: 20px 24px;
border-bottom: 1px solid #f1f5f9;
display: flex;
align-items: center;
gap: 12px;
background: #fafafa;
}
.sec-helper-notification-icon {
width: 28px;
height: 28px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 14px;
font-weight: 600;
}
.sec-helper-icon-safe { background: #10b981; }
.sec-helper-icon-warning { background: #f59e0b; }
.sec-helper-icon-danger { background: #ef4444; }
.sec-helper-notification-body {
padding: 24px;
}
.sec-helper-notify-content {
font-size: 15px;
line-height: 1.5;
color: #374151;
margin-bottom: 16px;
}
.sec-helper-progress-bar {
height: 6px;
background: #e5e7eb;
border-radius: 3px;
overflow: hidden;
margin-top: 16px;
}
.sec-helper-progress-fill {
height: 100%;
background: linear-gradient(90deg, #10b981, #34d399);
transition: width 0.5s ease;
border-radius: 3px;
}
/* 白名单管理界面 */
.sec-helper-whitelist-manager {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.6);
backdrop-filter: blur(8px);
z-index: 2147483647;
display: none;
align-items: center;
justify-content: center;
padding: 20px;
box-sizing: border-box;
}
.sec-helper-whitelist-container {
background: #fff;
border-radius: 20px;
width: 100%;
max-width: 900px;
max-height: 90vh;
display: flex;
flex-direction: column;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
animation: modalSlideIn 0.3s ease;
}
@keyframes modalSlideIn {
from { transform: scale(0.9); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.sec-helper-whitelist-header {
padding: 24px 32px;
border-bottom: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: center;
background: #f9fafb;
}
.sec-helper-whitelist-title {
font-size: 20px;
font-weight: 700;
color: #1f2937;
margin: 0;
display: flex;
align-items: center;
gap: 12px;
}
.sec-helper-whitelist-close {
background: none;
border: none;
font-size: 28px;
cursor: pointer;
color: #6b7280;
width: 44px;
height: 44px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
}
.sec-helper-whitelist-close:hover {
color: #dc2626;
background: #fee2e2;
}
.sec-helper-whitelist-content {
padding: 0;
overflow-y: auto;
flex: 1;
}
.sec-helper-whitelist-toolbar {
padding: 20px 32px;
border-bottom: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 16px;
background: #fafafa;
}
.sec-helper-whitelist-search {
flex: 1;
max-width: 350px;
position: relative;
}
.sec-helper-whitelist-search input {
width: 100%;
padding: 12px 12px 12px 44px;
border-radius: 10px;
border: 2px solid #e5e7eb;
font-size: 15px;
transition: all 0.2s;
background: #fff;
}
.sec-helper-whitelist-search input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
}
.sec-helper-whitelist-search::before {
content: "🔍";
position: absolute;
left: 16px;
top: 50%;
transform: translateY(-50%);
font-size: 16px;
color: #6b7280;
z-index: 1;
}
.sec-helper-whitelist-filters {
display: flex;
gap: 8px;
}
.sec-helper-filter-btn {
padding: 8px 16px;
border-radius: 8px;
border: 2px solid #e5e7eb;
background: #fff;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
font-weight: 500;
}
.sec-helper-filter-btn:hover, .sec-helper-filter-btn.active {
background: #eff6ff;
border-color: #3b82f6;
color: #2563eb;
}
.sec-helper-whitelist-empty {
text-align: center;
padding: 80px 20px;
color: #6b7280;
}
.sec-helper-whitelist-empty-icon {
font-size: 64px;
margin-bottom: 20px;
opacity: 0.3;
}
.sec-helper-whitelist-empty h3 {
font-size: 18px;
margin-bottom: 8px;
color: #374151;
}
.sec-helper-whitelist-empty p {
font-size: 14px;
opacity: 0.7;
}
.sec-helper-whitelist-list {
list-style: none;
margin: 0;
padding: 0;
}
.sec-helper-whitelist-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 32px;
border-bottom: 1px solid #f3f4f6;
transition: background 0.2s;
}
.sec-helper-whitelist-item:last-child { border-bottom: none; }
.sec-helper-whitelist-item:hover { background: #f9fafb; }
.sec-helper-whitelist-domain {
font-weight: 600;
color: #1f2937;
font-family: 'Courier New', monospace;
font-size: 15px;
}
.sec-helper-whitelist-info {
font-size: 13px;
color: #6b7280;
margin-top: 6px;
display: flex;
align-items: center;
gap: 16px;
}
.sec-helper-whitelist-badge {
font-size: 12px;
padding: 4px 10px;
border-radius: 6px;
font-weight: 600;
}
.sec-helper-badge-permanent { background: #ecfdf5; color: #059669; border: 1px solid #d1fae5; }
.sec-helper-badge-temporary { background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; }
.sec-helper-whitelist-actions {
display: flex;
gap: 8px;
}
.sec-helper-whitelist-btn {
padding: 8px 16px;
border-radius: 6px;
border: none;
cursor: pointer;
font-size: 13px;
transition: all 0.2s;
font-weight: 600;
}
.sec-helper-btn-edit {
background: #eff6ff;
color: #2563eb;
border: 1px solid #dbeafe;
}
.sec-helper-btn-edit:hover { background: #dbeafe; }
.sec-helper-btn-remove {
background: #fee2e2;
color: #dc2626;
border: 1px solid #fecaca;
}
.sec-helper-btn-remove:hover { background: #fecaca; }
.sec-helper-whitelist-footer {
padding: 24px 32px;
border-top: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: center;
background: #f9fafb;
flex-wrap: wrap;
gap: 16px;
}
.sec-helper-whitelist-stats {
font-size: 14px;
color: #6b7280;
font-weight: 500;
}
.sec-helper-btn-add-current {
background: #3b82f6;
color: #fff;
padding: 12px 24px;
border-radius: 10px;
border: none;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
font-size: 14px;
box-shadow: 0 2px 8px rgba(59,130,246,0.3);
}
.sec-helper-btn-add-current:hover {
background: #2563eb;
box-shadow: 0 4px 12px rgba(59,130,246,0.4);
}
/* 信任弹窗 */
.sec-helper-trust-modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.5);
backdrop-filter: blur(8px);
z-index: 2147483647;
display: none;
align-items: center;
justify-content: center;
padding: 20px;
box-sizing: border-box;
}
.sec-helper-trust-container {
background: #fff;
border-radius: 20px;
width: 100%;
max-width: 500px;
padding: 32px;
box-shadow: 0 20px 60px rgba(0,0,0,0.2);
animation: modalSlideIn 0.3s ease;
}
.sec-helper-trust-title {
font-size: 20px;
font-weight: 700;
color: #1f2937;
margin: 0 0 20px 0;
display: flex;
align-items: center;
gap: 12px;
}
.sec-helper-trust-domain {
font-family: 'Courier New', monospace;
background: #f8fafc;
padding: 16px;
border-radius: 10px;
margin-bottom: 24px;
word-break: break-all;
font-size: 15px;
font-weight: 600;
border: 1px solid #e5e7eb;
}
.sec-helper-trust-form-group {
margin-bottom: 24px;
}
.sec-helper-trust-label {
display: block;
margin-bottom: 10px;
font-weight: 600;
color: #374151;
font-size: 14px;
}
.sec-helper-trust-select {
width: 100%;
padding: 12px 16px;
border-radius: 10px;
border: 2px solid #e5e7eb;
font-size: 15px;
background: #fff;
transition: all 0.2s;
}
.sec-helper-trust-select:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
}
.sec-helper-trust-note {
font-size: 13px;
color: #dc2626;
margin-top: 12px;
padding: 12px;
background: #fef2f2;
border-radius: 8px;
border: 1px solid #fecaca;
font-weight: 500;
}
.sec-helper-trust-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
margin-top: 28px;
}
.sec-helper-btn-cancel {
padding: 12px 24px;
border-radius: 10px;
border: 2px solid #d1d5db;
background: #fff;
font-weight: 600;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}
.sec-helper-btn-cancel:hover {
background: #f9fafb;
border-color: #9ca3af;
}
.sec-helper-btn-confirm {
padding: 12px 24px;
border-radius: 10px;
border: none;
background: #10b981;
color: #fff;
font-weight: 600;
cursor: pointer;
font-size: 14px;
transition: background 0.2s;
box-shadow: 0 2px 8px rgba(16,185,129,0.3);
}
.sec-helper-btn-confirm:hover {
background: #059669;
box-shadow: 0 4px 12px rgba(16,185,129,0.4);
}
/* 下载提示样式 */
.sec-helper-download-prompt {
position: fixed;
bottom: 20px;
right: 20px;
background: #fff;
border-radius: 16px;
box-shadow: 0 10px 40px rgba(0,0,0,0.15);
padding: 24px;
z-index: 2147483647;
max-width: 380px;
border-left: 6px solid #f59e0b;
animation: slideUp 0.3s ease;
}
@keyframes slideUp {
from { transform: translateY(100%); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.sec-helper-download-title {
font-weight: 700;
margin-bottom: 12px;
color: #1f2937;
display: flex;
align-items: center;
gap: 10px;
font-size: 16px;
}
.sec-helper-download-risk {
color: #dc2626;
font-weight: 600;
}
.sec-helper-download-filename {
font-family: 'Courier New', monospace;
font-size: 14px;
color: #4b5563;
margin-bottom: 16px;
word-break: break-all;
background: #f8fafc;
padding: 12px;
border-radius: 8px;
border: 1px solid #e5e7eb;
}
.sec-helper-download-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
}
.sec-helper-download-btn {
padding: 10px 20px;
border-radius: 8px;
font-size: 14px;
cursor: pointer;
border: none;
font-weight: 600;
transition: all 0.2s;
}
.sec-helper-download-cancel {
background: #f3f4f6;
color: #4b5563;
border: 1px solid #d1d5db;
}
.sec-helper-download-cancel:hover {
background: #e5e7eb;
}
.sec-helper-download-proceed {
background: #ef4444;
color: #fff;
box-shadow: 0 2px 8px rgba(239,68,68,0.3);
}
.sec-helper-download-proceed:hover {
background: #dc2626;
box-shadow: 0 4px 12px rgba(239,68,68,0.4);
}
/* 调试面板 */
.sec-helper-debug-panel {
position: fixed;
bottom: 10px;
right: 10px;
background: #1f2937;
color: white;
padding: 12px 16px;
border-radius: 10px;
font-size: 12px;
z-index: 2147483646;
max-width: 280px;
font-family: 'Courier New', monospace;
border: 1px solid #374151;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}
.sec-helper-debug-header {
font-weight: 700;
margin-bottom: 6px;
color: #60a5fa;
display: flex;
align-items: center;
gap: 6px;
}
.sec-helper-debug-item {
margin: 4px 0;
display: flex;
justify-content: space-between;
}
.sec-helper-debug-label {
color: #9ca3af;
}
.sec-helper-debug-value {
color: #f3f4f6;
font-weight: 600;
}
/* 响应式适配 */
@media (max-width: 768px) {
.sec-helper-monitor-panel {
top: 10px;
left: 10px;
right: 10px;
max-width: none;
}
.sec-helper-smart-notification {
top: 10px;
right: 10px;
left: 10px;
max-width: none;
}
.sec-helper-block-btns {
flex-direction: column;
}
.sec-helper-block-btn {
width: 100%;
min-width: auto;
}
.sec-helper-whitelist-container {
margin: 10px;
max-height: 95vh;
}
.sec-helper-whitelist-toolbar {
flex-direction: column;
align-items: stretch;
}
.sec-helper-whitelist-search {
max-width: none;
}
}
@media (max-width: 480px) {
.sec-helper-whitelist-item {
flex-direction: column;
align-items: flex-start;
gap: 12px;
padding: 16px;
}
.sec-helper-whitelist-actions {
align-self: stretch;
justify-content: space-between;
}
.sec-helper-whitelist-btn {
flex: 1;
}
}
`);
debugLog('样式加载完成');
// 调试面板
function createDebugPanel() {
if (!DEBUG_MODE) return;
const panel = document.createElement('div');
panel.className = 'sec-helper-debug-panel';
panel.innerHTML = `
<div class="sec-helper-debug-header">🔧 安全助手调试面板</div>
<div class="sec-helper-debug-item">
<span class="sec-helper-debug-label">状态:</span>
<span class="sec-helper-debug-value" id="sec-helper-debug-status">运行中</span>
</div>
<div class="sec-helper-debug-item">
<span class="sec-helper-debug-label">网站:</span>
<span class="sec-helper-debug-value">${currentHost}</span>
</div>
<div class="sec-helper-debug-item">
<span class="sec-helper-debug-label">风险:</span>
<span class="sec-helper-debug-value" id="sec-helper-debug-risk">0%</span>
</div>
<div class="sec-helper-debug-item">
<span class="sec-helper-debug-label">威胁:</span>
<span class="sec-helper-debug-value" id="sec-helper-debug-threats">0</span>
</div>
`;
document.body.appendChild(panel);
debugLog('调试面板创建完成');
// 更新调试信息
setInterval(() => {
const riskEl = document.getElementById('sec-helper-debug-risk');
const threatsEl = document.getElementById('sec-helper-debug-threats');
if (riskEl) riskEl.textContent = `${Math.round(securityState.riskScore * 100)}%`;
if (threatsEl) threatsEl.textContent = securityState.detectedThreats.length;
}, 1000);
}
// AI增强检测引擎
class AIEnhancedDetector {
constructor() {
this.modelWeights = {
domainRisk: 0.3,
behaviorRisk: 0.25,
contentRisk: 0.2,
networkRisk: 0.15,
reputationRisk: 0.1
};
}
// 提取网站特征
extractFeatures() {
debugLog('开始提取网站特征...');
const features = {
// 域名特征
domainLength: currentHost.length,
domainEntropy: this.calculateEntropy(currentHost),
subdomainCount: currentHost.split('.').length - 2,
isIPAddress: /^(\d+\.){3}\d+$/.test(currentHost),
// SSL特征
hasSSL: currentProtocol === 'https:',
certificateValid: this.checkCertificate(),
// 内容特征
scriptCount: document.scripts ? document.scripts.length : 0,
iframeCount: document.querySelectorAll('iframe').length,
formCount: document.querySelectorAll('form').length,
hiddenElements: document.querySelectorAll('[style*="display: none"], [style*="visibility: hidden"]').length,
// 行为特征
externalRequests: this.countExternalResources(),
suspiciousPatterns: this.detectSuspiciousPatterns()
};
debugLog('网站特征提取完成:', features);
return features;
}
calculateEntropy(str) {
const len = str.length;
if (len === 0) return 0;
const freq = {};
for (let char of str) {
freq[char] = (freq[char] || 0) + 1;
}
return -Object.values(freq).reduce((sum, f) => {
const p = f / len;
return sum + p * Math.log2(p);
}, 0);
}
checkCertificate() {
return currentProtocol === 'https:' &&
!window.location.port &&
window.location.hostname.includes('.');
}
countExternalResources() {
try {
const resources = performance.getEntriesByType('resource');
return resources.filter(r => !r.name.includes(window.location.hostname)).length;
} catch {
return 0;
}
}
detectSuspiciousPatterns() {
const scripts = Array.from(document.scripts);
let suspiciousCount = 0;
scripts.forEach(script => {
const src = script.src.toLowerCase();
const content = script.textContent.toLowerCase();
if (src.includes('cryptonight') || src.includes('coinhive') ||
content.includes('cryptonight') || content.includes('coinhive')) {
suspiciousCount++;
}
});
return suspiciousCount;
}
// 机器学习风险评估
async assessRisk() {
debugLog('开始AI风险评估...');
const features = this.extractFeatures();
let riskScore = 0;
const details = [];
// 域名风险评估
const domainRisk = this.assessDomainRisk(features);
riskScore += domainRisk * this.modelWeights.domainRisk;
if (domainRisk > 0.3) details.push(`域名特征可疑`);
// 行为风险评估
const behaviorRisk = this.assessBehaviorRisk(features);
riskScore += behaviorRisk * this.modelWeights.behaviorRisk;
if (behaviorRisk > 0.3) details.push(`页面行为异常`);
// 内容风险评估
const contentRisk = this.assessContentRisk(features);
riskScore += contentRisk * this.modelWeights.contentRisk;
if (contentRisk > 0.3) details.push(`页面内容风险`);
// 网络风险评估
const networkRisk = this.assessNetworkRisk(features);
riskScore += networkRisk * this.modelWeights.networkRisk;
if (networkRisk > 0.3) details.push(`网络请求异常`);
securityState.aiConfidence = this.calculateConfidence(features);
securityState.riskScore = riskScore;
const result = {
score: riskScore,
confidence: securityState.aiConfidence,
features: features,
details: details,
threatLevel: this.getThreatLevel(riskScore)
};
debugLog('AI风险评估完成:', result);
return result;
}
assessDomainRisk(features) {
let risk = 0;
if (features.domainLength > 50) risk += 0.3;
if (features.domainEntropy > 4) risk += 0.2;
if (features.subdomainCount > 3) risk += 0.2;
if (features.isIPAddress) risk += 0.4;
if (!features.hasSSL) risk += 0.3;
return Math.min(1, risk);
}
assessBehaviorRisk(features) {
let risk = 0;
if (features.externalRequests > 50) risk += 0.4;
if (features.suspiciousPatterns > 0) risk += 0.6;
return Math.min(1, risk);
}
assessContentRisk(features) {
let risk = 0;
if (features.scriptCount > 30) risk += 0.4;
if (features.hiddenElements > 20) risk += 0.3;
if (features.iframeCount > 5) risk += 0.2;
if (features.formCount > 10) risk += 0.2;
return Math.min(1, risk);
}
assessNetworkRisk(features) {
let risk = 0;
if (features.externalRequests > 100) risk += 0.5;
return Math.min(1, risk);
}
calculateConfidence(features) {
const dataPoints = Object.values(features).filter(val => val > 0).length;
return Math.min(1, dataPoints / Object.keys(features).length * 0.8 + 0.2);
}
getThreatLevel(score) {
if (score < 0.3) return 'low';
if (score < 0.6) return 'medium';
if (score < 0.8) return 'high';
return 'critical';
}
}
// 假冒域名检测
function detectFakeDomain() {
if (!CONFIG.fakeDomainCheck.enable) return null;
const cleanHost = currentHost.replace(/^www\./, '');
let maxSimilarity = 0;
let detectedBrand = null;
for (const brand of CONFIG.fakeDomainCheck.knownBrands) {
const similarity = stringSimilarity(cleanHost, brand.domain);
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
detectedBrand = brand;
}
}
if (detectedBrand && maxSimilarity >= detectedBrand.threshold && !cleanHost.includes(detectedBrand.domain)) {
debugLog('检测到假冒域名:', detectedBrand.name, '相似度:', maxSimilarity);
return {
brand: detectedBrand.name,
official: detectedBrand.domain,
similarity: Math.round(maxSimilarity * 100),
weight: detectedBrand.weight
};
}
return null;
}
// 字符串相似度算法
function stringSimilarity(str1, str2) {
const len1 = str1.length;
const len2 = str2.length;
const matrix = Array.from({length: len1 + 1}, () => Array(len2 + 1).fill(0));
for (let i = 0; i <= len1; i++) matrix[i][0] = i;
for (let j = 0; j <= len2; j++) matrix[0][j] = j;
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
const cost = str1[i-1] === str2[j-1] ? 0 : 1;
matrix[i][j] = Math.min(
matrix[i-1][j] + 1,
matrix[i][j-1] + 1,
matrix[i-1][j-1] + cost
);
}
}
return 1 - matrix[len1][len2] / Math.max(len1, len2);
}
// 下载保护系统
class DownloadProtector {
constructor() {
this.init();
}
init() {
this.monitorDownloads();
debugLog('下载保护系统初始化完成');
}
monitorDownloads() {
// 拦截a标签下载
document.addEventListener('click', (e) => {
const link = e.target.closest('a');
if (link && link.href && this.isDownloadLink(link)) {
e.preventDefault();
e.stopPropagation();
this.analyzeDownload(link.href, link.download || this.getFilenameFromURL(link.href));
}
}, true);
}
isDownloadLink(link) {
return link.download ||
this.isExecutableFile(link.href) ||
(link.getAttribute('target') === '_blank' && this.isSuspiciousFile(link.href));
}
isExecutableFile(url) {
const ext = this.getFileExtension(url).toLowerCase();
return CONFIG.downloadMonitor.riskyExtensions.includes(ext);
}
isSuspiciousFile(url) {
const filename = this.getFilenameFromURL(url).toLowerCase();
return CONFIG.downloadMonitor.suspiciousPatterns.some(pattern =>
filename.includes(pattern));
}
getFileExtension(url) {
return url.split('.').pop().split(/[#?]/)[0];
}
getFilenameFromURL(url) {
return url.split('/').pop().split(/[#?]/)[0];
}
async analyzeDownload(url, filename) {
const extension = this.getFileExtension(url).toLowerCase();
const riskLevel = this.assessDownloadRisk(extension, filename, url);
if (riskLevel === 'high') {
this.showDownloadWarning(url, filename, '高风险文件类型');
} else if (riskLevel === 'medium') {
this.showDownloadWarning(url, filename, '潜在风险文件');
} else {
this.proceedWithDownload(url);
}
}
assessDownloadRisk(extension, filename, url) {
if (CONFIG.downloadMonitor.riskyExtensions.includes(extension)) {
return 'high';
}
if (CONFIG.downloadMonitor.suspiciousPatterns.some(pattern =>
filename.toLowerCase().includes(pattern))) {
return 'medium';
}
return 'low';
}
showDownloadWarning(url, filename, reason) {
const warning = document.createElement('div');
warning.className = 'sec-helper-download-prompt';
warning.innerHTML = `
<div class="sec-helper-download-title">
⚠️ 下载安全警告
<span class="sec-helper-download-risk">${reason}</span>
</div>
<div class="sec-helper-download-filename">${filename}</div>
<div style="font-size: 13px; color: #6b7280; margin: 12px 0;">
文件类型: ${this.getFileExtension(url).toUpperCase()} | 来源: ${currentHost}
</div>
<div class="sec-helper-download-actions">
<button class="sec-helper-download-btn sec-helper-download-cancel">取消下载</button>
<button class="sec-helper-download-btn sec-helper-download-proceed">继续下载</button>
</div>
`;
const cancelBtn = warning.querySelector('.sec-helper-download-cancel');
const proceedBtn = warning.querySelector('.sec-helper-download-proceed');
cancelBtn.addEventListener('click', () => warning.remove());
proceedBtn.addEventListener('click', () => {
warning.remove();
this.proceedWithDownload(url);
});
document.body.appendChild(warning);
// 15秒后自动关闭
setTimeout(() => {
if (warning.parentNode) {
warning.remove();
}
}, 15000);
debugLog('下载警告已显示:', filename, reason);
}
proceedWithDownload(url) {
window.open(url, '_blank');
debugLog('允许下载:', url);
}
}
// 信任域名管理
function isTrustedDomain() {
cleanupExpiredDomains();
const isTrusted = !!trustedDomains[currentHost];
debugLog('信任域名检查:', currentHost, isTrusted ? '已信任' : '未信任');
return isTrusted;
}
function hasTemporaryBypass() {
const now = Date.now();
Object.keys(temporaryBypasses).forEach(domain => {
if (temporaryBypasses[domain] < now) delete temporaryBypasses[domain];
});
GM_setValue('temporaryBypasses', temporaryBypasses);
const hasBypass = !!temporaryBypasses[currentHost];
debugLog('临时绕过检查:', hasBypass ? '已绕过' : '未绕过');
return hasBypass;
}
function addTemporaryBypass() {
temporaryBypasses[currentHost] = Date.now() + CONFIG.highRiskBlock.bypassExpire;
GM_setValue('temporaryBypasses', temporaryBypasses);
debugLog('添加临时绕过:', currentHost);
}
function cleanupExpiredDomains() {
const now = Date.now();
let changed = false;
Object.keys(trustedDomains).forEach(domain => {
const info = trustedDomains[domain];
if (info.duration !== 0 && info.expire < now) {
delete trustedDomains[domain];
changed = true;
debugLog('清理过期域名:', domain);
}
});
if (changed) {
GM_setValue('trustedDomains', trustedDomains);
}
}
// 白名单管理功能
function initWhitelistManager() {
if (document.getElementById('sec-helper-whitelistManager')) return;
const manager = document.createElement('div');
manager.id = 'sec-helper-whitelistManager';
manager.className = 'sec-helper-whitelist-manager';
const container = document.createElement('div');
container.className = 'sec-helper-whitelist-container';
// 头部区域
const header = document.createElement('div');
header.className = 'sec-helper-whitelist-header';
const title = document.createElement('h2');
title.className = 'sec-helper-whitelist-title';
title.innerHTML = '🛡️ 信任网站管理';
const closeBtn = document.createElement('button');
closeBtn.className = 'sec-helper-whitelist-close';
closeBtn.textContent = '×';
closeBtn.addEventListener('click', hideWhitelistManager);
header.appendChild(title);
header.appendChild(closeBtn);
container.appendChild(header);
// 工具栏
const toolbar = document.createElement('div');
toolbar.className = 'sec-helper-whitelist-toolbar';
// 搜索框
const search = document.createElement('div');
search.className = 'sec-helper-whitelist-search';
const searchInput = document.createElement('input');
searchInput.placeholder = '搜索信任网站...';
searchInput.addEventListener('input', (e) => filterWhitelist(e.target.value));
search.appendChild(searchInput);
toolbar.appendChild(search);
// 过滤按钮
const filters = document.createElement('div');
filters.className = 'sec-helper-whitelist-filters';
const filterTypes = [
{type: 'all', text: '全部'},
{type: 'permanent', text: '永久信任'},
{type: 'temporary', text: '临时信任'}
];
filterTypes.forEach(type => {
const btn = document.createElement('button');
btn.className = `sec-helper-filter-btn ${type.type === 'all' ? 'active' : ''}`;
btn.dataset.filter = type.type;
btn.textContent = type.text;
btn.addEventListener('click', () => {
document.querySelectorAll('.sec-helper-filter-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
filterWhitelist(searchInput.value, type.type);
});
filters.appendChild(btn);
});
toolbar.appendChild(filters);
container.appendChild(toolbar);
// 内容区域
const content = document.createElement('div');
content.className = 'sec-helper-whitelist-content';
content.id = 'sec-helper-whitelistContent';
container.appendChild(content);
// 底部区域
const footer = document.createElement('div');
footer.className = 'sec-helper-whitelist-footer';
const stats = document.createElement('div');
stats.className = 'sec-helper-whitelist-stats';
stats.innerHTML = `共 <span id="sec-helper-domainCount">0</span> 个信任网站(最多 ${CONFIG.whitelist.maxDomains} 个)`;
const addBtn = document.createElement('button');
addBtn.className = 'sec-helper-btn-add-current';
addBtn.textContent = '添加当前网站到信任列表';
addBtn.addEventListener('click', () => showTrustModal(currentHost));
footer.appendChild(stats);
footer.appendChild(addBtn);
container.appendChild(footer);
manager.appendChild(container);
document.body.appendChild(manager);
debugLog('白名单管理器初始化完成');
}
function showWhitelistManager() {
initWhitelistManager();
cleanupExpiredDomains();
const content = document.getElementById('sec-helper-whitelistContent');
const domainCount = document.getElementById('sec-helper-domainCount');
content.innerHTML = '';
// 排序并渲染信任域名
const sortedDomains = Object.entries(trustedDomains)
.sort((a, b) => b[1].added - a[1].added);
domainCount.textContent = sortedDomains.length;
if (sortedDomains.length === 0) {
content.innerHTML = `
<div class="sec-helper-whitelist-empty">
<div class="sec-helper-whitelist-empty-icon">📋</div>
<h3>您的信任网站列表为空</h3>
<p>添加网站可避免安全检测提示,让浏览更便捷</p>
</div>
`;
} else {
const list = document.createElement('ul');
list.className = 'sec-helper-whitelist-list';
sortedDomains.forEach(([domain, info]) => {
const li = document.createElement('li');
li.className = 'sec-helper-whitelist-item';
li.dataset.domain = domain;
li.dataset.permanent = info.duration === 0;
// 域名信息
const domainInfo = document.createElement('div');
const domainName = document.createElement('div');
domainName.className = 'sec-helper-whitelist-domain';
domainName.textContent = domain;
const infoLine = document.createElement('div');
infoLine.className = 'sec-helper-whitelist-info';
const badge = document.createElement('span');
badge.className = `sec-helper-whitelist-badge ${info.duration === 0 ? 'sec-helper-badge-permanent' : 'sec-helper-badge-temporary'}`;
badge.textContent = info.duration === 0 ? '永久信任' : `有效期至: ${formatDate(info.expire)}`;
const addedDate = document.createElement('span');
addedDate.textContent = `添加于: ${formatDate(info.added)}`;
infoLine.appendChild(badge);
infoLine.appendChild(addedDate);
domainInfo.appendChild(domainName);
domainInfo.appendChild(infoLine);
// 操作按钮
const actions = document.createElement('div');
actions.className = 'sec-helper-whitelist-actions';
const editBtn = document.createElement('button');
editBtn.className = 'sec-helper-whitelist-btn sec-helper-btn-edit';
editBtn.textContent = '编辑';
editBtn.addEventListener('click', () => editWhitelistDomain(domain));
const removeBtn = document.createElement('button');
removeBtn.className = 'sec-helper-whitelist-btn sec-helper-btn-remove';
removeBtn.textContent = '移除';
removeBtn.addEventListener('click', () => removeFromWhitelist(domain));
actions.appendChild(editBtn);
actions.appendChild(removeBtn);
li.appendChild(domainInfo);
li.appendChild(actions);
list.appendChild(li);
});
content.appendChild(list);
}
document.getElementById('sec-helper-whitelistManager').style.display = 'flex';
debugLog('显示白名单管理器');
}
function hideWhitelistManager() {
const manager = document.getElementById('sec-helper-whitelistManager');
if (manager) {
manager.style.display = 'none';
}
}
function filterWhitelist(searchTerm = '', filterType = 'all') {
cleanupExpiredDomains();
const searchLower = searchTerm.toLowerCase();
const items = document.querySelectorAll('.sec-helper-whitelist-item');
let visibleCount = 0;
items.forEach(item => {
const domain = item.querySelector('.sec-helper-whitelist-domain').textContent.toLowerCase();
const isPermanent = item.dataset.permanent === 'true';
const matchSearch = domain.includes(searchLower);
let matchFilter = true;
if (filterType === 'permanent') matchFilter = isPermanent;
if (filterType === 'temporary') matchFilter = !isPermanent;
if (matchSearch && matchFilter) {
item.style.display = 'flex';
visibleCount++;
} else {
item.style.display = 'none';
}
});
// 空状态处理
let emptyState = document.querySelector('.sec-helper-whitelist-empty');
const content = document.getElementById('sec-helper-whitelistContent');
if (visibleCount === 0 && !emptyState && content) {
emptyState = document.createElement('div');
emptyState.className = 'sec-helper-whitelist-empty';
emptyState.innerHTML = '<div class="sec-helper-whitelist-empty-icon">🔍</div><h3>未找到匹配的信任网站</h3><p>尝试调整搜索条件或筛选类型</p>';
content.appendChild(emptyState);
} else if (visibleCount > 0 && emptyState) {
emptyState.remove();
}
}
// 信任弹窗功能
function createTrustModal() {
if (document.getElementById('sec-helper-trustModal')) return;
const modal = document.createElement('div');
modal.id = 'sec-helper-trustModal';
modal.className = 'sec-helper-trust-modal';
const container = document.createElement('div');
container.className = 'sec-helper-trust-container';
// 标题
const title = document.createElement('h3');
title.className = 'sec-helper-trust-title';
title.innerHTML = '✅ 添加信任网站';
// 域名显示
const domainDisplay = document.createElement('div');
domainDisplay.className = 'sec-helper-trust-domain';
domainDisplay.id = 'sec-helper-trustDomain';
domainDisplay.textContent = currentHost;
// 有效期选择
const formGroup = document.createElement('div');
formGroup.className = 'sec-helper-trust-form-group';
const label = document.createElement('label');
label.className = 'sec-helper-trust-label';
label.textContent = '信任有效期';
formGroup.appendChild(label);
const select = document.createElement('select');
select.className = 'sec-helper-trust-select';
select.id = 'sec-helper-trustDuration';
const durations = [7, 30, 90];
durations.forEach(dur => {
const option = document.createElement('option');
option.value = dur;
option.textContent = `${dur}天`;
if (dur === 30) option.selected = true;
select.appendChild(option);
});
if (CONFIG.whitelist.allowPermanent) {
const permOption = document.createElement('option');
permOption.value = '0';
permOption.textContent = '永久信任';
select.appendChild(permOption);
}
formGroup.appendChild(select);
// 风险提示
const note = document.createElement('div');
note.className = 'sec-helper-trust-note';
note.textContent = '⚠️ 仅信任确认安全的网站,未知网站可能存在风险';
// 操作按钮
const actions = document.createElement('div');
actions.className = 'sec-helper-trust-actions';
const cancelBtn = document.createElement('button');
cancelBtn.className = 'sec-helper-btn-cancel';
cancelBtn.textContent = '取消';
cancelBtn.addEventListener('click', hideTrustModal);
const confirmBtn = document.createElement('button');
confirmBtn.className = 'sec-helper-btn-confirm';
confirmBtn.textContent = '确认添加';
confirmBtn.addEventListener('click', () => {
const domain = document.getElementById('sec-helper-trustDomain').textContent;
const duration = parseInt(document.getElementById('sec-helper-trustDuration').value);
addToWhitelist(domain, duration);
});
actions.appendChild(cancelBtn);
actions.appendChild(confirmBtn);
container.appendChild(title);
container.appendChild(domainDisplay);
container.appendChild(formGroup);
container.appendChild(note);
container.appendChild(actions);
modal.appendChild(container);
document.body.appendChild(modal);
debugLog('信任弹窗创建完成');
}
function showTrustModal(domain, isEdit = false) {
createTrustModal();
const modal = document.getElementById('sec-helper-trustModal');
const domainEl = document.getElementById('sec-helper-trustDomain');
const titleEl = modal.querySelector('.sec-helper-trust-title');
const durationEl = document.getElementById('sec-helper-trustDuration');
domainEl.textContent = domain;
if (isEdit) {
titleEl.innerHTML = '✏️ 编辑信任设置';
if (trustedDomains[domain]) {
durationEl.value = trustedDomains[domain].duration.toString();
}
} else {
titleEl.innerHTML = '✅ 添加信任网站';
durationEl.value = '30';
}
modal.style.display = 'flex';
debugLog('显示信任弹窗:', domain, isEdit ? '编辑模式' : '添加模式');
}
function hideTrustModal() {
const modal = document.getElementById('sec-helper-trustModal');
if (modal) {
modal.style.display = 'none';
}
}
function addToWhitelist(domain, duration) {
if (Object.keys(trustedDomains).length >= CONFIG.whitelist.maxDomains) {
alert(`已达最大信任数量(${CONFIG.whitelist.maxDomains}个),请先移除部分网站`);
return;
}
const now = Date.now();
const expire = duration > 0 ? now + duration * 24 * 60 * 60 * 1000 : 0;
trustedDomains[domain] = {
added: now,
expire: expire,
duration: duration
};
GM_setValue('trustedDomains', trustedDomains);
hideTrustModal();
hideWhitelistManager();
GM_notification({
title: '信任设置成功',
text: `网站 ${domain} 已添加到信任列表`,
timeout: 3000
});
// 添加信任后自动刷新页面
setTimeout(() => {
window.location.reload();
}, 1000);
debugLog('添加到白名单:', domain, '有效期:', duration);
}
function removeFromWhitelist(domain) {
if (confirm(`确定移除 ${domain} 的信任吗?`)) {
delete trustedDomains[domain];
GM_setValue('trustedDomains', trustedDomains);
showWhitelistManager();
GM_notification({
title: '信任已移除',
text: `网站 ${domain} 已从信任列表中移除`,
timeout: 3000
});
debugLog('从白名单移除:', domain);
}
}
function editWhitelistDomain(domain) {
hideWhitelistManager();
showTrustModal(domain, true);
}
// 智能通知系统
function showSmartNotification() {
debugLog('显示智能通知:', detectionResult.level, detectionResult.message);
// 移除之前的通知
const oldNotification = document.querySelector('.sec-helper-smart-notification');
if (oldNotification) {
oldNotification.remove();
}
const notification = document.createElement('div');
notification.className = `sec-helper-smart-notification sec-helper-notify-${detectionResult.level}`;
const iconClass = detectionResult.level === 'danger' ? 'sec-helper-icon-danger' :
detectionResult.level === 'warning' ? 'sec-helper-icon-warning' : 'sec-helper-icon-safe';
const iconText = detectionResult.level === 'danger' ? '⚠️' :
detectionResult.level === 'warning' ? '🔔' : '✅';
notification.innerHTML = `
<div class="sec-helper-notification-header">
<div class="sec-helper-notification-icon ${iconClass}">${iconText}</div>
<div class="sec-helper-notification-title">
${detectionResult.level === 'danger' ? '高风险警告' :
detectionResult.level === 'warning' ? '安全提醒' : '安全状态'}
<span class="sec-helper-threat-level sec-helper-level-${detectionResult.threatLevel}">
${detectionResult.threatLevel.toUpperCase()}
</span>
</div>
</div>
<div class="sec-helper-notification-body">
<div class="sec-helper-notify-content">${detectionResult.message}</div>
${detectionResult.aiAnalysis ? `
<div class="sec-helper-ai-confidence">
AI风险评估: ${(detectionResult.aiAnalysis.score * 100).toFixed(1)}% (置信度: ${(detectionResult.aiAnalysis.confidence * 100).toFixed(1)}%)
</div>
` : ''}
${detectionResult.details.length > 0 ? `
<div style="margin-top: 16px; font-size: 13px; color: #6b7280; line-height: 1.5;">
<strong>检测详情:</strong><br>
${detectionResult.details.join('<br>')}
</div>
` : ''}
<div class="sec-helper-progress-bar">
<div class="sec-helper-progress-fill" style="width: ${securityState.riskScore * 100}%"></div>
</div>
</div>
`;
document.body.appendChild(notification);
// 显示动画
setTimeout(() => notification.classList.add('show'), 100);
// 安全通知自动关闭
if (detectionResult.level === 'safe') {
setTimeout(() => {
notification.classList.remove('show');
setTimeout(() => {
if (notification.parentNode) {
notification.remove();
}
}, 300);
}, CONFIG.autoCloseSafe);
} else {
// 危险警告需要手动关闭
const closeBtn = document.createElement('div');
closeBtn.className = 'sec-helper-notify-close';
closeBtn.textContent = '×';
closeBtn.style.position = 'absolute';
closeBtn.style.top = '12px';
closeBtn.style.right = '16px';
closeBtn.style.cursor = 'pointer';
closeBtn.style.fontWeight = 'bold';
closeBtn.style.fontSize = '20px';
closeBtn.style.color = '#6b7280';
closeBtn.addEventListener('click', () => {
notification.classList.remove('show');
setTimeout(() => {
if (notification.parentNode) {
notification.remove();
}
}, 300);
});
notification.appendChild(closeBtn);
}
}
// 实时监控面板
function createMonitorPanel() {
const panel = document.createElement('div');
panel.className = 'sec-helper-monitor-panel';
panel.innerHTML = `
<div class="sec-helper-monitor-header">
<div class="sec-helper-monitor-title">🛡️ 安全监控</div>
<button class="sec-helper-monitor-close">×</button>
</div>
<div class="sec-helper-monitor-metrics">
<div class="sec-helper-metric">
<div class="sec-helper-metric-value" id="sec-helper-riskScore">0%</div>
<div class="sec-helper-metric-label">风险评分</div>
</div>
<div class="sec-helper-metric">
<div class="sec-helper-metric-value" id="sec-helper-threatCount">0</div>
<div class="sec-helper-metric-label">威胁数量</div>
</div>
<div class="sec-helper-metric">
<div class="sec-helper-metric-value" id="sec-helper-aiConfidence">0%</div>
<div class="sec-helper-metric-label">AI置信度</div>
</div>
</div>
<div style="font-size: 11px; color: #9ca3af; text-align: center; margin-top: 8px;">
实时更新 • 网站: ${currentHost}
</div>
`;
const closeBtn = panel.querySelector('.sec-helper-monitor-close');
closeBtn.addEventListener('click', () => {
panel.style.display = 'none';
});
document.body.appendChild(panel);
debugLog('监控面板创建完成');
// 更新监控数据
setInterval(() => {
const riskScore = panel.querySelector('#sec-helper-riskScore');
const threatCount = panel.querySelector('#sec-helper-threatCount');
const aiConfidence = panel.querySelector('#sec-helper-aiConfidence');
if (riskScore) riskScore.textContent = `${Math.round(securityState.riskScore * 100)}%`;
if (threatCount) threatCount.textContent = securityState.detectedThreats.length;
if (aiConfidence) aiConfidence.textContent = `${Math.round(securityState.aiConfidence * 100)}%`;
}, 2000);
}
// 阻断页面
function blockImmediately(riskDetails) {
if (securityState.isBlocked) return;
securityState.isBlocked = true;
debugLog('开始阻断页面,风险详情:', riskDetails);
// 强制停止页面加载
try {
window.stop();
document.documentElement.innerHTML = '';
document.body.innerHTML = '';
document.body.className = '';
document.body.style.cssText = 'margin: 0; padding: 0;';
} catch (e) {
debugLog('清理页面时出错:', e);
}
// 检测假冒域名
const fakeDomain = detectFakeDomain();
if (fakeDomain) {
riskDetails.push(`假冒网站: 模仿"${fakeDomain.brand}",相似度${fakeDomain.similarity}%`);
}
// 创建阻断页面
const overlay = document.createElement('div');
overlay.className = 'sec-helper-block-overlay';
// 图标
const icon = document.createElement('div');
icon.className = 'sec-helper-block-icon';
icon.textContent = '🚫';
overlay.appendChild(icon);
// 标题
const title = document.createElement('div');
title.className = 'sec-helper-block-title';
title.textContent = '危险网站已拦截';
overlay.appendChild(title);
// 描述
const desc = document.createElement('div');
desc.className = 'sec-helper-block-desc';
desc.textContent = 'AI安全系统检测到高风险威胁,为保护您的设备和信息安全,已自动阻断访问。';
overlay.appendChild(desc);
// 域名
const domain = document.createElement('div');
domain.className = 'sec-helper-block-domain';
domain.textContent = `被拦截网站:${currentHost}`;
overlay.appendChild(domain);
// 风险详情
if (riskDetails.length > 0) {
const risks = document.createElement('div');
risks.className = 'sec-helper-block-risks';
const risksTitle = document.createElement('div');
risksTitle.className = 'sec-helper-block-risks-title';
risksTitle.innerHTML = '🔍 风险详情:';
risks.appendChild(risksTitle);
const risksList = document.createElement('ul');
risksList.className = 'sec-helper-block-risks-list';
riskDetails.forEach(detail => {
const li = document.createElement('li');
li.className = 'sec-helper-block-risks-item';
li.textContent = detail;
risksList.appendChild(li);
});
risks.appendChild(risksList);
overlay.appendChild(risks);
}
// AI分析显示
if (detectionResult.aiAnalysis) {
const aiAnalysis = document.createElement('div');
aiAnalysis.className = 'sec-helper-ai-analysis';
aiAnalysis.innerHTML = `
<div class="sec-helper-ai-header">
🤖 AI风险分析
<div class="sec-helper-ai-confidence">
威胁等级: ${detectionResult.threatLevel.toUpperCase()}
</div>
</div>
<div class="sec-helper-ai-details">
<div class="sec-helper-ai-feature">
<div class="sec-helper-ai-feature-name">综合风险评分</div>
<div class="sec-helper-ai-feature-value">${(detectionResult.aiAnalysis.score * 100).toFixed(1)}%</div>
</div>
<div class="sec-helper-ai-feature">
<div class="sec-helper-ai-feature-name">AI置信度</div>
<div class="sec-helper-ai-feature-value">${(detectionResult.aiAnalysis.confidence * 100).toFixed(1)}%</div>
</div>
<div class="sec-helper-ai-feature">
<div class="sec-helper-ai-feature-name">检测时间</div>
<div class="sec-helper-ai-feature-value">${new Date().toLocaleTimeString()}</div>
</div>
</div>
`;
overlay.appendChild(aiAnalysis);
}
// 操作按钮区
const btns = document.createElement('div');
btns.className = 'sec-helper-block-btns';
// 1. 前往安全页面按钮
const safeBtn = document.createElement('button');
safeBtn.className = 'sec-helper-block-btn sec-helper-btn-safe';
safeBtn.textContent = '前往安全页面';
safeBtn.addEventListener('click', () => window.location.href = CONFIG.safePage);
btns.appendChild(safeBtn);
// 2. 临时绕过按钮
if (CONFIG.highRiskBlock.allowTemporaryBypass) {
const bypassBtn = document.createElement('button');
bypassBtn.className = 'sec-helper-block-btn sec-helper-btn-bypass';
bypassBtn.textContent = '临时绕过(15分钟)';
bypassBtn.addEventListener('click', () => {
addTemporaryBypass();
window.location.reload();
});
btns.appendChild(bypassBtn);
}
// 3. 添加信任按钮
const trustBtn = document.createElement('button');
trustBtn.className = 'sec-helper-block-btn sec-helper-btn-trust';
trustBtn.textContent = '添加信任';
trustBtn.addEventListener('click', () => {
showTrustModal(currentHost);
});
btns.appendChild(trustBtn);
overlay.appendChild(btns);
// 底部信息
const footer = document.createElement('div');
footer.className = 'sec-helper-block-footer';
footer.innerHTML = '网站安全助手 AI增强版 © 2024 | 保护您的上网安全';
overlay.appendChild(footer);
document.body.appendChild(overlay);
// 发送通知
GM_notification({
title: '危险网站拦截',
text: `已阻断高风险网站:${currentHost}`,
timeout: 5000,
image: 'https://img.icons8.com/color/48/000000/security-checked.png'
});
debugLog('阻断页面创建完成');
}
// 增强的安全检测主函数
async function runEnhancedSecurityChecks() {
debugLog('开始增强安全检测...');
// 基础安全检查
if (isTrustedDomain() || hasTemporaryBypass()) {
if (hasTemporaryBypass()) {
const remaining = Math.ceil((temporaryBypasses[currentHost] - Date.now()) / 60000);
showSmartNotification();
debugLog('网站处于临时绕过状态,剩余时间:', remaining, '分钟');
} else {
debugLog('网站在信任列表中,跳过检测');
}
return;
}
// AI增强风险评估
if (CONFIG.aiEnhanced.enable) {
try {
const aiDetector = new AIEnhancedDetector();
const aiResult = await aiDetector.assessRisk();
detectionResult.aiAnalysis = aiResult;
detectionResult.threatLevel = aiResult.threatLevel;
if (aiResult.score > CONFIG.aiEnhanced.confidenceThreshold) {
detectionResult.level = "danger";
detectionResult.message = "AI检测到高风险威胁";
detectionResult.details.push(`AI风险评估: ${(aiResult.score * 100).toFixed(1)}%`);
securityState.detectedThreats.push('AI检测到高风险');
}
} catch (error) {
debugLog('AI风险评估失败:', error);
}
}
// 假冒域名检测
const fakeDomain = detectFakeDomain();
if (fakeDomain) {
detectionResult.level = fakeDomain.weight > 1.1 ? "danger" : "warning";
detectionResult.details.push(`疑似假冒"${fakeDomain.brand}"网站(相似度${fakeDomain.similarity}%),官方域名:${fakeDomain.official}`);
securityState.detectedThreats.push(`假冒域名: ${fakeDomain.brand}`);
}
// 基础安全检测
if (currentProtocol === "http:") {
detectionResult.details.push("非加密HTTP连接,数据传输有风险");
if (detectionResult.level === "safe") {
detectionResult.level = "warning";
detectionResult.message = "检测到潜在安全风险";
}
securityState.detectedThreats.push('HTTP非加密连接');
}
// 恶意特征检测
const maliciousSignatures = {
domains: [
/\bmalware\b/, /\bvirus\b/, /\btrojan\b/, /\bransomware\b/,
/\bphishing\b/, /\bfake\b/, /\bscam\b/, /\bfraud\b/,
/\b(?:[a-z0-9]{1,61})\.(?:tk|ml|ga|cf|gq)\b/,
/\b(?:[a-z0-9]{1,61})\.(?:xyz|top|club|win|bid)\b/,
/\bcrypt\b.*\block\b/, /\bencrypt\b.*\bfile\b/
]
};
maliciousSignatures.domains.forEach(pattern => {
if ((typeof pattern === 'string' && currentHost.includes(pattern)) ||
(pattern instanceof RegExp && pattern.test(currentHost))) {
detectionResult.level = "danger";
detectionResult.details.push("域名包含已知恶意特征");
securityState.detectedThreats.push('恶意域名特征');
}
});
// 更新风险评分
if (detectionResult.level === "danger") {
securityState.riskScore = Math.max(securityState.riskScore, 0.8);
} else if (detectionResult.level === "warning") {
securityState.riskScore = Math.max(securityState.riskScore, 0.5);
}
debugLog('安全检测完成:', detectionResult);
// 执行阻断逻辑
if (detectionResult.level === "danger" && CONFIG.highRiskBlock.enable) {
blockImmediately(detectionResult.details);
return;
}
// 显示智能通知
showSmartNotification();
}
// 初始化增强功能
function initEnhancedFeatures() {
debugLog('初始化增强功能...');
// 创建监控面板
createMonitorPanel();
// 创建调试面板
createDebugPanel();
// 初始化下载保护
if (CONFIG.downloadMonitor.enable) {
new DownloadProtector();
}
// 初始化白名单管理器
initWhitelistManager();
createTrustModal();
// 注册增强菜单命令
GM_registerMenuCommand("🔍 安全仪表盘", showWhitelistManager);
GM_registerMenuCommand("🤖 AI风险分析", () => {
const aiDetector = new AIEnhancedDetector();
aiDetector.assessRisk().then(result => {
GM_notification({
title: 'AI风险分析结果',
text: `威胁等级: ${result.threatLevel}, 评分: ${(result.score * 100).toFixed(1)}%`,
timeout: 5000
});
});
});
GM_registerMenuCommand("📊 实时监控", () => {
const panel = document.querySelector('.sec-helper-monitor-panel');
if (panel) {
panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}
});
GM_registerMenuCommand("🐛 调试信息", () => {
debugLog('手动触发调试信息');
console.log('=== 安全助手调试信息 ===');
console.log('安全状态:', securityState);
console.log('检测结果:', detectionResult);
console.log('信任域名:', trustedDomains);
console.log('临时绕过:', temporaryBypasses);
console.log('配置设置:', CONFIG);
console.log('=====================');
});
GM_registerMenuCommand("🛡️ 添加当前信任", () => {
showTrustModal(currentHost);
});
debugLog('增强功能初始化完成');
}
// 工具函数
function formatDate(timestamp) {
const date = new Date(timestamp);
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
}
// 主执行逻辑
function main() {
debugLog('主函数开始执行');
// 发送启动通知
GM_notification({
title: '🛡️ 安全助手已启动',
text: `正在保护: ${currentHost}`,
timeout: 2000
});
if (!isTrustedDomain()) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
debugLog('DOM加载完成,开始安全检测');
setTimeout(() => {
runEnhancedSecurityChecks();
initEnhancedFeatures();
}, 1000);
});
} else {
debugLog('DOM已就绪,开始安全检测');
setTimeout(() => {
runEnhancedSecurityChecks();
initEnhancedFeatures();
}, 1000);
}
} else {
debugLog('网站已在信任列表中,跳过检测');
initEnhancedFeatures();
}
debugLog('脚本初始化完成');
}
// 启动脚本
main();
})();
本脚本由AI制作,本脚本(网站安全助手)仅供个人学习和研究网络安全技术使用。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)