Open History to see the last commit
1import {
2 ByokBlockedError,
3 byokHeaderName,
4 isProviderId,
5 maskKey,
6} from '@tanstack/ai/byok'
7import { memoryStorage } from './storage'
8import type { ByokProvider, ProviderId } from '@tanstack/ai/byok'
9import type { Keyring, KeyringStorage } from './storage'
10
11export type KeyStatus =
12 | { state: 'empty' }
13 | { state: 'set'; masked: string }
14 | { state: 'locked'; masked: string }
15 | { state: 'error'; masked: string; message: string }
16
17export type ByokPrompt = {
18 provider: ProviderId
19 reason: 'missing' | 'locked'
20}
21
22export type ByokSnapshot = {
23 status: Partial<Record<string, KeyStatus>>
24 locked: boolean
25 prompt: ByokPrompt | null
26 storageError: string | null
27}
28
29export interface DefineByokOptions {
30 storage?: KeyringStorage
31 /**
32 * Descriptors whose `with` companions the store expands: `headers()` and
33 * `prepare()` for such a provider cover its companions too.
34 */
35 providers?: ReadonlyArray<ByokProvider>
36}
37
38export const EMPTY_BYOK_SNAPSHOT: ByokSnapshot = {
39 status: {},
40 locked: false,
41 prompt: null,
42 storageError: null,
43}
44
45const registeredProviderIds = new WeakMap<ByokClient, Array<ProviderId>>()
46
47/**
48 * Provider to stamp when the caller did not pass a slug.
49 * One saved key wins. Else the only provider listed in `defineByok({ providers })`.
50 */
51export function byokFallbackProviderId(byok: ByokClient) {
52 const savedIds = Object.entries(byok.keys())
53 .filter((entry) => Boolean(entry[1]))
54 .map((entry) => entry[0])
55 .filter(isProviderId)
56 if (savedIds.length === 1) return savedIds[0]
57 const registered = registeredProviderIds.get(byok) ?? []
58 if (registered.length === 1) return registered[0]
59 return undefined
60}
61
62function requireProviderId(value: string): ProviderId {
63 if (!isProviderId(value)) {
64 throw new Error(`Invalid BYOK provider id: ${value}`)
65 }
66 return value
67}
68
69function errorMessage(error: unknown, fallback: string): string {
70 return error instanceof Error && error.message.length > 0
71 ? error.message
72 : fallback
73}
74
75function isByokCeremonyCancel(error: unknown): boolean {
76 if (
77 typeof DOMException !== 'undefined' &&
78 error instanceof DOMException &&
79 error.name === 'NotAllowedError'
80 ) {
81 return true
82 }
83 if (error instanceof Error) {
84 if (error.name === 'NotAllowedError') return true
85 const message = error.message.toLowerCase()
86 return message.includes('cancelled') || message.includes('not allowed')
87 }
88 return false
89}
90
91function sanitizeKeyring(value: unknown): Keyring {
92 if (typeof value !== 'object' || value === null) return {}
93 const keys: Keyring = {}
94 for (const [provider, key] of Object.entries(value)) {
95 if (isProviderId(provider) && typeof key === 'string' && key.length > 0) {
96 keys[provider] = key
97 }
98 }
99 return keys
100}
101
102export class ByokClient {
103 readonly storage: KeyringStorage
104 #keys: Keyring = {}
105 #statuses: Partial<Record<string, KeyStatus>> = {}
106 #locked: boolean
107 #prompt: ByokPrompt | null = null
108 #coverageAll = false
109 #coverage: Record<string, boolean> = {}
110 readonly #companions: Record<string, Array<ProviderId>> = {}
111 readonly #listeners = new Set<() => void>()
112 #snapshot: ByokSnapshot
113 #storageError: string | null = null
114 readonly #ready: Promise<void>
115
116 constructor(options: DefineByokOptions = {}) {
117 this.storage = options.storage ?? memoryStorage()
118 const registered: Array<ProviderId> = []
119 for (const provider of options.providers ?? []) {
120 const id = requireProviderId(provider.id)
121 registered.push(id)
122 if (provider.with?.length) {
123 this.#companions[id] = provider.with.map((companion) =>
124 requireProviderId(companion.id),
125 )
126 }
127 }
128 registeredProviderIds.set(this, registered)
129 this.#locked = Boolean(this.storage.unlockable)
130 this.#snapshot = this.#buildSnapshot()
131 this.#ready = this.#hydrate()
132 }
133
134 /** Resolves when constructor hydration (peek/load) finishes. */
135 ready = (): Promise<void> => this.#ready
136
137 subscribe = (listener: () => void): (() => void) => {
138 this.#listeners.add(listener)
139 return () => {
140 this.#listeners.delete(listener)
141 }
142 }
143
144 getSnapshot = (): ByokSnapshot => this.#snapshot
145
146 #buildSnapshot(): ByokSnapshot {
147 return {
148 status: { ...this.#statuses },
149 locked: this.#locked,
150 prompt: this.#prompt,
151 storageError: this.#storageError,
152 }
153 }
154
155 keys(): Keyring {
156 return { ...this.#keys }
157 }
158
159 request(provider: ProviderId, reason: ByokPrompt['reason']): void {
160 this.#prompt = { provider: requireProviderId(provider), reason }
161 this.#emit()
162 }
163
164 /**
165 * `true` — the server can fill any slug from env.
166 * `false` — no env coverage.
167 * A record merges per-id flags and clears the all/none boolean.
168 */
169 setServerCoverage(flags: boolean | Readonly<Record<string, boolean>>): void {
170 if (typeof flags === 'boolean') {
171 this.#coverageAll = flags
172 this.#coverage = {}
173 return
174 }
175 this.#coverageAll = false
176 this.#coverage = { ...this.#coverage, ...flags }
177 }
178
179 #hasCoverage(provider: string): boolean {
180 return this.#coverageAll || this.#coverage[provider] === true
181 }
182
183 /** The slug plus every companion declared on its descriptor. */
184 #expand(provider: ProviderId): Array<ProviderId> {
185 return [provider, ...(this.#companions[provider] ?? [])]
186 }
187
188 headers(provider?: ProviderId): Record<string, string> {
189 const headers: Record<string, string> = {}
190 if (provider) {
191 requireProviderId(provider)
192 for (const id of this.#expand(provider)) {
193 const key = this.#keys[id]
194 if (key) headers[byokHeaderName(id)] = key
195 }
196 return headers
197 }
198 for (const [id, key] of Object.entries(this.#keys)) {
199 if (key) headers[byokHeaderName(id)] = key
200 }
201 return headers
202 }
203
204 async prepare(provider?: ProviderId): Promise<void> {
205 await this.#ready
206 if (this.storage.unlockable && this.#locked) {
207 await this.unlock()
208 }
209 if (!provider) return
210 requireProviderId(provider)
211 for (const id of this.#expand(provider)) {
212 if (this.#keys[id] || this.#hasCoverage(id)) continue
213 this.request(id, 'missing')
214 throw new ByokBlockedError(id, 'missing')
215 }
216 }
217
218 async update(
219 providerOrKey: ProviderId | string,
220 key?: string,
221 ): Promise<void> {
222 await this.#ready
223 let provider: ProviderId
224 let nextKey: string
225 if (key === undefined) {
226 if (!this.#prompt) {
227 throw new Error('byok.update(key) cannot run when prompt is null')
228 }
229 provider = this.#prompt.provider
230 nextKey = providerOrKey
231 } else {
232 provider = requireProviderId(providerOrKey)
233 nextKey = key
234 }
235 nextKey = nextKey.trim()
236 if (nextKey.length === 0) {
237 throw new Error('BYOK key must be non-empty')
238 }
239 if (this.storage.unlockable && this.#locked) {
240 await this.unlock()
241 }
242 const previousKeys = this.#keys
243 const previousStatuses = { ...this.#statuses }
244 const previousLocked = this.#locked
245 const previousPrompt = this.#prompt
246 const previousStorageError = this.#storageError
247 const next = { ...this.#keys, [provider]: nextKey }
248 try {
249 await this.storage.save(next)
250 } catch (error) {
251 this.#keys = previousKeys
252 this.#statuses = previousStatuses
253 this.#locked = previousLocked
254 this.#prompt = previousPrompt
255 this.#storageError = previousStorageError
256 this.#statuses[provider] = {
257 state: 'error',
258 masked: maskKey(nextKey),
259 message: errorMessage(error, `Failed to persist ${provider} key`),
260 }
261 this.#emit()
262 throw error
263 }
264 this.#keys = next
265 this.#statuses[provider] = { state: 'set', masked: maskKey(nextKey) }
266 this.#locked = false
267 this.#prompt = null
268 this.#storageError = null
269 this.#emit()
270 }
271
272 async clear(provider?: ProviderId): Promise<void> {
273 await this.#ready
274 if (provider) {
275 requireProviderId(provider)
276 if (this.storage.unlockable && this.#locked) {
277 await this.unlock()
278 }
279 const previousKeys = this.#keys
280 const previousStatuses = { ...this.#statuses }
281 const next = { ...this.#keys }
282 delete next[provider]
283 try {
284 await this.storage.save(next)
285 } catch (error) {
286 this.#keys = previousKeys
287 this.#statuses = previousStatuses
288 this.#emit()
289 throw error
290 }
291 this.#keys = next
292 delete this.#statuses[provider]
293 this.#emit()
294 return
295 }
296 const previousKeys = this.#keys
297 const previousStatuses = this.#statuses
298 const previousLocked = this.#locked
299 const previousPrompt = this.#prompt
300 try {
301 await this.storage.clear()
302 } catch (error) {
303 this.#keys = previousKeys
304 this.#statuses = previousStatuses
305 this.#locked = previousLocked
306 this.#prompt = previousPrompt
307 this.#emit()
308 throw error
309 }
310 this.#keys = {}
311 this.#statuses = {}
312 this.#locked = false
313 this.#prompt = null
314 this.#storageError = null
315 this.#emit()
316 }
317
318 async unlock(): Promise<void> {
319 await this.#ready
320 if (!this.storage.unlockable) return
321 try {
322 const loaded = sanitizeKeyring(await this.storage.load())
323 this.#keys = { ...loaded, ...this.#keys }
324 for (const [id, value] of Object.entries(loaded)) {
325 if (!isProviderId(id) || !value) continue
326 const existing = this.#statuses[id]
327 if (!existing || existing.state === 'locked') {
328 this.#statuses[id] = { state: 'set', masked: maskKey(value) }
329 }
330 }
331 this.#locked = false
332 this.#storageError = null
333 this.#emit()
334 } catch (error) {
335 if (isByokCeremonyCancel(error)) {
336 const provider = this.#lockedProvider()
337 if (provider) {
338 this.request(provider, 'locked')
339 throw new ByokBlockedError(provider, 'locked')
340 }
341 }
342 this.#storageError = errorMessage(error, 'Failed to unlock keyring')
343 this.#emit()
344 throw error instanceof Error ? error : new Error(String(error))
345 }
346 }
347
348 #lockedProvider(): ProviderId | undefined {
349 if (this.#prompt && isProviderId(this.#prompt.provider)) {
350 return this.#prompt.provider
351 }
352 for (const [id, status] of Object.entries(this.#statuses)) {
353 if (status?.state === 'locked' && isProviderId(id)) return id
354 }
355 return undefined
356 }
357
358 async #hydrate(): Promise<void> {
359 if (this.storage.unlockable) {
360 if (!this.storage.peek) return
361 try {
362 const preview = await this.storage.peek()
363 for (const [id, last4] of Object.entries(preview)) {
364 if (!isProviderId(id) || this.#statuses[id]) continue
365 this.#statuses[id] = {
366 state: 'locked',
367 masked: last4 ? last4 : '••',
368 }
369 }
370 this.#locked = Object.keys(preview).length > 0
371 this.#storageError = null
372 this.#emit()
373 } catch (error) {
374 this.#storageError = errorMessage(error, 'Failed to read keyring')
375 this.#emit()
376 }
377 return
378 }
379 try {
380 const loaded = sanitizeKeyring(await this.storage.load())
381 this.#keys = { ...loaded, ...this.#keys }
382 for (const [id, value] of Object.entries(loaded)) {
383 if (!isProviderId(id) || !value) continue
384 this.#statuses[id] = { state: 'set', masked: maskKey(value) }
385 }
386 this.#storageError = null
387 this.#emit()
388 } catch (error) {
389 this.#storageError = errorMessage(error, 'Failed to read keyring')
390 this.#emit()
391 }
392 }
393
394 #emit(): void {
395 this.#snapshot = this.#buildSnapshot()
396 for (const listener of this.#listeners) listener()
397 }
398}
399
400export function defineByok(options: DefineByokOptions = {}): ByokClient {
401 return new ByokClient(options)
402}