1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
| class SecurityMonitor {
constructor() {
this.init()
}
init() {
// 监控XSS尝试
this.monitorXSS()
// 监控异常请求
this.monitorRequests()
// 监控控制台错误
this.monitorErrors()
}
monitorXSS() {
const originalCreateElement = document.createElement
document.createElement = function(tagName) {
const element = originalCreateElement.call(this, tagName)
if (tagName === 'script') {
let originalSrc = ''
Object.defineProperty(element, 'src', {
get() {
return originalSrc
},
set(value) {
// 检查脚本来源
if (!this.isTrustedSource(value)) {
console.warn('Untrusted script source:', value)
securityEvent('untrusted_script', { src: value })
}
originalSrc = value
}
})
}
return element
}
}
monitorRequests() {
const originalFetch = window.fetch
window.fetch = function(...args) {
const url = args[0]
// 检查请求目标
if (!this.isTrustedDomain(url)) {
console.warn('Request to untrusted domain:', url)
securityEvent('untrusted_request', { url })
}
return originalFetch.apply(this, args)
}
}
monitorErrors() {
window.addEventListener('error', (event) => {
if (event.message.includes('Script error')) {
securityEvent('possible_xss', {
message: event.message,
filename: event.filename
})
}
})
}
isTrustedSource(url) {
const trusted = ['https://cdn.trusted.com', 'https://api.trusted.com']
return trusted.some(domain => url.startsWith(domain))
}
isTrustedDomain(url) {
try {
const urlObj = new URL(url, window.location.origin)
return urlObj.origin === window.location.origin
} catch {
return false
}
}
}
|