Writing for a user from an operation
Some writes belong to a user who is not the one making them. A buyer at a guest checkout has no account until the checkout makes one, and their order should be theirs the moment it exists. A user whose role lets them run the checkout for someone else rings up an order at the till for the person standing in front of them. A ticket is handed to a friend. In each case your code decides who the record belongs to, and the user never signs in to make the write themselves.
That code runs in an operation. The storefront, the till and the ticket page reach it by running the operation, and the operation’s endpoint makes the writes with the dispatch token it is called with. There is no server route holding a key, and there is no key in the endpoint either.
The grants
An operation declares what its token may do as grants. Two cover writing for a user, and two more cover reading one:
| Grant | What it lets the operation do |
|---|---|
users:create | Create a user, such as the buyer at a guest checkout who has never signed in, or answer with the one who already has that email (returnExisting). |
users:read.named | Read one user the operation names: user(id:), or user(email:) with their exact address. It cannot list users. |
users:read.all | Read users: one it names, and the users list. An operation declaring this holds the named read too. |
records:attribute:<model> | Name the user a new record belongs to (ownerId on create<Model>), and hand an existing record to another user (set<Model>Owner). records:attribute with no model covers every model. |
export default defineConfig({
key: 'shop',
name: 'Shop',
operations: [
{
key: 'checkout',
name: 'Checkout',
endpoint: 'https://shop.example.com/api/checkout',
grants: ['users:create', 'records:create:order', 'records:attribute:order'],
inputSchema: {
type: 'object',
properties: { email: { type: 'string' }, items: { type: 'array', items: { type: 'string' } } },
required: ['email', 'items'],
},
},
],
});A grant an operation may not declare is refused at push, naming it, so a misspelt one never ships as a grant that gives nothing. Operation permissions lists every one.
Only an operation names a record’s owner on the data API. A request that names an owner from anywhere else there is refused, with this page named in the error. That includes an admin key, whatever it holds: a server deciding on its own who owns a record is the pattern this replaces. An admin key may be made holding records:attribute, and neither a publishable nor a server key may (Key Permissions), and holding it changes nothing here: the data API takes an owner’s name from an operation alone. A user naming themselves as the owner is accepted and changes nothing, since their own records are already theirs.
Guest checkout, end to end
The storefront runs the operation with its publishable key. To let someone check out without signing in, name the operation under What anyone can do without signing in on that key (operations:execute:checkout in its anonymous list):
// The storefront's client, built from its publishable key.
const checkout = await foir.ns.operations['execute.checkout']({
input: { email, items },
mode: 'SYNC',
});The endpoint verifies the dispatch, builds a client from the token it was called with, creates the buyer and then the order that belongs to them:
import { createFoirClient } from '@foir/sdk/data';
import { readDispatch, requireScopedToken } from '@foir/sdk/server';
// foir types --operation checkout --out src/checkout.generated.ts
import * as generated from './checkout.generated';
export async function POST(request: Request) {
const { dispatch } = await requireScopedToken(request, {
expectedProjectId: process.env.FOIR_PROJECT_ID,
});
const { input } = await readDispatch<{ email: string; items: string[] }>(request);
const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, dispatch, generated });
// A returning buyer is already a user: returnExisting answers with them
// rather than refusing, and a new one is made the first time.
const buyer = await foir.ns.users.createUser({
input: { email: input.email, returnExisting: true },
});
const { record: order } = await foir.order.create({
input: { items: input.items },
ownerId: buyer.id,
});
return Response.json({ orderId: order._id });
}checkout.generated is the module foir types --operation checkout wrote: its types are what the checkout’s token is served, so foir.order.create takes ownerId because the operation declared records:attribute:order, and a model it declared nothing for is not on the client at all (types for the operation’s token).
A returning buyer is the same user. Without returnExisting the create refuses an email that already has a user, and users:create alone cannot look users up to find them: it creates the users an operation attributes records to and reads no one. With it, the create answers with the user who has that email in the sign-in the operation’s place uses, so a second order lands on the first order’s user and a retry of the operation lands on the same one. One address is one user in a sign-in, wherever they stand in it:
- somebody the operation’s place reaches is the answer: a member there, or a member of the project at an organization that shares the project’s sign-in;
- somebody it does not reach is the answer only where its organization lets them in without an invitation (it is open, or their verified address is at its open domain), and they join it first;
- anybody else is refused, without saying who holds the address, and no second user is made for it.
It is refused with a password, because an existing user’s password is theirs.
The answer says whether the address is proved. emailVerifiedAt on the user that comes back (verified on the app client’s users.ensure) is set only when the user has proved the address is theirs. A user an operation made from an address somebody typed has not, and the create answers with them all the same: the same shopper asking twice must be one user. So write what the address is owed, such as an order confirmation or the alert they asked for, and ask the flag before anything that should wait for proof.
The buyer holds no role and never needed one: the order is theirs because the operation said so, not because they were allowed to write it. When they sign in later, their own bearer reads it, and nobody else’s does. A hook on RECORD_CREATED whose notification goes to the record’s owner reaches them too, so the confirmation email is copy you edit in the console rather than code you deploy.
Handing a record to another user
set<Model>Owner moves a record to another user. The operation must declare records:attribute:<model> for the record’s model, and the record must be one it can reach: an operation run by the ticket’s holder reaches that ticket.
const { input } = await readDispatch<{ ticketId: string; friendId: string }>(request);
const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, dispatch, generated });
await foir.ticket.setOwner({ id: input.ticketId, ownerId: input.friendId });The new owner reads the ticket as themselves, and the previous owner no longer can. The record’s variants and versions move with it. The audit log’s RECORD_OWNER_SET entry names both owners and the execution that decided the move, so the business rule behind it can be traced to the run and its input.
Whether this ticket may go to that person is your code’s decision, which is why it lives in the operation: declared, signed, quota’d and audited, rather than in a route holding a long-lived key.
What is checked, for every surface
Wherever a record’s owner is named, from an operation, the console, the CLI or an agent, the platform checks it once:
- The id must name a user of this project. Anything else is refused, naming
ownerId. - When the request acts in an organization, the user must belong to it.
- The owner is always a user, and the model must be user-owned. A project model’s records belong to the project, whoever creates them, so naming an owner on one is refused, at create and when a record is reassigned; who created a record is kept as its
createdBy. An organization-owned model’s records belong to the organization and take no user owner.
A user signed in to the console, the CLI (foir login, then foir records create --owner-id) or an agent tool keeps naming owners and reassigning records with their own standing, and is held to the same checks. An API key is not a user. With FOIR_API_KEY set, or calling the platform API directly, naming an owner or handing a record to another user is refused just as it is on the data API, and the refusal names the operation path.
Who may run the operation
The operation decides what is written; who may run it is set on the API key and on roles:
- Anyone, when the storefront’s publishable key names the operation in its anonymous list. Those runs count against the publishable key’s rate limit, and the operation’s own quotas and preconditions still apply.
- A signed-in user, when their role grants it.
operations:executeruns every operation the key exposes;operations:execute:<operation>runs that one alone, so a role can let every user check out and keep rebooking for the users whose role grants it.
The walk-in sale is the same checkout, run by a signed-in user whose role grants executing it: an operation triggered by that user, naming the buyer at the till as the owner. There is no separate kind of account for the person at the till. The operation writes as itself, so the order is the buyer’s, and the user who rang it up is neither its owner nor its author.
See Writing an operation endpoint for the dispatch token, and API authentication for per-operation grants.