API reference
This content is not available in your language yet.
One entry point per mode. There is no root import. Install: npm install @geometer/trust. Until the package is published, your Geometer contact gives you the install command.
| Entry point | Runs in | Mode |
|---|---|---|
@geometer/trust/vault |
browser | Vault |
@geometer/trust/sealed-ai |
browser | Sealed AI |
@geometer/trust/sealed-ai/server |
your server route | Sealed AI |
@geometer/trust/masked-ai |
browser | Masked AI |
@geometer/trust/masked-ai/server |
your server route | Masked AI |
@geometer/trust/proof |
browser | all |
@geometer/trust/react |
browser (needs react) |
all |
What each entry point exports (names only; details below):
| Entry point | Exports |
|---|---|
vault |
openVault, recoverVault, startOverVault, acceptStartOverVault, supabaseKeyStore, firebaseKeyStore, memoryKeyStore, browserKeyStore, sanitizePasskeyOptions, sanitizePasskeyResponse, newId, TrustError, findTrustError; types Vault, OpenVaultOptions, RecoverVaultOptions, StartOverVaultOptions, AcceptStartOverVaultOptions, RecoveryCodeInfo, RecoveryCodeHandler, RecoveryCodeReason, ReceiptOptions, UnlockMethodInfo, KeyList, KeyStore, SupabaseLike, FirestoreFunctions, FirestoreCompatLike |
sealed-ai |
sealedFetch, prewarmSealedAI, MIN_RELEASE, RELEASE_REPO, TrustError, findTrustError; types SealedFetchOptions, PrewarmOptions, PrewarmResult, EvidenceReport, EvidenceChecker, EvidenceCheckInput, EvidenceResult, EvidenceCheckLine |
sealed-ai/server |
sealedRoute, toNodeHandler, TrustError, findTrustError |
masked-ai |
maskedFetch, TrustError, findTrustError; types MaskedFetchOptions, MaskedSummary |
masked-ai/server |
maskedRoute, toNodeHandler, TrustError, findTrustError |
proof |
listReceipts, exportReceipts, deleteReceipts, writeReceipt, readReceipt, encodeReceipt, blobDigest, createIndexedDbReceiptStore, createMemoryReceiptStore, CHECK_IDS, NOT_CHECKED_SENTENCES, RECEIPT_BODY_TYPE, RECEIPT_LEDGER, STATEMENTS, requiredNotChecked, TrustError, findTrustError, and the receipt types |
react |
TrustBadge, HOW_TO_CHECK; types TrustBadgeProps, BadgeLedger |
Apps rarely need writeReceipt, readReceipt, encodeReceipt and blobDigest: the modes call them.
Vault: @geometer/trust/vault
Section titled “Vault: @geometer/trust/vault”openVault(options): Promise<Vault>
Section titled “openVault(options): Promise<Vault>”| Option | Type | Meaning |
|---|---|---|
app |
string | Your app’s name. Keys are bound to it. Never change it later. |
user |
string | Your user’s stable id, for example the Supabase auth user id. |
keyStore |
KeyStore |
Where the user’s locked key file is kept (your own database). |
unlock |
"passkey", { passphrase } or { passkey: true, fallbackPassphrase: () => Promise<string> } |
How the user unlocks. Optional: a passkey is used when the key file has one. The last form tries the passkey and asks for a passphrase only on vault/passkey-unsupported (no WebAuthn or PRF, a preview frame), never on a cancel. Also accepted by startOverVault, acceptStartOverVault and resolveKeyFileBehind. |
rememberDevice |
{ days } |
Optional, off by default: remember this device for days (a whole number, 1 to 90). Also on recoverVault and acceptStartOverVault. The remembered Vault reads and writes values but cannot change keys. See Vault. |
skipRemembered |
boolean | openVault only. true ignores a remembered device and asks for the real unlock (after a remembered Vault threw vault/unlock-needed). |
onRecoveryCode |
({ code, replacesPrevious, reason }) => void |
Shows the recovery code. Required at first setup. reason is "setup", "recovery", "requested", "rotation" or "unconfirmed", so you can choose your words. After a rotation the old code has already stopped (replacesPrevious is false): say so. |
receiptStore, onReceipt, onReceiptError |
Where Vault key-event receipts are kept, and who hears of them or of a failure to write one. A failing receipt never blocks the Vault. | |
dangerouslyAllowKeyFileOverwrite |
boolean | Development only: allows a key store without create. |
recoveryKit({ code, app, user, appName? }): { text, filename, blob }
Section titled “recoveryKit({ code, app, user, appName? }): { text, filename, blob }”A plain-text Recovery Kit for the user to download or print: the code in 8 groups, what it is, where to keep it, that the app never asks for it by message, and the date. No network, never logs the code. A bad code is vault/bad-input.
recoverVault(options): Promise<Vault>
Section titled “recoverVault(options): Promise<Vault>”Options: app, user, keyStore, recoveryCode, onRecoveryCode (required: recovery makes a new code at once). After it returns, call vault.addPasskey() or vault.setPassphrase(p).
acceptStartOverVault(options): Promise<Vault>
Section titled “acceptStartOverVault(options): Promise<Vault>”Only when the user says they started over on another device, and this device opened a different Vault for this user before (vault/key-file-replaced). Options: app, user, keyStore, unlock? or recoveryCode?, and onRecoveryCode (needed with a recovery code). It opens the new Vault only if the user’s own secrets open it; the old one is then left behind on this device, and this device treats the new Vault as unverified until it sees a newer key file (see vault/key-file-behind). Anywhere else it fails with vault/bad-input.
startOverVault(options): Promise<Vault>
Section titled “startOverVault(options): Promise<Vault>”For a user who truly lost the Vault and wants a new, empty one. Old values will not open. It is a separate call on purpose: never call it automatically, or because an error happened. Options: app, user, keyStore, unlock?, onRecoveryCode and archive(oldKeyFile). archive is required and must finish before the old key file is replaced: save the old file somewhere safe, because if the user later finds the old recovery code, that file and code still open the old values. The returned Vault has replacedKeyFile.
forgetDevice({ app, user }): Promise<boolean>
Section titled “forgetDevice({ app, user }): Promise<boolean>”Static, from @geometer/trust/vault. Forgets “remember this device” for that user with no open Vault, for your sign-out handler (also after a page reload). Wait for it. Resolves true when the remembered keys are gone (or never were), false when the browser could not delete them (they still end at their expiry). Throws vault/bad-input for an empty app or user.
ref below is { table, id, field }: the table (or collection), the row id and the column. Use the same three when you decrypt.
| Method | Returns | Meaning |
|---|---|---|
encrypt(text, ref) |
Promise<string> |
A plain string for any text column. |
decrypt(stored, ref) |
Promise<string> |
Needs the same table, id and field. |
encryptJSON(value, ref) |
Promise<string> |
Same, for any JSON value. |
decryptJSON(stored, ref) |
Promise<unknown> |
|
needsReencrypt(stored) |
boolean |
True when the value was saved under an older key. |
reencrypt(stored, ref) |
Promise<string> |
Saves it again under the current key. |
searchKey(value, { table, field }) |
Promise<string> |
Same input gives the same output. Store it in a plain column for exact-match lookups. |
searchKeys(value, { table, field }) |
Promise<string[]> |
The same, for every key still in use (after a rotation). |
addPasskey({ name? }) |
Promise<void> |
Adds a passkey. |
setPassphrase(p) |
Promise<void> |
Sets a passphrase (at least 15 characters). |
removePasskey(slotId), removePassphrase() |
Promise<void> |
Remove an unlock method. The last one cannot go. |
listUnlockMethods() |
UnlockMethodInfo[] |
The unlock methods. |
newRecoveryCode() |
Promise<void> |
Makes a new recovery code; the handler shows it. |
rotateKey({ newPassphrase? }) |
Promise<void> |
Starts a new key and a new recovery code (the old code stops at once). Needs onRecoveryCode. Never blocked: from 8 old keys on previousKeyWarning is true; above 32 the oldest keys are retired automatically. |
resolveKeyFileBehind({ unlock?, confirm }) |
Promise<boolean> |
The way out of vault/key-file-behind: the user re-unlocks with their own secret, then confirm() (ask the user whether they checked the key file) must return true. Returns false if it did not. |
retireKey(kid) |
Promise<void> |
Stops accepting an old key. Re-encrypt first. |
listKeys() |
KeyList |
The current, previous and retired key ids. |
lock({ forget? }) |
void |
Forgets the key in memory; forget: true also forgets this device. |
addUnlock({ passkey: true, fallbackPassphrase, name? }) |
Promise<"passkey" | "passphrase"> |
Adds a passkey, or sets a passphrase where passkeys cannot work (the follow-up after recoverVault). |
forgetDevice() |
Promise<void> |
Ends “remember this device”. |
rememberedUntil |
Date | null |
When this device stops opening without a prompt. |
rememberedSession |
boolean |
True when this Vault was opened from the remembered device. It does encrypt, decrypt, encryptJSON, decryptJSON, reencrypt, searchKey(s); addPasskey, addUnlock, setPassphrase, removePasskey, removePassphrase, newRecoveryCode, rotateKey and retireKey throw vault/unlock-needed. |
deviceHistoryNotUpdated |
boolean |
True when a change was saved but this device’s history note could not be updated (“saved; device history not updated”). The change worked. |
newId() |
string |
A new random id (crypto.randomUUID()). Make the row id with it before you encrypt, because the id is bound into the encryption. A database default such as gen_random_uuid() comes too late. |
recoveryCodePending |
boolean |
True while a new code was made and the user has not confirmed it. |
previousKeyWarning |
boolean |
True from 8 previous keys on: re-encrypt old values and retire old keys. |
replacedKeyFile |
string or null |
After startOverVault: the key file it replaced. |
sanitizePasskeyOptions(options) and sanitizePasskeyResponse(json) are for apps that also sign users in with passkeys: they remove the PRF part (and the raw hmacCreateSecret and hmacGetSecret inputs) so Vault’s secret never reaches your server.
KeyStore
Section titled “KeyStore”type KeyStore = { load(): Promise<string | null>; // null only for a confirmed absence; throws on any error create?(keyFile: string): Promise<boolean>; // insert only: false if a key file already exists. A store without it is refused at first setup unless dangerouslyAllowKeyFileOverwrite replace?(previous: string, next: string): Promise<boolean>; // compare-and-swap save?(keyFile: string): Promise<void>; // unconditional write};| Helper | Use |
|---|---|
supabaseKeyStore(supabase, { app, user, table = "trust_keys" }) |
Supabase table with row-level security. Columns: app text, user_id uuid (references auth.users), key_file text not null, updated_at timestamptz. Primary key (app, user_id). |
firebaseKeyStore(firestore, { app, user, collection = "trustKeys", functions }) |
One Firestore document per user and app: id <user>__<encodeURIComponent(app)>, field keyFile. With the modular API pass functions: { doc, getDoc, setDoc, runTransaction } from firebase/firestore; without runTransaction, first setup is refused. The older compat Firestore needs no functions. |
memoryKeyStore() |
Tests. Lost when the page closes. |
browserKeyStore() |
localStorage. Development only. |
Sealed AI: @geometer/trust/sealed-ai
Section titled “Sealed AI: @geometer/trust/sealed-ai”new OpenAI({ baseURL: `${window.location.origin}/api/trust/sealed-ai/v1`, apiKey: "not-used", dangerouslyAllowBrowser: true, maxRetries: 0, fetch: sealedFetch({ onReceipt }),});sealedFetch(options?) returns a fetch for the openai client (chat completions and responses). It checks the server, seals the request and opens the answer. If it cannot check the server, the call fails.
| Option | Meaning |
|---|---|
expectedMeasurement? |
Advanced: pin the code measurement (96 hex characters). Must agree with the release if both are used. |
release?: false |
Turn the release check off. Only with expectedMeasurement; otherwise sealed-ai/no-expected-measurement. |
minRelease? |
Raise the oldest provider release you accept (a tag such as "v0.0.185"). Can only raise the SDK’s floor. |
onEvidence?(report) |
After each successful check: the result, the documents, the release and the time. |
keyLifetimeMs? |
How long a verified key is trusted. Default 5 minutes. |
onReceipt?, onReceiptError?, app?, user?, receiptStore? |
Receipts. See Proof below. |
fetch? |
A custom fetch for your route (custom runtimes). The evidence is self-authenticating, so it cannot fake a pass. There is no option to replace the checker or the clock: sealedFetch refuses unknown options. |
MIN_RELEASE is the SDK’s floor. RELEASE_REPO is the provider repository whose releases it trusts.
prewarmSealedAI(options)
Section titled “prewarmSealedAI(options)”prewarmSealedAI({ baseURL, provider?, headers?, credentials?, fetch?, signal?, evidenceTimeoutMs? }): Promise<{ ok: boolean; code?: string }>Runs the Sealed AI check in the background and fills the verified-key cache that sealedFetch reads, so the first message needs no evidence calls. Call it when the chat page or component mounts. It never throws, never sends a chat, and calls at the same moment share one check. baseURL is the client’s baseURL (it must contain /sealed-ai/). provider ("tinfoil" or "geometer") makes the pre-warm fail with sealed-ai/not-verified if the route talks to the other one. headers carry the sign-in the route’s authorize expects. On failure code is the sealed-ai/... code (not-verified, service-busy, upstream-timeout, release-too-old, bad-option, not-via-route, key-in-browser); the first message repeats the check. It warms the default settings only. What it keeps on the device: see Sealed AI.
@geometer/trust/sealed-ai/server
Section titled “@geometer/trust/sealed-ai/server”sealedRoute({ provider: "tinfoil", apiKey, authorize, limits?, allowedOrigins?, baseURL?, maxBodyBytes?, fetch? }): (request: Request) => Promise<Response>Mount at /api/trust/sealed-ai/* (or any path that contains /sealed-ai/, such as a Supabase Edge Function named sealed-ai). It forwards the evidence calls, the AMD certificate calls, the signed release records and sealed bodies only. It refuses a plain body (sealed-ai/plain-body). maxBodyBytes defaults to 4 MB.
Masked AI: @geometer/trust/masked-ai
Section titled “Masked AI: @geometer/trust/masked-ai”// OpenAInew OpenAI({ baseURL: `${window.location.origin}/api/trust/masked-ai/v1`, apiKey: "not-used", dangerouslyAllowBrowser: true, maxRetries: 0, fetch: maskedFetch({ alsoMask, neverMask, onMasked, onRestored, placeholderHint, onReceipt }),});
// Anthropicnew Anthropic({ baseURL: `${window.location.origin}/api/trust/masked-ai`, apiKey: "not-used", dangerouslyAllowBrowser: true, maxRetries: 0, fetch: maskedFetch(),});Option of maskedFetch |
Meaning |
|---|---|
alsoMask?: string[] |
Names and words your app knows (customer names, company names). |
neverMask?: string[] |
Words to leave as they are. |
onMasked?(summary) |
Gets { counts } by type (EMAIL, PHONE, NAME and so on), never values. |
onRestored?(summary) |
Called once per answer (after a stream ends) to a request that masked something. Gets { unrestored }: how many placeholder-shaped tokens could not be put back (counts only). Show a warning when it is above 0. |
placeholderHint?: boolean |
Default true. Adds one short instruction to the system prompt asking the model to copy placeholders exactly. It reveals nothing; set false to turn it off. |
onReceipt?, onReceiptError?, app?, user?, receiptStore? |
Receipts. See Proof below. |
Detected by default: emails, phone numbers (including Indian), card numbers (checksum), Aadhaar (checksum) and PAN formats, API keys and tokens, IBAN.
@geometer/trust/masked-ai/server
Section titled “@geometer/trust/masked-ai/server”maskedRoute({ provider: "openai" | "anthropic" | "gemini" | "openai-compatible", apiKey, authorize, limits?, allowedOrigins?, baseURL?, maxBodyBytes?, fetch? }): (request: Request) => Promise<Response>Mount at /api/trust/masked-ai/* (or any path that contains /masked-ai/, such as a Supabase Edge Function named masked-ai). baseURL is required for "openai-compatible", written as the provider documents it, with its /v1. maxBodyBytes defaults to 2 MB. provider: "gemini" is the Google native API (generateContent, streamGenerateContent; the key goes in x-goog-api-key) for the @google/genai client.
Both routes need authorize
Section titled “Both routes need authorize”authorize(request) => boolean | { user: string } | Promise<boolean | { user: string }> is required. It decides who may spend your AI key: without it, anyone who finds the route could use your account. It runs before any body is read (after the origin check), and receives a copy of the request without its body. Return true to let the caller in, { user: "<id>" } to let them in and name them (for limits.perUser), or false to refuse. An empty user is a refusal. Check your own sign-in there (for example the Supabase access token, which the browser sends as the client’s apiKey, or your Next.js session). The route answers 401 with <mode>/not-authorized when it returns false or throws. A route made without it throws <mode>/no-authorize at setup. To let everyone in on purpose (not recommended), pass authorize: () => true.
Each route forwards only the headers it needs and drops the incoming Authorization, x-api-key and Cookie before it adds your provider key. It calls a fixed list of paths, follows no redirects and logs nothing.
Both routes answer with the header x-geometer-trust-adapter, naming the provider and host.
limits: rate limits and spending caps (both routes)
Section titled “limits: rate limits and spending caps (both routes)”limits?: { perUser?: { requestsPerMinute?: number; requestsPerDay?: number }; perRoute?: { requestsPerMinute?: number }; maxOutputTokens?: number; // Masked AI only; refused on sealedRoute (encrypted bodies) key?: (request: Request) => string | Promise<string>; // the user id, when authorize returns plain true store?: LimitStore; // default memoryLimitStore(): in this process's memory}interface LimitStore { increment(key: string, windowMs: number): { count: number; resetInMs: number } | Promise<{ count: number; resetInMs: number }>;}Fixed windows. Over a limit: 429 <mode>/rate-limited with Retry-After in seconds and the body { error: { code, message: "Too many requests. Please wait a minute.", type } }. A store that throws gives 503 <mode>/service-busy. perUser without a way to find the user gives 500 <mode>/limits-no-user. memoryLimitStore() and the LimitStore and RouteLimits types are exported from both server entry points. How to write a Redis store: Masked AI.
allowedOrigins (both routes)
Section titled “allowedOrigins (both routes)”allowedOrigins?: string[]: full origins (for example "https://app.example.com") of other sites that may call the route from a browser. Default none: the route answers its own site only (Sec-Fetch-Site when the browser sends it, else Origin against the request’s host); a request from another site answers 403 <mode>/cross-origin. Requests with neither header pass to authorize. For a listed origin the route answers the preflight (204) and adds Access-Control-Allow-Origin for that origin only, with credentials allowed.
Server helpers work with
Section titled “Server helpers work with”Both server helpers are standard Fetch handlers: Next.js App Router, Supabase Edge Functions (Deno, npm: specifiers), Vercel, Netlify, Cloudflare, Hono and Bun. For Express and plain Node, wrap the handler with toNodeHandler(handler), imported from the same server entry point. Mount it before express.json(); a body that was already read is handled.
Proof: @geometer/trust/proof
Section titled “Proof: @geometer/trust/proof”| Function | Returns |
|---|---|
listReceipts(options?) |
Promise<Receipt[]>, oldest first. Throws proof/ledger-damaged if an entry was changed. |
exportReceipts({ withOpenings?, ...options }) |
Promise<string>: the receipt file (one JSON string: the pack, the anchor and the public bytes receipts cite). withOpenings adds the salts, for trust-verify receipts --openings. After deleteReceipts the file starts mid-chain (base_prev) and verifies as before. |
deleteReceipts({ before?, keepLast?, ...options }) |
Promise<{ deleted, kept }>. Deletes old receipts from the start of the ledger (those written before the Date, or all but the newest keepLast; either or both). The newest receipt is never deleted; proof/bad-argument for no option, keepLast below 1 or a bad date. Irreversible; export first to keep them. |
createIndexedDbReceiptStore(), createMemoryReceiptStore() |
Where receipts are kept. The default is IndexedDB in a browser, memory elsewhere. |
options are { app?, user?, receiptStore? }. Use the same app and user that you gave sealedFetch or maskedFetch; they name the ledger.
Receipt.mode is "vault", "sealed-ai" or "masked-ai". A receipt holds fingerprints, never chat text. trust-verify receipts FILE checks the whole receipt file. trust-verify unpack FILE --out DIR writes pack.json and anchor.json, which the public geo-verify checks. See proof and the badge.
React: @geometer/trust/react
Section titled “React: @geometer/trust/react”<TrustBadge receipt={receipt} ledger? onExport? defaultOpen? />: fixed words for each mode and a panel with what was and was not checked. The badge itself is not proof. react is an optional peer dependency.
Errors
Section titled “Errors”TrustError { mode, code: "<mode>/<kebab-case>", message }findTrustError(err): TrustError | undefinedEvery entry point exports TrustError and findTrustError, for example import { findTrustError } from "@geometer/trust/masked-ai". The openai and @anthropic-ai/sdk clients wrap an error from a custom fetch (they report “Connection error.” and keep ours in .cause) and retry it. So create the client with maxRetries: 0 and read errors with findTrustError(err), never instanceof.
Every message ends with the next step. See errors.