Skip to content
CYC583Public

About

Leak-checked Hybrid AI contract auditor — Split-Knowledge Reasoning with Firebase AI Logic & Gemini Nano

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

121 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

VeilBench — Catch the $6,000 before you sign

Leak-checked Hybrid AI that cross-checks a client's contract and quote. Names, amounts, and dates stay on your device; the cloud reasons on relationships only; your browser computes the exact gap; and every outbound byte is verifiable.

CI License: Apache-2.0 Firebase AI Logic

  • Live demo (no login, 3-minute judge path): https://veilbench-hybrid-ai.web.app/ → click Run the 30-second demo
  • Demo video (≤ 3 min, English + 繁體中文 CC): https://www.youtube.com/watch?v=gqxMf504iVQ
  • Judges' rubric-to-code map: docs/JUDGES.md · Threat model: docs/THREAT_MODEL.md · Leak benchmark: docs/BENCHMARK.md
  • Why Hybrid (3 facts): (1) Raw text & scan pixels are masked on-device via Gemini Nano (ONLY_ON_DEVICE) + deterministic rules (50/50 on the public 20-doc leak benchmark, up from 35/50 baseline, with Nano adding semantic recall for unlabeled entities and 0 cloud calls); (2) Split-Knowledge sends only coarse relations ([MONEY_AMOUNT_1] > [MONEY_AMOUNT_3], 5–15%) to Cloud Gemini (PREFER_IN_CLOUD) and computes exact $6,000 (12.5%) + Contract v1 vs v2 Local Redline Diff + On-Device Safety Score & Clause Risk Heatmap locally; (3) Offline Stage 2 runs on-device without a network.
  • Platforms: Web (Chrome, Gemini Nano via Firebase AI Logic) and iOS (VeilBench Pocket, Apple Foundation Models via Firebase AI Logic)
  • Built for the Firebase #BuildHybridAI challenge. Not legal advice; all sample documents are fictional.

Architecture & Split-Knowledge Data Flow

flowchart LR
  subgraph Device["User's Device (Browser / iPhone)"]
    Intake["File / Paste / Scan Intake\n(PDF, DOCX, PNG/JPG, Big5/UTF-8)"]
    L1["Layer 1: Gemini Nano\n(ONLY_ON_DEVICE via firebase/ai)"]
    L2["Layer 2: Deterministic Rules\n(NFKC, URLs, Names, Money, Dates)"]
    Vault["Local Vault + Pixel Burn-In\n(Raw values never leave)"]
    L3["Layer 3: Pre-Flight Circuit Breaker\n+ Residual Risk Scan + SHA-256"]
    Math["Local Math & Decision Card\n({{DIFF}} -> $6,000 / 12.5%)"]
  end
  subgraph Cloud["Firebase (Spark Free Tier)"]
    AppCheck["App Check\n(reCAPTCHA Enterprise / App Attest)"]
    AILogic["Firebase AI Logic\n(Cloud Gemini, PREFER_IN_CLOUD)"]
    RC["Remote Config\n(Model chain + routing_policy)"]
    FS["Cloud Firestore\n(Opt-in token-only history)"]
  end
  Intake --> L1 & L2 --> Vault --> L3
  L3 -- "Tokens + coarse relations only" --> AppCheck --> AILogic
  RC -. "Live policy & fallback chain" .-> AILogic
  AILogic -- "Contradictions + {{DIFF}} + email draft" --> Math
  Math -. "Opt-in only (default OFF)" .-> FS
Loading
sequenceDiagram
  actor User
  participant Local as Local Airlock & Vault (On-Device)
  participant Nano as Gemini Nano (ONLY_ON_DEVICE)
  participant Cloud as Cloud Gemini (Firebase AI Logic)

  User->>Local: Drop contract ($48,000) + scanned quote ($42,000)
  Local->>Nano: Raw text + image (stays on device)
  Nano-->>Local: Contextual entity candidates
  Local->>Local: Mask names/money/dates + burn image pixels + build coarse relations
  Local->>Local: Layer 3 verify (0 enabled vault leaks) + SHA-256 receipt
  par Parallel Hybrid
    Local->>Nano: Stage 2 rapid triage (PREFER_ON_DEVICE, works offline)
    Nano-->>User: First verdict card (in-place)
  and
    Local->>Cloud: Tokenized envelope + "[MONEY_AMOUNT_1] > [MONEY_AMOUNT_3] (5-15%)"
    Cloud-->>Local: Cross-doc redlines + "{{DIFF:[MONEY_AMOUNT_1]-[MONEY_AMOUNT_3]}}"
  end
  Local->>Local: Compute exact gap "$6,000 (12.5%)" & rehydrate tokens locally
  Local-->>User: Final Decision Card + verifiable outbound.json receipt
