-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse-interceptor.js
More file actions
248 lines (211 loc) · 8.76 KB
/
response-interceptor.js
File metadata and controls
248 lines (211 loc) · 8.76 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// Hera Response Interceptor
// Intercepts fetch() and XMLHttpRequest to capture response bodies
// WITHOUT requiring the invasive debugger permission
// SECURITY FIX: Added rate limiting, size limits, and nonce validation
//
// P2-SIXTEENTH-2: EXECUTION CONTEXT CLARIFICATION
// This script is injected via chrome.scripting.executeScript() which runs in the MAIN world by default
// (not ISOLATED world despite what manifest.json says - manifest only controls content_scripts).
// However, it uses chrome.runtime.sendMessage which is safe because:
// 1. Messages are sent directly to background (not via postMessage)
// 2. Background validates sender.id matches chrome.runtime.id
// 3. Page JavaScript cannot intercept chrome.runtime.sendMessage calls
// Security boundary: Extension API access, not DOM isolation
(function() {
'use strict';
// SECURITY FIX P1-1: Using chrome.runtime.sendMessage (secure even in MAIN world)
// The page's JavaScript cannot intercept extension API calls
// This prevents malicious pages from:
// 1. Stealing response data
// 2. Overriding chrome.runtime before we load (impossible)
// 3. Injecting fake response data (validated by sender.id)
// 4. Preventing interception entirely
console.log('Hera: Response interceptor initialized (secure extension API communication)');
// Store original functions
const originalFetch = window.fetch;
const originalXHROpen = XMLHttpRequest.prototype.open;
const originalXHRSend = XMLHttpRequest.prototype.send;
// Rate limiting per domain
const RATE_LIMIT_PER_DOMAIN = 50; // Max 50 intercepts per minute per domain
const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
const MAX_RESPONSE_SIZE = 100 * 1024; // 100KB max response size
const domainInterceptCounts = new Map();
// Clean up old rate limit entries
setInterval(() => {
const now = Date.now();
for (const [domain, data] of domainInterceptCounts.entries()) {
if (now - data.windowStart > RATE_LIMIT_WINDOW) {
domainInterceptCounts.delete(domain);
}
}
}, RATE_LIMIT_WINDOW);
// Check if domain is rate limited
function checkRateLimit(url) {
try {
const urlObj = new URL(url, window.location.href);
// P2-TENTH-1 FIX: Use base domain to prevent subdomain bypass
// Extract eTLD+1 (e.g., api1.evil.com → evil.com)
const parts = urlObj.hostname.split('.');
const baseDomain = parts.length >= 2 ? parts.slice(-2).join('.') : urlObj.hostname;
const now = Date.now();
// P2-TENTH-2 FIX: Limit Map size to prevent memory leak
const MAX_RATE_LIMIT_ENTRIES = 500;
if (domainInterceptCounts.size >= MAX_RATE_LIMIT_ENTRIES && !domainInterceptCounts.has(baseDomain)) {
// Evict oldest entry (first in Map)
const oldestKey = domainInterceptCounts.keys().next().value;
domainInterceptCounts.delete(oldestKey);
console.warn(`Hera: Rate limit cache full, evicted ${oldestKey}`);
}
if (!domainInterceptCounts.has(baseDomain)) {
domainInterceptCounts.set(baseDomain, {
count: 1,
windowStart: now
});
return true;
}
const data = domainInterceptCounts.get(baseDomain);
// Reset window if expired
if (now - data.windowStart > RATE_LIMIT_WINDOW) {
data.count = 1;
data.windowStart = now;
return true;
}
// Check limit
if (data.count >= RATE_LIMIT_PER_DOMAIN) {
console.warn(`Hera: Rate limit exceeded for ${baseDomain} (${data.count}/${RATE_LIMIT_PER_DOMAIN})`);
return false;
}
data.count++;
return true;
} catch (error) {
return true; // Allow on error
}
}
// Helper to check if this is an auth-related request
function isAuthRequest(url) {
const authPatterns = [
'/oauth', '/authorize', '/token', '/login', '/signin', '/auth',
'/api/auth', '/session', '/connect', '/saml', '/oidc', '/scim'
];
const urlLower = url.toLowerCase();
return authPatterns.some(pattern => urlLower.includes(pattern));
}
// Intercept fetch()
window.fetch = async function(...args) {
const [resource, config] = args;
const url = typeof resource === 'string' ? resource : resource.url;
// Call original fetch
const response = await originalFetch.apply(this, args);
// Only intercept auth-related requests
if (isAuthRequest(url)) {
// SECURITY FIX: Rate limiting check
if (!checkRateLimit(url)) {
return response; // Skip interception if rate limited
}
// Clone the response so we can read the body
const clonedResponse = response.clone();
try {
const text = await clonedResponse.text();
// SECURITY FIX: Size limit check
if (text.length > MAX_RESPONSE_SIZE) {
console.warn(`Hera: Response too large (${text.length} bytes), truncating to ${MAX_RESPONSE_SIZE}`);
const truncated = text.substring(0, MAX_RESPONSE_SIZE);
// SECURITY FIX P1-1: Send directly to background in isolated world
chrome.runtime.sendMessage({
action: 'responseIntercepted',
data: {
source: 'fetch',
url: url,
method: config?.method || 'GET',
statusCode: response.status,
headers: Object.fromEntries(response.headers.entries()),
body: truncated + '\n\n[TRUNCATED - Response exceeded 100KB limit]',
timestamp: new Date().toISOString(),
truncated: true
}
}).catch(error => {
console.error('Hera: Failed to send intercepted response:', error);
});
return response;
}
// SECURITY FIX P1-1: In isolated world, send directly to background via chrome.runtime
// No need for window.postMessage or nonce validation - we're in secure context
chrome.runtime.sendMessage({
action: 'responseIntercepted',
data: {
source: 'fetch',
url: url,
method: config?.method || 'GET',
statusCode: response.status,
headers: Object.fromEntries(response.headers.entries()),
body: text,
timestamp: new Date().toISOString()
}
}).catch(error => {
console.error('Hera: Failed to send intercepted response:', error);
}); // Explicit origin instead of '*'
} catch (error) {
console.warn('Hera: Failed to capture fetch response:', error);
}
}
return response;
};
// Intercept XMLHttpRequest
XMLHttpRequest.prototype.open = function(method, url, ...args) {
this._heraMethod = method;
this._heraUrl = url;
return originalXHROpen.apply(this, [method, url, ...args]);
};
XMLHttpRequest.prototype.send = function(...args) {
const xhr = this;
if (isAuthRequest(xhr._heraUrl)) {
// SECURITY FIX: Rate limiting check
if (!checkRateLimit(xhr._heraUrl)) {
return originalXHRSend.apply(this, args); // Skip interception if rate limited
}
// Add load event listener to capture response
xhr.addEventListener('load', function() {
try {
const responseBody = xhr.responseText || xhr.response;
// SECURITY FIX: Size limit check
let body = responseBody;
let truncated = false;
if (typeof body === 'string' && body.length > MAX_RESPONSE_SIZE) {
console.warn(`Hera: XHR response too large (${body.length} bytes), truncating`);
body = body.substring(0, MAX_RESPONSE_SIZE) + '\n\n[TRUNCATED - Response exceeded 100KB limit]';
truncated = true;
}
// Get response headers
const headersText = xhr.getAllResponseHeaders();
const headers = {};
headersText.split('\r\n').forEach(line => {
const parts = line.split(': ');
if (parts.length === 2) {
headers[parts[0]] = parts[1];
}
});
// SECURITY FIX P1-1: Send directly to background in isolated world
chrome.runtime.sendMessage({
action: 'responseIntercepted',
data: {
source: 'xhr',
url: xhr._heraUrl,
method: xhr._heraMethod,
statusCode: xhr.status,
headers: headers,
body: body,
timestamp: new Date().toISOString(),
truncated: truncated
}
}).catch(error => {
console.error('Hera: Failed to send intercepted XHR response:', error);
});
} catch (error) {
console.warn('Hera: Failed to capture XHR response:', error);
}
});
}
return originalXHRSend.apply(this, args);
};
console.log('Hera: Response interceptor initialized (fetch + XHR) with rate limiting');
})();