Open History to see the last commit
1import type { SessionMember } from '@tanstack/ai-persistence'
2import type { HarnessInput, HarnessUser } from './types'
3import type { WaitKind } from './waits'
4
5/**
6 * What a user tries to do with a session.
7 *
8 * - `read`: stream, snapshot, transcript, media, and child runs.
9 * - `list`: see the session in a list of sessions.
10 * - `send`: prompt, steer, follow up, start agents, and run commands.
11 * - `answer`: answer a question or an approval of a run.
12 * - `operator`: answer a `human` wait of any run, and reply as an operator
13 * who takes over from the agent. A `human` wait takes only `operator`,
14 * so the user who waits for a person cannot answer it.
15 * - `cancel`: stop a run.
16 * - `configure`: change the settings of the thread.
17 * - `share`: add or remove members.
18 * - `delete`: delete the session.
19 * - `erase`: erase the messages of one user from the session, with
20 * `host.sessions.eraseUser`.
21 * - `fork`: copy the session into a new session.
22 * - `transfer`: move the conversation to a new thread, maybe of another
23 * harness, with `host.transfer`.
24 */
25export type AccessAction =
26 | 'read'
27 | 'send'
28 | 'answer'
29 | 'operator'
30 | 'cancel'
31 | 'configure'
32 | 'share'
33 | 'delete'
34 | 'erase'
35 | 'fork'
36 | 'transfer'
37 | 'list'
38
39/** The session that an action targets, as the index row has it. */
40export interface AccessSession {
41 threadId: string
42 tenantId?: string
43 /** The thread that started this one. Set on a subagent child. */
44 parentThreadId?: string
45 /**
46 * The users of the session. The owner is the member with the role
47 * `owner`. Without one, the session has no owner.
48 */
49 members: ReadonlyArray<SessionMember>
50}
51
52/** The run that an `answer` or `cancel` targets: who started it. */
53export interface AccessRun {
54 runId: string
55 /** The id of the user who started the run. */
56 userId?: string
57}
58
59/** The wait that an `answer` or `operator` action answers. */
60export interface AccessWait {
61 waitId: string
62 kind: WaitKind
63}
64
65/** What `isAllowed` gets for one action. */
66export interface AuthorizeInput<U extends HarnessUser = HarnessUser> {
67 user: U
68 action: AccessAction
69 session: AccessSession
70 /** The run that an `answer` or `cancel` targets, when the host knows it. */
71 run?: AccessRun
72 /** The wait that an `answer` or `operator` action answers, when the host knows it. */
73 wait?: AccessWait
74}
75
76/**
77 * What `acceptInput` returns: the input to store (the same input, or a
78 * changed one with the same `op`), or `{ refuse: reason }`.
79 */
80export type AcceptedInput = HarnessInput | { refuse: string }
81
82/**
83 * Look at an input before the session stores it, after the access check.
84 * Return the input, a changed input, or `{ refuse: reason }`. See
85 * `acceptInput` in the host options.
86 */
87export type AcceptInput<U extends HarnessUser = HarnessUser> = (
88 input: HarnessInput,
89 info: {
90 /** Who sent the input. `undefined` on a host without `access` and no user. */
91 user: U | undefined
92 threadId: string
93 },
94) => AcceptedInput | Promise<AcceptedInput>
95
96/**
97 * @internal What `acceptInput` returned for `input`: a changed input must
98 * keep its `op`, else it is refused.
99 */
100export function acceptedAs<TInput extends HarnessInput>(
101 input: TInput,
102 accepted: AcceptedInput,
103): TInput | { refuse: string } {
104 if ('refuse' in accepted) return accepted
105 if (accepted.op !== input.op) {
106 return {
107 refuse: `acceptInput changed the op of the input from ${input.op} to ${accepted.op}.`,
108 }
109 }
110 // ponytail: the same `op`, so the same member of `HarnessInput`.
111 return accepted as TInput
112}
113
114/** Decide if a user may do one action. Return `false` to refuse. */
115export type Authorize<U extends HarnessUser = HarnessUser> = (
116 input: AuthorizeInput<U>,
117) => boolean | Promise<boolean>
118
119/**
120 * What the host does with the members list of a session: `share` and
121 * `unshare` change it, and a fork copies it.
122 */
123export interface AccessMembers {
124 /**
125 * Who is a member of the new session after a fork without a `members`
126 * option.
127 *
128 * - `'self'` (default): only the user who forked it, as the owner.
129 * - `'all'`: the members of the source session too.
130 */
131 fork?: 'self' | 'all'
132}
133
134/**
135 * The rules of a host: `rules` in {@link HarnessAccess}.
136 * {@link membersOnly} returns one, or write your own with only `isAllowed`.
137 */
138export interface AccessPolicy<U extends HarnessUser = HarnessUser> {
139 /**
140 * What a user may do. Called for every action. The harness checks
141 * the tenant before it calls this.
142 */
143 isAllowed: Authorize<U>
144 /**
145 * A filter that `host.sessions.list` passes to the sessions store, so a
146 * page holds only sessions that the user can list. `isAllowed` still
147 * checks each entry. Without it, the store gives every session of the
148 * tenant, and `isAllowed` drops the others, so a page can come back short.
149 */
150 filterSessionList?: (user: U) => { memberId?: string }
151 /**
152 * Turn on `host.sessions.share` and `unshare`, which change the members
153 * list of a session, and set the members of a fork. Without it, `share`
154 * and `unshare` throw: change your own access tables and call
155 * `host.revoke`.
156 */
157 members?: AccessMembers
158}
159
160/**
161 * Who may use the sessions of a host, and what they may do. The type of the
162 * user comes from the return value of `getUser`.
163 *
164 * @example
165 * access: {
166 * getUser: ({ request }) => findUser(request),
167 * rules: membersOnly(),
168 * }
169 */
170export interface HarnessAccess<U extends HarnessUser = HarnessUser> {
171 /**
172 * Who is calling: your own login check, once per request. Return null to
173 * refuse with 401.
174 */
175 getUser: (input: { request: Request }) => U | null | Promise<U | null>
176 /**
177 * What each user may do: `membersOnly()`, or your own
178 * `{ isAllowed, filterSessionList?, members? }`.
179 */
180 rules: AccessPolicy<U>
181 /**
182 * A guest for a signed media URL with no login, for example an `<img>`
183 * that sends no cookies. The handler calls it only on the signed media
184 * route, after the signature checks out, and only when `getUser` finds no
185 * user. `tenantId` is the tenant of the URL. `isAllowed` then decides
186 * `read` for the guest. Return null, or leave it out, to answer 401. A
187 * guest never reaches another route.
188 *
189 * @example
190 * getGuestUser: ({ tenantId }) => ({ id: 'guest', tenantId, isGuest: true })
191 */
192 getGuestUser?: (input: {
193 tenantId: string | undefined
194 }) => U | null | Promise<U | null>
195 /**
196 * Let keyed (BYOK) adapters and `ctx.keys` fall back to the server's env
197 * vars. Default `false` when access is on.
198 */
199 allowServerEnvKeys?: boolean
200}
201
202/**
203 * Thrown when the host refuses an action: `isAllowed` returned `false`, or
204 * `host.revoke` took the access of the handle's user. The HTTP handler
205 * answers it with 403. Catch it with `instanceof AccessDeniedError`.
206 */
207export class AccessDeniedError extends Error {
208 readonly code = 'forbidden'
209 readonly action: AccessAction
210 readonly threadId: string
211
212 constructor({
213 action,
214 threadId,
215 }: {
216 action: AccessAction
217 threadId: string
218 }) {
219 super(`Access denied: ${action} on thread ${JSON.stringify(threadId)}.`)
220 this.name = 'AccessDeniedError'
221 this.action = action
222 this.threadId = threadId
223 }
224}
225
226/** Options for {@link membersOnly}. */
227export interface MembersOnlyOptions {
228 fork?: {
229 /**
230 * Who is a member of the new session after a fork.
231 *
232 * - `'self'` (default): only the user who forked it, as the owner.
233 * - `'all'`: the members of the source session too.
234 */
235 members?: 'self' | 'all'
236 }
237 operator?: {
238 /**
239 * The roles that have the `operator` action: they answer a `human` wait
240 * and reply as an operator. Default `['operator']`: only members with
241 * the role `operator`. The owner and plain members do not have it, so
242 * the user who waits for a person cannot act as that person.
243 */
244 roles?: ReadonlyArray<SessionMember['role']>
245 }
246}
247
248type Role = SessionMember['role']
249
250/** The role of a user in a session. */
251function roleOf(session: AccessSession, userId: string) {
252 return session.members.find((member) => member.userId === userId)?.role
253}
254
255/** The user id of the owner of a session, or `undefined` for no owner. */
256export function ownerOf(session: Pick<AccessSession, 'members'>) {
257 return session.members.find((member) => member.role === 'owner')?.userId
258}
259
260function allows(
261 role: Role,
262 { user, action, run }: AuthorizeInput,
263 operators: ReadonlyArray<Role>,
264) {
265 switch (action) {
266 case 'read':
267 case 'list':
268 return true
269 case 'send':
270 case 'fork':
271 return role === 'owner' || role === 'member'
272 case 'operator':
273 return operators.includes(role)
274 case 'answer':
275 case 'cancel': {
276 const startedTheRun = run?.userId === user.id
277 return role === 'owner' || (role === 'member' && startedTheRun)
278 }
279 case 'configure':
280 case 'share':
281 case 'delete':
282 case 'erase':
283 case 'transfer':
284 return role === 'owner'
285 }
286}
287
288/**
289 * Ready-made access rules: only the members of a session may use it, each
290 * with the limits of the member's role. Use it as the `rules` of `access`.
291 *
292 * - Owner: every action but `operator`.
293 * - Member: read, list, send, and fork. Answer and cancel only the runs
294 * that the member started.
295 * - Operator: read, list, and `operator` (answer a `human` wait, and reply
296 * as an operator).
297 * - Viewer: read and list.
298 * - Not a member: no action.
299 *
300 * `operator.roles` changes who has `operator`.
301 *
302 * The owner is the member with the role `owner`. `isAllowed` does not check
303 * the tenant: the host does that before it calls it. For a child thread, the
304 * host passes the root session, so it has no special rules for children.
305 *
306 * It also lists only the sessions of a member (`filterSessionList`), and turns on
307 * `host.sessions.share` and `unshare` (`members`).
308 *
309 * @param options - `fork.members` sets who is a member of a forked session.
310 * The default is `'self'`. `operator.roles` sets the roles with the
311 * `operator` action. The default is `['operator']`.
312 *
313 * @example
314 * access: {
315 * getUser: ({ request }) => findUser(request),
316 * rules: membersOnly({ fork: { members: 'self' } }),
317 * }
318 */
319export function membersOnly(
320 options: MembersOnlyOptions = {},
321): Required<AccessPolicy> {
322 const operators = options.operator?.roles ?? ['operator']
323 return {
324 isAllowed: (input) => {
325 const role = roleOf(input.session, input.user.id)
326 if (role === undefined) return false
327 return allows(role, input, operators)
328 },
329 filterSessionList: (user) => ({ memberId: user.id }),
330 members: { fork: options.fork?.members ?? 'self' },
331 }
332}