SPB Git

Repository Public

store.ts 4.2 KB 108 lines typescript

1import { b64, unb64 } from "./bytes"23/** Minimal key-value persistence used by the engine. Browser: IndexedDB. Tests: memory. */4export interface Store {5  get<T = unknown>(key: string): Promise<T | undefined>6  set(key: string, value: unknown): Promise<void>7  del(key: string): Promise<void>8  list<T = unknown>(prefix: string): Promise<[string, T][]>9  clear(): Promise<void>10}1112export class MemoryStore implements Store {13  private m = new Map<string, unknown>()14  async get<T>(key: string) {15    const v = this.m.get(key)16    return v === undefined ? undefined : (structuredClone(v) as T)17  }18  async set(key: string, value: unknown) {19    this.m.set(key, structuredClone(value))20  }21  async del(key: string) {22    this.m.delete(key)23  }24  async list<T>(prefix: string) {25    return [...this.m.entries()].filter(([k]) => k.startsWith(prefix)).sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => [k, structuredClone(v) as T] as [string, T])26  }27  async clear() {28    this.m.clear()29  }30}3132/**33 * IndexedDB store. Values under the `secret/` prefix are sealed with a non-extractable AES-GCM key34 * that itself lives in IndexedDB: script running on this origin can use it, but the raw key cannot35 * be read out and copied elsewhere.36 */37export class IdbStore implements Store {38  private db!: IDBDatabase39  private wrapKey!: CryptoKey40  constructor(private name: string) {}4142  async open() {43    this.db = await new Promise<IDBDatabase>((resolve, reject) => {44      const r = indexedDB.open(this.name, 1)45      r.onupgradeneeded = () => {46        r.result.createObjectStore("kv")47        r.result.createObjectStore("meta")48      }49      r.onsuccess = () => resolve(r.result)50      r.onerror = () => reject(r.error)51    })52    let k = await this.raw<CryptoKey>("meta", "readonly", (s) => s.get("wrap"))53    if (!k) {54      k = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"])55      await this.raw("meta", "readwrite", (s) => s.put(k, "wrap"))56    }57    this.wrapKey = k58    return this59  }60  private raw<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest): Promise<T> {61    return new Promise((resolve, reject) => {62      const r = fn(this.db.transaction(store, mode).objectStore(store))63      r.onsuccess = () => resolve(r.result as T)64      r.onerror = () => reject(r.error)65    })66  }67  private async wrap(value: unknown) {68    const iv = crypto.getRandomValues(new Uint8Array(12))69    const data = new TextEncoder().encode(JSON.stringify(value, (_k, v) => (v instanceof Uint8Array ? { $b: b64(v) } : v)))70    return { $sealed: true, iv, ct: new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, this.wrapKey, data)) }71  }72  private async unwrap(v: { iv: Uint8Array; ct: Uint8Array }) {73    const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: v.iv as BufferSource }, this.wrapKey, v.ct as BufferSource)74    return JSON.parse(new TextDecoder().decode(pt), (_k, x) => (x && typeof x === "object" && "$b" in x ? unb64(x.$b) : x))75  }76  async get<T>(key: string) {77    const v = await this.raw<unknown>("kv", "readonly", (s) => s.get(key))78    if (v && typeof v === "object" && "$sealed" in v) return (await this.unwrap(v as never)) as T79    return v as T | undefined80  }81  async set(key: string, value: unknown) {82    const v = key.startsWith("secret/") ? await this.wrap(value) : value83    await this.raw("kv", "readwrite", (s) => s.put(v, key))84  }85  async del(key: string) {86    await this.raw("kv", "readwrite", (s) => s.delete(key))87  }88  async list<T>(prefix: string) {89    const range = IDBKeyRange.bound(prefix, prefix + "￿")90    const [keys, values] = await new Promise<[string[], unknown[]]>((resolve, reject) => {91      const tx = this.db.transaction("kv", "readonly")92      const s = tx.objectStore("kv")93      const k = s.getAllKeys(range), v = s.getAll(range)94      tx.oncomplete = () => resolve([k.result as string[], v.result])95      tx.onerror = () => reject(tx.error)96    })97    const out: [string, T][] = []98    for (let i = 0; i < keys.length; i++) {99      const v = values[i]100      out.push([keys[i], (v && typeof v === "object" && "$sealed" in v ? await this.unwrap(v as never) : v) as T])101    }102    return out103  }104  async clear() {105    await this.raw("kv", "readwrite", (s) => s.clear())106  }107}108
Files main
Menu

Theme