UNPKG

@stainless-code/persist

Version:

Hydration-aware persistence for any reactive store — zero-dep persistSource core; codecs, backends, cross-tab transport, source + framework hydration adapters ship as opt-in recipes

40 lines (39 loc) • 2.01 kB
import { f as StateStorage } from "../persist-core-B649IGlX.mjs"; //#region src/adapters/backends/encrypted.d.ts interface CreateEncryptedStorageOptions { /** AES-GCM `CryptoKey` — derive via `crypto.subtle.importKey` / `generateKey`. */ key: CryptoKey; } /** * AES-GCM encryption over a string-wire `StateStorage` (WebCrypto). Each * stored value is `base64(iv).base64(ciphertext)` (12-byte IV prepended); the * AES-GCM auth tag means a wrong key or tampered ciphertext throws on decrypt. * That throw surfaces in the backend's async `getItem` → persist-core reports * it via `onError` phase `"hydrate"` (NOT the corrupt-payload self-heal — * `clearCorruptOnFailure` only fires when the *codec* throws parsing a * non-corrupt raw, not when the *backend* rejects reading it). * * A backend **wrapper**, not a sync `StorageCodec`, because `crypto.subtle` * is async — the codec serializes (sync), this encrypts the string (async). * Compose: `createStorage(() => createEncryptedStorage(backend, { key }), codec)`. * Returns `undefined` when `crypto.subtle` is unavailable. * * @example * ```ts * import { createStorage } from "@stainless-code/persist"; * import { createEncryptedStorage } from "@stainless-code/persist/backends/encrypted"; * import { serovalCodec } from "@stainless-code/persist/codecs/seroval"; * import { persistStore } from "@stainless-code/persist/sources/tanstack-store"; * * const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); * const storage = createStorage<Prefs>( * () => createEncryptedStorage(() => localStorage, { key })!, * serovalCodec(), * { clearCorruptOnFailure: true }, * ); * persistStore(store, { name: "app:prefs:v1", storage }); * ``` */ declare function createEncryptedStorage(getStorage: () => StateStorage<string>, options: CreateEncryptedStorageOptions): StateStorage<string> | undefined; //#endregion export { CreateEncryptedStorageOptions, createEncryptedStorage };