Masked AI
This content is not available in your language yet.
Use GPT, Claude or Gemini with names, numbers and secrets swapped for placeholders before the chat leaves the device. When the answer comes back, the device swaps the real values back in.
What this does not protect
- Masked AI is not encryption. The AI company reads everything that was not masked.
- Detection is by pattern. Names are masked only if you list them in
alsoMask. A name you did not list goes through as written.- The shape of the chat. The AI company still sees the topic, the length and the words around a placeholder.
- Your server route. It forwards the masked chat as readable text.
- Your app’s own code. It runs inside your app and sees the plain text first.
If you need a chat that nobody can read, use Sealed AI. The full list: limits.
Never put the AI provider’s key in the browser. The browser calls your own server route. The route holds the key.
What is detected by default
Section titled “What is detected by default”| Type | Placeholder | Examples |
|---|---|---|
| Emails | [EMAIL_1] |
asha@example.com |
| Phone numbers | [PHONE_1] |
including Indian numbers, also written in Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada or Malayalam digits |
| Card numbers | [CARD_1] |
checked with the card checksum |
| Aadhaar and PAN | [AADHAAR_1], [PAN_1] |
Aadhaar checked with its checksum; PAN by its format. Indian-script digits count here too |
| API keys and tokens | [SECRET_1] |
known key prefixes, private keys, long random strings |
| IBAN | [IBAN_1] |
checked with the IBAN checksum |
| Names you list | [NAME_1] |
only the words in alsoMask |
The same value gets the same placeholder for as long as you keep using one maskedFetch() result. The table lives in memory only.
Add your own words with alsoMask (customer names, company names; whole words, any case). Protect a word from masking with neverMask.
Numbers written in Indian-script digits (nine scripts) are found: the detector reads them as the ASCII digits they look like, only to decide what to mask. What is sent and what you get back is always the user’s own characters. Masked AI does not catch a listed name with a suffix glued on.
Which providers
Section titled “Which providers”provider |
Client | Mount the route so the client reaches |
|---|---|---|
"openai" |
openai |
/api/trust/masked-ai/v1/chat/completions (baseURL .../masked-ai/v1) |
"anthropic" |
@anthropic-ai/sdk |
/api/trust/masked-ai/v1/messages (baseURL .../masked-ai) |
"gemini" |
@google/genai |
/api/trust/masked-ai/v1beta/models/<model>:generateContent (and :streamGenerateContent) |
"openai-compatible" |
openai |
any OpenAI-style server; needs baseURL |
Gemini through the native API:
import { GoogleGenAI } from "@google/genai";import { maskedFetch } from "@geometer/trust/masked-ai";
const ai = new GoogleGenAI({ apiKey: "not-used", // the key lives in the route httpOptions: { baseUrl: `${window.location.origin}/api/trust/masked-ai`, apiVersion: "v1beta", fetch: maskedFetch({ alsoMask: ["Customer Name"], app: "my-app", user: user.id }), retryOptions: { attempts: 1 }, // the client would retry our errors, which never helps },});On the server use maskedRoute({ provider: "gemini", apiKey: process.env.GEMINI_API_KEY!, authorize }). The route sends your key as x-goog-api-key and calls generateContent and streamGenerateContent only (countTokens, files, caches and tuning are refused). Text, system instructions, function-call arguments and function responses are masked; image, file and audio parts (inlineData, fileData) are refused with masked-ai/unmaskable-part. A Gemini receipt names the provider as openai-compatible with the real host, because the receipt format has three provider names.
What real models do to placeholders
Section titled “What real models do to placeholders”The chat goes out with [EMAIL_1], [NAME_1] and so on. Real models (GPT, Claude, Gemini) often write them back a little differently: without the brackets (EMAIL_1), in another case ([email_1]), with spaces ([ EMAIL_1 ]), escaped for Markdown (\[EMAIL\_1\]), inside backticks or bold, or with 's or s after them. Masked AI restores all of these, but only for placeholders it issued itself; text that merely looks like one is left alone. It also restores them when a model’s answer arrives in pieces and a placeholder is cut between two of them.
Two things help you:
- The hint. When a request has placeholders,
maskedFetchadds one short sentence to the system prompt asking the model to copy them exactly as written. The AI company sees that sentence; it reveals nothing about your data. Turn it off withmaskedFetch({ placeholderHint: false })if you compare prompts byte for byte or count prompt tokens. - A count.
maskedFetch({ onRestored: (s) => ... })is called when an answer has been restored, withs.unrestored: how many placeholder-like strings could not be restored (for example[EMAIL_9], a number that was never issued, or a placeholder cut off at the end). Show a small warning when it is not 0. It is a count only, never a value.
What cannot be restored: a model that rewrites a placeholder in words (“her email address”) or translates it. There is nothing left to match. Keep prompts short and concrete, tell the model to “copy placeholders exactly” if you have your own system prompt, and watch unrestored.
Thinking (Anthropic extended thinking)
Section titled “Thinking (Anthropic extended thinking)”Claude’s thinking and redacted_thinking blocks are signed by Anthropic over their exact text, and the API refuses a conversation that replays them changed. So Masked AI passes these blocks through unchanged in both directions. In practice: the thinking text you see is the placeholder version ([NAME_1]), not the restored one, and you replay the blocks as they came. This does not leak: the provider only ever saw placeholders, so its thinking holds placeholders. Keep passing the response’s blocks back as they are. Only blocks that carry the provider’s signature (or data) are passed through; a block without one is masked like text. Everything else around a thinking block is masked as usual.
One full example: Next.js
Section titled “One full example: Next.js”1. The server route, app/api/trust/masked-ai/[...path]/route.ts:
import { maskedRoute } from "@geometer/trust/masked-ai/server";import { isSignedIn } from "@/lib/authorize"; // your own check of the session: see the Next.js recipe
const handler = maskedRoute({ provider: "openai", // or "anthropic", or "openai-compatible" (add baseURL) apiKey: process.env.OPENAI_API_KEY!, authorize: (request) => isSignedIn(request), // required: only signed-in users may use your key});
export const GET = handler;export const POST = handler;authorize is required. If it is missing, maskedRoute throws masked-ai/no-authorize when your server starts. If it returns false, the route answers 401 with masked-ai/not-authorized. Never use authorize: () => true unless you are building a public demo.
Add OPENAI_API_KEY=... to .env.local and to your host’s settings. Do not prefix it with NEXT_PUBLIC_.
2. The browser, src/maskedChat.ts:
import OpenAI from "openai";import { findTrustError, maskedFetch } from "@geometer/trust/masked-ai";
export function makeAi(customerNames: string[]) { return new OpenAI({ baseURL: `${window.location.origin}/api/trust/masked-ai/v1`, apiKey: "not-used", // the real key lives only on the server dangerouslyAllowBrowser: true, maxRetries: 0, // see "Handle a failure" below fetch: maskedFetch({ alsoMask: customerNames, neverMask: ["Geometer"], onMasked: (summary) => { // Counts by type, for example { EMAIL: 1, NAME: 2 }. Never the values. console.log("Masked before sending:", summary.counts); }, }), });}
export async function draftReminder(customerNames: string[], text: string) { const ai = makeAi(customerNames); try { const reply = await ai.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: text }], }); return reply.choices[0]?.message.content; // real values are back in place } catch (err) { const problem = findTrustError(err); // see "Handle a failure" if (problem) throw new Error(problem.message); throw err; }}Example: draftReminder(["Asha Menon"], "Remind Asha Menon (asha@example.com) about invoice 42.") sends [NAME_1] and [EMAIL_1]. The answer you read has the real ones.
Anthropic uses a different base URL (no /v1):
import Anthropic from "@anthropic-ai/sdk";import { maskedFetch } from "@geometer/trust/masked-ai";
const ai = new Anthropic({ baseURL: `${window.location.origin}/api/trust/masked-ai`, apiKey: "not-used", dangerouslyAllowBrowser: true, maxRetries: 0, fetch: maskedFetch(),});Then set provider: "anthropic" in maskedRoute.
Handle a failure
Section titled “Handle a failure”Masked AI throws a TrustError before it sends anything it cannot mask. The openai and @anthropic-ai/sdk clients wrap that error: you catch APIConnectionError("Connection error."), and the Trust error sits in .cause. The clients also retry it twice by default, which can never help.
So do both of these every time:
- Create the client with
maxRetries: 0. - Read the error with
findTrustError(err), not withinstanceof. It returns theTrustError(withcodeandmessage) orundefined.
The message ends with the next step. Show it. The codes are in errors.
findTrustError finds errors the browser raised before sending. An answer from your route (401 masked-ai/not-authorized when nobody is signed in, 403 masked-ai/path-not-allowed, 413 for a body over the limit) comes back as the client’s own error (AuthenticationError and so on) with err.status and err.code (for example "masked-ai/not-authorized"), and findTrustError returns undefined for it. Handle both:
const problem = findTrustError(err);if (problem) showMessage(problem.message);else if (err instanceof OpenAI.APIError && err.code?.startsWith("masked-ai/")) showMessage("Please sign in again."); // your words: the route's own text is written for developerselse throw err;Where the route can run
Section titled “Where the route can run”The route is a standard Fetch handler. It works under any path that contains /masked-ai/: /api/trust/masked-ai/v1/... on Next.js, or /functions/v1/masked-ai/v1/... for a Supabase Edge Function named masked-ai. Express needs toNodeHandler, imported from the same server entry point:
import express from "express";import { maskedRoute, toNodeHandler } from "@geometer/trust/masked-ai/server";
const app = express();app.all("/api/trust/masked-ai/*", toNodeHandler(maskedRoute({ provider: "openai", apiKey: process.env.OPENAI_API_KEY!, authorize })));What the route does and does not do:
| It | Detail |
|---|---|
| Answers its own site only | A request a browser marks as coming from another site is refused with 403 masked-ai/cross-origin, before authorize. See other sites. |
Needs authorize |
Runs before the body is read. May return { user } to name the user. |
Limits use (limits) |
Per user and per route request counts and an answer-size cap. See limits. |
| Calls only these paths | Chat completions, responses and messages (POST, plus Anthropic count_tokens), Gemini generateContent and streamGenerateContent, and the models list (GET). Anything else answers 403 masked-ai/path-not-allowed. |
| Forwards only these headers | content-type, accept, anthropic-version, anthropic-beta, openai-beta. Your user’s Authorization, x-api-key and Cookie are dropped. |
| Limits the body | 2 MB by default. Change it with maxBodyBytes. |
| Follows no redirects | A redirect cannot carry your key to another host. |
| Logs nothing | Not bodies, not keys. |
Adds x-geometer-trust-adapter |
For example openai; host=api.openai.com. The device writes it into the receipt as the app’s own word. |
Limits and spending caps
Section titled “Limits and spending caps”Set limits on every route. authorize says who may use your key; limits says how much. Without it, one signed-in user in a loop (or a script that stole a token) can spend as much as the provider allows.
const handler = maskedRoute({ provider: "openai", apiKey: process.env.OPENAI_API_KEY!, authorize: async (request) => { const id = await getUserId(request); // your own check of the user's session return id ? { user: id } : false; // { user } names the user, so limits count per user }, limits: { perUser: { requestsPerMinute: 10, requestsPerDay: 200 }, perRoute: { requestsPerMinute: 120 }, // everyone together maxOutputTokens: 2000, // the largest answer one request may ask for },});| Option | Meaning |
|---|---|
perUser.requestsPerMinute, perUser.requestsPerDay |
Per user id. Over the limit: 429 masked-ai/rate-limited with a Retry-After header (seconds). |
perRoute.requestsPerMinute |
For all users together: a ceiling on the bill if many accounts misbehave at once. |
maxOutputTokens |
Lowers max_tokens, max_completion_tokens, max_output_tokens (or Gemini generationConfig.maxOutputTokens) in the forwarded body to this number, and adds one when the request has none: max_completion_tokens for OpenAI chat, max_output_tokens for Responses, generationConfig.maxOutputTokens for Gemini, max_tokens otherwise. Anthropic count_tokens is left alone. Reasoning models count their thinking tokens in this number, so do not set it too low for them. |
key(request) |
Returns the user id when authorize returns plain true. If authorize returns { user }, that wins. |
store |
Where counters live (below). |
The user id comes from authorize (return { user: id } instead of true) or from limits.key. If perUser is set and the route cannot tell who the user is, it answers 500 masked-ai/limits-no-user rather than letting the request through unlimited.
Windows are fixed: a counter starts at a user’s first request and runs for one minute (or one day). A refused request counts toward the counters up to the one that refused it, so a user hammering the minute limit does not use up their day, and does not use up the route’s budget. A request refused by authorize, by the path list or by the origin check is not counted.
Counters. By default they live in this server process’s memory (memoryLimitStore()), which is right for one server or container and wrong for serverless hosts (Vercel, Netlify, Supabase Edge): each instance counts alone, so the real limit is higher. There, pass a shared store. A store is one method, the same three calls as Redis INCR, PEXPIRE ... NX and PTTL:
import type { LimitStore } from "@geometer/trust/masked-ai/server";
const store: LimitStore = { // Add one to the counter `key`. If it does not exist, start it at 1 for `windowMs`. async increment(key, windowMs) { const count = await redis.incr(key); if (count === 1) await redis.pexpire(key, windowMs); const resetInMs = await redis.pttl(key); return { count, resetInMs: Math.max(0, resetInMs) }; },};// maskedRoute({ ..., limits: { perUser: { requestsPerMinute: 10 }, store } })(Use Upstash’s @upstash/redis or a Supabase table the same way; Trust adds no dependency.) If the store throws, the route answers 503 masked-ai/service-busy instead of dropping the cap. The error body is short and safe to show: “Too many requests. Please wait a minute.”
Other sites (allowedOrigins)
Section titled “Other sites (allowedOrigins)”A route answers its own site only. Browsers say where a request comes from (Sec-Fetch-Site, Origin); a call from another website is refused with 403 masked-ai/cross-origin before authorize runs, so a page on another site cannot make a signed-in user’s browser spend your key. Calls that carry neither header (curl, a server, a mobile app) are not affected: they still go to authorize, which stays the real gate.
If your front end is on another origin (for example https://app.example.com calling https://api.example.com), list it:
maskedRoute({ ..., allowedOrigins: ["https://app.example.com"] })The route then answers that origin’s preflight (OPTIONS, allowing the headers the browser asks for) and adds the CORS headers for that origin only (never *). Write origins in full, without a path. The host must send OPTIONS to the route: in Next.js add export const OPTIONS = handler;; a Supabase Edge Function receives it already. If you already wrap the route in your own CORS code, remove it, or the browser sees two Access-Control-Allow-Origin headers and refuses the answer.
A Supabase Edge Function is another origin than your app’s page (https://<project>.supabase.co against your site), so a Supabase setup needs allowedOrigins: ["https://your-app.example"] (and http://localhost:5173 while developing).
For openai-compatible, give baseURL as the provider writes it, with its /v1: baseURL: "https://openrouter.ai/api/v1". Plain http:// is accepted only for localhost.
The browser client refuses a few things on purpose:
| Case | Error |
|---|---|
| A real-looking provider key in a header (a sign-in token such as a Supabase JWT is fine) | masked-ai/key-in-browser |
A baseURL that does not go through /masked-ai/ |
masked-ai/not-via-route |
An endpoint other than chat completions, responses, messages or Gemini generateContent |
masked-ai/unsupported-path |
| An image, file or audio part in the request | masked-ai/unmaskable-part |
Receipts
Section titled “Receipts”Each masked chat writes one receipt on the device after the answer ends: counts by type, how many names you listed, salted fingerprints of what was sent and received, and whether the answer ended cleanly. It never holds text. See proof and the badge.
fetch: maskedFetch({ app: "my-app", // the ledger's owner: your app's name user: user.id, // pass it, so people who share a browser do not share receipts onReceipt: (receipt) => setLastReceipt(receipt), onReceiptError: (error) => console.warn(error.code), // the chat is not affected}),Check what left the device
Section titled “Check what left the device”- Open your browser’s developer tools, then the Network tab.
- Send a chat. Open the request to
/api/trust/masked-ai/.... - The body should hold placeholders where the name and email were.
If a real value is in the body, it was not detected. Add it to alsoMask.
Common mistakes
Section titled “Common mistakes”| Mistake | What goes wrong | Do this instead |
|---|---|---|
Writing authorize: () => true |
Anyone who finds the route can spend your key. | Check the user’s real session. |
Leaving limits out |
One user or script can run up your bill. | Set limits (per user, per route, maxOutputTokens). |
| In-memory limits on a serverless host | Each instance counts alone, so the limit is higher than you wrote. | Pass a shared store. |
| Putting the provider key in the browser | Anyone can read it and use your account. | Keep it in the route. Keep apiKey: "not-used" in the browser. |
Leaving maxRetries at its default |
The client retries an error that cannot succeed. | Set maxRetries: 0. |
Checking err instanceof TrustError |
The client wrapped the error, so the check is false. | Use findTrustError(err). |
| Telling users “the AI cannot see your data” | It sees everything that was not masked. | Say “names, numbers and secrets are hidden before sending”. |
Forgetting alsoMask |
Names are not found by patterns. | List the names your app knows. |
| Expecting Masked AI to be sealed | It is not. | For a chat nobody can read, use Sealed AI. |
| Sending a Sealed AI failure to Masked AI | The user was promised sealed. | Show the error. |
| Putting a secret in a prompt on purpose and hoping to mask it | Patterns miss things. | Keep secrets out of prompts. |
See also: API reference, errors.