Open History to see the last commit
1import { isProviderId } from '@tanstack/ai/byok'
2import { memoryStorage } from './storage'
3import type { KeyPreview, Keyring, KeyringStorage } from './storage'
4
5/**
6 * Passkey-encrypted keyring storage (WebAuthn PRF → HKDF → AES-256-GCM).
7 *
8 * The keyring is encrypted at rest in IndexedDB with an AES-256-GCM key derived
9 * from a passkey's PRF output, unwrapped on demand with a biometric/PIN tap.
10 * Decryption happens entirely client-side with the user present — no server,
11 * no custodian.
12 *
13 * Honest scope: this protects against at-rest theft (stolen device,
14 * storage-dumping extension, backups). It does NOT defeat live in-page XSS —
15 * an attacker running JS in the origin after the user unlocks can read the
16 * decrypted keys from memory.
17 */
18
19const STORE_NAME = 'keyring'
20const RECORD_ID = 'default'
21const HKDF_INFO = 'byok:keyring:v1'
22const DEFAULT_DB = 'byok'
23
24interface StoredRecord {
25 id: string
26 /** The passkey's raw credential id, replayed in the unlock ceremony. */
27 credentialId: ArrayBuffer
28 /** Fixed per-install PRF evaluation input (not secret). */
29 salt: ArrayBuffer
30 /** AES-GCM initialization vector for this ciphertext. */
31 iv: ArrayBuffer
32 /** Encrypted keyring JSON. */
33 ciphertext: ArrayBuffer
34 /**
35 * Unencrypted presence metadata (`provider → last 4`). Non-sensitive, so it
36 * can be read via {@link KeyringStorage.peek} without an unlock ceremony to
37 * show saved keys as "locked" after a refresh.
38 */
39 preview: KeyPreview
40}
41
42function sanitizeKeyring(value: unknown): Keyring {
43 if (typeof value !== 'object' || value === null) return {}
44 const keys: Keyring = {}
45 for (const [provider, key] of Object.entries(value)) {
46 if (isProviderId(provider) && typeof key === 'string' && key.length > 0) {
47 keys[provider] = key
48 }
49 }
50 return keys
51}
52
53/** Build the non-sensitive `provider → last 4` preview from a keyring. */
54function previewOf(keys: Keyring): KeyPreview {
55 const preview: KeyPreview = {}
56 for (const [provider, key] of Object.entries(keys)) {
57 if (!key || !isProviderId(provider)) continue
58 // Keys of length ≤ 4 would make last-4 the whole secret — store presence only.
59 preview[provider] = key.length > 4 ? key.slice(-4) : ''
60 }
61 return preview
62}
63
64/**
65 * Whether the current environment exposes WebAuthn. Actual PRF support can
66 * only be confirmed during registration; `passkeyStorage` throws if the
67 * chosen authenticator does not support PRF.
68 */
69export function isPasskeyStorageSupported(): boolean {
70 return (
71 typeof globalThis !== 'undefined' &&
72 typeof globalThis.PublicKeyCredential !== 'undefined' &&
73 typeof globalThis.navigator !== 'undefined' &&
74 typeof globalThis.navigator.credentials.create === 'function'
75 )
76}
77
78// ---------------------------------------------------------------------------
79// Crypto (exported for testing; the WebAuthn ceremony below feeds `deriveAesKey`)
80// ---------------------------------------------------------------------------
81
82/** Derive a non-extractable AES-256-GCM key from a 32-byte PRF output. */
83export async function deriveAesKey(
84 prfOutput: BufferSource,
85): Promise<CryptoKey> {
86 // Some passkey providers return a plain byte array instead of BufferSource.
87 if (Array.isArray(prfOutput)) {
88 if (
89 prfOutput.length !== 32 ||
90 !Array.from(prfOutput).every(
91 (byte: unknown) =>
92 typeof byte === 'number' &&
93 Number.isInteger(byte) &&
94 byte >= 0 &&
95 byte <= 255,
96 )
97 ) {
98 throw new Error('Invalid passkey PRF byte array')
99 }
100 prfOutput = new Uint8Array(prfOutput)
101 }
102 const base = await crypto.subtle.importKey('raw', prfOutput, 'HKDF', false, [
103 'deriveKey',
104 ])
105 return crypto.subtle.deriveKey(
106 {
107 name: 'HKDF',
108 hash: 'SHA-256',
109 salt: new Uint8Array(0),
110 info: new TextEncoder().encode(HKDF_INFO),
111 },
112 base,
113 { name: 'AES-GCM', length: 256 },
114 false,
115 ['encrypt', 'decrypt'],
116 )
117}
118
119export async function encryptKeyring(
120 key: CryptoKey,
121 keys: Keyring,
122): Promise<{ iv: ArrayBuffer; ciphertext: ArrayBuffer }> {
123 const iv = crypto.getRandomValues(new Uint8Array(12))
124 const plaintext = new TextEncoder().encode(JSON.stringify(keys))
125 const ciphertext = await crypto.subtle.encrypt(
126 { name: 'AES-GCM', iv },
127 key,
128 plaintext,
129 )
130 return { iv: iv.buffer, ciphertext }
131}
132
133export async function decryptKeyring(
134 key: CryptoKey,
135 iv: BufferSource,
136 ciphertext: BufferSource,
137): Promise<Keyring> {
138 const plaintext = await crypto.subtle.decrypt(
139 { name: 'AES-GCM', iv },
140 key,
141 ciphertext,
142 )
143 const parsed: unknown = JSON.parse(new TextDecoder().decode(plaintext))
144 return sanitizeKeyring(parsed)
145}
146
147// ---------------------------------------------------------------------------
148// IndexedDB
149// ---------------------------------------------------------------------------
150
151function openDb(dbName: string): Promise<IDBDatabase> {
152 return new Promise((resolve, reject) => {
153 const request = indexedDB.open(dbName, 1)
154 request.onupgradeneeded = () => {
155 request.result.createObjectStore(STORE_NAME, { keyPath: 'id' })
156 }
157 request.onsuccess = () => resolve(request.result)
158 request.onerror = () => reject(request.error)
159 })
160}
161
162function idbGet(dbName: string): Promise<StoredRecord | null> {
163 return openDb(dbName).then(
164 (db) =>
165 new Promise((resolve, reject) => {
166 const request = db
167 .transaction(STORE_NAME, 'readonly')
168 .objectStore(STORE_NAME)
169 .get(RECORD_ID)
170 request.onsuccess = () => resolve(request.result ?? null)
171 request.onerror = () => reject(request.error)
172 }),
173 )
174}
175
176function idbPut(dbName: string, record: StoredRecord): Promise<void> {
177 return openDb(dbName).then(
178 (db) =>
179 new Promise((resolve, reject) => {
180 const tx = db.transaction(STORE_NAME, 'readwrite')
181 tx.objectStore(STORE_NAME).put(record)
182 tx.oncomplete = () => resolve()
183 tx.onerror = () => reject(tx.error)
184 }),
185 )
186}
187
188function idbClear(dbName: string): Promise<void> {
189 return openDb(dbName).then(
190 (db) =>
191 new Promise((resolve, reject) => {
192 const tx = db.transaction(STORE_NAME, 'readwrite')
193 tx.objectStore(STORE_NAME).delete(RECORD_ID)
194 tx.oncomplete = () => resolve()
195 tx.onerror = () => reject(tx.error)
196 }),
197 )
198}
199
200// ---------------------------------------------------------------------------
201// WebAuthn ceremonies
202// ---------------------------------------------------------------------------
203
204function requirePublicKeyCredential(
205 credential: Credential | null,
206 action: string,
207): PublicKeyCredential {
208 if (!credential) throw new Error(`Passkey ${action} was cancelled`)
209 if (!(credential instanceof PublicKeyCredential)) {
210 throw new Error(`Unexpected credential type during ${action}`)
211 }
212 return credential
213}
214
215/**
216 * Some browsers (Dia, Safari) silently suppress `navigator.credentials.get()`
217 * — no prompt, never resolves — when it runs without transient user activation.
218 * The activation from a click expires (~5s) and is lost across enough async
219 * work, so an unlock buried deep in a send pipeline just hangs. Fail fast with
220 * a clear, catchable error so the app can re-run it from a fresh gesture.
221 */
222function requireUserActivation(action: string): void {
223 // ponytail: only enforce where the API exists; absent means "can't tell", so
224 // fall through rather than block a ceremony that would have worked.
225 const activation = globalThis.navigator?.userActivation
226 if (activation && activation.isActive === false) {
227 throw new Error(
228 `Passkey ${action} needs a fresh user action (e.g. a click). Run it ` +
229 'directly from the event handler, before awaiting other work.',
230 )
231 }
232}
233
234async function registerPasskey(
235 rpName: string,
236 userName: string,
237 rpId?: string,
238): Promise<{
239 credentialId: ArrayBuffer
240 salt: Uint8Array<ArrayBuffer>
241 prf?: BufferSource
242}> {
243 const salt = crypto.getRandomValues(new Uint8Array(32))
244 const credential = requirePublicKeyCredential(
245 await navigator.credentials.create({
246 publicKey: {
247 challenge: crypto.getRandomValues(new Uint8Array(32)),
248 // Omit `id` to let the browser bind the passkey to the current origin's
249 // effective domain; set it to scope across subdomains of a self-host.
250 rp: rpId ? { name: rpName, id: rpId } : { name: rpName },
251 user: {
252 id: crypto.getRandomValues(new Uint8Array(16)),
253 name: userName,
254 displayName: userName,
255 },
256 pubKeyCredParams: [
257 { type: 'public-key', alg: -7 },
258 { type: 'public-key', alg: -257 },
259 ],
260 authenticatorSelection: {
261 residentKey: 'required',
262 userVerification: 'required',
263 },
264 extensions: { prf: { eval: { first: salt } } },
265 },
266 }),
267 'registration',
268 )
269
270 const prf = credential.getClientExtensionResults().prf
271 if (!prf?.enabled) {
272 throw new Error(
273 'This authenticator does not support the WebAuthn PRF extension',
274 )
275 }
276 return { credentialId: credential.rawId, salt, prf: prf.results?.first }
277}
278
279async function evaluatePrf(
280 credentialId: BufferSource,
281 salt: BufferSource,
282): Promise<BufferSource> {
283 const credential = requirePublicKeyCredential(
284 await navigator.credentials.get({
285 publicKey: {
286 challenge: crypto.getRandomValues(new Uint8Array(32)),
287 allowCredentials: [{ type: 'public-key', id: credentialId }],
288 userVerification: 'required',
289 extensions: { prf: { eval: { first: salt } } },
290 },
291 }),
292 'unlock',
293 )
294 const result = credential.getClientExtensionResults().prf?.results?.first
295 if (!result) {
296 throw new Error('Authenticator did not return a PRF result')
297 }
298 return result
299}
300
301// ---------------------------------------------------------------------------
302// Storage strategy
303// ---------------------------------------------------------------------------
304
305export interface PasskeyStorageOptions {
306 /** Relying-party name shown in the passkey prompt. */
307 rpName?: string
308 /** Username label attached to the created passkey. */
309 userName?: string
310 /**
311 * WebAuthn Relying Party ID. Omit to bind the passkey to the current origin's
312 * effective domain (the default — no central/hardcoded domain). Set it to a
313 * registrable parent domain to share the credential across subdomains of your
314 * own deployment. The encrypted keyring is never portable across unrelated
315 * domains.
316 */
317 rpId?: string
318 /** IndexedDB database name. Defaults to `byok`. */
319 dbName?: string
320}
321
322/**
323 * Passkey-encrypted persistence. `ByokClient` treats this as `unlockable`, so
324 * nothing is decrypted until the user calls `unlock()` (or saves a key, which
325 * registers a passkey on first use). The derived key is cached in memory for
326 * the session so repeated saves don't re-prompt.
327 */
328export function passkeyStorage(
329 options: PasskeyStorageOptions = {},
330): KeyringStorage {
331 const rpName = options.rpName ?? 'BYOK'
332 const userName = options.userName ?? 'byok-keyring'
333 const { rpId } = options
334 const dbName = options.dbName ?? DEFAULT_DB
335
336 let cachedKey: CryptoKey | null = null
337 let cachedMeta: {
338 credentialId: ArrayBuffer
339 salt: Uint8Array<ArrayBuffer>
340 } | null = null
341
342 // Obtain the AES key, running exactly one WebAuthn ceremony if it isn't
343 // already cached for this session (unlock if a passkey exists, else register).
344 async function ensureKey(): Promise<{
345 key: CryptoKey
346 credentialId: ArrayBuffer
347 salt: Uint8Array<ArrayBuffer>
348 }> {
349 if (cachedKey && cachedMeta) {
350 return { key: cachedKey, ...cachedMeta }
351 }
352 const existing = await idbGet(dbName)
353 if (existing) {
354 requireUserActivation('unlock')
355 const prf = await evaluatePrf(existing.credentialId, existing.salt)
356 cachedKey = await deriveAesKey(prf)
357 cachedMeta = {
358 credentialId: existing.credentialId,
359 salt: new Uint8Array(existing.salt),
360 }
361 } else {
362 const reg = await registerPasskey(rpName, userName, rpId)
363 // Registration can consume activation. Let the browser handle its
364 // follow-up PRF ceremony rather than rejecting a valid new-key save.
365 const prf = reg.prf ?? (await evaluatePrf(reg.credentialId, reg.salt))
366 cachedKey = await deriveAesKey(prf)
367 cachedMeta = { credentialId: reg.credentialId, salt: reg.salt }
368 }
369 return { key: cachedKey, ...cachedMeta }
370 }
371
372 return {
373 id: 'passkey',
374 label: 'Passkey-encrypted (this device)',
375 persistent: true,
376 unlockable: true,
377 warning:
378 'Keys are encrypted with your passkey and unlocked with biometrics. ' +
379 'This protects saved keys if your device is stolen, but not against code ' +
380 'running on this page after you unlock.',
381 peek: async () => {
382 // Unencrypted last-4 sidecar — no key material, no unlock ceremony.
383 const existing = await idbGet(dbName)
384 return existing?.preview ?? {}
385 },
386 load: async () => {
387 const existing = await idbGet(dbName)
388 if (!existing) return {}
389 const { key } = await ensureKey()
390 return decryptKeyring(key, existing.iv, existing.ciphertext)
391 },
392 save: async (keys) => {
393 const existing = await idbGet(dbName)
394 const hasKeys = Object.values(keys).some(Boolean)
395 // First save with an empty keyring is a no-op — avoids a passkey ceremony
396 // when another storage tier writes an empty ring.
397 if (!hasKeys && !existing) return
398
399 const { key, credentialId, salt } = await ensureKey()
400 const { iv, ciphertext } = await encryptKeyring(key, keys)
401 await idbPut(dbName, {
402 id: RECORD_ID,
403 credentialId,
404 salt: salt.buffer,
405 iv,
406 ciphertext,
407 preview: previewOf(keys),
408 })
409 },
410 clear: async () => {
411 cachedKey = null
412 cachedMeta = null
413 await idbClear(dbName)
414 },
415 }
416}
417
418/**
419 * Passkey-encrypted storage when WebAuthn is available in a secure context.
420 * Otherwise session memory, with a warning — this is not an automatic PRF
421 * fallback. First save still throws if the authenticator lacks PRF.
422 */
423export function defaultByokStorage(
424 options?: PasskeyStorageOptions,
425): KeyringStorage {
426 const secure =
427 typeof globalThis.isSecureContext !== 'boolean' ||
428 globalThis.isSecureContext
429 if (!isPasskeyStorageSupported() || !secure) {
430 return {
431 ...memoryStorage(),
432 warning:
433 'Passkeys are unavailable in this context. Keys stay in memory for this tab only.',
434 }
435 }
436 return passkeyStorage(options)
437}