Server API Reference
The server entry point (@foir/sdk/server) provides utilities for app and extension API backends running on Node.js or Cloudflare Workers. It has zero dependencies and uses the Web Crypto API for token verification and HMAC.
import {
createServerClient,
requireScopedToken,
readDispatch,
verifyScopedToken,
parseSubject,
parseContextHeader,
recordsReadModels,
recordsWriteModels,
createCallbackClient,
verifyWebhookSignature,
ServerClientError,
} from '@foir/sdk/server';
import type {
ServerClient,
ServerClientOptions,
GraphQLResponse,
EditorPlacement,
ScopedTokenClaims,
ScopedTokenSubject,
VerifyScopedTokenOptions,
OperationPayload,
CallbackClient,
CallbackResult,
} from '@foir/sdk/server';createServerClient
Creates a client for a machine of your own, such as an integration syncing another system into Foir, authenticated with an admin key. An operation’s endpoint does not use it: it builds its client from the dispatch token it is handed, with no key (Writing an Operation Endpoint). It exposes a single query() method, a thin transport over the per-model public GraphQL API. Use it to read records and to issue record-write mutations.
import { createServerClient } from '@foir/sdk/server';
const client = createServerClient({
baseUrl: 'https://api.foir.dev',
apiKey: process.env.FOIR_ADMIN_KEY!, // foir_adm_...
});ServerClientOptions
interface ServerClientOptions {
/** Base URL for the platform API (e.g., 'https://api.foir.dev'). */
baseUrl: string;
/** A project's admin key (foir_adm_...). */
apiKey: string;
/**
* Optional. Retained for backwards compatibility with older extension
* scaffolds that pass it; the current client ignores it.
*/
configKey?: string;
}ServerClient interface
interface ServerClient {
query<T = Record<string, unknown>>(
query: string,
variables?: Record<string, unknown>
): Promise<GraphQLResponse<T>>;
}query
Execute a GraphQL query or mutation against the platform’s public API. The public API is per-model typed: each model exposes its own list query (products(first:) { edges { node { ... } } }), singular query (product(id:)), and mutations. Typed per-model queries are the recommended path; generic record(id:) and records(modelKey:) escape-hatch queries also exist, returning untyped JSON (and requiring the records:read scope).
const { data } = await client.query<{
products: { edges: Array<{ node: { _id: string; title: string } }> };
}>(`
query ListProducts($first: Int) {
products(first: $first) {
edges { node { _id title } }
}
}
`, { first: 100 });To write records with an admin key, issue the per-model create<Model> / update<Model> mutation through the same query() method:
await client.query(`
mutation CreateProduct($input: CreateProductInput!) {
createProduct(input: $input) { record { _id } }
}
`, {
input: {
naturalKey: 't-shirt',
title: 'T-Shirt',
price: 29.99,
},
});An app’s scoped token additionally reaches an upsertRecord mutation that creates-or-merges a record by (modelKey, naturalKey):
upsertRecord(modelKey: String!, naturalKey: String!, data: JSON!, ownerId: ID, sourceModifiedAt: String): UpsertRecordResult!It returns UpsertRecordResult { record, created, stale }: record is the upserted row as JSON, created is true when the row was inserted (rather than merged), and stale is true when the save wrote nothing because the record already holds a newer copy than sourceModifiedAt. It is reachable only with an app’s scoped token; API-key callers must use the per-model create<Model> / update<Model> mutations above.
EditorPlacement
EditorPlacement describes where an editor iframe appears in the console record editor. Apps return placements from their config so the platform knows how to mount the iframe.
interface EditorPlacement {
/** 'main-editor' replaces / augments the content tab; 'sidebar' renders in the sidebar. */
type: 'main-editor' | 'sidebar';
/** Full URL of the editor iframe. */
url: string;
/** Allowed postMessage origin (defaults to url origin). */
allowedOrigin?: string;
/** Iframe height: 'auto' (resize via postMessage), 'fill' (100%), or fixed px. */
height?: 'auto' | 'fill' | number;
/** Tab label for main-editor placements (defaults to config name). */
tabName?: string;
/** When true, hides the standard Content tab (main-editor only). */
hideContentTab?: boolean;
/** Which model keys this placement applies to; omit for all models. */
modelKeys?: string[];
}Operation Verification (Scoped Tokens)
Operation dispatches from the platform carry a short-lived scoped token in the X-Foir-Token header. Verify it against the platform’s JWKS endpoint before processing the request. The legacy HMAC X-Foir-Signature path is no longer used for operation dispatches; its helpers were removed in v0.8.0 (see Migrating from HMAC below).
requireScopedToken and readDispatch
The two calls an operation endpoint starts with. requireScopedToken reads and verifies the token and returns { claims, subject, context, dispatch }; dispatch is the verified token as a data-client credential. readDispatch parses the body into a typed OperationPayload. The third call is the client built from the token:
import { createFoirClient } from '@foir/sdk/data';
import { readDispatch, requireScopedToken } from '@foir/sdk/server';
// foir types --operation fulfil-order --out src/fulfil-order.generated.ts
import * as generated from './fulfil-order.generated';
export async function POST(request: Request) {
const { dispatch } = await requireScopedToken(request, {
expectedProjectId: process.env.FOIR_PROJECT_ID,
});
const { input, executionId } = await readDispatch<{ orderId: string }>(request);
const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, dispatch, generated });
// ...
}The client sends the token as X-Foir-Token and never an api key, and calls Foir as the operation with the grants it declares. generated is the module foir types --operation <key> wrote for this operation: its types are the surface the token is served, and a dispatch client takes no other (types for the operation’s token). requireScopedToken throws ScopedTokenError (401 or 403) and readDispatch throws OperationPayloadError (400); both carry the status to answer with. readDispatch reads the body, so call it once, before anything else consumes it.
verifyScopedToken
Verifies the JWT signature against the platform JWKS, checks the issuer, and validates exp / nbf. Returns the parsed claims on success; throws on any failure.
A token that verifies was signed by Foir. It was not necessarily signed for your project: every project is handed one with each of its own dispatches. An endpoint that acts with anything but the token itself (a key in its environment, its own database) uses requireScopedToken with expectedProjectId, or checks parseSubject(claims.sub) against its own project before it does anything.
import { verifyScopedToken } from '@foir/sdk/server';
const claims = await verifyScopedToken(
token,
'https://api.foir.dev/.well-known/jwks.json',
);Parameters
| Parameter | Type | Description |
|---|---|---|
token | string | The raw JWT from the X-Foir-Token header. |
jwksUrl | string | The platform’s scoped-token JWKS endpoint — https://api.foir.dev/.well-known/jwks.json. |
options | VerifyScopedTokenOptions | Optional. { expectedIssuer?: string } — expectedIssuer defaults to 'foir-platform'. |
ScopedTokenClaims
interface ScopedTokenClaims {
iss: string; // 'foir-platform'
sub: string; // pipe-delimited '<tenantId>|<projectId>|<appName>'
grants: string[]; // what the token carries, e.g. ['records:read:product', 'appsecrets:read']
jti: string; // unique token id
exp: number; // expiry (unix seconds)
nbf: number; // not-before (unix seconds)
iat: number; // issued-at (unix seconds)
ctx?: Record<string, string>; // operation/execution context
cid?: string; // the user the token acts for, when it acts for one
}grants is the whole of what the token may do, in the permission catalogue’s names: see Operation permissions. It is always set: a token that does not say its grants is refused, by verifyScopedToken as by the platform. The token carries none of the claims one carried before it said them (cap, rrm, rwm).
JWKS keys are cached per-isolate via globalThis for 5 minutes.
VerifyScopedTokenOptions
interface VerifyScopedTokenOptions {
/**
* Expected `iss` claim. Defaults to `'foir-platform'`. Override only
* when verifying tokens from a non-default issuer (test harnesses,
* alternate deploys).
*/
expectedIssuer?: string;
}parseSubject
Splits the pipe-delimited sub claim into a typed ScopedTokenSubject. Throws when the tenant or project segment is missing or empty. appName may be empty, for a token bound to the project rather than an app.
const { tenantId, projectId, appName } = parseSubject(claims.sub);interface ScopedTokenSubject {
tenantId: string;
projectId: string;
appName: string;
}parseContextHeader
Parses the semicolon-delimited X-Foir-Context header the platform attaches to dispatched operation requests. Shape: project=P;app=A;operation=O;triggered_by=T;execution_id=E;causation_chain=a,b,c.
const ctx = parseContextHeader(req.headers.get('x-foir-context'));
console.log(ctx.execution_id, ctx.triggered_by);recordsReadModels / recordsWriteModels / recordsCreateModels
The models a token’s grants name for the read, the write and the create of records. Changing a record and making one are two grants, so a token that may make records of a model is in recordsCreateModels and not necessarily in recordsWriteModels.
const readable = recordsReadModels(claims);
if (!readable.includes('product')) {
return new Response('forbidden', { status: 403 });
}Full middleware example (Hono)
import { Hono } from 'hono';
import {
verifyScopedToken,
parseSubject,
parseContextHeader,
readDispatch,
} from '@foir/sdk/server';
import type { ScopedTokenClaims } from '@foir/sdk/server';
const JWKS_URL = 'https://api.foir.dev/.well-known/jwks.json';
const app = new Hono<{
Variables: { claims: ScopedTokenClaims; ctx: Record<string, string> };
}>();
async function verifyDispatch(c, next) {
const token = c.req.header('x-foir-token');
if (!token) return c.json({ error: 'missing token' }, 401);
try {
const claims = await verifyScopedToken(token, JWKS_URL);
c.set('claims', claims);
c.set('ctx', parseContextHeader(c.req.header('x-foir-context')));
await next();
} catch (err) {
return c.json({ error: 'invalid token', detail: String(err) }, 401);
}
}
app.post('/operations/*', verifyDispatch);
app.post('/operations/process', async (c) => {
const claims = c.get('claims');
const ctx = c.get('ctx');
const { appName, projectId } = parseSubject(claims.sub);
const payload = await readDispatch(c.req.raw);
// Use claims.grants / recordsReadModels(claims) to authorize what this
// dispatch is allowed to do; use ctx.execution_id for callback wiring.
return c.json({ success: true, result: { processed: true } });
});Async-Callback Client
When the platform dispatches an operation in async mode, the request body includes a callback block. Your endpoint returns 202 Accepted, queues the work, then later calls back to the public API to report progress or terminal state. Use createCallbackClient to wrap that callback API.
createCallbackClient
import { createCallbackClient, readDispatch } from '@foir/sdk/server';
const payload = await readDispatch(request);
// `callback` is present only on an async dispatch.
if (payload.callback) {
const cb = createCallbackClient(payload.callback, {
executionId: payload.executionId,
});
// Report progress as work proceeds
await cb.progress({ pct: 25, message: 'Fetched source data' });
// ... do work ...
// Report success
await cb.complete({ recordCount: 142, durationMs: 3500 });
}continueRun
An async run that is not finished can answer a slice with a continuation instead of 202 Accepted: the cursor the next slice resumes from. Foir queues the next call and hands the cursor back as payload.continuation, with a fresh callback block. The slice that finishes reports through its callback as usual. See a run cut into slices for the contract.
import { continueRun, createCallbackClient, readDispatch } from '@foir/sdk/server';
const payload = await readDispatch(request);
const page = await syncOnePage(payload.continuation?.cursor);
if (page.next) {
return continueRun({ cursor: page.next, progressPct: page.pct });
}
const cb = createCallbackClient(payload.callback!, {
executionId: payload.executionId,
});
await cb.complete(page.summary);
return new Response(null, { status: 202 });continueRun returns a fetch Response, and throws before anything is sent on a continuation Foir would refuse: an empty cursor, one over 16 KiB, a delayMs outside 0 to 900000, or a progressPct outside 0 to 100. In a framework without Response objects, answer 200 with the CONTINUATION_MEDIA_TYPE content type and JSON.stringify(continuation) as the body.
CallbackClient interface
interface CallbackClient<TResult = unknown> {
complete(result: TResult): Promise<CallbackResult>;
fail(
code: string,
message: string,
opts?: { retryable?: boolean; details?: Record<string, unknown> }
): Promise<CallbackResult>;
progress(update: {
pct?: number;
message?: string;
metadata?: Record<string, unknown>;
}): Promise<CallbackResult>;
cancel(): Promise<CallbackResult>;
}
interface CallbackResult {
/** Status as seen by the platform AFTER the call. */
status: string;
/** True when the execution was cancelled from the console while the extension was working. */
cancelled: boolean;
/** Progress only: false when the monotonic guard rejected an out-of-order update. */
applied?: boolean;
}Auth on callback requests
Each reply goes to the run’s own reply route, callback.endpoint, and carries two pieces of auth:
Authorization: Bearer <callback.token>: the token bundled in the dispatch envelope, which is good for this run’s replies alone.X-Foir-Signature: sha256=<hex>: HMAC-SHA256 of the raw request body, keyed on the run’s owncallback.signingKey, which the platform sends with every async dispatch. An endpoint that holds the project’s signing secret (FOIR_SIGNING_SECRET, published byfoir push) can pass it assigningSecretinstead, and it is then the key used.
The SDK handles both. With the dispatch’s callback block passed in, you need no signing secret of your own.
Cancellation handling
progress returns { cancelled: true } when someone has cancelled the execution while your service was still working. Stop work immediately and (optionally) call fail('CANCELLED', '...') to record the terminal state.
for (let i = 0; i < items.length; i++) {
const result = await cb.progress({
pct: Math.floor((i / items.length) * 100),
message: `Processed ${i} of ${items.length}`,
});
if (result.cancelled) {
console.log('cancelled, stopping work');
return;
}
await processItem(items[i]);
}
await cb.complete({ processedCount: items.length });Typed results
createCallbackClient<TResult> accepts a generic for the operation’s result shape, so complete takes only a result of that shape. Use the operation’s output type, the same type its execute<Op> mutation answers with.
import type { TranslateOutput } from './generated';
const cb = createCallbackClient<TranslateOutput>(payload.callback!, {
executionId: payload.executionId!,
});Webhook Verification
For inbound webhooks where an external service signs the request body, verify with verifyWebhookSignature. It takes an HMAC-SHA256 of the raw body, keyed on a shared secret, in hex (either case) or in base64 (standard or URL-safe), so Shopify’s base64 header verifies as it arrives. A signature with a prefix such as GitHub’s sha256=, or a timestamped scheme such as Stripe’s, is not read: strip the prefix, or use the sender’s own library.
This is unrelated to operation dispatches. Operation dispatches use scoped tokens (above); only inbound webhooks from third-party services use HMAC.
import { verifyWebhookSignature } from '@foir/sdk/server';
app.post('/webhooks/shopify', async (c) => {
const body = await c.req.text();
const signature = c.req.header('x-shopify-hmac-sha256') ?? '';
const valid = await verifyWebhookSignature(
body,
signature,
process.env.SHOPIFY_WEBHOOK_SECRET!,
);
if (!valid) {
return c.text('Invalid signature', 401);
}
const payload = JSON.parse(body);
// Process webhook...
});Parameters
| Parameter | Type | Description |
|---|---|---|
payload | string | The raw request body as a string. |
signature | string | The HMAC signature from the request header, in hex or in base64. |
secret | string | The shared secret with the source service. |
Returns Promise<boolean> — true if the signature is valid, false otherwise.
OperationPayload
The body the platform POSTs to your operation endpoint, field for field. Read it with readDispatch(request).
interface OperationPayload<TInput extends object = Record<string, unknown>> {
/** The run. Always present. */
executionId: string;
/** The key of the operation being run. */
operationKey: string;
/** How the run was started. */
trigger: OperationTrigger;
/** The caller's input. Always an object. */
input: TInput;
/** The tenant, project and principal the run belongs to. */
context: OperationContext;
/** Present only when the caller that started the run attached one. */
content?: Record<string, unknown>;
/** Present only when the caller that started the run attached one, as written. */
record?: OperationRecordContext;
/** Present only when the caller supplied one. */
triggerContext?: Record<string, unknown>;
/**
* Present only on an ASYNC dispatch. A blocking (SYNC) dispatch carries
* no callback: the response body is the result.
*/
callback?: OperationCallback;
/**
* Present on a slice of a run after its first: the cursor the previous
* slice answered with continueRun, and which slice this is.
*/
continuation?: { cursor: string; slice: number };
}
interface OperationTrigger {
type: 'ui' | 'api' | 'lifecycle' | 'schedule' | 'webhook';
}
/** Forwarded as the caller wrote it; the platform does not shape it. */
type OperationRecordContext = Record<string, unknown>;
interface OperationContext {
tenantId: string;
projectId: string;
actorId: string; // empty when no principal started the run
userId?: string; // when the run acts for a user
timestamp: string; // RFC 3339, UTC
}
interface OperationCallback {
endpoint: string; // the run's own reply route
token: string; // Bearer token for this run's replies
expiresAt: string; // RFC3339
causationChain?: string[];
signingKey?: string; // the key this run signs its replies with
}OperationResult
The standard response shape your operation endpoint should return for sync dispatches. Async dispatches return 202 Accepted and report results via the callback client instead.
interface OperationResult {
success: boolean;
result?: unknown;
error?: {
code: string;
message: string;
details?: Record<string, unknown>;
};
metadata?: Record<string, unknown>;
}Success example:
return c.json({
success: true,
result: { redirectCount: 42 },
metadata: { durationMs: 1200 },
});Error example:
return c.json({
success: false,
error: {
code: 'MISSING_CREDENTIALS',
message: 'Cloudflare API token is not configured',
},
});Error Classes
ServerClientError
Thrown by createServerClient methods when a platform API request fails.
class ServerClientError extends Error {
status?: number;
response?: unknown;
}Migrating from HMAC
Earlier SDK versions shipped verifyOperationSignature / verifyAndParseOperation (and the OperationVerificationError class) for the legacy HMAC operation-dispatch path. These were removed in @foir/sdk@0.8.0 — scoped tokens are now the only inbound auth path.
The platform stopped emitting X-Foir-Signature for operation dispatches when the scoped-token model shipped — every operation request now carries X-Foir-Token instead. If you are upgrading from v0.7.x:
- import { verifyAndParseOperation } from '@foir/sdk/server';
+ import { verifyScopedToken, parseSubject } from '@foir/sdk/server';
app.post('/operations/process', async (c) => {
- const body = await c.req.text();
- const signature = c.req.header('x-foir-signature');
- const payload = await verifyAndParseOperation(body, signature, {
- webhookSecret: process.env.WEBHOOK_SECRET!,
- });
+ const token = c.req.header('x-foir-token');
+ if (!token) return c.json({ error: 'missing token' }, 401);
+ const claims = await verifyScopedToken(
+ token,
+ 'https://api.foir.dev/.well-known/jwks.json',
+ );
+ const payload = await c.req.json();
+ const { appName } = parseSubject(claims.sub);
// ...
});WEBHOOK_SECRET (or FOIR_SIGNING_SECRET) is no longer needed for the inbound path. Outbound callbacks in async mode are signed with the run’s own callback.signingKey by default; see Async-Callback Client above.