forked from repplus/rep-firefox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js.bak
More file actions
525 lines (467 loc) · 19.7 KB
/
background.js.bak
File metadata and controls
525 lines (467 loc) · 19.7 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// Background script
const ports = new Set();
const requestMap = new Map();
// Handle connections from DevTools panels
browser.runtime.onConnect.addListener((port) => {
if (port.name !== "rep-panel") return;
console.log("DevTools panel connected");
ports.add(port);
port.onDisconnect.addListener(() => {
console.log("DevTools panel disconnected");
ports.delete(port);
});
// Listen for messages from panel (e.g. to toggle capture, local model requests)
port.onMessage.addListener((msg) => {
console.log('Background: Received port message:', msg.type);
if (msg.type === 'ping') {
console.log('Background: Responding to ping');
port.postMessage({ type: 'pong' });
} else if (msg.type === 'local-model-request' || msg.type === 'local-model-chat') {
// Handle local model request via port
const requestId = msg.requestId || `local-${Date.now()}-${Math.random()}`;
console.log('Background: Received local model request', requestId, 'URL:', msg.url, 'Body:', JSON.stringify(msg.body).substring(0, 100));
// Check if port is still connected before making request
if (!port || !port.onDisconnect) {
console.error('Background: Port already disconnected');
return;
}
// Proxy the request to localhost
// Note: Background scripts need host_permissions for localhost in MV3
// Support both old format (prompt) and new format (messages array)
const requestBody = msg.body.messages
? {
model: msg.body.model,
messages: msg.body.messages,
stream: msg.body.stream !== undefined ? msg.body.stream : true
}
: {
model: msg.body.model,
prompt: msg.body.prompt,
stream: msg.body.stream !== undefined ? msg.body.stream : true
};
console.log('Background: Sending fetch request to', msg.url, 'with body:', JSON.stringify(requestBody).substring(0, 200));
// Try to match curl's request format exactly
fetch(msg.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(requestBody),
// Don't send credentials or referrer that might trigger security
credentials: 'omit',
referrerPolicy: 'no-referrer'
})
.then(response => {
console.log('Background: Fetch response status', response.status);
// Log response headers for debugging
const responseHeaders = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
console.log('Background: Response headers:', responseHeaders);
if (!response.ok) {
return response.text().then(text => {
console.error('Background: Fetch failed with status', response.status, 'Response body length:', text?.length || 0, 'Response body:', text || '(empty)');
// Provide more helpful error message
let errorMsg = `Request failed with status ${response.status}`;
if (text && text.trim()) {
try {
const errorData = JSON.parse(text);
errorMsg = errorData.error || errorData.message || errorMsg;
} catch (e) {
errorMsg = text.length > 200 ? text.substring(0, 200) + '...' : text;
}
} else if (response.status === 403) {
errorMsg = '403 Forbidden: Ollama is blocking the request. ' +
'This might be due to CORS or security settings. ' +
'Try restarting Ollama with: OLLAMA_ORIGINS="*" ollama serve ' +
'Or check Ollama configuration for access restrictions.';
}
throw new Error(errorMsg);
});
}
return response.body;
})
.then(body => {
if (!body) {
throw new Error('No response body received');
}
// Stream the response back via this specific port
const reader = body.getReader();
const decoder = new TextDecoder();
let hasError = false;
function readChunk() {
if (hasError) return;
reader.read().then(({ done, value }) => {
if (done) {
// Send final message
try {
port.postMessage({
type: 'local-model-stream-done',
requestId: requestId
});
console.log('Background: Sent stream-done for', requestId);
} catch (e) {
console.error('Background: Error sending stream-done', e);
hasError = true;
}
return;
}
const chunk = decoder.decode(value, { stream: true });
// Send chunk message
try {
port.postMessage({
type: 'local-model-stream-chunk',
chunk: chunk,
requestId: requestId
});
} catch (e) {
console.error('Background: Port disconnected during streaming', e);
hasError = true;
reader.cancel().catch(() => { });
return;
}
// Continue reading
readChunk();
}).catch(error => {
console.error('Background: Error reading chunk', error);
hasError = true;
try {
port.postMessage({
type: 'local-model-stream-error',
error: error.message,
requestId: requestId
});
} catch (e) {
console.error('Background: Error sending error message', e);
}
});
}
readChunk();
})
.catch(error => {
console.error('Background: Fetch error', error, error.stack);
let errorMessage = error.message || 'Failed to fetch from local model API';
// Provide helpful error message for CORS issues
if (errorMessage.includes('CORS') || errorMessage.includes('Failed to fetch')) {
errorMessage = 'CORS error: Ollama needs to allow CORS. ' +
'Start Ollama with: OLLAMA_ORIGINS="moz-extension://*" ollama serve ' +
'Or configure your Ollama server to send CORS headers. ' +
'Original error: ' + errorMessage;
}
try {
port.postMessage({
type: 'local-model-error',
error: errorMessage,
requestId: requestId
});
} catch (e) {
console.error('Background: Port disconnected, cannot send error', e);
}
});
}
});
});
// Handle local model API requests (bypass CORS)
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'local-model-request') {
const requestId = request.requestId || `local-${Date.now()}-${Math.random()}`;
// Proxy the request to localhost (service workers can bypass CORS)
fetch(request.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(request.body)
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error(text || 'Request failed');
});
}
return response.body;
})
.then(body => {
// Stream the response back via port connections (for DevTools panels)
const reader = body.getReader();
const decoder = new TextDecoder();
function readChunk() {
reader.read().then(({ done, value }) => {
if (done) {
// Send final message to all connected ports
ports.forEach(port => {
try {
port.postMessage({
type: 'local-model-stream-done',
requestId: requestId
});
} catch (e) {
// Port might be disconnected, remove it
ports.delete(port);
}
});
return;
}
const chunk = decoder.decode(value, { stream: true });
// Send chunk message to all connected ports
ports.forEach(port => {
try {
port.postMessage({
type: 'local-model-stream-chunk',
chunk: chunk,
requestId: requestId
});
} catch (e) {
// Port might be disconnected, remove it
ports.delete(port);
}
});
// Continue reading
readChunk();
}).catch(error => {
ports.forEach(port => {
try {
port.postMessage({
type: 'local-model-stream-error',
error: error.message,
requestId: requestId
});
} catch (e) {
ports.delete(port);
}
});
});
}
readChunk();
})
.catch(error => {
ports.forEach(port => {
try {
port.postMessage({
type: 'local-model-error',
error: error.message,
requestId: requestId
});
} catch (e) {
ports.delete(port);
}
});
});
// Return true to indicate we'll send responses asynchronously
return true;
}
});
// Helper to process request body
function parseRequestBody(requestBody) {
if (!requestBody) return null;
if (requestBody.raw && requestBody.raw.length > 0) {
try {
const decoder = new TextDecoder('utf-8');
return requestBody.raw.map(bytes => {
if (bytes.bytes) {
return decoder.decode(bytes.bytes);
}
return '';
}).join('');
} catch (e) {
console.error('Error decoding request body:', e);
return null;
}
}
if (requestBody.formData) {
// Convert formData object to URL encoded string
const params = new URLSearchParams();
for (const [key, values] of Object.entries(requestBody.formData)) {
values.forEach(value => params.append(key, value));
}
return params.toString();
}
return null;
}
// Listener functions
function handleBeforeRequest(details) {
if (ports.size === 0) return;
// Filter out Firefox extension URLs
if (details.url.startsWith('moz-extension://')) return;
requestMap.set(details.requestId, {
requestId: details.requestId,
url: details.url,
method: details.method,
type: details.type,
timeStamp: Date.now(),
requestBody: parseRequestBody(details.requestBody),
tabId: details.tabId,
initiator: details.initiator
});
}
function handleBeforeSendHeaders(details) {
if (ports.size === 0) return;
const req = requestMap.get(details.requestId);
if (req) {
req.requestHeaders = details.requestHeaders;
}
// COOKIE INJECTION: Check if this is a replayed request with custom cookie
const headers = details.requestHeaders;
const isReplay = headers.some(h =>
h.name === 'X-Rep-Plus-Replay' && h.value === 'true'
);
if (isReplay) {
// Find our custom cookie header
const cookieHeaderIndex = headers.findIndex(h =>
h.name === 'X-Rep-Plus-Cookie'
);
if (cookieHeaderIndex !== -1) {
const cookieValue = headers[cookieHeaderIndex].value;
// Remove the custom header (don't send it to server)
headers.splice(cookieHeaderIndex, 1);
// Remove existing Cookie header from browser jar (if any)
const existingCookieIndex = headers.findIndex(h =>
h.name.toLowerCase() === 'cookie'
);
if (existingCookieIndex !== -1) {
headers.splice(existingCookieIndex, 1);
}
// Inject our Cookie header from request text
headers.push({
name: 'Cookie',
value: cookieValue
});
console.log('[Cookie Injection] Injected cookie for:', details.url.substring(0, 80));
return { requestHeaders: headers };
}
}
}
function handleCompleted(details) {
if (ports.size === 0) return;
const req = requestMap.get(details.requestId);
if (req) {
req.statusCode = details.statusCode;
req.statusLine = details.statusLine;
req.responseHeaders = details.responseHeaders;
const message = {
type: 'captured_request',
data: req
};
ports.forEach(p => {
try {
p.postMessage(message);
} catch (e) {
console.error('Error sending to port:', e);
ports.delete(p);
}
});
requestMap.delete(details.requestId);
}
}
function handleErrorOccurred(details) {
requestMap.delete(details.requestId);
}
function setupListeners() {
if (browser.webRequest) {
if (!browser.webRequest.onBeforeRequest.hasListener(handleBeforeRequest)) {
browser.webRequest.onBeforeRequest.addListener(
handleBeforeRequest,
{ urls: ["<all_urls>"] },
["requestBody"]
);
}
if (!browser.webRequest.onBeforeSendHeaders.hasListener(handleBeforeSendHeaders)) {
browser.webRequest.onBeforeSendHeaders.addListener(
handleBeforeSendHeaders,
{ urls: ["<all_urls>"] },
["requestHeaders"]
);
}
if (!browser.webRequest.onCompleted.hasListener(handleCompleted)) {
browser.webRequest.onCompleted.addListener(
handleCompleted,
{ urls: ["<all_urls>"] },
["responseHeaders"]
);
}
if (!browser.webRequest.onErrorOccurred.hasListener(handleErrorOccurred)) {
browser.webRequest.onErrorOccurred.addListener(
handleErrorOccurred,
{ urls: ["<all_urls>"] }
);
}
console.log("WebRequest listeners registered");
} else {
console.log("WebRequest permission not granted");
}
}
/**
* Intercept replayed requests to inject Cookie header from request text
* This bypasses Firefox's forbidden header restriction
*/
function handleCookieInjection(details) {
const headers = details.requestHeaders;
// Check if this is a replayed request
const isReplay = headers.some(h =>
h.name === 'X-Rep-Plus-Replay' && h.value === 'true'
);
if (!isReplay) {
return {}; // Not a replayed request, do nothing
}
// Find our custom cookie header
const cookieHeaderIndex = headers.findIndex(h =>
h.name === 'X-Rep-Plus-Cookie'
);
if (cookieHeaderIndex === -1) {
return {}; // No custom cookie, do nothing
}
const cookieValue = headers[cookieHeaderIndex].value;
// Remove the custom header (don't send it to server)
headers.splice(cookieHeaderIndex, 1);
// Remove existing Cookie header from browser jar (if any)
const existingCookieIndex = headers.findIndex(h =>
h.name.toLowerCase() === 'cookie'
);
if (existingCookieIndex !== -1) {
headers.splice(existingCookieIndex, 1);
}
// Inject our Cookie header from request text
headers.push({
name: 'Cookie',
value: cookieValue
});
console.log('[Cookie Injection] Injected cookie for:', details.url.substring(0, 80));
return { requestHeaders: headers };
}
// Register cookie injection listener with BLOCKING mode
if (browser.webRequest) {
try {
browser.webRequest.onBeforeSendHeaders.addListener(
handleCookieInjection,
{ urls: ["<all_urls>"] },
["blocking", "requestHeaders", "extraHeaders"]
);
console.log("Cookie injection listener registered");
} catch (e) {
console.error("Failed to register cookie injection listener:", e);
// Fallback without extraHeaders if not supported
try {
browser.webRequest.onBeforeSendHeaders.addListener(
handleCookieInjection,
{ urls: ["<all_urls>"] },
["blocking", "requestHeaders"]
);
console.log("Cookie injection listener registered (without extraHeaders)");
} catch (e2) {
console.error("Failed to register cookie injection listener (fallback):", e2);
}
}
}
// Initial setup
setupListeners();
// Periodic cleanup of stale requests (older than 1 minute)
setInterval(() => {
const now = Date.now();
for (const [id, req] of requestMap.entries()) {
if (now - req.timeStamp > 60000) {
requestMap.delete(id);
}
}
}, 30000);