browser-assistant 2.9.40 → 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.
@@ -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.41",
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.41",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -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=
@@ -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
@@ -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.40", lifespan=lifespan)
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)