-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathipc-security.js
More file actions
91 lines (80 loc) · 2.38 KB
/
ipc-security.js
File metadata and controls
91 lines (80 loc) · 2.38 KB
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
83
84
85
86
87
88
89
90
91
/**
* IPC Security - Trusted Domain Validation
*
* This module implements security measures to ensure Electron APIs are only
* accessible from trusted origins. Trust is evaluated at window load/navigation
* time (not on every IPC call) for optimal performance.
*
* Trust rules:
* - Dev stage: trustedElectronDomains + all localhost URLs
* - Other stages (staging/prod): only trustedElectronDomains
*/
const { stage, trustedElectronDomains } = require('./config');
// Track trusted webContents IDs (Set for O(1) lookup)
const _trustedWebContents = new Set();
/**
* Check if a URL is trusted based on stage configuration.
* - Dev stage: trustedElectronDomains + all localhost URLs
* - Other stages: only trustedElectronDomains
*/
function isTrustedOrigin(url) {
if (!url) return false;
// Check against trustedElectronDomains
for (const domain of trustedElectronDomains) {
if (url.startsWith(domain)) {
return true;
}
}
// In dev stage, also allow localhost URLs
if (stage === 'dev') {
try {
const parsed = new URL(url);
if (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1') {
return true;
}
} catch {
return false;
}
}
return false;
}
/**
* Mark a webContents as trusted/untrusted based on its current URL.
* Call this when window loads or navigates.
*/
function updateTrustStatus(webContents) {
const url = webContents.getURL();
if (isTrustedOrigin(url)) {
_trustedWebContents.add(webContents.id);
} else {
_trustedWebContents.delete(webContents.id);
}
}
/**
* Remove trust tracking when webContents is destroyed.
*/
function cleanupTrust(webContentsId) {
_trustedWebContents.delete(webContentsId);
}
/**
* Fast check if webContents is trusted (O(1) lookup).
*/
function _isWebContentsTrusted(webContentsId) {
return _trustedWebContents.has(webContentsId);
}
/**
* Assert that IPC event comes from trusted webContents.
* Throws error if not trusted.
*/
function assertTrusted(event) {
if (!_isWebContentsTrusted(event.sender.id)) {
const url = event.senderFrame?.url || event.sender.getURL() || 'unknown';
throw new Error(`Blocked IPC from untrusted origin: ${url}`);
}
}
module.exports = {
isTrustedOrigin,
updateTrustStatus,
cleanupTrust,
assertTrusted
};