@thesmallfield/node
v0.0.3
Published
Small Field for app backends and scripts: files, email, identity.
Maintainers
Readme
@thesmallfield/node
npm i @thesmallfield/nodeSmall Field for app backends and scripts. Node 22+, ESM only. Never import it in browser code: browser bundles get
a stub that throws @thesmallfield/node holds your app key. In browser code use @thesmallfield/web.
import { createClient } from '@thesmallfield/node';
const sf = createClient(); // reads SMALLFIELD_API_URL, SF_AUTH_URL, SMALLFIELD_APP_HOSTS (every deployed app) and SMALLFIELD_API_KEY
const script = createClient({ apiUrl, authUrl, clientId, clientSecret }); // the app key rotates on every deploy
const forPerson = sf.as(req); // each call also carries the signed-in person (x-smallfield-token)
const projects = await sf.request('/projects').catch((e) => e); // SmallFieldError { code: 'forbidden', message }On an install with its own names (say APP_FOUNDRY_API_KEY and x-app-foundry-token), every deployed app gets
PLATFORM_NAMES and the client reads the variables and headers under those names. A script elsewhere passes
createClient({ names: { env: 'APP_FOUNDRY', header: 'x-app-foundry' } }). sf.as(req) also accepts the
x-smallfield-token header.
Who is calling (verifies the gate token against SF_AUTH_URL/.well-known/jwks.json, keys cached 5 min):
Pin the hosts your app answers on, so a token is only accepted for them whatever Host header arrives. Set
SMALLFIELD_APP_HOSTS (comma list) or pass audience. Without a pin, the request's Host is used.
const sf = createClient({ audience: ['helloworld-dev.apps.example.com'] }); // recommended
const who = await sf.identity.fromRequest(req); // { id, email, name, role, roles, scopes }, or null
if (!who) return res.status(401).send('Sign in first.'); // stranger on a public path, or a bad token
if (!hasRole(who, 'reports')) return res.status(403).send('Reports only.');
if (!can(who, 'reports:export')) return res.status(403).send('No export.'); // scopes from roles
// who.scopes: the app scopes from the person's roles. who.via.scopes: the link scopes of a calling app.
const raw = await sf.identity.verify(jwt, { audience: 'helloworld-dev.apps.example.com' });Email, shaped like AWS SESv2 SendEmail (server-side only; browser code can never send email):
const { MessageId } = await sf.email.send({
Destination: { ToAddresses: ['[email protected]'] },
Content: {
Simple: {
Subject: { Data: 'Q3 plan' },
Body: { Text: { Data: 'Hi' }, Html: { Data: '<p>Hi</p>' } },
},
},
});
await sf.as(req).email.send({ Content }); // no Destination: goes to the signed-in personErrors carry the SES exception name, so AWS SDK error handling keeps working:
try {
await sf.email.send(input);
} catch (e) {
if (e instanceof SmallFieldError && e.name === 'TooManyRequestsException')
retryLater(e.retryAfterMs); // also MessageRejected, …
else throw e; // SmallFieldError { status, code, message, requestId }
}Vault: secrets your app keeps at runtime, encrypted. Turn it on under Capabilities.
await sf.vault.set('autodesk-secret', secret); // shared by this app environment
const key = await sf.as(req).vault.get('openai-key'); // the signed-in person's; null when not saved
await sf.as(req).vault.set('openai-key', body.key);
await sf.vault.user(userId).remove('openai-key'); // app backend only (a nightly job), by id; also get, set, list
const { secrets } = await sf.vault.list(); // names and times, never valuesFiles (SF_FILES_URL), as the app or, with sf.as(req), as the signed-in person:
const file = await sf.files.upload('./q3.pdf', {
tags: ['q3'],
audience: 'roles',
audienceRoles: ['reports'],
});
await sf.files.upload(buffer, { name: 'note.txt' }); // Buffer, Blob, path, or a stream with sizeBytes
await sf.files.upload('./part-0.parquet', { path: 'sales/year=2026/part-0.parquet' }); // shows in S3
await sf.files.setPath(file.id, 'sales/q3.pdf'); // null takes it out of S3
await sf.files.upload(req, { name: 'video.mp4', sizeBytes: Number(req.headers['content-length']) });
const { stream, contentType, status } = await sf.files.download(file.id, {
range: req.headers.range,
});
await sf.files.downloadTo(file.id, './copy.pdf');
const { files } = await sf.as(req).files.search({ owner: 'me', kind: ['pdf', 'photo'] });
await sf.files.setAccess(file.id, {
audience: 'app',
sharing: 'apps',
sharedApps: [roomsProjectId],
});
await sf.files.share(file.id, { role: 'editor' }); // or { userId }; shares(id), unshare(id, shareId)
const { url } = await sf.files.link(file.id); // 5 minutes, for a browserUploads are resumable (tus, 50 MiB chunks, retried for about 90 s after a drop) and return a task: await it, or use
.promise, .pause(), .resume(), .abort(), onProgress(sent, total). A person's gate token lasts 5 minutes,
so a long upload as(req) should be done as the app.
Read the log: await sf.email.get(MessageId) and await sf.email.list({ limit: 50, search: 'priya' }) →
{ emails, nextBefore }. Not supported: Content.Raw, Content.Template, attachments, ConfigurationSetName.
email.send never retries; reads retry three times on 502/503/504.
Call another app that shared something with yours (its admins tick it in the console, and your
smallfield.json lists it under uses):
const orders = await sf.apps('rooms').fetch('/api/orders'); // as your app; JSON parsed
const mine = await sf.as(req).apps('rooms').fetch('/api/orders?mine=1'); // as the signed-in person
await sf.apps('rooms', { scope: 'orders.write' }).fetch('/api/orders', { method: 'POST', body }); // when you use two scopes
const run = await sf.apps('rooms').jobs.run('report'); // { runId, job }
const done = await sf.apps('rooms').jobs.wait(run, { timeoutMs: 120_000 }); // { status, exitCode, log, ... }
await sf
.apps('rooms')
.jobs.run('report', { input: { from: '2026-10-01' }, secretInput: { apiKey } });input reaches the job as SF_JOB_INPUT (a JSON object, at most 64 KB). secretInput (at most 16 KB) reaches it
as SF_JOB_SECRET_INPUT and is never shown again: the run lists only its key names.
Tokens last 5 minutes and are cached per app, scope and person. In the app you call, sf.identity.callerOf(req)
says who is calling: { app, environment, scopes, user, browser }, or null for an ordinary visit.
sf.identity.fromRequest(req) then has via: { app, scopes } on the person. Refusals arrive as a
SmallFieldError with the server's plain-English text. SMALLFIELD_USES (set for you at deploy) lists the scopes in use, from smallfield.json and the console; it picks the scope when you pass none.
Environment (all but the key are set on every deployed app; SMALLFIELD_API_KEY only when email, files or uses is on): SMALLFIELD_API_URL, SMALLFIELD_API_KEY, SMALLFIELD_PROJECT, SMALLFIELD_ENVIRONMENT,
SF_FILES_URL, SF_AUTH_URL (or pass authUrl to createClient()), SMALLFIELD_APP_HOSTS, or
SMALLFIELD_CLIENT_ID + SMALLFIELD_CLIENT_SECRET for scripts.
Keep it out of browser packages with one oxlint rule in ui/.oxlintrc.json:
{
"rules": {
"no-restricted-imports": [
"error",
{
"paths": [
{
"name": "@thesmallfield/node",
"message": "Use @thesmallfield/web in browser code."
}
]
}
]
}
}