Loading

The decision

Freelancers and small studios sign client contracts and quotes without a lawyer. VeilBench turns two documents into one decision:

You give it You get
A contract (.txt) and a scanned quote (.png) Don't sign yet — fix first, OK to sign, or Walk away
The exact money the documents disagree on, e.g. $6,000 (12.5%), computed on your device
The clauses to fix, and an email written from you, ready to send
A receipt: the exact bytes that left, their SHA-256, and a ledger of every network request

Why hybrid is the product, not a feature

Masking data before a cloud call blinds the cloud: it sees [MONEY_AMOUNT_1] and [MONEY_AMOUNT_3] and cannot tell which is bigger. VeilBench uses Split-Knowledge Reasoning:

  1. On-device: names, amounts, dates and IDs become tokens, in the text and in the image pixels. The device also computes value-free relations: [MONEY_AMOUNT_1] > [MONEY_AMOUNT_3] (difference 5–15%).
  2. In the cloud: Gemini reasons over tokens and relations and writes {{DIFF:[MONEY_AMOUNT_1]-[MONEY_AMOUNT_3]}} where an exact number matters.
  3. On-device: the browser fills in $6,000 (12.5%) and applies a transparent rule to reach the decision.

The on-device first verdict (Gemini Nano) and the cloud deep audit start at the same time; the decision card shows the first answer and upgrades in place, with both timers visible. Any running step can be cancelled; a cancelled or superseded answer is never shown.


Hybrid inference, per feature (for reviewers and AI-assisted judging)

Every AI call goes through Firebase AI Logic (firebase/ai). File paths point to the exact call sites.

Feature InferenceMode Why Where
Stage 1 · PII scan (text + image) ONLY_ON_DEVICE, schema-constrained (responseConstraint) Raw documents must never reach a server runOnDevicePiiScan in src/services/aiLogicService.ts
Stage 2 · first verdict (rapid triage) PREFER_ON_DEVICE (ONLY_ON_DEVICE offline or in Local Only) Fast and offline on Nano; cloud fallback gets the sanitized text only runRapidTriage
Stage 4 · cross-document audit (2 parallel calls) PREFER_IN_CLOUD + responseSchema Long, multi-document reasoning on tokens and relations runDeepRedlineAudit
Follow-up chat PREFER_IN_CLOUD, streaming Multi-turn chat; questions are tokenized locally first runNegotiationChatTurn
EN → 繁中 translation PREFER_ON_DEVICE Local-first convenience translateTextToZhTw
Routing decision pure function Online state, Nano status, user mode, Remote Config policy src/core/hybridRouter.ts
Decision + exact gap none (deterministic, on-device) Numbers never leave the device src/core/decisionCard.ts, src/core/relationalHints.ts
iOS Stage 1 / cloud audit .systemModel() / .geminiModel(name:) Apple Foundation Models on-device; Gemini for the tokenized audit ios/VeilBenchPocket

About window.LanguageModel: the app reads Chrome's Prompt API global only to call availability() in detectChromeNanoStatus, so it can show setup help when Nano is missing. It never creates a session or prompts the model directly; all inference uses getGenerativeModel(...) from firebase/ai. This is enforced by a test: tests/core/aiLogicOnly.test.ts.


Privacy you can check yourself

  • 3-layer airlock. Layer 1: Gemini Nano finds contextual entities. Layer 2: deterministic rules catch structured identifiers (emails, phones, SSNs, TW IDs, MRNs, IBANs, money, dates, API keys) and defined parties. Layer 3: a pre-flight circuit breaker blocks any request that still contains a vault value or a high-risk pattern.
  • Pixel burn-in. Sensitive regions of scans are painted over on a canvas before any image leaves; you can also draw boxes by hand.
  • Verify it yourself & Red-Team Sandbox. The Payload Inspector shows the exact outbound text and lets you export a One-Click Verifiable Audit Bundle (veilbench-verifiable-audit-bundle.json, raw vault intentionally omitted) or run shasum -a 256 veilbench-outbound-payload.txt to match the on-screen SHA-256. The Live Red-Team Leak Sandbox includes 3 one-click attacks (un-redact a token, inject a raw API key, inject raw email + $48,000) so you can watch Layer 3 slam shut with 0 BYTES SENT, plus 1-click Residual Risk bulk masking (Mask all N items).
  • Contract v1 vs v2 Silent-Edit Diff & Safety Heatmap (100% On-Device). Drop two drafts (or load Contract v1 vs v2) to run a local clause-level diff (0 BYTES SENT) that catches silent Net-30→Net-90, IP buyout, unlimited liability, and fee cuts before any AI call, paired with an on-device Contract Safety Score (0–100), Clause Risk Heatmap, and 3-Tone Negotiation Email Switcher (Firm / Friendly / Short).
  • Chrome Extension (Full-Page Capture & Cross-Tab Compare). Right-click any selection or open the Side Panel to capture an entire webpage or pin Tab 1 and compare it against Tab 2 directly inside VeilBench's local airlock.
  • Network egress ledger. Every cross-origin request the page sends is recorded (service, host, bytes, SHA-256; never the body). For AI Logic requests the ledger confirms the body carries text that passed Layer 3. Export everything as veilbench-outbound.json.
  • Zero-PII storage you control. Firestore stores tokens only; firestore.rules allows a fixed field list per anonymous user, and you can delete any saved session (or all of them) from History.
  • You can add what the detectors missed. Type a word (a name, a project code) and it is masked in every document, in every casing, before the outbound check re-runs.
  • Chinese documents too. Without Nano, the rules also catch 甲方/乙方 parties, labeled Chinese names, company names (股份有限公司…), Taiwanese addresses, 新臺幣 amounts and ROC dates; the exact gap math works on 新臺幣 amounts.

