Identity from a session JWT
SSR pattern — verify your app's session JWT, derive the caller's (namespace, space), and run each request under that scope with act_as.
Brain's identity is a (namespace, space) pair carried by the API key; the
server derives it from the credential and clients never send a scope. There are
two ways to give each user their own slice of memory:
- Per-tenant keys — one key per
(namespace, space), minted on the admin plane (POST /v1/api-keys) and stored encrypted. Simple, but you manage N secrets. act_asfront door (shown here) — hold one pooled service key that has been grantedcan_act_as, and stamp each request with the effective(namespace, spaceId)you derived from the JWT. One secret, many tenants.
The act_as grant is a wire-protocol capability, so this pattern uses the
wire client (BrainClient), which multiplexes many requests over one
pooled connection.
Verify the JWT, derive the scope
Your app already validates the session JWT. Map its claims to a Brain scope —
namespace is the tenant, space is the isolation unit inside it.
import { jwtVerify } from 'jose';
async function scopeFromJwt(token: string): Promise<{ namespace: string; space: string }> {
const { payload } = await jwtVerify(token, KEY);
// Map your own claims onto Brain's identity model. Both are strings you
// choose; the space is an opaque selector, not an id you construct.
return { namespace: payload.org as string, space: `user:${payload.sub as string}` };
}The space is a selector, not an id
Brain derives the 16-byte storage space id from this string at ingress —
UUIDv5(UUIDv5(ROOT, namespace), space). Client code never constructs a
space id, which is what stops one being forged by guessing. Pass a stable
string you own, such as user:<sub>, and let the server do the derivation.
Run the request under that scope
// Construct one shared, pooled wire client at startup with the service key.
import { BrainClient, EncodeBuilder, RecallBuilder } from '@brain-db/sdk';
const brain = await BrainClient.connect('brain.internal', 8080, {
// The token is BYTES, not a string — encode it yourself.
auth: {
kind: 'token',
token: new TextEncoder().encode(process.env.BRAIN_SERVICE_KEY!),
},
});
// Next.js Route Handler — runs per request.
export async function POST(req: Request) {
const token = req.headers.get('authorization')?.replace('Bearer ', '');
if (!token) return new Response('unauthenticated', { status: 401 });
const { namespace, space } = await scopeFromJwt(token);
const { message } = await req.json();
// Every op runs as the effective (namespace, space).
await brain.encode(
new EncodeBuilder(message).actAs(namespace, space).build(),
);
const answer = await brain.recall(
new RecallBuilder(message).actAs(namespace, space).maxResults(5).build(),
);
return Response.json({ answerKind: answer.answerKind });
}# FastAPI route — one shared wire client, per-request act_as.
# An async route needs the asyncio tier: BrainClient's verbs block and are
# not awaitable, so `await brain.encode(...)` on it is a TypeError.
from fastapi import APIRouter, Header
from brain_db_sdk import AsyncBrainClient, Auth, EncodeBuilder, RecallBuilder
router = APIRouter()
brain = await AsyncBrainClient.connect(
'brain.internal', 8080, Auth.token(SERVICE_KEY.encode())
)
@router.post('/chat')
async def chat(message: str, authorization: str = Header(...)):
namespace, space = scope_from_jwt(authorization.removeprefix('Bearer '))
await brain.encode(
EncodeBuilder(message).act_as(namespace, space).build()
)
answer = await brain.recall(
RecallBuilder(message).act_as(namespace, space).limit(5).build()
)
return {'answer_kind': answer.answer_kind}The service key must be granted can_act_as with an allowlist of namespaces
it may impersonate. A request whose derived namespace is outside that
allowlist is rejected — the SDK surfaces it as an act_as denial
(isActAsDenied). Keep the service key server-side; never ship it to a
browser.
Don't fall back to the service key's own scope when the JWT is missing or
invalid. A dropped act_as silently writes to the wrong tenant — the failure
mode is corrupted memory, not an error. Reject the request instead.
RecallBuilder exposes .limit(n), while the HTTP client's keyword is
max_results. Same meaning, two spellings — see
recall.
Why this is the wire client and not HTTP
act_as is a wire-protocol capability. The HTTP API takes its space from
the credential and accepts no selector on any route, so this pattern cannot be
expressed over /v1/*. One pooled wire connection multiplexes every tenant's
requests, so the shared client above is not a bottleneck — vary the selector
per request rather than opening a connection per user.
Prefer pool.getHealthy() over a single long-lived client in anything
long-running: a pooled member outlives any request, so a server restart
otherwise leaves every borrower holding the same dead socket. See
Wire client.
Was this page helpful?
Session summary
At session end, recall the salient memories, summarize them with your LLM, and encode the summary back as one durable memory.
Tune salience decay
Run the salience-decay worker on a faster cadence for a deployment whose memories go stale quickly — and understand why that changes what recall filters, not how it ranks.