Open History to see the last commit
1import { isKeyedAdapter } from '@tanstack/ai'
2import { scrubSecrets } from '@tanstack/ai/byok'
3import {
4 envKeyEntry,
5 readCredential,
6 readCredentialEntry,
7 tenantScopeOf,
8} from '@tanstack/ai/byok/server'
9import type { ChatMiddleware, ProviderKeys, Scope } from '@tanstack/ai'
10import type {
11 ByokProvider,
12 Credential,
13 CredentialScope,
14 CredentialStore,
15 ProviderId,
16} from '@tanstack/ai/byok'
17
18// The harness API had its own copy. The core one is the only body now.
19export { scrubSecrets }
20
21/**
22 * @internal The id prefix of a secret answer in the credential store. A host
23 * that does not own the log saves the answer there, and the owner reads it
24 * once. Its credential type is `secret_answer`, which `list` hides.
25 */
26export const SECRET_ANSWER_PREFIX = 'harness:answer:'
27
28/**
29 * Thrown when a tool or command needs a credential the user has not saved.
30 * The session publishes `harness.auth_required`, so a host can show the
31 * sign-in link or run `/connect`.
32 */
33export class AuthRequiredError extends Error {
34 readonly connector: string
35 readonly url: string | undefined
36 constructor(connector: string, url?: string) {
37 super(
38 url
39 ? `Sign in to ${connector} first: ${url}`
40 : `Sign in to ${connector} first. Run /connect ${connector}.`,
41 )
42 this.name = 'AuthRequiredError'
43 this.connector = connector
44 this.url = url
45 }
46}
47
48/**
49 * The credentials of one user: the user of a run (`ctx.context.run`), or of
50 * a command. Reads and saves go to that user only.
51 */
52export interface CredentialsAccess {
53 get: (id: string) => Promise<Credential | null>
54 /**
55 * Like `get`, but throws {@link AuthRequiredError} when the credential is
56 * missing. With `wait: true`, a tool of a chat turn or of a background
57 * agent run waits for the sign-in instead: the run stops with an
58 * interrupt with the reason `'auth_required'`, a `sign-in` wait. When the
59 * credential is saved (for example by `connect:<id>`), the run goes on
60 * and the tool runs again. Cancel the interrupt to fail the tool. The
61 * wait expires after 15 minutes, and then the tool fails too. Do not pass
62 * `wait` elsewhere (a command, a hook): the credentials of a command never
63 * wait, and outside a run `wait` does nothing.
64 */
65 require: (id: string, options?: { wait?: boolean }) => Promise<Credential>
66 set: (entry: { id: string; credential: Credential }) => Promise<void>
67 /**
68 * Swap the saved credential `id` for a new one, for example an OAuth
69 * refresh. `update` gets the saved credential and returns the new one, or
70 * the same object to keep it. Resolves with the credential to use, or
71 * `null` when none is saved.
72 *
73 * - The new credential goes back to the scope where it was found. A
74 * tenant credential stays the tenant's, and is not copied to the user.
75 * - One host runs one `update` at a time per saved credential. A call
76 * that comes while one runs waits for it and gets its result.
77 * - When the store has `getVersioned` and `setIf`, the save is a
78 * compare-and-set. If another host saved first, the call uses that
79 * credential, and does not run `update` again.
80 * - `update` gets the signal of the host, not of a caller: an abort of
81 * `options.signal` rejects this call only, and the refresh goes on for
82 * the calls that wait for it.
83 */
84 refresh: (
85 id: string,
86 update: (current: Credential, signal: AbortSignal) => Promise<Credential>,
87 options?: { signal?: AbortSignal },
88 ) => Promise<Credential | null>
89 delete: (id: string) => Promise<void>
90 list: () => Promise<
91 Array<{ id: string; type: Credential['type']; expiresAt?: number }>
92 >
93}
94
95/**
96 * What a session adds to `credentialsFor`: `canWait` says if a `require`
97 * with `wait` can stop the turn now, and `onSet` runs after each save.
98 * `secrets` gets each secret value the access reads or saves, so the session
99 * can scrub them from what it stores, publishes, and sends to a model.
100 */
101export interface CredentialHooks {
102 canWait?: (id: string) => boolean
103 onSet?: (id: string) => Promise<void>
104 secrets?: Redactor
105 /**
106 * The refreshes that run now, shared by every access of one host. See
107 * {@link RefreshFlights}. Without it, only the calls of this access share
108 * a refresh.
109 */
110 refreshes?: RefreshFlights
111}
112
113/**
114 * @internal The refreshes of one host. A host keeps one for all its
115 * sessions.
116 */
117export interface RefreshFlights {
118 /** The refresh that runs now for each saved credential, by {@link refreshKey}. */
119 running: Map<string, Promise<Credential | null>>
120 /** The signal of each refresh. The host aborts it when it closes. */
121 signal: AbortSignal
122}
123
124/** A {@link RefreshFlights} whose signal aborts with `controller`. */
125export function refreshFlights(
126 controller = new AbortController(),
127): RefreshFlights {
128 return { running: new Map(), signal: controller.signal }
129}
130
131/**
132 * `promise`, or a rejection with the reason of `signal` when it aborts
133 * first. The work of `promise` goes on.
134 */
135function untilAborted<T>(promise: Promise<T>, signal?: AbortSignal) {
136 if (!signal) return promise
137 if (signal.aborted) return Promise.reject<T>(signal.reason)
138 return new Promise<T>((resolve, reject) => {
139 const onAbort = () => reject(signal.reason)
140 signal.addEventListener('abort', onAbort, { once: true })
141 promise
142 .then(resolve, reject)
143 .finally(() => signal.removeEventListener('abort', onAbort))
144 })
145}
146
147/** The key of one saved credential: its tenant, its user, and its id. */
148const refreshKey = (scope: CredentialScope, id: string) =>
149 JSON.stringify([scope.tenantId ?? null, scope.userId ?? null, id])
150
151/**
152 * The error that chat() reads as "stop the turn for input" (the shape of
153 * `MCPInputRequiredError`), with the reason `'auth_required'`.
154 */
155function signInRequired(error: AuthRequiredError) {
156 return Object.assign(new Error(error.message), {
157 name: 'MCPInputRequiredError',
158 kind: 'form' as const,
159 reason: 'auth_required',
160 request: {
161 connector: error.connector,
162 ...(error.url ? { url: error.url } : {}),
163 },
164 })
165}
166
167function secretValues(credential: Credential) {
168 if (credential.type !== 'oauth') return [credential.value]
169 const { accessToken, refreshToken, client } = credential
170 return [accessToken, refreshToken, client?.clientSecret].filter(
171 (value) => value !== undefined,
172 )
173}
174
175/**
176 * Scope credentials to one user and thread.
177 *
178 * A read finds the user's own credential first, then the tenant's (saved
179 * without a `userId`). A save or a delete changes the user's own only. A
180 * `refresh` writes back to the scope where it found the credential.
181 */
182export function credentialsFor(
183 store: CredentialStore,
184 scope: Scope,
185 onMissing: (error: AuthRequiredError) => void,
186 hooks?: CredentialHooks,
187): CredentialsAccess {
188 const secrets = hooks?.secrets
189 const keep = (credential: Credential | null) => {
190 for (const value of credential ? secretValues(credential) : []) {
191 secrets?.add(value)
192 }
193 return credential
194 }
195 const get = async (id: string) => keep(await readCredential(store, scope, id))
196 const flights = hooks?.refreshes ?? refreshFlights()
197 type Entry = NonNullable<Awaited<ReturnType<typeof readCredentialEntry>>>
198 /** True when the saved credential is not the one in `seen` any more. */
199 const isChanged = (seen: Entry, now: Entry) =>
200 seen.revision !== undefined && now.revision !== undefined
201 ? seen.revision !== now.revision
202 : JSON.stringify(seen.credential) !== JSON.stringify(now.credential)
203 const runRefresh = async (
204 id: string,
205 seen: Entry,
206 update: (current: Credential, signal: AbortSignal) => Promise<Credential>,
207 ): Promise<Credential | null> => {
208 let next: Credential
209 try {
210 next = await update(seen.credential, flights.signal)
211 } catch (error) {
212 // Another host can refresh first and use up the refresh token, so
213 // this refresh fails. Then the token that host saved wins.
214 const now = await readCredentialEntry(store, scope, id)
215 if (now && isChanged(seen, now)) return now.credential
216 throw error
217 }
218 if (next === seen.credential) return next
219 if (store.setIf && seen.revision !== undefined) {
220 const saved = await store.setIf({
221 scope: seen.scope,
222 id,
223 credential: next,
224 expectedRevision: seen.revision,
225 })
226 if (saved.ok) return next
227 // Another host saved first. Use its credential, and do not refresh
228 // again: with refresh token rotation, a second refresh can revoke
229 // both tokens.
230 return (await readCredentialEntry(store, scope, id))?.credential ?? null
231 }
232 // A store without `getVersioned` and `setIf` has no compare-and-set.
233 // Then the refresh is single-flight on this host only: two hosts can
234 // refresh at the same time, and the last save wins.
235 await store.set({ scope: seen.scope, id, credential: next })
236 return next
237 }
238 const access: CredentialsAccess = {
239 get,
240 require: async (id, options) => {
241 const credential = await get(id)
242 if (credential) return credential
243 const error = new AuthRequiredError(id)
244 onMissing(error)
245 if (options?.wait && hooks?.canWait?.(id)) throw signInRequired(error)
246 throw error
247 },
248 set: async ({ id, credential }) => {
249 keep(credential)
250 await store.set({ scope, id, credential })
251 await hooks?.onSet?.(id)
252 },
253 refresh: async (id, update, options) => {
254 options?.signal?.throwIfAborted()
255 const seen = await readCredentialEntry(store, scope, id)
256 if (!seen) return null
257 // Keyed by the scope where the credential is, so the users of one
258 // tenant credential share one refresh too.
259 const key = refreshKey(seen.scope, id)
260 let flight = flights.running.get(key)
261 if (!flight) {
262 // The calls that join use the first call's `update`. It runs with
263 // the host signal, so an abort of one caller stops no other caller.
264 flight = runRefresh(id, seen, update).finally(() => {
265 flights.running.delete(key)
266 })
267 flights.running.set(key, flight)
268 }
269 return keep(await untilAborted(flight, options?.signal))
270 },
271 delete: (id) => store.delete({ scope, id }),
272 list: async () => {
273 // A secret answer that the harness keeps is not the user's own.
274 const saved = async (at: CredentialScope) =>
275 (await store.list(at)).filter((item) => item.type !== 'secret_answer')
276 const tenant = tenantScopeOf(scope)
277 const own = await saved(scope)
278 if (!tenant) return own
279 const shared = await saved(tenant)
280 return [
281 ...own,
282 ...shared.filter((item) => !own.some((o) => o.id === item.id)),
283 ]
284 },
285 }
286 return access
287}
288
289/**
290 * The provider keys of the user of `credentials`. A key is the `api_key`
291 * credential saved under the provider id (`/connect <id>` saves it), else
292 * the first `provider.env` name that is set. With `envFallback: false`, env
293 * vars are not read. A missing key calls `onMissing` and throws
294 * {@link AuthRequiredError}, so the user sees `/connect <id>`. A key read
295 * from env goes in `secrets`, like a saved credential.
296 */
297export function providerKeysFor(
298 credentials: CredentialsAccess,
299 onMissing: (error: AuthRequiredError) => void,
300 { secrets, envFallback }: { secrets?: Redactor; envFallback: boolean },
301) {
302 const providerIdOf = (provider: ByokProvider | ProviderId) =>
303 typeof provider === 'string' ? provider : provider.id
304 const get = async (provider: ByokProvider | ProviderId) => {
305 const saved = await credentials.get(providerIdOf(provider))
306 if (saved?.type === 'api_key') return saved.value
307 if (!envFallback) return null
308 const fromEnv = envKeyEntry(provider)?.value
309 if (fromEnv) secrets?.add(fromEnv)
310 return fromEnv ?? null
311 }
312 const requireKey = async (provider: ByokProvider | ProviderId) => {
313 const key = await get(provider)
314 if (key !== null) return key
315 const error = new AuthRequiredError(providerIdOf(provider))
316 onMissing(error)
317 throw error
318 }
319 const keys: ProviderKeys = {
320 get,
321 require: requireKey,
322 adapter: async (adapter) =>
323 isKeyedAdapter(adapter)
324 ? adapter.create(await requireKey(adapter.provider))
325 : adapter,
326 }
327 return keys
328}
329
330/**
331 * @internal The secret values that one session handed out, and the scrub of
332 * them. The session sends each log record, feed event, and model call
333 * through it. See {@link createRedactor}.
334 */
335export type Redactor = ReturnType<typeof createRedactor>
336
337/**
338 * @internal A {@link Redactor} with no secret yet.
339 *
340 * `redact` never changes its input. It returns the same value when no
341 * secret is in it, so a check of identity downstream stays cheap.
342 */
343export function createRedactor() {
344 const values: Array<string> = []
345 /** Each form that `scrubSecrets` replaces: raw, JSON-escaped, URL-encoded. */
346 const forms: Array<string> = []
347
348 /**
349 * Scrub `value` from now on: a string, or each string in an array or a
350 * plain object (a secret answer with fields). A string shorter than 6
351 * characters is left.
352 */
353 const add = (value: unknown): void => {
354 if (typeof value === 'object' && value !== null) {
355 for (const item of Object.values(value)) add(item)
356 return
357 }
358 if (typeof value !== 'string' || value.length < 6) return
359 if (values.includes(value)) return
360 values.push(value)
361 for (const form of [
362 value,
363 JSON.stringify(value).slice(1, -1),
364 encodeURIComponent(value),
365 ]) {
366 if (!forms.includes(form)) forms.push(form)
367 }
368 }
369
370 /** `text` without the secrets. The same string when it has none. */
371 const scrub = (text: string): string => {
372 // A quick check first, so a text without a secret makes no copy.
373 for (const form of forms) {
374 if (text.includes(form)) return scrubSecrets(text, values)
375 }
376 return text
377 }
378
379 /** `items` with their secrets scrubbed, or `undefined` when none changed. */
380 const walkAll = (items: Array<unknown>) => {
381 let isChanged = false
382 const next = items.map((item) => {
383 const walked = walk(item)
384 if (walked !== item) isChanged = true
385 return walked
386 })
387 return isChanged ? next : undefined
388 }
389
390 /** `value` with its secrets scrubbed. A changed container is a copy. */
391 const walk = (value: unknown): unknown => {
392 if (typeof value === 'string') return scrub(value)
393 if (typeof value !== 'object' || value === null) return value
394 if (Array.isArray(value)) return walkAll(value) ?? value
395 // Each entry is a fresh `[key, value]` array, so an entry that did not
396 // change comes back as it is.
397 if (value instanceof Map) {
398 const entries = walkAll([...value])
399 return entries ? new Map(entries as Array<[unknown, unknown]>) : value
400 }
401 if (value instanceof Set) {
402 const items = walkAll([...value])
403 return items ? new Set(items) : value
404 }
405 // ponytail: other class instances (`Uint8Array`, `Date`, an app class)
406 // stay as they are, since a copy could break them. Walk them if a
407 // plugin keeps a secret in one.
408 const proto: unknown = Object.getPrototypeOf(value)
409 if (proto !== Object.prototype && proto !== null) return value
410 const record = value as Record<string, unknown>
411 let copy: Record<string, unknown> | undefined
412 for (const key of Object.keys(record)) {
413 const item = record[key]
414 const next = walk(item)
415 if (next === item) continue
416 copy ??= Object.assign(Object.create(proto) as object, record)
417 copy[key] = next
418 }
419 return copy ?? value
420 }
421
422 return {
423 /** No secret to scrub yet. Then `redact` and `scrub` do no work. */
424 get isEmpty(): boolean {
425 return forms.length === 0
426 },
427 add,
428 scrub,
429 /**
430 * `value` with each string in it scrubbed, in arrays, plain objects,
431 * `Map`s, and `Set`s at any depth. A changed container is a copy. Other
432 * values (numbers, class instances like `Uint8Array`) stay as they are.
433 */
434 redact: <T>(value: T): T =>
435 forms.length === 0 ? value : (walk(value) as T),
436 }
437}
438
439/**
440 * @internal The model gets the context without the secrets of `redactor`.
441 * Put it after `mediaMiddleware`, so no later middleware sets the messages
442 * again. The transcript itself is not changed here: the log view scrubs it.
443 */
444export function redactMiddleware(redactor: Redactor): ChatMiddleware {
445 return {
446 name: 'harness:redact',
447 onConfig(_ctx, config) {
448 if (redactor.isEmpty) return undefined
449 const messages = config.providerMessages ?? config.messages
450 const providerMessages = redactor.redact(messages)
451 const systemPrompts = redactor.redact(config.systemPrompts)
452 if (
453 providerMessages === messages &&
454 systemPrompts === config.systemPrompts
455 ) {
456 return undefined
457 }
458 return { providerMessages, systemPrompts }
459 },
460 }
461}