browser-assistant 2.9.39 → 2.9.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/extension/background.js +30 -4
- package/extension/coding-automation.js +32 -1
- package/extension/content.js +6 -3
- package/extension/manifest.json +1 -1
- package/extension/popup.html +11 -0
- package/extension/popup.js +32 -0
- package/extension/styles.css +4 -0
- package/package.json +1 -1
- package/server/.env.example +3 -0
- package/server/local_security.py +17 -3
- package/server/main.py +1 -1
package/extension/background.js
CHANGED
|
@@ -4,6 +4,28 @@ importScripts('editor-bridge.js', 'detached-panel-background.js');
|
|
|
4
4
|
// Read the files from Chrome's own extension folder, independently of FastAPI.
|
|
5
5
|
let updateCheckRunning = false;
|
|
6
6
|
let lastWorkspaceCheck = -Infinity;
|
|
7
|
+
const LOCAL_BACKEND_URL = 'http://127.0.0.1:8000';
|
|
8
|
+
async function backendConnection() {
|
|
9
|
+
if (!chrome.storage?.local)
|
|
10
|
+
return { url: LOCAL_BACKEND_URL, token: '' };
|
|
11
|
+
const saved = await chrome.storage.local.get(['assistantBackendUrl', 'assistantBackendToken']);
|
|
12
|
+
const rawUrl = typeof saved.assistantBackendUrl === 'string' ? saved.assistantBackendUrl.trim() : '';
|
|
13
|
+
const token = typeof saved.assistantBackendToken === 'string' ? saved.assistantBackendToken.trim() : '';
|
|
14
|
+
if (!rawUrl)
|
|
15
|
+
return { url: LOCAL_BACKEND_URL, token: '' };
|
|
16
|
+
let parsed;
|
|
17
|
+
try {
|
|
18
|
+
parsed = new URL(rawUrl);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return { url: LOCAL_BACKEND_URL, token: '' };
|
|
22
|
+
}
|
|
23
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname);
|
|
24
|
+
if (parsed.username || parsed.password || !['http:', 'https:'].includes(parsed.protocol)
|
|
25
|
+
|| (!local && parsed.protocol !== 'https:'))
|
|
26
|
+
return { url: LOCAL_BACKEND_URL, token: '' };
|
|
27
|
+
return { url: parsed.origin, token };
|
|
28
|
+
}
|
|
7
29
|
async function workspaceVersionFile(file) {
|
|
8
30
|
const response = await fetch(`${chrome.runtime.getURL(file)}?workspace=${Date.now()}`, {
|
|
9
31
|
cache: 'no-store', signal: AbortSignal.timeout(4000),
|
|
@@ -363,12 +385,16 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
|
363
385
|
const longRequest = ['/solve', '/solve-vision', '/journal'].includes(request.path);
|
|
364
386
|
const keepAlive = longRequest && typeof chrome.runtime.getPlatformInfo === 'function'
|
|
365
387
|
? setInterval(() => chrome.runtime.getPlatformInfo(() => { void chrome.runtime.lastError; }), 25000) : null;
|
|
366
|
-
fetch(
|
|
388
|
+
const sendToBackend = ({ url, token }) => fetch(`${url}${request.path}`, {
|
|
367
389
|
signal: AbortSignal.timeout(['/solve', '/solve-vision', '/journal'].includes(request.path) ? 360000 : 8000),
|
|
368
390
|
method,
|
|
369
|
-
headers: { "Content-Type": "application/json" },
|
|
391
|
+
headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
|
370
392
|
body,
|
|
371
|
-
})
|
|
393
|
+
});
|
|
394
|
+
const backendRequest = chrome.storage?.local
|
|
395
|
+
? backendConnection().then(sendToBackend)
|
|
396
|
+
: sendToBackend({ url: LOCAL_BACKEND_URL, token: '' });
|
|
397
|
+
backendRequest
|
|
372
398
|
.then(async (response) => {
|
|
373
399
|
const text = await response.text();
|
|
374
400
|
let data;
|
|
@@ -380,7 +406,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
|
380
406
|
}
|
|
381
407
|
sendResponse({ ok: response.ok, status: response.status, data });
|
|
382
408
|
})
|
|
383
|
-
.catch(error => sendResponse({ error: error.name === 'TimeoutError' ? '
|
|
409
|
+
.catch(error => sendResponse({ error: error.name === 'TimeoutError' ? 'Backend request timed out.' : 'Backend is offline. Check the configured server.' }))
|
|
384
410
|
.finally(() => { if (keepAlive !== null)
|
|
385
411
|
clearInterval(keepAlive); });
|
|
386
412
|
return true;
|
|
@@ -58,6 +58,28 @@
|
|
|
58
58
|
return null;
|
|
59
59
|
}
|
|
60
60
|
function descriptionText(description) {
|
|
61
|
+
// Read-only Ace examples contain hidden input/measurement text and
|
|
62
|
+
// line-number gutters. Only their rendered source lines are examples.
|
|
63
|
+
for (const editor of description.querySelectorAll('.ace_editor')) {
|
|
64
|
+
const lines = [...editor.querySelectorAll('.ace_text-layer .ace_line,.ace_line')];
|
|
65
|
+
if (lines.length) {
|
|
66
|
+
const pre = description.ownerDocument.createElement('pre');
|
|
67
|
+
pre.textContent = lines.map(line => line.textContent || '').join('\n');
|
|
68
|
+
editor.replaceWith(pre);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
for (const node of description.querySelectorAll('.ace_text-input,.ace_gutter,.ace_gutter-layer,.ace_scrollbar,.ace_tooltip,[hidden]'))
|
|
72
|
+
node.remove();
|
|
73
|
+
const removeLayoutIndent = node => {
|
|
74
|
+
for (const child of [...node.childNodes]) {
|
|
75
|
+
if (child.nodeType === 3 && /^[\t \r\n]*[\r\n][\t \r\n]*$/.test(child.textContent || '')
|
|
76
|
+
&& !child.parentElement?.closest('pre,code'))
|
|
77
|
+
child.remove();
|
|
78
|
+
else if (child.nodeType === 1)
|
|
79
|
+
removeLayoutIndent(child);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
removeLayoutIndent(description);
|
|
61
83
|
// A detached clone loses innerText's layout line breaks. Keep the line
|
|
62
84
|
// structure of examples and the distinction between headings and prose.
|
|
63
85
|
description.querySelectorAll('br').forEach(node => node.replaceWith('\n'));
|
|
@@ -68,7 +90,9 @@
|
|
|
68
90
|
node.before('\n');
|
|
69
91
|
node.after('\n');
|
|
70
92
|
}
|
|
71
|
-
|
|
93
|
+
// Do not trim spaces from the last sample: some pattern tasks
|
|
94
|
+
// explicitly require a space after every star, including the last one.
|
|
95
|
+
return (description.textContent || '').replace(/^\n+|\n+$/g, '');
|
|
72
96
|
}
|
|
73
97
|
const aliases = { python: 'python', python3: 'python', javascript: 'javascript', 'node.js': 'javascript', java: 'java', 'c++': 'cpp', cpp: 'cpp', c: 'c', 'c#': 'csharp', go: 'go', rust: 'rust', kotlin: 'kotlin', php: 'php', sql: 'sql' };
|
|
74
98
|
function parseLanguage(label) {
|
|
@@ -125,6 +149,13 @@
|
|
|
125
149
|
if (!language)
|
|
126
150
|
return unavailable('CODE-LANGUAGE: Editor and description found, but the selected language is missing or ambiguous.');
|
|
127
151
|
const description = region.cloneNode(true);
|
|
152
|
+
const originals = [...region.querySelectorAll('*')];
|
|
153
|
+
const copies = [...description.querySelectorAll('*')];
|
|
154
|
+
originals.forEach((node, index) => {
|
|
155
|
+
const style = doc.defaultView?.getComputedStyle?.(node);
|
|
156
|
+
if (node.hasAttribute('hidden') || style?.display === 'none' || style?.visibility === 'hidden')
|
|
157
|
+
copies[index].remove();
|
|
158
|
+
});
|
|
128
159
|
for (const node of description.querySelectorAll('button,[role="tab"],script,style'))
|
|
129
160
|
node.remove();
|
|
130
161
|
for (const node of [...description.querySelectorAll('*')].reverse()) {
|
package/extension/content.js
CHANGED
|
@@ -734,8 +734,11 @@ function mountJournalCountdown(signal) {
|
|
|
734
734
|
diagnostic.hidden = false;
|
|
735
735
|
const context = getAutomationContext();
|
|
736
736
|
const authorized = context.mode === 'FULL';
|
|
737
|
-
|
|
738
|
-
|
|
737
|
+
let currentQuestion = automation.batch?.title || (automation.running && automation.codingQuestionText);
|
|
738
|
+
if (!currentQuestion && authorized) {
|
|
739
|
+
const detected = getAuthorizedQuestion(context);
|
|
740
|
+
currentQuestion = detected?.title || detected?.text;
|
|
741
|
+
}
|
|
739
742
|
const pageName = authorized ? context.target.id : window.location.hostname;
|
|
740
743
|
const deferred = automation.deferredQuestions?.size ?? 0;
|
|
741
744
|
if (status) {
|
|
@@ -1034,7 +1037,7 @@ function mountJournalCountdown(signal) {
|
|
|
1034
1037
|
return null;
|
|
1035
1038
|
}
|
|
1036
1039
|
async function runCodingAutomation(question, runId, repairAttempt = 0, feedback = '', starterCode = null) {
|
|
1037
|
-
automation.codingQuestionText = question.
|
|
1040
|
+
automation.codingQuestionText = question.title || 'Coding question';
|
|
1038
1041
|
const active = () => automation.running && automation.runId === runId;
|
|
1039
1042
|
const webProject = question.language === 'web';
|
|
1040
1043
|
const read = () => safeSendMessage({ action: 'codingEditor', operation: webProject ? 'readProject' : 'read', selector: question.editorSelector });
|
package/extension/manifest.json
CHANGED
package/extension/popup.html
CHANGED
|
@@ -18,6 +18,17 @@
|
|
|
18
18
|
<button type="button" id="open-separate-panel">Open separate panel for this tab</button>
|
|
19
19
|
<p id="separate-panel-status" role="status" hidden></p>
|
|
20
20
|
</section>
|
|
21
|
+
<section class="popup-card" aria-labelledby="backend-settings-title">
|
|
22
|
+
<h2 id="backend-settings-title">Backend connection</h2>
|
|
23
|
+
<label class="popup-field">Server URL
|
|
24
|
+
<input id="backend-url" type="url" placeholder="http://127.0.0.1:8000" autocomplete="off">
|
|
25
|
+
</label>
|
|
26
|
+
<label class="popup-field">API password
|
|
27
|
+
<input id="backend-token" type="password" placeholder="Required for a hosted server" autocomplete="new-password">
|
|
28
|
+
</label>
|
|
29
|
+
<button type="button" id="save-backend">Save backend</button>
|
|
30
|
+
<p id="backend-settings-status" role="status" hidden></p>
|
|
31
|
+
</section>
|
|
21
32
|
<section class="popup-card" aria-labelledby="popup-shortcuts">
|
|
22
33
|
<h2 id="popup-shortcuts">Keyboard shortcuts</h2>
|
|
23
34
|
<div class="shortcut-row"><span>Open panel</span> <span><kbd>`</kbd> <kbd>⌃⇧O</kbd></span></div>
|
package/extension/popup.js
CHANGED
|
@@ -17,6 +17,38 @@ new Promise((resolve, reject) => {
|
|
|
17
17
|
el.textContent = 'offline';
|
|
18
18
|
el.className = 'offline';
|
|
19
19
|
});
|
|
20
|
+
const backendUrl = document.querySelector('#backend-url');
|
|
21
|
+
const backendToken = document.querySelector('#backend-token');
|
|
22
|
+
const saveBackend = document.querySelector('#save-backend');
|
|
23
|
+
const backendSettingsStatus = document.getElementById('backend-settings-status');
|
|
24
|
+
const POPUP_LOCAL_BACKEND_URL = 'http://127.0.0.1:8000';
|
|
25
|
+
void chrome.storage.local.get(['assistantBackendUrl', 'assistantBackendToken']).then(saved => {
|
|
26
|
+
if (backendUrl)
|
|
27
|
+
backendUrl.value = typeof saved.assistantBackendUrl === 'string' ? saved.assistantBackendUrl : '';
|
|
28
|
+
if (backendToken)
|
|
29
|
+
backendToken.value = typeof saved.assistantBackendToken === 'string' ? saved.assistantBackendToken : '';
|
|
30
|
+
});
|
|
31
|
+
saveBackend?.addEventListener('click', async () => {
|
|
32
|
+
const rawUrl = backendUrl?.value.trim() || '';
|
|
33
|
+
const token = backendToken?.value.trim() || '';
|
|
34
|
+
try {
|
|
35
|
+
if (rawUrl) {
|
|
36
|
+
const parsed = new URL(rawUrl);
|
|
37
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname);
|
|
38
|
+
if (parsed.username || parsed.password || !['http:', 'https:'].includes(parsed.protocol)
|
|
39
|
+
|| (!local && parsed.protocol !== 'https:') || parsed.pathname !== '/') {
|
|
40
|
+
throw Error('Use a plain HTTPS server URL, for example https://browser-assistant.onrender.com');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
await chrome.storage.local.set({ assistantBackendUrl: rawUrl, assistantBackendToken: token });
|
|
44
|
+
backendSettingsStatus.textContent = rawUrl ? `Saved: ${rawUrl}` : `Saved: ${POPUP_LOCAL_BACKEND_URL}`;
|
|
45
|
+
backendSettingsStatus.hidden = false;
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
backendSettingsStatus.textContent = error.message;
|
|
49
|
+
backendSettingsStatus.hidden = false;
|
|
50
|
+
}
|
|
51
|
+
});
|
|
20
52
|
const journalCountdown = document.getElementById('journal-countdown');
|
|
21
53
|
let journalTimers = [];
|
|
22
54
|
function showJournalCountdown() {
|
package/extension/styles.css
CHANGED
|
@@ -591,6 +591,10 @@ body.assistant-popup {
|
|
|
591
591
|
}
|
|
592
592
|
.assistant-popup #open-separate-panel:hover { border-color: var(--ink); }
|
|
593
593
|
.assistant-popup #separate-panel-status { color: var(--ink); font-weight: 650; }
|
|
594
|
+
.assistant-popup .popup-field { display: grid; gap: 4px; margin-top: 8px; font-size: 11px; font-weight: 700; }
|
|
595
|
+
.assistant-popup .popup-field input { width: 100%; box-sizing: border-box; padding: 7px; color: var(--ink); background: transparent; border: 1px solid var(--line); border-radius: 4px; }
|
|
596
|
+
.assistant-popup #save-backend { margin-top: 8px; }
|
|
597
|
+
.assistant-popup #backend-settings-status { margin: 7px 0 0; color: var(--ink); font-size: 11px; overflow-wrap: anywhere; }
|
|
594
598
|
#assistant-automation-notice {
|
|
595
599
|
position: fixed;
|
|
596
600
|
right: 16px;
|
package/package.json
CHANGED
package/server/.env.example
CHANGED
|
@@ -15,5 +15,8 @@ GROQ_REVIEW_TOKEN_LIMIT=4096
|
|
|
15
15
|
SERVER_HOST=127.0.0.1
|
|
16
16
|
# Optional additional hostnames for a deliberately configured local deployment.
|
|
17
17
|
SERVER_ALLOWED_HOSTS=
|
|
18
|
+
# Required when the API is hosted outside your computer. The extension sends it
|
|
19
|
+
# as Authorization: Bearer <value>; keep this value private.
|
|
20
|
+
SERVER_API_TOKEN=
|
|
18
21
|
# Empty preserves the existing server/scan_history.db location.
|
|
19
22
|
HISTORY_DB_PATH=
|
package/server/local_security.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""Local browser-request guards and secret-safe error text; no user credentials stored."""
|
|
2
2
|
import os
|
|
3
3
|
import re
|
|
4
|
+
import hmac
|
|
4
5
|
from urllib.parse import urlsplit
|
|
5
6
|
|
|
6
7
|
from starlette.responses import JSONResponse
|
|
@@ -25,6 +26,14 @@ def sanitize_data(value, secrets=()):
|
|
|
25
26
|
def install_local_guards(app):
|
|
26
27
|
allowed_hosts = {'localhost', '127.0.0.1', '::1', 'testserver'}
|
|
27
28
|
allowed_hosts.update(name.strip().lower() for name in os.getenv('SERVER_ALLOWED_HOSTS', '').split(',') if name.strip())
|
|
29
|
+
api_token = os.getenv('SERVER_API_TOKEN', '').strip()
|
|
30
|
+
|
|
31
|
+
def public_render_host(host):
|
|
32
|
+
# A Render service is deliberately public, but every API request is
|
|
33
|
+
# protected by SERVER_API_TOKEN. Accepting the assigned onrender.com
|
|
34
|
+
# hostname removes the chicken-and-egg step of knowing it before the
|
|
35
|
+
# first deployment.
|
|
36
|
+
return bool(api_token and host.endswith('.onrender.com'))
|
|
28
37
|
|
|
29
38
|
@app.middleware('http')
|
|
30
39
|
async def local_browser_guard(request, call_next):
|
|
@@ -32,8 +41,8 @@ def install_local_guards(app):
|
|
|
32
41
|
host = urlsplit('http://' + request.headers.get('host', '')).hostname
|
|
33
42
|
except ValueError:
|
|
34
43
|
return JSONResponse({'detail':'Invalid Host header.'}, status_code=400)
|
|
35
|
-
if not host or host.lower() not in allowed_hosts:
|
|
36
|
-
return JSONResponse({'detail':'Host is not allowed for this
|
|
44
|
+
if not host or (host.lower() not in allowed_hosts and not public_render_host(host.lower())):
|
|
45
|
+
return JSONResponse({'detail':'Host is not allowed for this API.'}, status_code=400)
|
|
37
46
|
origin = request.headers.get('origin')
|
|
38
47
|
if origin:
|
|
39
48
|
try:
|
|
@@ -43,5 +52,10 @@ def install_local_guards(app):
|
|
|
43
52
|
extension_origin = bool(re.fullmatch(r'chrome-extension://[a-p]{32}', origin))
|
|
44
53
|
local_origin = parsed.scheme in {'http', 'https'} and parsed.hostname in {'localhost','127.0.0.1','::1'}
|
|
45
54
|
if not extension_origin and not local_origin:
|
|
46
|
-
return JSONResponse({'detail':'Cross-site access to
|
|
55
|
+
return JSONResponse({'detail':'Cross-site access to this API is not allowed.'}, status_code=403)
|
|
56
|
+
if api_token:
|
|
57
|
+
authorization = request.headers.get('authorization', '')
|
|
58
|
+
scheme, _, supplied = authorization.partition(' ')
|
|
59
|
+
if scheme.lower() != 'bearer' or not supplied or not hmac.compare_digest(supplied, api_token):
|
|
60
|
+
return JSONResponse({'detail':'API authorization is required.'}, status_code=401)
|
|
47
61
|
return await call_next(request)
|
package/server/main.py
CHANGED
|
@@ -195,7 +195,7 @@ async def lifespan(_app: FastAPI):
|
|
|
195
195
|
client.close()
|
|
196
196
|
|
|
197
197
|
|
|
198
|
-
app = FastAPI(title="Browser Assistant API", version="2.9.
|
|
198
|
+
app = FastAPI(title="Browser Assistant API", version="2.9.41", lifespan=lifespan)
|
|
199
199
|
install_local_guards(app)
|
|
200
200
|
|
|
201
201
|
@app.exception_handler(HTTPException)
|