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