Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

auth.md

332 lines15.9 KB

1---
2title: Auth and connectors
3id: harness-auth
4order: 7
5description: "Let users sign in to GitHub and other OAuth services from the harness. Tokens stay in your credential store and never reach the model."
6keywords:
7 - tanstack ai
8 - harness
9 - oauth
10 - connectors
11 - credentials
12---
13​
14Your agent needs to open a pull request, so it needs the user's GitHub token. The user should sign in once, in the browser, and the model should never see the token. `oauthConnector` does that: it adds `/connect github`, stores the token, and hands it to your tools.
15​
16## 1. Add a connector
17​
18```ts group=harness-auth
19import { toolDefinition } from '@tanstack/ai'
20import { defineHarness, oauthConnector } from '@tanstack/ai-harness'
21import { openaiText } from '@tanstack/ai-openai'
22import type { HarnessRunContext } from '@tanstack/ai-harness'
23​
24const github = oauthConnector({
25 id: 'github',
26 label: 'GitHub',
27 // The harness runs on the user's machine (a CLI), so open a browser here.
28 login: 'loopback',
29 oauth: {
30 authorizationUrl: 'https://github.com/login/oauth/authorize',
31 tokenUrl: 'https://github.com/login/oauth/access_token',
32 deviceUrl: 'https://github.com/login/device/code',
33 clientId: 'your-github-oauth-app-client-id',
34 scopes: ['repo'],
35 },
36 tools: (token) => [
37 toolDefinition({ name: 'list_issues', description: 'List my open issues' }).server<HarnessRunContext>(
38 async (_args, ctx) => {
39 const response = await fetch('https://api.github.com/issues', {
40 headers: { authorization: `Bearer ${await token({ run: ctx.context.run })}` },
41 })
42 return response.json()
43 },
44 ),
45 ],
46})
47​
48export const assistant = defineHarness({
49 name: 'acme/assistant',
50 adapter: openaiText('gpt-6.1-sol'),
51 plugins: () => [github],
52})
53```
54​
55`token({ run })` returns a fresh access token of the user of that run. If the token is expired and the service gave a refresh token, `token` refreshes it first, one time for all the calls that need it. See [Refresh a token](#refresh-a-token). Pass the `run` of the tool call, `ctx.context.run`, so each user gets their own token. See [Act as the user of a run](./plugins#act-as-the-user-of-a-run).
56​
57## 2. Sign in
58​
59- The user runs `/connect github`.
60- With `login: 'loopback'`, the CLI opens the browser. The harness listens on `127.0.0.1` on a random port for one callback, with PKCE and a random `state`.
61- With `oauth.issuer` set, the sign-in refuses a code that the service sends with another `iss` (RFC 9207).
62- The token goes into the credential store. `/disconnect github` deletes it.
63- A cancel of the command, or a close of the session, stops a sign-in that waits. The listener on `127.0.0.1` closes at once.
64​
65`login` is required. Use `login: 'device'` for a harness on a server, and for SSH sessions, containers, and CI. The user then gets a code to enter on the service's page. Device login needs `oauth.deviceUrl`.
66​
67If a tool runs before sign-in, it stops with a `harness.auth_required` event. The CLI shows which service to connect. In your own app, `session.onAuthRequired` tells you which service to show:
68​
69```ts group=harness-auth-prompt
70import type { HarnessSession } from '@tanstack/ai-harness'
71​
72export function showSignIns(session: HarnessSession) {
73 // Call the returned function to stop the calls.
74 return session.onAuthRequired(({ connector, url, userCode }) => {
75 console.log(`Sign in to ${connector}: ${url ?? `run /connect ${connector}`}`)
76 if (userCode) console.log(`Enter this code on that page: ${userCode}`)
77 })
79```
80​
81## Wait for the sign-in
82​
83A turn from a background agent or an email runs while nobody watches it. That turn can need a sign-in. Without a sign-in, the tool fails, and the work of that turn stops. Pass `wait: true` to `token`. Then the turn waits for the sign-in and continues after it.
84​
85```ts group=harness-auth-wait
86import { toolDefinition } from '@tanstack/ai'
87import { defineHarness, oauthConnector } from '@tanstack/ai-harness'
88import { openaiText } from '@tanstack/ai-openai'
89import type { HarnessRunContext } from '@tanstack/ai-harness'
90​
91const github = oauthConnector({
92 id: 'github',
93 label: 'GitHub',
94 // The server cannot open a browser for the user, so show a code.
95 login: 'device',
96 oauth: {
97 authorizationUrl: 'https://github.com/login/oauth/authorize',
98 tokenUrl: 'https://github.com/login/oauth/access_token',
99 deviceUrl: 'https://github.com/login/device/code',
100 clientId: 'your-github-oauth-app-client-id',
101 scopes: ['repo'],
102 },
103 tools: (token) => [
104 toolDefinition({ name: 'list_issues', description: 'List my open issues' }).server<HarnessRunContext>(
105 async (_args, ctx) => {
106 const response = await fetch('https://api.github.com/issues', {
107 headers: { authorization: `Bearer ${await token({ run: ctx.context.run, wait: true })}` },
108 })
109 return response.json()
110 },
111 ),
112 ],
113})
114​
115export const assistant = defineHarness({
116 name: 'acme/assistant',
117 adapter: openaiText('gpt-6.1-sol'),
118 plugins: () => [github],
119 // A web app starts the sign-in with this command.
120 expose: { commands: ['connect:github'] },
121})
122```
123​
124In a tool of your own plugin, use `ctx.context.run.credentials.require('github', { wait: true })`.
125​
126When the credential is missing, the turn stops with an interrupt:
127​
128- The interrupt has `reason: 'auth_required'`. Its `metadata['tanstack:interruptPayload'].request.connector` is `'github'`.
129- The sign-in belongs to the sender of the stopped turn. When that person saves the credential, the same turn continues as that person, and the tool runs again. The save can be `/connect github`, the `connect:github` command, or `run.credentials.set` in a command of your own.
130- A credential that another person saves never continues the turn.
131- To stop the wait, resolve the interrupt with `status: 'cancelled'`. Then the tool fails, the same as without `wait`.
132- On a [durable host](./durable-sessions), the wait continues after a restart.
133- `wait` is for a tool of the running chat turn. Do not pass it in a command, a background agent, or a hook. The credentials of a command never wait.
134- Provider keys (`run.keys.require`) do not wait.
135​
136In a web app, the wait shows in `state.signIns` of the session view, also after a reload. When the user presses your connect button, run the connector command. Each sign-in then has the `url` and the `userCode` to show. A client can run only the commands in `expose.commands`, so the harness above exposes `connect:github` (see [Choose what clients can change](./connect#choose-what-clients-can-change)):
137​
138```ts group=harness-auth-wait-client
139import { createHarnessClient } from '@tanstack/ai-harness/client'
140import { createSessionView } from '@tanstack/ai-harness/view'
141​
142const view = createSessionView(
143 createHarnessClient({ url: '/api/harness', threadId: 'user-1-thread' }),
145​
146view.on('signIn', (signIn) => {
147 console.log(`Connect ${signIn.connector} to continue the turn.`)
148})
149​
150export const connectGithub = () => view.runCommand({ name: 'connect:github' })
151```
152​
153After the sign-in, the turn finishes its work with no new message.
154​
155## Keep credentials
156​
157Pass a credential store to the host. The host reads credentials from it, keyed by the user of each run. Without one, credentials live in memory until the process stops. When several people write in one thread, see [Share a thread between people](./shared-threads).
158​
159```ts group=harness-auth
160import { defineCredentialStore } from '@tanstack/ai/byok'
161import type { Credential } from '@tanstack/ai/byok'
162​
163const saved = new Map<string, Credential>()
164const keyOf = (userId: string | undefined, id: string) => `${userId ?? 'tenant'}:${id}`
165​
166export const credentials = defineCredentialStore({
167 get: async ({ scope, id }) => saved.get(keyOf(scope.userId, id)) ?? null,
168 set: async ({ scope, id, credential }) => {
169 saved.set(keyOf(scope.userId, id), credential)
170 },
171 delete: async ({ scope, id }) => {
172 saved.delete(keyOf(scope.userId, id))
173 },
174 list: async (scope) =>
175 [...saved.entries()]
176 .filter(([key]) => key.startsWith(`${scope.userId ?? 'tenant'}:`))
177 .map(([key, credential]) => ({ id: key.split(':')[1] ?? key, type: credential.type })),
178})
179```
180​
181```ts group=harness-auth
182import { createHarnessHost } from '@tanstack/ai-harness'
183​
184export const host = createHarnessHost({ credentials })
185```
186​
187The store can be a table in your own database or a secrets manager. See the rules in [Write a store for production](../advanced/server-keys#write-a-store-for-production).
188​
189- Encrypt tokens at rest in a real store.
190- `list` returns ids and types only, never the secret values.
191- The harness keeps a secret answer in the store for a short time, with the type `secret_answer`. Leave that type out of a list of connected accounts. See [Secret answers on another host](./durable-sessions#secret-answers-on-another-host).
192- A credential saved without a `userId` belongs to the whole tenant. A user who has no credential of their own uses it. See [Share one credential with the whole organization](./shared-threads#share-one-credential-with-the-whole-organization).
193- If more than one host uses the store, add `getVersioned` and `setIf`. Then two hosts do not both save a refreshed token. See [Add compare-and-set](../advanced/server-keys#add-compare-and-set).
194​
195## Read credentials in your own plugin
196​
197Your plugin reads the credentials of the user of each run:
198​
199- In a tool or a middleware hook, `ctx.context.run.credentials.require('github')` returns the credential. Before the user signs in, it stops with `auth_required`.
200- In a command, use `run.credentials` of the command context.
201- The `ctx.credentials` of a session plugin have no user, so each call throws.
202​
203See [Act as the user of a run](./plugins#act-as-the-user-of-a-run).
204​
205## Keep tokens out of the log and the model
206​
207A tool can show a token by mistake: an error message with the request URL, or a debug field in its result. The session replaces each secret that it gave out with `[redacted]` before it keeps or sends anything.
208​
209The secrets that the session knows:
210​
211- The provider keys of `run.keys`, also a key from an env var.
212- The credentials of `run.credentials` and of the connectors: API keys, OAuth tokens, and the OAuth client secret.
213- The answer to a question with `secret: true`. For an answer with fields, each string field.
214​
215Where the session replaces them:
216​
217- The session log: your records, the transcript, plugin state (also in a `Map` or a `Set`), notes, and tool results.
218- The events that clients get.
219- The model context, so the model never sees a secret.
220- The error frames of the HTTP handler, the WebSocket, and the stdio worker.
221​
222A [durable step](./durable-tools) value with a secret throws, so the log never keeps it. Read the secret outside `step.do`.
223​
224The session finds the raw value, its JSON-escaped form, and its URL-encoded form. It does not find:
225​
226- A value shorter than 6 characters. So a short value does not remove common words.
227- A secret that a stream splits across two deltas, in those two events. The message in the transcript does not have the secret.
228- A secret that is JSON-escaped two times.
229- A secret in an instance of your own class, a `Date`, or a typed array in plugin state.
230​
231To scrub a text of your own, use `scrubSecrets(text, secrets)` from `@tanstack/ai/byok`. It uses the same rules.
232​
233## Write your own sign-in command
234​
235`oauthConnector` covers most services. For a sign-in of your own, use the helpers from `@tanstack/ai-harness/oauth`. Pass the `signal` of the command, so a cancel stops the sign-in at once:
236​
237```ts group=harness-auth-own
238import { defineCommand, definePlugin } from '@tanstack/ai-harness'
239import { deviceLogin, isExpired, refreshCredential } from '@tanstack/ai-harness/oauth'
240import type { OAuthConfig } from '@tanstack/ai-harness/oauth'
241​
242const gitlab: OAuthConfig = {
243 authorizationUrl: 'https://gitlab.com/oauth/authorize',
244 tokenUrl: 'https://gitlab.com/oauth/token',
245 deviceUrl: 'https://gitlab.com/oauth/authorize_device',
246 clientId: 'your-gitlab-app-client-id',
247 scopes: ['read_api'],
249​
250export const gitlabLogin = definePlugin({
251 name: 'acme/gitlab-login',
252 setup: (ctx) => ({
253 commands: {
254 'connect:gitlab': defineCommand({
255 description: 'Sign in to GitLab',
256 run: async (_input, { credentials, signal }) => {
257 const credential = await deviceLogin(gitlab, {
258 onCode: ({ userCode, verificationUri }) =>
259 ctx.session.authRequired({ connector: 'gitlab', url: verificationUri, userCode }),
260 signal,
261 })
262 await credentials.set({ id: 'gitlab', credential })
263 return 'Connected to GitLab.'
264 },
265 }),
266 },
267 }),
268})
269```
270​
271- `deviceLogin`, `loopbackLogin`, `exchangeCode`, and `refreshCredential` take a `signal`. When it aborts, the call stops at once and rejects with the reason of the signal.
272- The `signal` of a command aborts on a cancel of the command and on a close of the session.
273- `loopbackLogin` takes `timeoutMs`. The default is 10 minutes. This timer does not keep the process alive.
274- When another library runs the OAuth flow, `startLoopbackReceiver({ timeoutMs, signal })` only waits for the callback. `waitForCode(state)` gives the code and the `iss` of the callback.
275​
276### Refresh a token
277​
278An access token expires, and several tool calls can need it at the same time. Some services rotate the refresh token: after one refresh, the old refresh token stops working. Then a second refresh at the same time fails, and the user must sign in again.
279​
280`run.credentials.refresh(id, update, { signal })` runs one refresh, and every caller gets its result:
281​
282```ts group=harness-auth-own
283import { toolDefinition } from '@tanstack/ai'
284import type { HarnessRunContext } from '@tanstack/ai-harness'
285​
286export const gitlabProjects = toolDefinition({
287 name: 'gitlab_projects',
288 description: 'List my GitLab projects',
289}).server<HarnessRunContext>(async (_args, ctx) => {
290 const { credentials, signal } = ctx.context.run
291 let credential = await credentials.require('gitlab')
292 if (isExpired(credential)) {
293 const fresh = await credentials.refresh(
294 'gitlab',
295 // Another call can refresh first. Then keep its credential.
296 (current, hostSignal) =>
297 isExpired(current)
298 ? refreshCredential(gitlab, current, { signal: hostSignal })
299 : Promise.resolve(current),
300 { signal },
301 )
302 // The user disconnected meanwhile: ask for a sign-in.
303 credential = fresh ?? (await credentials.require('gitlab'))
304 }
305 const token = credential.type === 'oauth' ? credential.accessToken : credential.value
306 const response = await fetch('https://gitlab.com/api/v4/projects?membership=true', {
307 headers: { authorization: `Bearer ${token}` },
308 signal,
309 })
310 return response.json()
311})
312```
313​
314`update` gets the saved credential and returns the new one. Return `current` to keep it. `refresh` resolves with the credential to use, or `null` when none is saved. `oauthConnector` refreshes with `refresh` too.
315​
316What `refresh` does:
317​
318- One host runs one `update` at a time for each saved credential. A call that comes while one runs waits for it, and gets the same credential.
319- It saves the new credential to the scope where it found it. A tenant token stays the tenant's, so every user of the tenant gets the new token.
320- If the store has `getVersioned` and `setIf`, the save is a compare-and-set. When another host saved first, the call uses that token and does not refresh again.
321- Without that pair, the one-at-a-time rule is per host only. Two hosts can refresh at the same time, and the last save wins.
322- `update` gets a signal of the host, which only `host.close()` aborts. An abort of your `signal` rejects only your call. The refresh goes on for the other calls.
323​
324`refreshCredential` keeps the OAuth `client` of the old credential, so the next refresh has it too.
325​
326## What you have now
327​
328- Browser and device-code sign-in for any OAuth service, and sign-ins of your own that stop at once on a cancel.
329- Tools that get a fresh token without the model seeing it.
330- One refresh for each expired token, also on many hosts.
331- A log, events, and a model context with `[redacted]` in place of each secret.
332- Turns that wait for a sign-in and then finish their work.