Open History to see the last commit
1---
2title: Access and tenants
3id: harness-access
4order: 3
5description: "Decide who can use each session of a harness. Read the user of each request, check each action, and keep the threads of each organization apart."
6keywords:
7 - tanstack ai
8 - harness
9 - access
10 - getUser
11 - isAllowed
12 - tenantId
13 - membersOnly
14---
15
16Your harness serves many users. Ada must not read the threads of Bob, and the company Acme must never see a thread of the company Globex. Give the host `access`. Then the host reads the user of each request, asks you about each action, and keeps each organization apart.
17
18A user here is `{ id, name?, tenantId? }`: who a call acts for. Its type is `HarnessUser`.
19
20## 1. Turn on access
21
22Give `createHarnessHost` an `access` object and a `sessions` store. The store keeps the owner and the members of each session:
23
24```ts group=harness-access
25import { createHarnessHost, defineHarness, membersOnly } from '@tanstack/ai-harness'
26import { createHarnessHandler } from '@tanstack/ai-harness/server'
27import { memoryPersistence } from '@tanstack/ai-persistence'
28import { openaiText } from '@tanstack/ai-openai'
29
30export const assistant = defineHarness({
31 name: 'acme/assistant',
32 adapter: openaiText('gpt-6.1-sol'),
33})
34
35// Your own login check: a session token to a user.
36const users = new Map([
37 ['Bearer token-ada', { id: 'ada', tenantId: 'acme' }],
38 ['Bearer token-gus', { id: 'gus', tenantId: 'globex' }],
39])
40
41export const host = createHarnessHost({
42 persistence: memoryPersistence(),
43 access: {
44 getUser: ({ request }) => users.get(request.headers.get('authorization') ?? '') ?? null,
45 rules: membersOnly(),
46 },
47})
48
49export const handler = createHarnessHandler({ host, harness: assistant })
50```
51
52- `getUser` reads the user of a request with your own login check. Return `null` to refuse the request with `401`.
53- `rules` decides each action. `membersOnly()` gives ready rules: only the members of a session can use it. See [Share a thread between people](./shared-threads).
54- `memoryPersistence()` has a `sessions` store. Without `stores.sessions`, `createHarnessHost` throws.
55
56The handler gets the user from `getUser`, so it needs no login option of its own. A new thread belongs to the user who opens it first.
57
58## 2. Write your own rule
59
60Give `access` your own `rules` with an `isAllowed` function. `isAllowed` gets the user, the action, and the session. Return `false` to refuse. The user has the type that `getUser` returns, so your own fields are typed too:
61
62```ts group=harness-access-rule
63import { createHarnessHost } from '@tanstack/ai-harness'
64import { memoryPersistence } from '@tanstack/ai-persistence'
65
66interface User {
67 id: string
68 tenantId: string
69 isAdmin: boolean
70}
71
72const users = new Map<string, User>([
73 ['Bearer token-ada', { id: 'ada', tenantId: 'acme', isAdmin: false }],
74 ['Bearer token-eve', { id: 'eve', tenantId: 'acme', isAdmin: true }],
75])
76
77export const host = createHarnessHost({
78 persistence: memoryPersistence(),
79 access: {
80 getUser: ({ request }) => users.get(request.headers.get('authorization') ?? '') ?? null,
81 rules: { isAllowed: ({ user, action, session }) => {
82 const isOwner = session.members.some(
83 (member) => member.userId === user.id && member.role === 'owner',
84 )
85 if (isOwner || user.isAdmin) return true
86 // Everyone in the organization can read every thread of it.
87 return action === 'read' || action === 'list'
88 } },
89 },
90})
91```
92
93Each action covers these calls:
94
95| Action | What it covers |
96| --- | --- |
97| `read` | Open the session, and read its stream, snapshot, transcript, media, and child runs. |
98| `list` | See the session in `host.sessions.list`. |
99| `send` | Prompt, steer, follow up, run a command or a tool, start an agent, and upload media. |
100| `answer` | Answer a question or an approval. |
101| `operator` | Reply as an operator with `send(text, { as: 'operator' })`, and answer a `human` wait of any run. See [Hand off to a person](./handoffs#4-hand-off-to-a-person). |
102| `cancel` | Stop a run, or drop an input that waits. |
103| `configure` | Change the thread settings, the plugin config, the title, and the metadata. |
104| `share` | Add or remove members. |
105| `delete` | Remove the session from the index. |
106| `erase` | Erase the messages of one user with `host.sessions.eraseUser`. See [Erase the messages of one person](./shared-threads#9-erase-the-messages-of-one-person). |
107| `fork` | Copy the session into a new session. |
108| `transfer` | Move the conversation to another thread, also of another harness, with `host.transfer`. See [Move a conversation to another harness](./handoffs#5-move-a-conversation-to-another-harness). |
109
110- For `answer` and `cancel`, `isAllowed` also gets `run`: the `runId` and the `userId` of the user who started that run.
111- For `answer` and `operator`, `isAllowed` also gets `wait`: the `waitId` and the `kind` of the [wait](./waits) that the input answers, when the host knows it. A `human` wait takes only `operator`, also for a resolve that ends it.
112- For `cancelSchedule`, `run` is the schedule: the `runId` is the schedule id, and the `userId` is the user who made it.
113- `host.submit` and `schedule` check an answer or a cancel when you send it, with `run` from the log. A run that the log does not have is refused with `unknown_run`: `submit` returns a `rejected` receipt, and `schedule` throws `InputRejectedError`.
114- A handle checks `read` once, when it opens. Each action that changes the session asks `isAllowed` again. This includes `cancel` and `send` on an operation or an agent run that the handle returns.
115- `isAllowed` does not get the input. To check what an input says, or to replace its `context`, give the host `acceptInput`. It runs after `isAllowed`. See [Check an input on the server](./inputs#check-an-input-on-the-server).
116
117The rules have two more keys. `membersOnly()` sets both. Your own rules can leave them out:
118
119- `filterSessionList`: the filter that `host.sessions.list` gives the store, for example `{ memberId }`. Without it, the store reads every session of the tenant, and `isAllowed` drops the others, so a page can have fewer entries than `limit`.
120- `members`: turns on `host.sessions.share` and `unshare`, and `members.fork` sets the members of a fork. Without it, `share` and `unshare` throw.
121
122## What the host checks for you
123
124`isAllowed` decides only the rule of your app. The host does these checks before it calls it:
125
126- The tenant. A user reaches only the sessions of their own tenant. `isAllowed` never gets a session of another tenant.
127- A user on every call. With access, `host.open`, `host.fork`, `host.transfer`, and each `host.sessions` method need a `user`. A call without one throws.
128- One user per handle. `host.open` returns a session that acts only as its `user`. A call on it that passes another `user` throws.
129- Child threads. The host checks a subagent child as its root thread, so `session` is the root session. A user who cannot read the root gets `403` for the child, and does not learn its root.
130- Missing threads. A read of a thread with no entry answers `404` and starts no session. `GET run?threadId=` answers an empty hydration instead, because `useChat` reads it before the first message.
131
132A refused action throws `AccessDeniedError`, with `code: 'forbidden'`, the `action`, and the `threadId`. The handler answers it with `403`.
133
134The host keeps only the `id` and the `tenantId` of a user in the log. So `isAllowed` can get a user with only these two fields. A rule that reads another field, such as `isAdmin` above, must refuse when the field is missing.
135
136A signed media URL is no login. The handler runs `getUser` for it too, and checks `read` for that user, in the tenant of the URL. A request with no user gets `401`. So load the file with a request that sends the login, for example an `<img>` on the same site, which sends its cookies.
137
138### Serve media to a request with no login
139
140An `<img>` on another site sends no cookies, so `getUser` finds no user. Give `access` a `getGuestUser` function. It returns a guest for that request, and `isAllowed` decides `read` for the guest:
141
142```ts group=harness-access-guest
143import { createHarnessHost, membersOnly } from '@tanstack/ai-harness'
144import { memoryPersistence } from '@tanstack/ai-persistence'
145
146interface User {
147 id: string
148 tenantId?: string
149 isGuest?: boolean
150}
151
152const members = membersOnly()
153
154export const host = createHarnessHost<User>({
155 persistence: memoryPersistence(),
156 access: {
157 getUser: () => null,
158 // `tenantId` is the tenant of the signed URL.
159 getGuestUser: ({ tenantId }) => ({ id: 'guest', tenantId, isGuest: true }),
160 rules: {
161 isAllowed: (input) =>
162 input.user.isGuest === true ? input.action === 'read' : members.isAllowed(input),
163 filterSessionList: members.filterSessionList,
164 members: members.members,
165 },
166 },
167})
168```
169
170- The handler calls `getGuestUser` only for a signed media URL, after the signature checks out, and only when `getUser` finds no user.
171- The guest gets nothing else. Every other route still needs a user from `getUser`.
172- Without `getGuestUser`, or when it returns `null`, the request gets `401`.
173- The guest needs the tenant of the URL, else the request gets `403`.
174
175## Keep tenants apart
176
177Give each user a `tenantId` in `getUser`. The tenant keeps each organization apart:
178
179- One `threadId` in two tenants is two sessions, with two index entries and two logs.
180- `host.sessions.list` reads one tenant: the tenant of `user`. A user with no `tenantId` is in the default tenant.
181- The log store keeps each session tree under `logIdOf({ tenantId, logId })`, for example `acme:thread-1`. The default tenant gives `:thread-1`. Use `logIdOf` when you read a log yourself.
182- The credentials of a user are kept per tenant. See [Keep organizations apart](./shared-threads#7-keep-organizations-apart).
183
184## Call the host from code with no request
185
186A cron job, an admin tool, or a queue worker has no request, so `getUser` cannot run. Pass the user yourself. The host checks the action for that user, the same as for a request:
187
188```ts group=harness-access
189// Your database knows the owner of each thread.
190export async function nightlyReport(threadId: string, owner: { id: string; tenantId: string }) {
191 const session = await host.open(assistant, { threadId, user: owner })
192 await session.send('Write the report of today.')
193}
194```
195
196Your own routes and an MCP server have a request. Read its user with `host.getUserOfRequest`:
197
198```ts group=harness-access
199export async function myThreads(request: Request) {
200 const user = await host.getUserOfRequest({ request })
201 if (!user) return new Response('Unauthorized', { status: 401 })
202 const page = await host.sessions.list({ user, limit: 20 })
203 return Response.json(page.entries.map((entry) => entry.title ?? 'New chat'))
204}
205```
206
207`host.getUserOfRequest` throws on a host with no `access`.
208
209## Use your own access tables
210
211Your app already keeps who can use each thread, for example a table of teams. Read it in `isAllowed`. When you take a user out of the table, call `host.revoke`:
212
213```ts group=harness-access-own-tables
214import { createHarnessHost } from '@tanstack/ai-harness'
215import { memoryPersistence } from '@tanstack/ai-persistence'
216
217const users = new Map([
218 ['Bearer token-ada', { id: 'ada', tenantId: 'acme' }],
219 ['Bearer token-bob', { id: 'bob', tenantId: 'acme' }],
220])
221
222// Your own table: the team of each thread.
223const teams = new Map([['plan-q3', new Set(['ada', 'bob'])]])
224
225export const host = createHarnessHost({
226 persistence: memoryPersistence(),
227 access: {
228 getUser: ({ request }) => users.get(request.headers.get('authorization') ?? '') ?? null,
229 rules: { isAllowed: ({ user, session }) =>
230 session.members.some((member) => member.userId === user.id) ||
231 (teams.get(session.threadId)?.has(user.id) ?? false) },
232 },
233})
234
235export async function removeFromTeam(threadId: string, user: { id: string; tenantId: string }) {
236 teams.get(threadId)?.delete(user.id)
237 await host.revoke({ threadId, user })
238}
239```
240
241When the promise of `host.revoke` resolves:
242
243- The running and queued work of the user on the thread is cancelled, on every host. The schedules of the user on the thread are removed.
244- The streams of the user on the thread close. A socket gets a `forbidden` error frame. A running `events()` read of a handle or a view ends with `AccessDeniedError`.
245- The open handles and views of the user on the thread throw `AccessDeniedError`. A new `host.open` asks `isAllowed` again.
246- The signed media URLs stop working for the user. The handler checks the user of each request again when it serves the file.
247- `host.events()` yields a `revoked` event.
248
249When the cancels cannot be sent (for example, the log store fails), the promise rejects. The access is gone already. Call `host.revoke` again to stop the work. `host.sessions.unshare` rejects the same way, after it removed the member.
250
251`host.sessions.share` and `unshare` need `members` in the rules, which `membersOnly()` has. With your own tables, change the tables, then call `host.revoke`.
252
253## Serve with no login
254
255A demo, or a tool on your own machine, has no login. Give the handler `openAccess` on a host with no `access`:
256
257```ts group=harness-access-open
258import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
259import { createHarnessHandler } from '@tanstack/ai-harness/server'
260import { memoryPersistence } from '@tanstack/ai-persistence'
261import { openaiText } from '@tanstack/ai-openai'
262
263const assistant = defineHarness({
264 name: 'acme/assistant',
265 adapter: openaiText('gpt-6.1-sol'),
266})
267
268const host = createHarnessHost({ persistence: memoryPersistence() })
269
270// One user on this machine: every request runs as Ada.
271export const handler = createHarnessHandler({
272 host,
273 harness: assistant,
274 openAccess: { user: { id: 'ada' } },
275})
276```
277
278- `openAccess: true`: every request runs with no user, in the default tenant.
279- `openAccess: { user }`: every request runs as that one user. Their credentials and keys do the work.
280- Without host `access` and without `openAccess`, `createHarnessHandler` throws at the start. So a server never serves every thread to everyone by mistake.
281- On a host with `access`, `openAccess` throws. The host reads the user itself.
282- `handleHarnessSocket` takes the same option.
283
284CAUTION: Do not use `openAccess` on a server that the internet can reach. Every caller can then use every thread.
285
286## Use the provider keys of the server
287
288With access, a keyed adapter and `run.keys` read only the keys that each user saved. They do not read the env vars of the server, so a user never spends the key of the server. To let users fall back to the server key, set `allowServerEnvKeys: true` in `access`, next to `getUser` and `policy`. See [Connect model providers](./provider-keys).
289
290## What you have now
291
292- A host that reads the user of each request, and checks each action.
293- A rule of your own, typed from what `getUser` returns.
294- Organizations that never see each other's threads.
295- Cron jobs and admin tools that act as a user they name.
296- A way to take access away from a user at once.