Zero-dependency, production-grade browser encrypted storage using non-extractable Web Crypto AES-256-GCM CryptoKeys persisted in IndexedDB.
Features multi-tab first-key race arbitration, zero-downtime migration from localStorage, PBKDF2-SHA512 client password stretching, and Ed25519 update manifest signature verification.
Most "encrypted localStorage" packages on npm suffer from critical architectural flaws:
- They keep the secret key or passphrase as a plaintext string in JavaScript memory, environment variables, or directly inside
localStorage. - In the event of a Cross-Site Scripting (XSS) attack, an attacker can trivially extract the key and decrypt all customer data offline.
- When multiple browser tabs open simultaneously for the first time, naive key generation causes a race condition where tabs overwrite each other's keys, permanently corrupting saved data.
webcrypto-secure-storage addresses these issues from the ground up:
- Non-Extractable Master Keys (
extractable: false): Keys are generated natively via the Web Crypto API (AES-256-GCM, 256-bit) and stored directly inIndexedDBas structured cloneableCryptoKeyobjects. Becauseextractable: falseis enforced by the browser engine, the raw key bytes cannot be exported from theCryptoKeyeven if arbitrary JavaScript is injected via XSS. Non-extractability does not stop active same-origin JavaScript from calling this library's APIs or reading plaintext returned to the application. - Multi-Tab First-Key Race Arbitration:
Uses
IDBObjectStore.add()with atomicConstraintErrorhandling. If two tabs initialize the key store at the exact same millisecond, the losing tab catches the conflict, discards its tentative key, and loads the committed winner's key. - Fail-Closed Security:
Never silently falls back to Base64 or unencrypted storage. If Web Crypto or IndexedDB is unavailable, it throws a strict
CryptoUnavailableError(unless legacy migration fallback is explicitly configured). - Seamless Migration from Legacy
localStorage: Automatically detects and decrypts legacylocalStoragekeys, securely migrates both key and payload to IndexedDB with non-extractable flags, and purges the plaintext key fromlocalStorage. - Zero External Dependencies:
Built exclusively on modern Web APIs (
crypto.subtleandindexedDB). Tiny footprint (~17 kB tarball).
npm install webcrypto-secure-storageimport { SecureStorage } from 'webcrypto-secure-storage';
// Initialize storage with a master key name
const storage = new SecureStorage('my-app-auth-key');
// Store sensitive user profile or credentials (with optional TTL auto-expiration)
await storage.setItem('auth_session', {
userId: 'usr_98124',
token: 'secret-auth-token',
role: 'admin',
}, { ttlMs: 1000 * 60 * 60 }); // Auto-expires after 1 hour
// Retrieve typed data (returns null and auto-purges if expired or absent)
interface Session {
userId: string;
token: string;
role: string;
}
const session = await storage.getItem<Session>('auth_session');
console.log(session?.userId); // 'usr_98124'
// Inspect item metadata (expiration timestamp and status)
const meta = await storage.getMetadata<Session>('auth_session');
console.log(meta?.expiresAt, meta?.expired);
// Key management, clearing and expired item purging
const allKeys = await storage.keys();
const purgedCount = await storage.purgeExpired();
// await storage.clear();
// Multi-tab atomic coordination via Web Locks API
await storage.withLock(async () => {
const current = (await storage.getItem<number>('counter')) ?? 0;
await storage.setItem('counter', current + 1);
});
// Passphrase-encrypted backup bundle export and import
const backupBundle = await storage.exportEncryptedBundle('super-secret-passphrase');
// In another tab or after restore:
await storage.importEncryptedBundle(backupBundle, 'super-secret-passphrase');
// Remove item
await storage.removeItem('auth_session');You can also use the storage instance for direct string encryption:
const storage = new SecureStorage('my-master-key');
const cipherText = await storage.encrypt('Confidential Data');
const plainText = await storage.decrypt(cipherText);
console.log(plainText); // 'Confidential Data'Optionally derives a deterministic client-side PBKDF2-SHA512 pre-hash before transmission. Treat the result as a replayable password-equivalent: this does not replace HTTPS, server-side password hashing, or login rate limits. The server should still store a separately salted adaptive password hash (such as Argon2id, scrypt, or bcrypt) and apply its normal authentication protections.
import { hashPasswordClient, deriveClientPasswordHash } from 'webcrypto-secure-storage/password';
// Uses 100,000 PBKDF2 rounds with SHA-512 and normalized loginId as a deterministic salt
const clientHash = await hashPasswordClient('userPassword123', 'User@Example.com');
console.log(clientHash); // 128-character hex stringFor complete update responses, use verifyUpdateManifestSignature from the root export.
The signed payload must bind product, channel, downloadUrl, sha256, publishedAt,
and latestVersion (or version), plus forceUpdate and any supplied policy/display fields.
Unsigned sibling artifact fields and partially signed responses are rejected. See migration details.
The low-level function below authenticates only the payload passed to it. Check the downloaded
artifact hash and enforce update freshness/anti-rollback in the consuming application.
Verify software update manifests or remote configurations using Ed25519 public keys:
import { verifyEd25519ManifestSignature } from 'webcrypto-secure-storage/signature';
const isValid = await verifyEd25519ManifestSignature(
{ version: '2.0.0', sha256: '...' },
manifestSignatureBase64,
publicKeyPem
);export interface SharedSecureStorageOptions {
/**
* Custom IndexedDB database name.
* Default: 'webcrypto_secure_key_db'
*/
databaseName?: string;
/**
* Temporary migration switch for legacy environments without IndexedDB.
* WARNING: Setting this to true stores extractable keys in localStorage.
* Default: false
*/
allowLegacyLocalStorageKeyFallback?: boolean;
}Example:
const storage = new SecureStorage('custom-key', {
databaseName: 'my_custom_db',
});ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Browser App β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β setItem('data', value) β
β β β
β βΌ β
β [Web Crypto API] βββ AES-256-GCM β
β β IV (12 bytes) + Tag (16 bytes) β
β β β
β [CryptoKey] ββββ extractable: false β
β β (JS cannot inspect raw key bytes) β
β βΌ β
β [IndexedDB Store] ββ Structured Clone Storage β
β β² β
β Multi-Tab Race ββ First-key-wins atomic arbitrationβ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The test suite runs with Node.js built-in test runner without external dependencies:
npm testComplementary zero-dependency, high-performance security modules for Edge runtimes, Cloudflare Workers, and modern Node.js:
- wasm-crypto-hash: Ultra-fast WebAssembly & WebCrypto cryptographic suite (SHA-2/3, BLAKE3, PQC, Argon2, TOTP, BIP-39).
- edge-rate-limiter: Zero-dependency sliding-window & token-bucket rate limiter with Zero-PII keyed hashing.
- edge-secure-token: Zero-dependency, timing-safe WebCrypto JWT suite with field-level claims encryption.
- edge-session-crypto: Stateless encrypted cookie session manager with AES-GCM and key rotation.
- zero-pii-redactor: High-speed, ReDoS-free PII redactor, tokenizer, and pseudonymizer for logs and AI prompts.
- edge-audit-crypto: Tamper-evident cryptographic append-only audit trail logging.
MIT License Β© 2026 takao-dev