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

byok-client.test.ts

376 lines11.8 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { ByokBlockedError, defineByokProvider } from '@tanstack/ai/byok'
3import { defineByok, memoryStorage } from '../src/byok'
4import type { KeyringStorage } from '../src/byok'
5​
6describe('defineByok memory', () => {
7 afterEach(() => {
8 vi.unstubAllGlobals()
9 })
10​
11 it('isolates and freezes nested snapshot state', async () => {
12 const byok = defineByok()
13 await byok.update('openai', 'sk-abcdefghij')
14 const snapshot = byok.getSnapshot()
15​
16 expect(Object.isFrozen(snapshot)).toBe(true)
17 expect(Object.isFrozen(snapshot.status)).toBe(true)
18 expect(Object.isFrozen(snapshot.status.openai)).toBe(true)
19 Reflect.set(snapshot.status.openai!, 'masked', 'leak')
20 expect(byok.getSnapshot().status.openai).toEqual({
21 state: 'set',
22 masked: 'ghij',
23 })
24 })
25​
26 it('uses Set subscription behavior', () => {
27 const byok = defineByok()
28 const listener = vi.fn()
29 const first = byok.subscribe(listener)
30 byok.subscribe(listener)
31​
32 byok.request('openai', 'missing')
33 expect(listener).toHaveBeenCalledTimes(1)
34 first()
35 byok.request('openai', 'missing')
36 expect(listener).toHaveBeenCalledTimes(1)
37 })
38​
39 it('a throwing listener does not skip the next listener', () => {
40 const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
41 const byok = defineByok()
42 const listener = vi.fn()
43 byok.subscribe(() => {
44 throw new Error('listener failed')
45 })
46 byok.subscribe(listener)
47​
48 byok.request('openai', 'missing')
49​
50 expect(listener).toHaveBeenCalledTimes(1)
51 expect(byok.getSnapshot().prompt?.provider).toBe('openai')
52 expect(consoleError).toHaveBeenCalledWith(new Error('listener failed'))
53 consoleError.mockRestore()
54 })
55​
56 it('updates and snapshots without exposing the raw key', async () => {
57 const byok = defineByok({ storage: memoryStorage() })
58 await byok.update('openai', 'sk-abcdefghij')
59 const snapshot = byok.getSnapshot()
60 expect(snapshot.status.openai).toEqual({ state: 'set', masked: 'ghij' })
61 expect(JSON.stringify(snapshot)).not.toContain('sk-abcdefghij')
62 expect(byok.headers('openai')).toEqual({ 'x-byok-openai': 'sk-abcdefghij' })
63 expect(byok.headers('anthropic')).toEqual({})
64 })
65​
66 it('sends and prepares companion credentials with the provider', async () => {
67 const account = defineByokProvider({ id: 'acme-account', label: 'Account' })
68 const token = defineByokProvider({
69 id: 'acme',
70 label: 'Token',
71 with: [account],
72 })
73 const byok = defineByok({ providers: [token, account] })
74 await byok.update('acme', 'tok-abcdefghij')
75 await expect(byok.prepare('acme')).rejects.toBeInstanceOf(ByokBlockedError)
76 expect(byok.getSnapshot().prompt).toEqual({
77 provider: 'acme-account',
78 reason: 'missing',
79 })
80 await byok.update('acme-account', 'acct-1')
81 await byok.prepare('acme')
82 expect(byok.headers('acme')).toEqual({
83 'x-byok-acme': 'tok-abcdefghij',
84 'x-byok-acme-account': 'acct-1',
85 })
86 })
87​
88 it('update(key) throws when prompt is null', async () => {
89 const byok = defineByok()
90 await expect(byok.update('sk-abcdefghij')).rejects.toThrow(
91 /prompt is null/i,
92 )
93 })
94​
95 it('rejects empty or whitespace keys', async () => {
96 const byok = defineByok()
97 await expect(byok.update('openai', ' ')).rejects.toThrow(/non-empty/i)
98 expect(byok.getSnapshot().status.openai).toBeUndefined()
99 })
100​
101 it('update(key) writes the prompted provider', async () => {
102 const byok = defineByok()
103 byok.request('anthropic', 'missing')
104 await byok.update('sk-abcdefghij')
105 expect(byok.getSnapshot().status.anthropic?.state).toBe('set')
106 expect(byok.getSnapshot().prompt).toBe(null)
107 })
108​
109 it('clear removes one key or all keys', async () => {
110 const byok = defineByok()
111 await byok.update('openai', 'sk-aaaaaaaaaa')
112 await byok.update('grok', 'xai-bbbbbbbb')
113 await byok.clear('openai')
114 expect(byok.getSnapshot().status.openai).toBeUndefined()
115 expect(byok.getSnapshot().status.grok?.state).toBe('set')
116 await byok.clear()
117 expect(byok.getSnapshot().status.grok).toBeUndefined()
118 })
119​
120 it('prepare throws ByokBlockedError when the provider is empty and uncovered', async () => {
121 const byok = defineByok()
122 await expect(byok.prepare('openai')).rejects.toBeInstanceOf(
123 ByokBlockedError,
124 )
125 expect(byok.getSnapshot().prompt).toEqual({
126 provider: 'openai',
127 reason: 'missing',
128 })
129 })
130​
131 it('prepare does not throw when server coverage is set', async () => {
132 const byok = defineByok()
133 byok.setServerCoverage({ openai: true })
134 await expect(byok.prepare('openai')).resolves.toBeUndefined()
135 expect(byok.getSnapshot().prompt).toBe(null)
136 })
137​
138 it('prepare does not throw when server coverage is true for any slug', async () => {
139 const byok = defineByok()
140 byok.setServerCoverage(true)
141 await expect(byok.prepare('bedrock')).resolves.toBeUndefined()
142 await expect(byok.prepare('my-llm')).resolves.toBeUndefined()
143 })
144​
145 it('accepts slugs that are not first-party adapter names', async () => {
146 const byok = defineByok()
147 await byok.update('bedrock', 'sk-bedrock-key')
148 expect(byok.getSnapshot().status.bedrock).toEqual({
149 state: 'set',
150 masked: '-key',
151 })
152 expect(byok.headers('bedrock')).toEqual({
153 'x-byok-bedrock': 'sk-bedrock-key',
154 })
155 })
156​
157 it('rejects invalid provider ids', async () => {
158 const byok = defineByok()
159 await expect(byok.update('OpenAI', 'sk-abcdefghij')).rejects.toThrow(
160 /Invalid BYOK provider id/,
161 )
162 expect(() => byok.headers('OpenAI')).toThrow(/Invalid BYOK provider id/)
163 })
164​
165 it('prepare skips the empty check when no provider is given', async () => {
166 const byok = defineByok()
167 await expect(byok.prepare()).resolves.toBeUndefined()
168 })
169​
170 it('headers() without a provider emits every present key', async () => {
171 const byok = defineByok()
172 await byok.update('openai', 'sk-aaaaaaaaaa')
173 await byok.update('grok', 'xai-bbbbbbbb')
174 expect(byok.headers()).toEqual({
175 'x-byok-openai': 'sk-aaaaaaaaaa',
176 'x-byok-grok': 'xai-bbbbbbbb',
177 })
178 })
179​
180 it('subscribe fires on update', async () => {
181 const byok = defineByok()
182 let calls = 0
183 const stop = byok.subscribe(() => {
184 calls += 1
185 })
186 await byok.update('openai', 'sk-aaaaaaaaaa')
187 expect(calls).toBeGreaterThan(0)
188 stop()
189 })
190​
191 it('getSnapshot returns the same object until state changes', async () => {
192 const byok = defineByok({ storage: memoryStorage() })
193 const first = byok.getSnapshot()
194 expect(byok.getSnapshot()).toBe(first)
195​
196 byok.request('openai', 'missing')
197 const afterRequest = byok.getSnapshot()
198 expect(afterRequest).not.toBe(first)
199 expect(byok.getSnapshot()).toBe(afterRequest)
200​
201 await byok.update('openai', 'sk-abcdefghij')
202 const afterUpdate = byok.getSnapshot()
203 expect(afterUpdate).not.toBe(afterRequest)
204 expect(byok.getSnapshot()).toBe(afterUpdate)
205​
206 await byok.clear('openai')
207 const afterClear = byok.getSnapshot()
208 expect(afterClear).not.toBe(afterUpdate)
209 expect(byok.getSnapshot()).toBe(afterClear)
210 })
211})
212​
213describe('defineByok unlockable update/clear', () => {
214 function unlockableStorage(save: KeyringStorage['save']): KeyringStorage {
215 return {
216 id: 'mock-passkey',
217 label: 'Mock passkey',
218 persistent: true,
219 unlockable: true,
220 peek: () => ({ openai: 'aaaa', anthropic: 'bbbb' }),
221 load: () => ({
222 openai: 'sk-openai-old',
223 anthropic: 'sk-anthropic-keep',
224 }),
225 save,
226 clear: () => {},
227 }
228 }
229​
230 it('update loads the locked ring so other providers survive', async () => {
231 const save = vi.fn()
232 const byok = defineByok({ storage: unlockableStorage(save) })
233​
234 await byok.update('openai', 'sk-openai-new')
235​
236 expect(save).toHaveBeenCalledWith(
237 expect.objectContaining({
238 openai: 'sk-openai-new',
239 anthropic: 'sk-anthropic-keep',
240 }),
241 )
242 })
243​
244 it('clear(provider) loads the locked ring so other providers survive', async () => {
245 const save = vi.fn()
246 const byok = defineByok({ storage: unlockableStorage(save) })
247​
248 await byok.clear('openai')
249​
250 expect(save).toHaveBeenCalledWith(
251 expect.objectContaining({
252 anthropic: 'sk-anthropic-keep',
253 }),
254 )
255 expect(save.mock.calls.at(-1)?.[0]).not.toHaveProperty('openai')
256 })
257})
258​
259describe('defineByok persist-then-emit', () => {
260 it('does not mark a key saved when storage.save throws', async () => {
261 const storage: KeyringStorage = {
262 id: 'failing',
263 label: 'Failing',
264 persistent: true,
265 load: () => ({}),
266 save: async () => {
267 throw new Error('quota')
268 },
269 clear: () => {},
270 }
271 const byok = defineByok({ storage })
272 await expect(byok.update('openai', 'sk-abcdefghij')).rejects.toThrow(
273 /quota/,
274 )
275 expect(byok.headers('openai')).toEqual({})
276 expect(byok.getSnapshot().status.openai).toEqual({
277 state: 'error',
278 masked: 'ghij',
279 message: 'quota',
280 })
281 expect(JSON.stringify(byok.getSnapshot())).not.toContain('sk-abcdefghij')
282 })
283​
284 it('does not clear keys when storage.clear throws', async () => {
285 const storage: KeyringStorage = {
286 id: 'failing-clear',
287 label: 'Failing clear',
288 persistent: true,
289 load: () => ({}),
290 save: () => {},
291 clear: async () => {
292 throw new Error('idb blocked')
293 },
294 }
295 const byok = defineByok({ storage })
296 await byok.update('openai', 'sk-abcdefghij')
297 await expect(byok.clear()).rejects.toThrow(/idb blocked/)
298 expect(byok.headers('openai')).toEqual({
299 'x-byok-openai': 'sk-abcdefghij',
300 })
301 })
302})
303​
304describe('defineByok locked snapshot', () => {
305 it('peeks last-4 as locked and omits headers until unlock', async () => {
306 const storage: KeyringStorage = {
307 id: 'mock-passkey',
308 label: 'Mock passkey',
309 persistent: true,
310 unlockable: true,
311 peek: () => ({ openai: 'ghij' }),
312 load: () => ({ openai: 'sk-abcdefghij' }),
313 save: () => {},
314 clear: () => {},
315 }
316 const byok = defineByok({ storage })
317 await byok.ready()
318​
319 expect(byok.getSnapshot().locked).toBe(true)
320 expect(byok.getSnapshot().status.openai).toEqual({
321 state: 'locked',
322 masked: 'ghij',
323 })
324 expect(byok.headers('openai')).toEqual({})
325 expect(JSON.stringify(byok.getSnapshot())).not.toContain('sk-abcdefghij')
326​
327 await byok.unlock()
328 expect(byok.getSnapshot().locked).toBe(false)
329 expect(byok.headers('openai')).toEqual({
330 'x-byok-openai': 'sk-abcdefghij',
331 })
332 })
333​
334 it('maps a cancelled unlock to ByokBlockedError locked', async () => {
335 const storage: KeyringStorage = {
336 id: 'mock-passkey',
337 label: 'Mock passkey',
338 persistent: true,
339 unlockable: true,
340 peek: () => ({ openai: 'ghij' }),
341 load: async () => {
342 throw new Error('Passkey unlock was cancelled')
343 },
344 save: () => {},
345 clear: () => {},
346 }
347 const byok = defineByok({ storage })
348 await byok.ready()
349 await expect(byok.unlock()).rejects.toBeInstanceOf(ByokBlockedError)
350 expect(byok.getSnapshot().prompt).toEqual({
351 provider: 'openai',
352 reason: 'locked',
353 })
354 expect(byok.getSnapshot().locked).toBe(true)
355 expect(byok.headers('openai')).toEqual({})
356 })
357​
358 it('records peek failures on the snapshot', async () => {
359 const storage: KeyringStorage = {
360 id: 'mock-passkey',
361 label: 'Mock passkey',
362 persistent: true,
363 unlockable: true,
364 peek: async () => {
365 throw new Error('IndexedDB blocked')
366 },
367 load: () => ({}),
368 save: () => {},
369 clear: () => {},
370 }
371 const byok = defineByok({ storage })
372 await byok.ready()
373 expect(byok.getSnapshot().storageError).toBe('IndexedDB blocked')
374 expect(byok.getSnapshot().locked).toBe(true)
375 })
376})