Recipe: Firebase
This content is not available in your language yet.
A complete setup with Firebase sign-in, Firestore and Firebase Hosting. The AI route runs as a Cloud Function. A Hosting rewrite puts it at /api/trust/masked-ai/* on your own address, so no cross-site setup is needed.
Files you will touch
Section titled “Files you will touch”firestore.rulesfirebase.jsonfunctions/src/index.ts (server)functions/package.json (dependencies)src/lib/firebase.tssrc/lib/vault.tssrc/lib/ai.ts1. Install
Section titled “1. Install”In the app:
npm install @geometer/trust firebase openaiIn the functions folder:
cd functions && npm install @geometer/trust firebase-adminUntil the package is published, your Geometer contact gives you the install command.
2. firestore.rules
Section titled “2. firestore.rules”Each user can read and write only their own key file. The key file is one document in trustKeys. Its id is the user’s id, two underscores, then the app name (percent-encoded). The field is keyFile.
rules_version = '2';service cloud.firestore { match /databases/{database}/documents { match /trustKeys/{docId} { allow read, write: if request.auth != null && docId.matches(request.auth.uid + '__.*'); }
// Your own data. Each note holds its owner's id in `userId`, and only that user can use it. match /notes/{noteId} { allow create: if request.auth != null && request.resource.data.userId == request.auth.uid; allow read, delete: if request.auth != null && resource.data.userId == request.auth.uid; allow update: if request.auth != null && resource.data.userId == request.auth.uid && request.resource.data.userId == request.auth.uid; } }}Without a rule for notes, Firestore refuses every read and write there. Add rules like this for every collection of your own. Deploy with firebase deploy --only firestore:rules.
3. src/lib/firebase.ts
Section titled “3. src/lib/firebase.ts”import { initializeApp } from "firebase/app";import { getAuth } from "firebase/auth";import { getFirestore } from "firebase/firestore";
const app = initializeApp({ apiKey: import.meta.env.VITE_FIREBASE_API_KEY, authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN, projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,});
export const auth = getAuth(app);export const firestore = getFirestore(app);These values are meant to be public. They are not the AI key.
4. src/lib/vault.ts
Section titled “4. src/lib/vault.ts”import { doc, getDoc, runTransaction, setDoc } from "firebase/firestore";import { openVault, firebaseKeyStore, type Vault } from "@geometer/trust/vault";import { auth, firestore } from "./firebase";
let vault: Vault | null = null;
export async function getVault(onRecoveryCode: (info: { code: string; replacesPrevious: boolean; reason: string }) => void): Promise<Vault> { if (vault) return vault; const user = auth.currentUser; if (!user) throw new Error("Sign in first."); vault = await openVault({ app: "my-notes", // your app's name. Never change it later. user: user.uid, keyStore: firebaseKeyStore(firestore, { app: "my-notes", user: user.uid, // The modular Firebase API is plain functions. Pass them in (Trust imports no Firebase code). // Without runTransaction first setup is refused: the key file could be overwritten. functions: { doc, getDoc, setDoc, runTransaction }, }), unlock: "passkey", onRecoveryCode, }); return vault;}Save an encrypted note:
import { doc, setDoc } from "firebase/firestore";import { auth, firestore } from "./firebase";import { getVault } from "./vault";
export async function saveNote(text: string) { const vault = await getVault(({ code }) => window.alert(`Write this recovery code down. Keep it safe; the app may show it again until you confirm it:\n\n${code}`), ); const id = vault.newId(); const body = await vault.encrypt(text, { table: "notes", id, field: "body" }); // `userId` is the owner field the `notes` rule above checks. Only `body` is encrypted. await setDoc(doc(firestore, "notes", id), { userId: auth.currentUser!.uid, body });}5. functions/src/index.ts
Section titled “5. functions/src/index.ts”Cloud Functions use Node’s request and response. toNodeHandler converts the Trust handler.
import { onRequest } from "firebase-functions/v2/https";import { defineSecret } from "firebase-functions/params";import { initializeApp } from "firebase-admin/app";import { getAuth } from "firebase-admin/auth";import { maskedRoute, toNodeHandler } from "@geometer/trust/masked-ai/server";
initializeApp();
// Decides who may use your AI key: the browser sends the signed-in user's Firebase ID token as apiKey.async function isSignedIn(request: Request): Promise<boolean> { const token = request.headers.get("authorization")?.replace(/^Bearer /i, ""); if (!token) return false; try { await getAuth().verifyIdToken(token); return true; } catch { return false; }}
const openaiKey = defineSecret("OPENAI_API_KEY");
export const maskedAi = onRequest({ secrets: [openaiKey] }, (req, res) => { const handler = maskedRoute({ provider: "openai", apiKey: openaiKey.value(), authorize: isSignedIn, // required }); return toNodeHandler(handler)(req, res);});Set the secret and deploy:
firebase functions:secrets:set OPENAI_API_KEYfirebase deploy --only functionsFor Sealed AI, add a second function with sealedRoute (same authorize: isSignedIn) and toNodeHandler from @geometer/trust/sealed-ai/server, a secret named SEALED_AI_KEY, and the export name sealedAi.
6. firebase.json: put the route on your own address
Section titled “6. firebase.json: put the route on your own address”{ "hosting": { "public": "dist", "rewrites": [ { "source": "/api/trust/masked-ai/**", "function": "maskedAi" }, { "source": "/api/trust/sealed-ai/**", "function": "sealedAi" }, { "source": "**", "destination": "/index.html" } ] }}Keep the two /api/... rewrites above the ** rule.
7. src/lib/ai.ts
Section titled “7. src/lib/ai.ts”import OpenAI from "openai";import { maskedFetch } from "@geometer/trust/masked-ai";
import { auth } from "./firebase";
export async function makeAi() { const user = auth.currentUser; if (!user) throw new Error("Sign in first."); return new OpenAI({ baseURL: `${window.location.origin}/api/trust/masked-ai/v1`, apiKey: await user.getIdToken(), // the user's Firebase token. The AI key stays in the Cloud Function. dangerouslyAllowBrowser: true, maxRetries: 0, // the client would retry our errors, which never helps fetch: maskedFetch(), });}Check it worked
Section titled “Check it worked”- In the Firebase console, the
notesdocuments hold scrambledbodytext. - A chat from the app returns an answer, and the Network tab shows placeholders.
- Your AI key is in Secret Manager only.
- A call with no token returns 401.
authorize is required. A call without a real Firebase token gets 401 with masked-ai/not-authorized. Never use authorize: () => true unless you are building a public demo.
Errors: the openai client wraps Trust errors, so read them with findTrustError(err) from @geometer/trust/masked-ai (or /sealed-ai) and keep maxRetries: 0 on the client. See Masked AI.
If something fails, see errors.