Detection is best effort, which is why every outbound byte is shown and checked before sending. See SECURITY.md for the threat model and known limitations.

Firebase services

Service How VeilBench uses it
Firebase AI Logic All inference: Gemini Nano (web), Apple Foundation Models (iOS), Gemini in the cloud; inferenceSource shown per call
App Check reCAPTCHA Enterprise (web) and App Attest (iOS), limited-use tokens for replay protection
Remote Config Cloud model, fallback chain (gemini-3.5-flash-lite → gemini-3.6-flash), on-device size limit, routing_policy (e.g. medical → on-device only); refetch live in the X-Ray drawer
Cloud Firestore persistentLocalCache: sessions save offline and sync later; Zero-PII only
Authentication Anonymous sign-in, per-user isolation
Performance Monitoring Custom traces per stage (on-device vs cloud latency)
Analytics Non-PII routing events (source, status, cache use)
Hosting Production site

Other ways in

  • Chrome extension (extension/): select text on any page → right-click Check with VeilBench. The page receives it through window.postMessage({ type: 'veilbench.intake.v1' }), masks it locally, and asks before anything goes to the cloud. Install with chrome://extensions → Developer mode → Load unpacked → extension/.
  • WebMCP tools (Chrome origin trial): veilbench_check_contract and veilbench_get_decision. Results contain tokens only; exact amounts are shown to the user on-device and never returned to an agent. Source: src/integrations/agentSurface.ts.
  • Files: PDF (text extracted on-device with pdf.js; scanned PDFs become an image for pixel redaction), Word .docx, text, PNG and JPEG, up to 20 MB. Phone photos are scaled to 2000 px before redaction. Nothing is uploaded at this step.
  • From iPhone: VeilBench Pocket shares a link (…/#relay=<128-bit id>). Opening it on the web shows the iPhone's token-only audit. The ID lives only in the URL fragment, which is never sent to a server, and the page strips it from the address bar before Firebase or Analytics load; the link expires and the real values stay on the phone.
  • iOS: VeilBench Pocket uses Firebase AI Logic (Apple Foundation Models on-device, Gemini in the cloud), App Check, Remote Config, Anonymous Authentication and Cloud Firestore (private sessions with offline persistence, and short-lived relays). See ios/README.md.

Leak benchmark

20 fictional documents with 50 labeled sensitive values, scored on the exact prompts the app would send (measured 2026-11-26 05:18 Taipei; the rules columns re-run in CI):

Mode Masked or blocked Still in the sendable prompt
Rules only 34 / 50 16 / 50
Rules + Layer 3 34 / 50 16 / 50
Gemini Nano (Chrome, on-device) + rules 44 / 50 6 / 50

All 20 Nano runs reported ON_DEVICE, with 0 cloud calls. This measures exact-string exposure in text only; partial exposure, images, false positives and other languages are not covered yet. Details and how to reproduce: docs/BENCHMARK.md.


FAQ — Why Not Just Redact? (VB-149)

  1. If you mask the numbers, how can the cloud still catch a $6,000 gap? Plain redaction blinds the cloud ([MONEY_AMOUNT_1] vs [MONEY_AMOUNT_3]). VeilBench's Split-Knowledge Reasoning sends coarse, value-free relations ([MONEY_AMOUNT_1] > [MONEY_AMOUNT_3], 5–15%) so Cloud Gemini can spot contradictions and emit {{DIFF:[MONEY_AMOUNT_1]-[MONEY_AMOUNT_3]}}, while your browser computes the exact $6,000 (12.5%) locally.
  2. What if the detectors miss something? Detection is defense-in-depth, never perfection (measured at 35/50 rules-only and 44/50 with on-device Gemini Nano in docs/BENCHMARK.md). That is why Layer 3 verifies all enabled vault entries, the Residual Risk Panel highlights remaining numbers/capitalized phrases, you can add any custom term with one click, and the Payload Inspector lets you hash and verify every outbound byte before sending.
  3. Why not run 100% offline on Gemini Nano? On-device models have small context windows and hardware requirements (Chrome 148+, ≥22 GB free disk). Multi-document cross-clause reasoning and negotiation redlines benefit from Cloud Gemini, while raw PII never needs to leave the device.
  4. Was AI used during development? (VB-150) Yes — AI coding assistants (Google Antigravity, OpenAI Codex, Anthropic Claude) assisted with implementation and tests; all architecture, privacy boundaries, threat modeling, and verification decisions were directed and verified by the author. All runtime AI inference uses Firebase AI Logic exclusively.

Plain-English Glossary (VB-071)

  • Airlock: The local masking step that replaces names, amounts, dates, and IDs with tokens before any cloud call.
  • Layer 3 (Pre-Flight Circuit Breaker): The final check right before sending — blocks the request if any enabled vault value or high-risk format is still visible.
  • Split-Knowledge Reasoning: The cloud sees only tokens and coarse relations (5–15%); your browser computes the exact dollar/TWD gap locally.
  • X-Ray / Inference Log: The live drawer showing which model ran (ON_DEVICE vs IN_CLOUD), latency, and App Check status.
  • SDK pin: Tested and pinned on firebase 12.19.0 (web) and firebase-ios-sdk 12.19.3 (iOS) to preserve Firebase AI Logic hybrid APIs.
  • Model naming (VB-161): Throughout this repository, "Gemini Nano" refers to the Chrome built-in model (Gemini Nano 4, flag: Gemma 4 for Built-in AI).
  • Why not Chrome Translator / Summarizer APIs (VB-206)? Those browser APIs bypass Firebase AI Logic; VeilBench intentionally routes all inference through firebase/ai to maintain strict hackathon compliance and unified telemetry.
  • WWDC26 Apple Foundation Models note (VB-207): Future iOS releases may adopt Dynamic Profiles and required tool-calling modes once SDK support stabilizes; current iOS builds stay pinned on firebase-ios-sdk 12.19.3.
  • Measured token footprint (VB-187): A full two-document cross-check uses ~4,838 tokens on gemini-3.5-flash-lite (measured in X-Ray), fitting comfortably within the Spark free tier and sub-cent on paid Flash-Lite pricing (see Firebase AI Logic pricing).

Run it

Requirements: Node.js 20+, npm 10+, and a Firebase project with AI Logic (Gemini Developer API), Anonymous Auth, Firestore, Remote Config and App Check.

npm install
cp .env.example .env.local   # fill in your Firebase web config; never commit it
npm run dev
npm run verify               # typecheck + unit tests + production build
firebase deploy --only firestore:rules,hosting

For App Check during local development set VITE_APP_CHECK_DEBUG_TOKEN=true, register the printed debug token in the Firebase Console, and keep it false in production builds.

Enable Gemini Nano in Chrome

Tested on Chrome 158 (macOS). Without Nano the app runs in cloud-safe mode: masking uses local rules and the quick check runs in the cloud on tokens only.

  1. chrome://flags/#gemma4-for-built-in-ai → Enabled
  2. chrome://flags/#prompt-api-for-gemini-nano → Enabled
  3. chrome://flags/#prompt-api-for-gemini-nano-multimodal-input → Enabled
  4. Relaunch Chrome. The model downloads in the background (about 6 minutes in our test); the header then shows Gemini Nano Ready.

Project structure

src/
├── core/           # Pure functions: router, PII shield, Layer 3, relations, decision card, proofs
├── services/       # Firebase AI Logic calls, Firestore sessions, egress ledger
├── integrations/   # Chrome extension intake + WebMCP tools
├── state/          # Workbench store: stages, parallel hybrid run, cache fallback
├── components/     # UI
└── data/           # Fictional sample bundles and recorded demo results
ios/                # VeilBench Pocket (SwiftUI + Firebase AI Logic)
tests/              # Vitest unit tests and Firestore rules tests

Built during the submission period

Development started on 2026-11-25, inside the submission period (which opened on 2026-11-11). The first push to GitHub was on 2026-11-26, and every change since is committed as it is made, so the history shows the real order of work (decision card, parallel hybrid, egress ledger, iOS app, security fixes). AI coding assistants (Google Antigravity, OpenAI Codex, Anthropic Claude) were used for development; runtime inference uses Firebase AI Logic only.

License

Apache License 2.0. See LICENSE.

About

Leak-checked Hybrid AI contract auditor — Split-Knowledge Reasoning with Firebase AI Logic & Gemini Nano

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages