Inspiration
Cloud AI is genuinely useful for contract review, and completely off-limits for the documents that need it most. A paralegal reviewing a vendor agreement cannot paste client names, an IBAN, and an API key someone left at the bottom into a chat box. "Redact it first" tools ask you to trust a scan you never see, and none of them tell you where the model finally ran.
Firebase AI Logic's hybrid inference gave us a way to make the privacy boundary a load-bearing, observable part of the product instead of a promise: run raw text only on-device, send only a payload the user approved, and display the inference source the SDK actually reported.
What it does
- Scan locally. Deterministic detectors find emails, phone numbers, IBANs (mod-97), payment cards (Luhn), SSNs, credentials, IPv4/IPv6, PEM private keys, bearer tokens, dates of birth, heuristic names, custom terms and user regex. When an on-device model is available it proposes extra spans; every proposal must be an exact substring of the document or it is discarded.
- Review and lock. Each finding carries type, severity, source and detector provenance. Credentials, cards, IBANs and SSNs are locked: un-redacting one requires typing
UNLOCK, which is written to the audit log. - Approve the exact payload. The sanitized text is shown byte for byte with its SHA-256. Approval binds hash + document revision + 10-minute expiry + single-use nonce. Editing one character invalidates it.
- Analyze in the cloud through one gateway. Every AI call in the product goes through
runInferenceRequest(). Only an approved payload can reachONLY_IN_CLOUD;prefer_*modes are restricted to sanitized or user-declared non-sensitive text. - Show where inference really ran. The Inspector displays requested mode versus observed source (
ON_DEVICE/IN_CLOUD), latency, model, status and the full lifecycle for a request ID. A missing or unexpected source makes the run untrusted and its output is discarded. - Fail closed, and count it. Expired or mutated approvals, missing App Check tokens and unavailable local models block the request instead of falling back. Blocked transmissions are counted in Overview and Audit.
How we use Firebase AI Logic
All four InferenceModes are used deliberately, not as a demo toggle:
| Mode | Where it is used | Content it may see |
|---|---|---|
ONLY_ON_DEVICE |
Local scan assist, local summary | Raw text, never leaves the device |
PREFER_ON_DEVICE |
Playground, Inspector lab | Sanitized or declared non-sensitive only |
PREFER_IN_CLOUD |
Playground, Inspector lab | Sanitized or declared non-sensitive only |
ONLY_IN_CLOUD |
Approved cloud analysis | The hash-bound approved payload |
getGenerativeModel(ai, { mode: InferenceMode.X }) → generateContent() → result.response.inferenceSource → normalized to ON_DEVICE / IN_CLOUD / UNKNOWN → compared against what the mode is allowed to return → persisted on the run. Requested mode and observed source are both shown; only the observed value is treated as truth.
App Check is initialized before any model is created and re-probed at dispatch; cloud runs require token_ok or they are blocked. Anonymous Auth scopes the optional metadata backend without collecting identity. Remote Config carries non-sensitive flags and limits with in-code defaults.
How we built it
React 19 + TypeScript (strict) + Vite + Tailwind 4, over a pure domain core:
privacy/— detectors, normalization with an NFC offset map, overlap merge, placeholder assignment, payload builder, approval, re-identification. No network, no Firebase, noany.inference/— the only layer allowed to importfirebase/*.storage/— IndexedDB via Dexie. Raw text and the placeholder map live here and nowhere else; the map is memory-only by default.- Optional Express + PostgreSQL service that stores run and audit metadata only (no raw-text column, no title column, no mapping table).
ESLint enforces the layering: Firebase imports outside inference/ fail the build, hard-coded gemini-* strings fail, logging document-derived values fails. 247 Vitest tests cover approval binding, router policy across mode × sensitivity, gateway ordering (the nonce is marked used before dispatch), storage sentinel sweeps and detector fixtures. Playwright covers the demo path, the fail-closed path, and a no-network assertion for local runs.
Challenges we ran into
- Making "observed" mean something. The web SDK reports lowercase
on_device/in_cloud; we normalize both spellings, treat anything else asUNKNOWN, and markONLY_ON_DEVICEruns untrusted unless the source is confirmed. The source is never inferred from latency. - Approval is a race, not a form. Hash, revision, expiry and a single-use nonce are checked on every dispatch, the nonce is consumed before the network call, and the payload hash is recomputed at send time. A failed call needs a new approval — that is said in the UI, not just in the tests.
- App Check on the web is the sharp edge. Enforcement is mandatory for AI Logic now. A local
getToken()success only proves a token can be minted; the AI backend still returned401 — Firebase App Check token is invalidfor the deployed origin, and each Playwright context mints its own debug token. The gateway blocks, with no retry loop and no fallback. We published that instead of simulating a cloud run. - Capability honesty. Chrome reported the on-device model as
downloadablewhile the SDK could already prepare and run it. We keepONLY_ON_DEVICEblocked until the state is genuinelyavailableor the user runs "Prepare local model" — conservative on purpose.
Accomplishments we're proud of
- Real hybrid inference, not a router costume. On the demo machine three modes observed
ON_DEVICE(1.0–2.5 s), including aprefer_in_cloudrequest the SDK answered on-device — displayed as observed, not as requested. The cloud path was blocked by App Check and reported as blocked. - The privacy boundary is testable. An e2e run with request interception asserts zero AI network requests during a local-only run; a 60-document synthetic corpus with 320 labeled entities gives a redaction leak rate of 0, with per-type precision/recall published, misses included.
- One coherent lifecycle. Workspace, Privacy Firewall and Inspector share one typed request record, so you can follow a single request from creation to observed execution.
- A product, not a proof of concept. Landing, workspace stepper, payload preview, approval countdown, result, inspector, audit, benchmark, settings, light/dark themes, keyboard navigation, a working 390 px layout.
What we learned
- Hybrid inference is a data-flow control first and a cost optimisation second. The interesting question is not "which model is faster" but "what is allowed to leave, and who said so".
- For redaction, deterministic code plus a human decision beats a model judgement. The model may suggest; it never decides.
- Honesty is a feature. Publishing the unregistered App Check token, the unavailable local model and the missed precision targets made the Inspector and Benchmark pages more convincing, not less.
What's next for ShieldDesk
Chunking for long documents, PDF/DOCX parsing inside a worker, per-organisation policy packs, local embeddings for retrieval, and an Android client sharing the same domain core.
Honest limitations
- Cloud inference on the deployed URL is blocked by App Check. The debug token for the deployed origin is not registered, so
ONLY_IN_CLOUDreturns401 — Firebase App Check token is invalid. The gateway blocks fail-closed and the UI says so. The demo shows realON_DEVICEruns plus that fail-closed moment; no cloud run is claimed as observed. - On-device inference on the web requires desktop Chrome 148+ with the Prompt API model downloaded and hardware meeting Chrome's requirements. Capability is probed at runtime, never assumed.
- Detectors are rules, not an oracle. Regex plus checksums, with measurable false negatives; names are heuristic. Measured precision on the synthetic corpus is below our aspirational targets for email and cards, and the Benchmark page lists the misses rather than hiding them.
- Placeholders preserve document structure, so layout still leaks. The placeholder map is memory-only by default and lost on reload.
- No OCR, no PDF/DOCX parsing, no chunking, no multi-user collaboration in the MVP; text input only, with a payload size cap.
- Not a compliance certification. No HIPAA/GDPR claim, no guaranteed anonymisation.
- The optional metadata backend stores no raw text, no titles and no mapping table; the frontend works fully without it.
Try it
Open the live demo, Workspace → Load sample document → Scan locally, review the findings, open Payload, Approve this payload, then Run cloud analysis. Open Inspector to compare requested mode with observed source, and edit one character afterwards to watch the approval die and the run be blocked.
No account is needed. If the on-device model is unavailable, Settings reports that truthfully and local-only runs are blocked rather than silently sent to the cloud; rule-based scanning still works.
Built With
- app-check
- dexie
- dompurify
- express.js
- firebase
- firebase-ai-logic
- firebase-auth
- gemini
- gemini-nano
- indexeddb
- node.js
- playwright
- postgresql
- react
- remote-config
- tailwind-css
- typescript
- vite
- vitest
- zod