Secret Vault
The secret vault is Foir’s built-in store for plaintext secrets that your project’s apps need at runtime — third-party API keys, signing certificates, push notification credentials, OAuth client secrets. Secrets are stored encrypted, addressed by an opaque reference, and accessed through scoped API calls that record an audit trail of every read.
When to use the vault
If you’re already using Foir as your data and content layer, the vault is the natural home for any secret your apps need. It sits alongside the rest of the platform — same project boundary, same console UI, same CLI, same audit surface — so secrets are managed in the same place as the records and operations they support, rather than in a separate service you have to wire up and pay for.
The vault is not trying to be a general-purpose enterprise secret store. It doesn’t replace AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault for organisations that need cross-cloud federation, dynamic secret generation, PKI / certificate issuance, KMS integration, or database credential leasing. Those are real features Foir doesn’t ship. But for the typical case — “my Foir-integrated app needs to call a third-party API at runtime and I’d rather not run a separate secret service for it” — the vault is the right answer.
The one secret that has to live outside the vault is the API key your app uses to call Foir in the first place — that’s a chicken-and-egg situation, and it lives in your deployment platform’s env-var system (wrangler secrets, Vercel env vars, Railway variables, etc.).
A simple rule of thumb:
| Secret shape | Right home |
|---|---|
| The API key your app uses to talk to Foir | env vars / wrangler / deploy platform |
| Any other runtime secret your Foir-integrated app needs | Foir vault |
| Secrets for workloads that aren’t on Foir at all | external (AWS Secrets Manager, Vault Cloud, etc.) |
What’s stored
Each secret in the vault is keyed by:
- Owner kind —
project(project-wide secret) orapp(scoped to a specific app installation) - Owner ID — the app name when the owner kind is
app; empty for project secrets - Label — a human-readable handle you choose (e.g.
apns_p8_prod,deepl_api_key)
Together these uniquely identify the secret within a project. Reads return the plaintext bytes. The vault never exposes plaintext through normal record reads — it’s only available through the dedicated getSecret field, gated by an explicit scope.
Reading secrets
Two callers can read secrets through Foir’s public API:
Direct: admin keys
A machine of your own (an integration, or your back-office tooling) that holds an admin key with the secrets:read scope can call getSecret. Your app’s own logic reads secrets from an operation instead, with the dispatch token (below):
query {
getSecret(ref: "sec_abc123...", purpose: "deepl_translation") {
plaintextBase64
label
lastWrittenAt
}
}The ref is the opaque handle returned when the secret was created. The purpose is required and recorded in the audit trail — describe why the secret is being read (e.g. "deepl_translation", "apns_jwt_mint", "shopify_admin_api_call"). plaintextBase64 is the secret’s bytes encoded with standard base64; decode in the receiving language.
secrets:read is restricted to admin keys — a publishable key cannot hold the scope, because it is designed to ship in browser bundles where plaintext exposure would be unsafe, and a server key holds only what an app’s key may.
The same read through the data client, where the vault is the secrets namespace and each operation is named after its GraphQL field:
const secret = await foir.ns.secrets.getSecret({
ref: 'sec_abc123...',
purpose: 'deepl_translation',
});Note: The namespace is on your client only if your key holds the matching
secrets:*scope, so it is absent from types generated with a publishable key. Namespace results come back verbatim;includeandomitdo not apply.
Operations: dispatched receivers
When Foir dispatches an operation to your endpoint, the request carries a scoped token (X-Foir-Token) with the grants the operation declares and nothing else. An operation that reads a secret declares the read, and which one depends on who owns the operation:
- A project’s own operation, one no app or config owns, declares
secrets:readand reads the project’s secrets. Writing them stays an admin key’s. - An operation an app or a config owns declares
appsecrets:readand reads its owner’s own credentials, never the project’s.
An operation that declares neither reads no secret. Whoever writes the grant onto the operation must hold it themselves.
The receiver calls the same getSecret field, authenticated with the dispatch token instead of an API key:
// inside an operation handler
const ref = lookupSecretRefForThisDispatch(); // your code
const resp = await fetch(`${FOIR_API_URL}/graphql`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Foir-Token': dispatchToken, // received with the operation
},
body: JSON.stringify({
query: `query($ref: String!, $purpose: String!) {
getSecret(ref: $ref, purpose: $purpose) {
plaintextBase64
}
}`,
variables: { ref, purpose: 'apns_jwt_mint' },
}),
});The dispatch token is bound to the project the operation was triggered for. The vault enforces this: a token bound to one project cannot read another project’s secrets, so multi-tenant apps that serve many Foir projects automatically read the right tenant’s secrets without extra plumbing.
Storing secrets
From the console
The fastest way for one-off secrets is Settings > Secrets in the console. Production secrets are typically managed here — users paste plaintext directly, and the vault handles encryption.
From the CLI
For repeatable workflows, use foir secrets:
foir secrets put --label deepl_api_key --value "$DEEPL_KEY"
foir secrets put --app shopify-app --label apns_p8_prod --file ./secrets/apns-prod.p8
foir secrets list
foir secrets rotate <ref> --file ./secrets/apns-prod-new.p8
foir secrets delete <ref>Config-as-code: foir.secrets.ts
Apps with several secrets can declare them in a committed config and reconcile them per-environment. The shape (no plaintext) lives in foir.secrets.ts:
import { defineSecrets } from '@foir/cli/configs';
export default defineSecrets({
secrets: [
{ ownerKind: 'project', label: 'deepl_api_key' },
{ ownerKind: 'app', ownerId: 'shopify-app', label: 'apns_p8_dev' },
{ ownerKind: 'app', ownerId: 'shopify-app', label: 'apns_p8_prod' },
{ ownerKind: 'app', ownerId: 'shopify-app', label: 'fcm_sa_prod' },
],
});Plaintext for development lives in a sibling file kept out of source control:
// local.foir.secrets.ts (gitignored)
import { readFileSync } from 'node:fs';
export default {
deepl_api_key: process.env.DEEPL_API_KEY!,
apns_p8_dev: readFileSync('./secrets/apns-dev.p8'),
apns_p8_prod: readFileSync('./secrets/apns-prod.p8'),
fcm_sa_prod: readFileSync('./secrets/fcm-sa-prod.json', 'utf-8'),
};Run the reconciler against the project the CLI is currently scoped to:
foir secrets push # create missing, leave existing alone
foir secrets push --rotate # rotate plaintext on every declared secret
foir secrets push --dry-run # preview without writingProduction secrets are not pushed via CLI in normal workflows — users set them through the console so plaintext never lives in any developer’s working tree. The reconciler is a dev-loop convenience.
From a machine of your own: admin keys
A machine of your own (an integration, or your back-office tooling) that holds an admin key can store secrets directly, without the console or CLI. This is the write counterpart to getSecret, and it’s how an integration stashes a secret it receives at runtime (for example, the credential another system issues it when the connection is made) so that only an opaque reference is ever persisted in your records. An admin key is never your app’s credential; see App architecture.
Storing a secret requires the secrets:put scope:
mutation {
putSecret(
plaintextBase64: "c2stbGl2ZS1hYmMxMjM..." # base64 of the plaintext
label: "acme_connection_key" # optional
) {
ref
}
}The same write through the data client:
const { ref } = await foir.ns.secrets.putSecret({
plaintextBase64: 'c2stbGl2ZS1hYmMxMjM...',
label: 'acme_connection_key',
});putSecret returns the opaque ref — store that on your record (never the plaintext) and resolve it back with getSecret when you need the value. Encode the plaintext with standard base64 before sending, so binary secrets survive the round trip unchanged. An optional expiresAt (an RFC 3339 timestamp) sets a TTL.
Secrets stored this way are always project-owned — the API-key path can’t create app- or user-owned secrets (those are managed by users and Foir’s auth flows). Like secrets:read, the write and delete scopes are restricted to admin keys; neither a publishable nor a server key can hold them.
From an operation, for the user it acts for
When a user connects a third-party account in your app, pasting an API key or finishing a vendor’s OAuth, the credential belongs in the vault with only its reference on the user’s records. Your app does this in an operation, with no server of its own: an operation a signed-in user triggers acts for that user, and can store a secret that user owns.
Declare the grants on the operation:
defineOperation({
key: 'connect_vendor',
grants: [
'usersecrets:put',
'usersecrets:read',
'records:create:vendor_connection',
'records:write:vendor_connection',
'records:read:vendor_connection',
],
// ...
});Then call putSecret from the endpoint with the dispatch client, exactly as an admin key would:
const { dispatch } = await requireScopedToken(request, { expectedProjectId: process.env.FOIR_PROJECT_ID });
const { input } = await readDispatch<{ vendorKey: string }>(request);
const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, dispatch, generated });
const { ref } = await foir.ns.secrets.putSecret({
plaintextBase64: btoa(input.vendorKey),
label: 'vendor_api_key',
});
// store `ref` on the user's vendor_connection recordThe secret is owned by the user the operation acts for, never by the project, and nobody chooses otherwise: the owner comes from the operation’s token. It follows these rules:
- Only that user’s operations reach it. An operation acting for another user cannot read, rotate or delete it.
- Each verb needs its grant.
usersecrets:putcovers storing, rotating and restoring,usersecrets:readreading back withgetSecret, andusersecrets:deletedeleting. An operation’s schema is built from what it declared, so one that did not declare a grant has no field for that verb at all: withoutusersecrets:put,putSecretis not in its schema. - A run that acts for no user reaches none. For example, an operation triggered by a schedule is refused, saying so.
- Enumerating the vault stays an admin key’s.
listSecretsis not reachable from an operation.
Rotation
foir secrets rotate <ref> (or foir secrets push --rotate) stores the new value under a new ref, moves every record field that held the old ref to it in the same transaction, and soft-deletes the old ref. The CLI prints both. A reader that finds the ref on a record keeps working without a deploy. Anything that holds the ref itself, in code, an environment variable or a config, must take the new one, because the old ref stops resolving.
There is a public mutation for the same thing, for an app rotating a credential it manages:
mutation {
rotateSecret(ref: "sec_abc123...", plaintextBase64: "dGhlLW5ldy1wbGFpbnRleHQ=") {
newRef
}
}Through the data client:
const { newRef } = await foir.ns.secrets.rotateSecret({
ref: 'sec_abc123...',
plaintextBase64: Buffer.from('the-new-plaintext').toString('base64'),
});The new value goes over the wire base64-encoded, like every other secret write: the argument is plaintextBase64, not a raw string. An optional expiresAt sets an expiry on the rotated value. Keep the returned newRef: it is the secret’s ref from now on.
Rotations are audited every time, with no sampling.
Deleting secrets
Users delete secrets from the console or with foir secrets delete <ref>. An external app can delete the project secrets it manages over the public API with the secrets:delete scope — useful when a user disconnects a third-party account:
mutation {
deleteSecret(ref: "sec_abc123...")
}Through the data client:
await foir.ns.secrets.deleteSecret({ ref: 'sec_abc123...' });Deletion is a soft delete: the secret stops resolving immediately but is recoverable for a grace period before it’s permanently purged. If a record still references the ref, deletion follows that field’s configured behaviour — it’s either blocked until you clear the reference, or it cascades and clears the field for you.
Finding and restoring a soft-deleted secret
The grace period is only useful if you can find the ref again, and a soft-deleted secret is hidden from an ordinary listing. listSecrets(includeSoftDeleted: true) is how you get it back. It needs the secrets:list scope on an admin key, and returns a paged connection:
{
listSecrets(includeSoftDeleted: true, first: 50) {
edges {
node {
ref
label
softDeletedAt
purgeAfter
}
}
pageInfo {
hasNextPage
endCursor
}
}
}Through the data client:
const page = (await foir.ns.secrets.listSecrets({ includeSoftDeleted: true, first: 50 })) as {
edges: Array<{ node: { ref: string; label: string | null; softDeletedAt: string | null; purgeAfter: string | null } }>;
pageInfo: { hasNextPage: boolean; endCursor: string | null };
};
const secrets = page.edges.map((edge) => edge.node);softDeletedAt is set while a secret is awaiting purge and null otherwise, so it is also how you tell which entries in that list are the deleted ones. Then:
mutation {
restoreSecret(ref: "sec_abc123...")
}Through the data client:
await foir.ns.secrets.restoreSecret({ ref: 'sec_abc123...' });listSecrets returns metadata only — never plaintext, and it takes no purpose argument, because nothing is being read. Reading the value is always getSecret.
Audit
Not every read writes an audit row, and the difference matters if you are reconciling against one.
A getSecret call — the explicit read, over the API — is audited every time. The in-process resolver, which is what resolves a secret for an operation at dispatch, samples at one percent. A full row per read would turn a high-traffic resolver into one audit write per read, so what the sampled rows give you is a representative access trail, not a complete one. lastReadAt is still bumped on every resolve, so “when was this last used” is exact even where “who used it, 200 reads ago” is not.
An audited read records:
- Who called (the API key, dispatch token, or console user)
- The
purposestring the caller supplied - When the read happened
Reads from API keys and operation receivers are distinguishable from reads in the console, and from each other. Writes (stores, rotations and deletes) are recorded every time, with no sampling, so the lifecycle of a secret is complete even where its read trail is a sample.
Choosing labels
Labels are the part you’ll touch most. A few rules of thumb:
- Stable. Labels live in your
foir.secrets.tsand in your consumer code; treat them like enum values, not user-editable strings. - Self-describing.
apns_p8_prodreads better thansecret1six months later. - Encode the variant. If the same secret kind exists per environment or per build target, encode that in the label (
apns_p8_dev/apns_p8_prod) so consumers can resolve the right one from the dispatch payload.
What’s not in the vault
- User-facing OAuth tokens managed by Foir’s user auth flows — those are handled separately by Foir on behalf of authenticated users and don’t appear in the vault.
- Bootstrap secrets like the API key your app uses to talk to Foir in the first place — those have to live in your deployment platform’s env-var system to break the chicken-and-egg problem.
- Per-record encrypted fields. If you want some fields of a record to be encrypted at rest, that’s a record-level concern, not a vault one.