The App Client
@foir/sdk/app is what a marketplace app calls Foir with. It is for a service that is installed in many projects and learns, per request, which project it is working for.
Writing an Operation Endpoint covers the other case: an endpoint that belongs to one project and has a generated client for it. An installed app has no project of its own to generate from. Each install maps the app’s sources onto whichever models the person installing it chose, so the app reads those model keys from the install at request time and names them in each call.
Foir’s own Shopify integration is built on exactly what is on this page, from the published package, with no private door.
npm install @foir/sdkOne request, start to finish
import { createAppClient, readAppDispatch } from '@foir/sdk/app';
import { createScopedTokenVerifier, requireScopedToken, ScopedTokenError } from '@foir/sdk/server';
// One verifier for the life of the process. It keeps the platform's signing
// keys and refreshes them, so a dispatch does not wait on a key fetch.
const verifier = createScopedTokenVerifier({ jwksUrl: process.env.FOIR_JWKS_URL! });
export async function POST(request: Request) {
let caller;
try {
caller = await requireScopedToken(request, { verifier });
} catch (error) {
if (error instanceof ScopedTokenError) return new Response(error.message, { status: error.status });
throw error;
}
const { input } = readAppDispatch(await request.json());
const foir = createAppClient({ apiUrl: process.env.FOIR_API_URL!, dispatch: caller.dispatch });
// Which model did this install map `product` onto?
const config = await foir.install.config();
const products = config.sources.find((source) => source.key === 'product');
if (!products) return Response.json({ success: true, result: { written: 0 } });
const credentials = await foir.install.credentials();
const items = await readFromYourVendor(credentials, input);
for (const item of items) {
await foir.records.upsert({
model: products.model,
naturalKey: item.handle,
data: item.fields,
sourceModifiedAt: item.updatedAt,
});
}
return Response.json({ success: true, result: { written: items.length } });
}caller says who the platform dispatched for. caller.subject holds tenantId, projectId and appName. caller.orgId is the level the install lives at: one organisation’s id, the empty string for the project itself, or null when the token states no level, which is a token you cannot place and should refuse. caller.userId is there when the run is for a user, and caller.expiresAt is when the token stops working. Those are the platform’s statement, verified. Use them to scope anything you hold yourself: an app installed at two organisations of one project is dispatched once for each.
A ScopedTokenError carries the status to answer with. 503 means the signing keys could not be fetched, which is your service’s outage and one the platform retries. It is not a verdict on the token, so do not answer it as a 401.
Nothing is checked before a call
The client does not read the token. What an operation may do is whatever its manifest declared and the person installing it approved, and the platform holds every call to that. A call the token cannot make is refused by the platform, and the refusal is the error you catch: a FoirRequestError carrying the platform’s answer.
That is deliberate. A check in your own code is a copy of the platform’s rule, and the copy is wrong the day the rule changes.
Three refusals are ones an app acts on rather than reports, and each has a reader that answers with data, never by matching a message:
import {
appUserEmailUnavailableOf,
appUserUnlinkedOf,
appLookupConflictOf,
isAppFieldWithheld,
} from '@foir/sdk/app';
try {
await foir.records.upsert({ model, naturalKey: item.handle, data: item.fields });
} catch (error) {
// Another record already holds this object's id under an older key: the
// vendor let its user change the value the record is keyed on. Move it.
const conflict = appLookupConflictOf(error);
if (conflict) {
await foir.records.rename(model, { externalId: { eq: item.id } }, item.handle);
await foir.records.upsert({ model, naturalKey: item.handle, data: item.fields });
} else {
throw error;
}
}appLookupConflictOf(error)names the lookup a write collided on.appUserUnlinkedOf(error)says a save to a user’s record found nobody holding that identity. Nothing is wrong with the row: the user is known once they sign in.appUserEmailUnavailableOf(error)says the request would have sent a user an email the project cannot send yet, with why. Nothing was written. It is the project’s team who fixes it, so say so rather than retry.install.config()answers the same thing ahead of time, asuserEmailUnavailable.install.config().userSignInis the user sign-in the install pairs with the app, for an app whose own system has users, ornullwhen it pairs none.users.byIdentityandusers.identitiesanswer through that pairing and no other, and are refused without one, so an app that shows its own state says the sign-in is missing rather than that it found nobody.isAppFieldWithheld(error, 'integrationConfig')says a read asked for a field this token is not served, which is how the platform refuses a read. A refused write is refused outright, with its reason in the error.
error.retryable separates a fault worth another attempt (no answer, a 5xx, a 429) from a refusal that will be refused again. The client already makes up to three attempts at the first kind (two retries).
What the client reaches
| Call | Needs the grant |
|---|---|
install.config() | appconfig:read |
install.credentials() | appsecrets:read |
install.writeCredentials(values) | appsecrets:put |
install.reportStatus(status) | status:write |
records.upsert that makes a record | records:create:<model> |
records.upsert that lands on a record, rename, updateMany, refresh | records:write:<model> and records:read:<model> |
records.read, list, aggregate | records:read:<model> |
records.delete | records:delete:<model> and records:read:<model> |
records.user.save, read | the model’s record grants, as for upsert and read, on a source that declares an identity |
records.user.erase | records:delete:<model>, records:read:<model> and identities:delete. The grant to save the record is not enough: an erase removes it |
users.ensure(email) | users:create |
users.get(id), users.byEmail(email) | users:read.named, or users:read.all |
users.byIdentity(identity), users.identities(userId) | identities:read, at an install that pairs a user sign-in. It is declared by name: users:read.all does not include it |
users.list(query) | users:read.all |
organizations.provision | organizations:create, and records:write:<model> for the settings model when it passes settings |
organizations.scheduleDeletion | organizations:delete, in a run that acts in an organization |
notifications.send | notifications:write.named |
notifications.setConsent | notifications:consent, and users:create when it names the user by email |
operations.start | none: a webhook delivery’s token only |
whoami() | none |
request(document, variables) | whatever the document asks for |
Making a record and changing one are two grants, and only making one takes no read. upsert makes the record when there is none at the key, which takes records:create:<model>, and changes the one that is there, which takes records:write:<model> and the read of it. So an operation that declared only the create of a model makes its records and is refused the first time it meets one it made: a second sync, a redelivered webhook, a retry. Declare the create, the write and the read of every model an operation syncs, and the read of every model it deletes or refreshes. An operation that only ever makes records can declare the create alone, and upsert then answers fieldsWithheld: true: the record was made, and the answer carries its id and nothing of it.
organizations.provision makes an organization with a user as its first member, in the role your project names for a founder. Pass settings and it writes the organization’s settings record with it, which takes the write of that model and answers settingsRecordId. Sending the same provisionId again answers the same organization, so it is safe to retry. Sign-up as one operation shows the whole of it.
organizations.scheduleDeletion schedules the deletion of the organization the run acts in, with everything beneath it, and takes no organization. The organization stops being active at once and nothing is removed for 30 days. Letting an organization close itself says who should be allowed to run it.
notifications.setConsent records an opt-in or an opt-out for a user your operation names. Say givenElsewhere: true when you are carrying over a consent the user gave in another system. Leave it out when your app collected the consent itself: the opt-in is then applied the way its category says, and in a category that confirms opt-ins by email the answer is confirmationPending: true and the preference switches on when the user follows the link they are sent. Pass the page’s locale so that email is in the language the user was reading.
Name the user by userId, or by email when the opt-in comes from somebody who may have no user yet, such as a sign-up form. By email, Foir finds the user holding the address at your install’s level, or makes one, together with the change. So a change Foir refuses (a category the project does not have, a confirmation email the project cannot send) leaves no user behind, which finding or making the user yourself with users.ensure first would. The answer is the same whether or not the address already had a user.
whoami() answers what the platform says the token is and may do. It is for an app that has to show that to someone. A call needs no check first.
request runs a document of your own, for a field the client has no method for. A model’s fields on the data API are named from its key: appModelTypeName('order_line') is OrderLine, and appModelFieldName('order_line') is orderLine.
Taking records in turn
records.updateMany changes every record a filter matches. When the work is handed out a few at a time, such as the next ten people waiting for a variant, list them in order and update the ones you were given:
const { records, hasMore } = await foir.records.list(model, {
where: { variantId: { eq: variantId }, toldAt: { isNull: true } },
orderBy: [{ field: 'askedAt' }],
first: 10,
});
await foir.records.updateMany(model, {
where: { id: { in: records.map((record) => record.id) }, toldAt: { isNull: true } },
data: { toldAt: { set: new Date().toISOString() } },
});The platform orders by createdAt, updatedAt, naturalKey and id, and by a field the model indexes. Keep the filter on the update as well as the ids: it is what stops a record being taken twice if two of your runs ever list at once. A concurrency key on the run is what stops them listing at once.
A run that outlives one call
An ASYNC operation answers 202 and reports its outcome later. The dispatch carries everything that takes: the address, a token, the mutation names, and the key this one run signs with.
import { readAppDispatch } from '@foir/sdk/app';
import { createCallbackClient } from '@foir/sdk/server';
const { executionId, callback } = readAppDispatch(body);
if (callback && executionId) {
const run = createCallbackClient(callback, { executionId, apiUrl: process.env.FOIR_API_URL! });
await run.progress({ pct: 40, message: 'Read 400 of 1,000' });
await run.complete({ written: 1000 });
}Your service holds no signing secret. callback.signingKey is made by the platform for the run and sent with it, and the client signs with that. Treat it as a secret: never log it or store it.
For work longer than one call can take, answer with continueRun and the platform queues the next slice with a fresh callback.
Handing a webhook delivery to an operation
When your vendor’s webhook reaches your app through Foir, it arrives with a token of its own. That token carries everything your install’s active operations declared, so you can do the delivery’s work right there: write the record that changed.
Two kinds of work do not fit in a delivery:
- Work the platform allows only inside a run. Setting a user’s consent is one. The change is recorded against the operation that made it, and a delivery is not an operation.
- Work that outlives the vendor’s patience. A vendor waits a few seconds. Releasing alerts in batches over an hour does not fit.
For both, start one of your own operations and answer the vendor:
const { executionId, joined } = await foir.operations.start('release-alerts', {
input: { variantId },
// The vendor's own delivery id: its redelivery starts nothing new.
idempotencyKey: deliveryId,
// One run per variant at a time: a second restock while one is running joins it.
concurrencyKey: `variant-${variantId}`,
});The run is queued and dispatched to your operation’s endpoint like any other, with a token of its own carrying that operation’s grants.
The two keys answer different questions. idempotencyKey names one delivery, and adopts the run it started for ever, so the same delivery never starts the work twice. concurrencyKey names work that recurs: while a run started under it is in flight a start joins that run, and once the run has ended the next start is a new one.
Only the token a delivery arrived with may call it, for an operation that is active at the install. An operation’s own token is refused: it carries that one operation’s grants, and starting another would reach past what it declared.
Connecting to a vendor with OAuth
When a user connects your app through your vendor’s consent screen, the platform hands your callback a single-use exchange ticket. Redeem it for a token that may write the install’s credentials, and write them:
import { createAppClient, redeemExchangeTicket } from '@foir/sdk/app';
const { dispatch } = await redeemExchangeTicket({ apiUrl, ticket });
await createAppClient({ apiUrl, dispatch }).install.writeCredentials({
accessToken: vendorToken,
account: vendorAccount,
});It makes one attempt, on purpose. The ticket is spent by the first call that reaches the platform, so repeating a call whose answer was lost would find it spent.
The manifest
Build the manifest from the platform’s own messages, and a key the platform does not accept cannot be written:
import { create, toJson } from '@bufbuild/protobuf';
import { AppConfigSchema } from '@foir/sdk/app/contract';
import type { AppGrant, AppHookEvent } from '@foir/sdk/app';
const grants: AppGrant[] = ['appconfig:read', 'appsecrets:read'];
const event: AppHookEvent = 'RECORD_PUBLISHED';
const manifest = toJson(AppConfigSchema, create(AppConfigSchema, {
name: 'redirector',
version: '1.0.0',
operations: [{ key: 'sync', name: 'Sync', endpoint: '/operations/sync', grants }],
}));@foir/sdk/app/contract needs @bufbuild/protobuf, which nothing else in the package asks for, so install it alongside. APP_GRANTS, APP_RECORD_GRANT_PREFIXES and APP_HOOK_EVENTS list what an operation may declare and what a hook may name, generated from the platform’s own lists. The discovery answer your __discover operation gives is DiscoveryResultSchema, from the same subpath.
Then ask the platform whether it would accept the manifest, in your build:
import { validateAppManifest } from '@foir/sdk/app';
const { ok, issues } = await validateAppManifest({ apiUrl, apiKey: process.env.FOIR_KEY!, manifest });
for (const issue of issues) console.log(`${issue.severity} ${issue.path}: ${issue.message}`);
if (!ok) process.exit(1);It is a dry run of the validation an install performs: nothing is registered and nothing is stored. Any key may ask, a publishable one included, because the check reads only the manifest it is handed. An agent asks the same question with the foir_validate_app_manifest tool.
An ERROR is something an install refuses the manifest over. A WARNING is not. Fail your build on the first and print the second.