browser-assistant 2.9.40 → 2.9.42

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.
@@ -18,9 +18,9 @@
18
18
  return error;
19
19
  }
20
20
  function temporary(error) {
21
- // The backend already tried the available vision keys.
21
+ // Retry exhausted vision keys only after their explicit cooldown expires.
22
22
  if (error.code === 'vision_rate_limited')
23
- return false;
23
+ return Number.isFinite(error.retryAfterMs) && error.retryAfterMs > 0;
24
24
  const text = error?.message || '';
25
25
  if (/access denied|forbidden|unauthorized|invalid.api.key|not configured|validation|not.support|model.*(?:not found|not exist)|illustration changed|question changed|context invalidated|extension was reloaded|no readable|unparseable/i.test(text))
26
26
  return false;
@@ -48,7 +48,7 @@
48
48
  catch (error) {
49
49
  if (!active())
50
50
  return null;
51
- if (attempt === attempts || !temporary(error) || error.retryAfterMs > 60_000)
51
+ if (attempt === attempts || !temporary(error) || error.retryAfterMs > 300_000)
52
52
  throw error;
53
53
  onRetry({ attempt: attempt + 1, attempts, message: error.message });
54
54
  // Short waits keep Stop/Pause responsive. Revalidate before the
@@ -57,6 +57,8 @@
57
57
  for (let elapsed = 0; elapsed < delay; elapsed += 100) {
58
58
  if (!active())
59
59
  return null;
60
+ if (!current())
61
+ throw new Error('Question changed while requesting an answer. No answer was selected.');
60
62
  await sleep(Math.min(100, delay - elapsed));
61
63
  }
62
64
  }
@@ -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(`http://127.0.0.1:8000${request.path}`, {
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' ? 'Local server request timed out.' : 'Local server is offline. Start it with the project virtual environment.' }))
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;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.40",
4
+ "version": "2.9.42",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -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>
@@ -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() {
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.40",
3
+ "version": "2.9.42",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -2,6 +2,10 @@
2
2
  GROQ_API_KEY=
3
3
  GROQ_API_KEY_2=
4
4
  GROQ_API_KEY_3=
5
+ GROQ_API_KEY_4=
6
+ GROQ_API_KEY_5=
7
+ GROQ_API_KEY_6=
8
+ GROQ_API_KEY_7=
5
9
  GROQ_TEXT_MODEL=openai/gpt-oss-120b
6
10
  GROQ_VISION_MODEL=qwen/qwen3.8-27b
7
11
  # Optional comma-separated vision models available on YOUR account; empty by default.
@@ -15,5 +19,8 @@ GROQ_REVIEW_TOKEN_LIMIT=4096
15
19
  SERVER_HOST=127.0.0.1
16
20
  # Optional additional hostnames for a deliberately configured local deployment.
17
21
  SERVER_ALLOWED_HOSTS=
22
+ # Required when the API is hosted outside your computer. The extension sends it
23
+ # as Authorization: Bearer <value>; keep this value private.
24
+ SERVER_API_TOKEN=
18
25
  # Empty preserves the existing server/scan_history.db location.
19
26
  HISTORY_DB_PATH=
@@ -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 local API.'}, status_code=400)
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 the local API is not allowed.'}, status_code=403)
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
@@ -41,11 +41,16 @@ logger = logging.getLogger("browser-assistant")
41
41
  load_dotenv(Path(__file__).with_name('.env'))
42
42
 
43
43
  # Setup Groq — multiple API keys for rate-limit rotation
44
- _groq_keys = []
45
- for env_var in ["GROQ_API_KEY", "GROQ_API_KEY_2", "GROQ_API_KEY_3"]:
46
- key = os.getenv(env_var)
47
- if key and key != "your_groq_api_key_here" and key not in _groq_keys:
48
- _groq_keys.append(key)
44
+ def load_groq_keys():
45
+ """Load up to seven distinct configured credentials in stable order."""
46
+ keys = []
47
+ for env_var in ["GROQ_API_KEY", *[f"GROQ_API_KEY_{i}" for i in range(2, 8)]]:
48
+ key = os.getenv(env_var, "").strip()
49
+ if key and key != "your_groq_api_key_here" and key not in keys:
50
+ keys.append(key)
51
+ return keys
52
+
53
+ _groq_keys = load_groq_keys()
49
54
 
50
55
  # Retry rotation is handled below. Disable the SDK's long exponential retry so
51
56
  # a rate-limited key cannot hold up every next question before we try another.
@@ -195,7 +200,7 @@ async def lifespan(_app: FastAPI):
195
200
  client.close()
196
201
 
197
202
 
198
- app = FastAPI(title="Browser Assistant API", version="2.9.40", lifespan=lifespan)
203
+ app = FastAPI(title="Browser Assistant API", version="2.9.42", lifespan=lifespan)
199
204
  install_local_guards(app)
200
205
 
201
206
  @app.exception_handler(HTTPException)