Skip to content

Fix/api safety score contract#22

Open
KevinRusu wants to merge 2 commits into
benevolentbandwidth:mainfrom
KevinRusu:fix/api-safety-score-contract
Open

Fix/api safety score contract#22
KevinRusu wants to merge 2 commits into
benevolentbandwidth:mainfrom
KevinRusu:fix/api-safety-score-contract

Conversation

@KevinRusu

Copy link
Copy Markdown
Contributor

Summary

  • Fixed a critical bug where a scam page checked by the AI could come back labeled "Safe" — the extension and the API disagreed on what the score meant (10 = safe vs 10 = dangerous). Standardized on one scale everywhere: 10 = safe, 0 = scam, for both the local check and the AI check.
  • created skeleton for server-side api deployment
  • Moved the AI network call from the popup into the background worker, so it finishes even if the popup is closed, and the result is cached per tab.
  • Hardened the AI prompt against being tricked by scam pages that try to inject fake instructions into their own text.
  • Added request size limits, better error logging, a /health endpoint, and 17 automated tests for the API.

Changes by area

API (api/)

  • schemas.py — renamed the response field risk_scoresafety_score, added size limits on request fields
  • mock_provider.py, gemini_provider.py — safety-scale scoring logic, hardened prompt with clear boundaries around untrusted page text
  • auth.py — replaced the shared API key check with an origin allowlist
  • main.py — fixed rate limiting to work behind a proxy, added /health, better error logging
  • Dockerfile — runs uvicorn with --proxy-headers so rate limiting sees real client IPs
  • tests/ — new test suite (17 tests) covering the score mapping, origin checks, and request validation
  • README.md, .env.example — updated to match

Extension (extension/)

  • types/api.ts, App.tsx — updated to the new safety_score field, no more score conversion
  • background/background.ts — new checkWithAI handler; this is now the only place that makes network calls
  • vite.config.ts, env.d.ts — stopped baking the API key into the build

Testing done

  • 17 automated tests pass (pytest api/tests/)
  • Ran the API live with the real Gemini API against 4 test cases: a real bank page, a fake phishing page, a page attempting prompt injection, and a borderline page — all classified correctly
  • Confirmed rate limiting rejects excess requests

KevinRusu and others added 2 commits July 9, 2026 16:41
Added testing instructions and updated environment variable descriptions in README.
Copilot AI review requested due to automatic review settings July 9, 2026 20:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR standardizes the Beacon “score” contract end-to-end to prevent inverted interpretations (10=safe, 0=scam), moves Tier-2 AI analysis networking into the extension background worker for durability/caching, and hardens/extends the server-side API (validation, origin gating, health check, logging, Docker proxy headers) with new contract tests.

Changes:

  • Standardized on a single safety_score scale (0–10, 10=safe) across extension + API; removed risk_score/inversion logic.
  • Moved the AI /v1/analyze fetch from the popup UI into the background service worker and cached results per tab.
  • Added/updated API validation, origin allowlist auth, /health, improved logging, Docker proxy-header support, and a new test suite.

Reviewed changes

Copilot reviewed 15 out of 16 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
extension/vite.config.ts Stops compiling an API key into the shipped extension bundle.
extension/src/types/api.ts Updates response contract to safety_score (consistent safety scale).
extension/src/popup/App.tsx Uses cached AI results and delegates Tier-2 analysis to background worker (no direct fetch).
extension/src/env.d.ts Removes the now-eliminated __BEACON_API_KEY__ global.
extension/src/background/background.ts Centralizes API payload building + fetching in the service worker; caches aiResult per tab.
api/tests/test_analyze.py Adds contract/validation/origin tests to pin the safety-score invariant and request limits.
api/tests/conftest.py Ensures env/config and import paths are set correctly for API tests.
api/schemas.py Renames response field to safety_score and adds request size constraints.
api/requirements-dev.txt Adds dev deps for running API tests.
api/README.md Documents score convention, env vars, and test running.
api/providers/mock_provider.py Updates mock provider to return consistent safety-score/label/action mapping.
api/providers/gemini_provider.py Updates prompt to safety-score scale and adds prompt-injection hardening boundaries.
api/main.py Switches auth to origin allowlist, updates rate limiting defaults, adds /health, improves logging.
api/Dockerfile Runs uvicorn with --proxy-headers for correct client-IP rate limiting behind proxies.
api/auth.py Replaces shared-key auth with origin allowlist verification.
api/.env.example Updates example env vars for new origin allowlist + rate limit format.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread api/main.py
Comment on lines +27 to +37
if not allowed_origins():
if use_mock:
logger.warning(
"ORIGIN CHECK DISABLED — ALLOWED_EXTENSION_ORIGINS not set (mock/dev mode only)"
)
else:
logger.warning(
"ALLOWED_EXTENSION_ORIGINS is not set with USE_MOCK=false: "
"the API will accept requests from any origin. Set it to the "
"extension origin (chrome-extension://<id>) before deploying."
)
Comment thread api/tests/test_analyze.py
Comment on lines +8 to +24
import pytest
from fastapi.testclient import TestClient

from main import app

client = TestClient(app)

BASE_BODY = {
"url": "https://example.com/login",
"text": "Enter your password to continue.",
"context": "page_body",
}


def analyze(score: int, headers: dict | None = None, **overrides):
body = {**BASE_BODY, "heuristic_score": score, **overrides}
return client.post("/v1/analyze", json=body, headers=headers or {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants