Skip to content
OSSAfricaPublic

About

Frontend library for encrypting data in the browser

Resources

Code of conduct

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

bVault-js — Encrypted Browser Storage

npm version wakatime NPM Type Definitions GitHub License

bVault-js encrypts data in localStorage and sessionStorage with a key that JavaScript cannot export. Applications routinely keep session tokens and personal data in browser storage, where any script that can read that storage can ship it elsewhere and replay it. bVault-js makes that copy worthless — the key will not serialize into it.

Read what this protects against before adopting it. The guarantee is specific, and it does not cover an attacker with access to the browser profile on disk.

  • 🔒 AES-GCM 256-bit authenticated encryption
  • 🔑 Non-extractable CryptoKey — the key material is never visible to JavaScript
  • 🧂 Fresh IV per write, carried inline with the ciphertext
  • 📦 Drop-in-shaped wrappers for localStorage and sessionStorage
  • 🌍 Safe to import under SSR (Next.js, Remix, SvelteKit)
  • 📐 Zero dependencies, fully typed

What this protects against

Be precise about this before adopting it. bVault-js narrows the blast radius of stolen storage; it is not a defence against an attacker who is already executing script on your page.

Attack Result Why
Storage copied and replayed in another browser Defeated The key does not serialize into the dump
Passive exfiltration (JSON.stringify(localStorage), extension scraping) Defeated Yields ciphertext only
Casual inspection via DevTools Defeated Nothing readable at rest
Live XSS calling subtle.decrypt() Not defeated Script in your origin can use the key handle
Whole-profile file copy Not defeated Non-extractable is an API restriction, not encryption at rest

Injected script can use the key while it runs on your page; it cannot steal it for offline or cross-browser use. That turns permanent session compromise into access that ends when the script does. bVault-js is not a substitute for preventing XSS, and session tokens are still safest in httpOnly cookies, which JavaScript cannot read at all.

For how the library works internally and a full list of its strengths and limitations, see How bVault-js works.

Non-extractable is not encryption at rest

extractable: false stops JavaScript from reading the key bytes. It does not stop a native process that can read the browser profile directory.

Firefox tracks "CryptoKeys stored in IndexedDB should be cryptographically bound to profile" as an open bug — they are not bound today. Chrome stores IndexedDB as LevelDB files that forensics tooling reads routinely. Chrome's own position, stated on the W3C WebCrypto list, is that non-extractable keys "are not meant to be a security primitive but purely for obfuscation".

So bVault-js protects against an attacker who can read your storage remotely — via XSS, a malicious extension, or any script that ships data off the machine. It does not protect against one who has the profile files themselves. Closing that gap requires key material that never touches the profile, which means hardware-backed derivation such as the WebAuthn PRF extension; full-disk encryption is the other mitigation worth having.

Installation

npm install bvault-js@preview

bVault-js is ESM-only. Use import in ESM applications or await import('bvault-js') from CommonJS. Synchronous require() is not supported.

Try the browser playground

The working example lets you initialize a vault, store a JSON object, inspect the ciphertext, reload and read it, then destroy it. From a checkout, run npm ci and npm run example.

Usage

Initialize once at your application's entry point, then use the wrappers anywhere.

import { initializeSecureStorage } from 'bvault-js';

async function bootstrap() {
  await initializeSecureStorage();
  // Continue with app startup...
}

bootstrap();

On first run this generates an AES-GCM key and stores it in IndexedDB. On later runs it loads the same key. No password is involved — see Why there is no password.

Secure local storage

import { secureLocalStorage } from 'bvault-js';

await secureLocalStorage.setItem('userProfile', {
  username: 'alice',
  email: 'alice@example.com',
});

const stored = await secureLocalStorage.getItem('userProfile');
const profile = stored ? JSON.parse(stored) : null;

secureLocalStorage.removeItem('userProfile');
secureLocalStorage.clear(); // removes only bVault's own entries

Secure session storage

import { secureSessionStorage } from 'bvault-js';

await secureSessionStorage.setItem('authToken', 'abc123');
const token = await secureSessionStorage.getItem('authToken'); // "abc123"

setItem and getItem are asynchronous because the Web Crypto API is asynchronous. This is not an implementation detail that can be removed: a synchronous API would require the raw key bytes to be held in JavaScript memory, which is exactly what makes a key stealable.

Framework examples

React

// main.tsx
import ReactDOM from 'react-dom/client';
import App from './App';
import { initializeSecureStorage } from 'bvault-js';

(async () => {
  await initializeSecureStorage();
  ReactDOM.createRoot(document.getElementById('root')!).render(<App />);
})();
// App.tsx
import { useEffect, useState } from 'react';
import { secureLocalStorage } from 'bvault-js';

export default function App() {
  const [profile, setProfile] = useState<{ username: string } | null>(null);

  useEffect(() => {
    (async () => {
      await secureLocalStorage.setItem('profile', { username: 'carol' });
      const data = await secureLocalStorage.getItem('profile');
      if (data) setProfile(JSON.parse(data));
    })();
  }, []);

  return <p>{profile ? `Hello ${profile.username}` : 'Loading...'}</p>;
}

Vue 3

// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { initializeSecureStorage } from 'bvault-js';

(async () => {
  await initializeSecureStorage();
  createApp(App).mount('#app');
})();
<!-- App.vue -->
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { secureLocalStorage } from 'bvault-js';

const profile = ref<{ username: string } | null>(null);

onMounted(async () => {
  await secureLocalStorage.setItem('profile', { username: 'bob' });
  const data = await secureLocalStorage.getItem('profile');
  if (data) profile.value = JSON.parse(data);
});
</script>

<template>
  <p v-if="profile">Hello {{ profile.username }}</p>
  <p v-else>Loading...</p>
</template>

Svelte

// main.ts
import App from './App.svelte';
import { initializeSecureStorage } from 'bvault-js';

(async () => {
  await initializeSecureStorage();
  new App({ target: document.getElementById('app')! });
})();

Limitations you must plan for

Key loss is total data loss

There is no password and therefore no recovery path. If IndexedDB is cleared — the user clears site data, or the browser evicts it under storage pressure — every stored value becomes permanently unreadable. bVault-js calls navigator.storage.persist() to reduce the risk, but browsers may refuse.

When a value cannot be decrypted, getItem returns null and logs a warning. It never deletes the stored value, so your application can decide what to do.

Treat bVault-js as a cache for data you can re-fetch, not as a system of record.

Safari discards everything after 7 days

WebKit deletes all script-writable storage — IndexedDB, localStorage, sessionStorage, Service Workers — after seven days of browser use without interaction with your site. The key and the ciphertext go together, so nothing is orphaned, but the vault is ephemeral on Safari. Web apps added to the home screen are exempt.

Why there is no password

Earlier versions derived the key from a password, and recommended sourcing it from a browser fingerprint. That recommendation has been withdrawn. A fingerprint is not secret — any script in your origin can recompute it — and it carries roughly 13 bits of entropy where key material needs 100+. It is also unstable: fingerprinting libraries report 90.5–95.5% accuracy, so a browser or driver update silently changes the key and renders stored data undecryptable.

A generated non-extractable key has none of these problems: full entropy, perfectly stable, and impossible to reconstruct off-device.

API Reference

initializeSecureStorage(): Promise<void>

Loads the encryption key for this origin, generating one on first use, and clears any data written by v0.x. Call once at startup before using the wrappers.

secureLocalStorage / secureSessionStorage

  • await setItem(key: string, value: unknown): Promise<void> — objects are JSON-stringified
  • await getItem(key: string): Promise<string | null> — null if absent or undecryptable
  • removeItem(key: string): void
  • clear(): void — removes only entries written by bVault-js

Keys are stored under a bv1: prefix so bVault-js never collides with, or clears, storage belonging to other libraries.

destroySecureStorage(): Promise<void>

Deletes the key and every value stored under it. Intended for logout or account switching. There is no recovery path.

Other open tabs invalidate their cached key and clear their bVault session values. Their next read or write rejects until they call initializeSecureStorage() again. A write already encrypting when destruction occurs is rejected before storage is updated. BroadcastChannel and storage events notify active tabs; a small bvault:key-lifecycle marker also lets resumed tabs detect a missed notification. No key material is included in these messages or the marker.

Destruction can reject with a storage error if the coordination marker cannot be written. In that case the IndexedDB key is not deleted; handle the error and retry rather than assuming logout cleanup succeeded.

isSecureStorageInitialized(): boolean

Errors

EncryptionError and DecryptionError are exported. setItem throws EncryptionError when encryption fails; getItem returns null on decryption failure. Both operations reject if the vault is not initialized or its key was invalidated during the operation.

Errors from the storage write itself are not wrapped. If storage is full, setItem rejects with the browser's native DOMException (name === 'QuotaExceededError'; older Firefox reports NS_ERROR_DOM_QUOTA_REACHED), so you can tell it apart from an encryption failure.

Migrating from 0.x

1.0.0 is a breaking release.

  • initializeSecureStorage() no longer takes a password
  • encrypt and decrypt have been removed — the library now does one job
  • Data written by 0.x cannot be migrated, because keys derived from a password or fingerprint are not recoverable. It is deleted once on first initialization, with a warning. Only keys that 0.x recorded in its own metadata are touched; storage belonging to other libraries is left alone.

If you need password-based encryption for something other than browser storage, use the Web Crypto API directly or a dedicated library.

Contributing

Read the contribution guidelines for setup, validation and pull request requirements. The OSSAfrica contribution guide and Code of Conduct also apply.

Every contribution commit requires a DCO sign-off and a GitHub-verified cryptographic signature (git commit -S -s).

License

MIT

About

Frontend library for encrypting data in the browser

Resources

Code of conduct

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages