Repository Public
1// Browser adapters for the engine: fetch transport, IndexedDB store (holds non-extractable CryptoKeys), passkeys.2import { startAuthentication, startRegistration } from "@simplewebauthn/browser";3import { ApiError, type Passkeys, type Store, type Transport } from "./engine.ts";45export class FetchTransport implements Transport {6 async request(method: string, path: string, body?: unknown, opts: { headers?: Record<string, string>; binary?: Uint8Array; raw?: boolean } = {}): Promise<any> {7 let res: Response;8 try {9 res = await fetch(path, { method, credentials: "same-origin", cache: "no-store", redirect: "error",10 headers: { "x-spv": "1", ...(opts.binary ? { "content-type": "application/octet-stream" } : body !== undefined ? { "content-type": "application/json" } : {}), ...opts.headers },11 body: opts.binary ? (opts.binary as unknown as BodyInit) : body === undefined ? undefined : JSON.stringify(body) });12 } catch { throw new ApiError(0, "offline", "The server cannot be reached"); }13 if (!res.ok) { const j: any = await res.json().catch(() => ({})); throw new ApiError(res.status, j.error ?? "error", j.message, j); }14 if (opts.raw) return new Uint8Array(await res.arrayBuffer());15 return res.json();16 }17}1819export class IdbStore implements Store {20 private db?: Promise<IDBDatabase>;21 private open(): Promise<IDBDatabase> {22 return (this.db ??= new Promise((resolve, reject) => {23 const r = indexedDB.open("sp-vault", 1);24 r.onupgradeneeded = () => r.result.createObjectStore("kv");25 r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error);26 }));27 }28 private async tx<T>(mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T> {29 const db = await this.open();30 return new Promise((resolve, reject) => { const t = db.transaction("kv", mode), r = fn(t.objectStore("kv")); t.oncomplete = () => resolve(r.result); t.onerror = () => reject(t.error); t.onabort = () => reject(t.error); });31 }32 get<T>(key: string) { return this.tx<T | undefined>("readonly", (s) => s.get(key)); }33 async set(key: string, value: unknown) { await this.tx("readwrite", (s) => s.put(value, key)); }34 async clear() { await this.tx("readwrite", (s) => s.clear()); }35}3637export const browserPasskeys: Passkeys = {38 create: (options) => startRegistration({ optionsJSON: options }),39 get: (options) => startAuthentication({ optionsJSON: options }),40};4142export function platformLabel(): string {43 const ua = navigator.userAgent;44 const browser = /Edg\//.test(ua) ? "Edge" : /Firefox\//.test(ua) ? "Firefox" : /Chrome\//.test(ua) ? "Chrome" : /Safari\//.test(ua) ? "Safari" : "Browser";45 const os = /iPhone/.test(ua) ? "iPhone" : /iPad/.test(ua) ? "iPad" : /Mac OS X/.test(ua) ? "Mac" : /Android/.test(ua) ? "Android" : /Windows/.test(ua) ? "Windows" : /Linux/.test(ua) ? "Linux" : "";46 return `Web · ${browser}${os ? ` (${os})` : ""}`;47}48