Skip to content
adelzemzemiPublic

About

Password-based encryption for browser storage and Node.js. AES-256-GCM on the Web Crypto API, zero dependencies.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

13 stars

Watchers

0 watching

Forks

Repository files navigation

CryptoBox: browser storage, encrypted. What your app stores is unreadable without the user's password.

Password-based encryption for browser storage and Node.js

CI npm version Node.js License

Whatever an application leaves in localStorage is plain text for anyone who gets a copy of it: a copied browser profile, a backup, a shared or synced device. CryptoBox stores it encrypted under a password the user supplies. The copy becomes unreadable, a modified value is rejected instead of returned, and a value moved to another key stops decrypting.

Try the live demo: store a value, then read it back with the wrong password or after flipping one stored bit.

What changes in your storage

await storage.setSecure('user', { id: 123 }, 'password');
What localStorage holds under user
Without CryptoBox {"id":123}
With CryptoBox AgAJJ8BRpePRUtROg3Bn2lf4qukLA08RLjZZxT2NGt9yQvstnZOo…

Reading it back has three possible outcomes, and no fourth:

Situation Result
The right password { id: 123 }
A wrong password, or a value altered by one bit DECRYPTION_FAILED
The same ciphertext copied under another key DECRYPTION_FAILED

This is protection for data at rest. Script running in your own page (an XSS, a malicious dependency) sees the plaintext after decryption whatever the cipher, and a password shipped inside the bundle protects nothing: see Security.

Why CryptoBox?

  • One call to adopt: setSecure() and getSecure() over localStorage, sessionStorage, IndexedDB or any key-value store
  • Safe defaults, no decisions to make: AES-256-GCM, PBKDF2 at 600,000 iterations, a fresh salt and IV per write, an authenticated header
  • Bound to its place: each stored value is tied to its key, so swapping two ciphertexts fails
  • Nothing to audit but this: zero runtime dependencies, about 6.5 kB gzipped, built on the Web Crypto API your runtime already ships
  • Data that survives upgrades: parameters travel inside each ciphertext, 1.x data still decrypts, and rewrap() migrates it in place
  • Typed end to end: strict TypeScript, one error class with stable codes, runtime validation on read
  • Runs where you do: browsers, Node.js 20+, Deno, Bun; synchronous and asynchronous backends alike

How it is checked

  • Frozen ciphertexts, including ones written by 1.0.x, are committed to the test suite: if one stops decrypting, the format broke
  • A second implementation agrees: envelopes are written and read by OpenSSL through node:crypto, in both directions
  • Hostile input: truncations and single-bit flips of a valid ciphertext, and thousands of random buffers, all end in a documented error
  • Coverage is a gate: 100% of lines, functions and statements, enforced in CI on Node.js 20, 22 and 24
  • Beyond Node.js: the packed tarball is installed and exercised under Bun and Deno, and the built module in headless Chrome, on every change
  • Traceable releases: published from CI with npm provenance, with no long-lived token

It has not been audited by a third party. SECURITY.md holds the threat model and the known limitations.

Requirements

  • Node.js 20 or later, or any runtime with the Web Crypto API: current browsers, Deno, Bun
  • A secure context in the browser (https or localhost), which Web Crypto requires
  • TypeScript types are included; TypeScript itself is optional

Installation

npm install @azemzemi/cryptobox

Upgrading from 1.0.x? See the migration guide.

Quick start

import { createSecureLocalStorage } from '@azemzemi/cryptobox';

const storage = createSecureLocalStorage();

await storage.setSecure('user', { id: 123 }, 'password');
const user = await storage.getSecure('user', 'password');

Every method is asynchronous, including has() and remove(), because the backend may be.

API

Storage

createSecureLocalStorage(); // Browser: localStorage
createSecureSessionStorage(); // Browser: sessionStorage
createSecureMemoryStorage(); // Universal: in-memory

All three are safe to construct anywhere, including during server-side rendering. The two browser-backed ones resolve their global lazily and throw STORAGE_UNAVAILABLE only when a read or write actually happens without one (Node.js, Deno, Bun, workers, SSR). So a module-scope store in a Next.js or Nuxt app is fine as long as it is only used in the browser; otherwise reach for createSecureMemoryStorage(), or supply your own IStorage.

Encryption

import { AesGcmEncryptor } from '@azemzemi/cryptobox';

const encryptor = new AesGcmEncryptor();
const encrypted = await encryptor.encrypt(data, 'password');
const decrypted = await encryptor.decrypt(encrypted, 'password');

Any JSON-serializable value works, including null. Values JSON cannot represent (undefined, functions, symbols) are rejected rather than silently corrupted.

getSecure() returns null both for a stored null and for a key that does not exist. Use has() when the difference matters.

A password is used exactly as given: its UTF-8 bytes go into the key derivation, with no Unicode normalization. café typed with a precomposed é (NFC) and with e plus a combining accent (NFD) look identical but are two different passwords, and one does not decrypt what the other wrote. Keyboards, input methods and operating systems do not all produce the same form, so normalize the password the same way before every call, for example with password.normalize('NFC'). Data already stored keeps needing the form it was written with.

Typed errors

Every failure raised by the package is a CryptoBoxError carrying a stable code. Match on the code, not on the message. Errors thrown by your own storage backend (a full quota, a closed database) pass through unchanged.

import { isCryptoBoxError } from '@azemzemi/cryptobox';

try {
  await storage.getSecure('session', password);
} catch (error) {
  if (isCryptoBoxError(error, 'DECRYPTION_FAILED')) promptForPassword();
  else throw error;
}
Code Meaning
DECRYPTION_FAILED Wrong password, tampered data, or a mismatched context
MALFORMED_CIPHERTEXT Not a well-formed envelope
UNSUPPORTED_ENVELOPE Readable version, refused by allowLegacy: false
INVALID_BASE64 Input is not valid base64
INVALID_ITERATIONS Iteration count out of range, too low to write, or above maxIterations
INVALID_ARGUMENT An argument does not have the expected shape
SERIALIZATION_FAILED Value is not representable in JSON
DESERIALIZATION_FAILED Decrypted payload is not valid JSON
VALIDATION_FAILED Decrypted payload rejected by the supplied validator
STORAGE_UNAVAILABLE The storage backend is absent from this runtime, or blocked
UNSUPPORTED_ENVIRONMENT A required global is missing

Use isCryptoBoxError() rather than instanceof: the package ships several entry points, and a duplicated copy of the class would defeat an identity check.

Validating what you decrypt

decrypt<T>() and getSecure<T>() cannot check T on their own: the bytes are authentic, but a payload written by an older version of your application may no longer have the shape you expect. Pass a type guard whenever the data outlives the code that wrote it.

import { isPlainObject } from '@azemzemi/cryptobox';

function isUser(value: unknown): value is User {
  if (!isPlainObject(value)) return false;

  const { id, name } = value;
  return typeof id === 'number' && typeof name === 'string';
}

const user = await storage.getSecure('user', password, { validate: isUser });

isPlainObject() narrows to Record<string, unknown>, so destructure the fields rather than reaching for them with dot notation: that keeps the guard compiling under noPropertyAccessFromIndexSignature.

const stale = await encryptor.encrypt({ id: 'not-a-number' }, password);

// CryptoBoxError, code VALIDATION_FAILED, instead of a crash further down.
await encryptor.decrypt(stale, password, { validate: isUser });

Context binding

Each value written through SecureStorage is bound to the key it lives under. An attacker who can write to localStorage therefore cannot swap two ciphertexts and have them decrypt in the wrong place.

await storage.setSecure('role:guest', { admin: false }, password);
await storage.setSecure('role:admin', { admin: true }, password);

// Copying the admin ciphertext over the guest key no longer decrypts.

Important

Binding covers values written by 2.x. A value written by 1.x has no binding, and while allowLegacy is on (the default) it is accepted under any key: an attacker can still place an old 1.x ciphertext where they like. The protection is complete once the data has been migrated with rewrap() and allowLegacy is false. rewrap() binds whatever sits under a key at that moment, so migrate from a store you trust.

The same binding is available directly:

const encrypted = await encryptor.encrypt(data, password, { context: 'tenant:42' });
await encryptor.decrypt(encrypted, password, { context: 'tenant:42' });

The context is not secret and is not stored: the caller must be able to reproduce it. It must be a string: a number or an object is refused with INVALID_ARGUMENT rather than converted, since every object would otherwise bind to the same "[object Object]". Leaving it out means no context. Pass { bindToKey: false } to a store whose ciphertexts must stay transferable.

Tuning the KDF, and migrating

// Slower, stronger. The value is stored in the ciphertext.
const strong = new AesGcmEncryptor({ iterations: 1_200_000 });

// Decryption reads the iteration count from the data; nothing to configure.
await new AesGcmEncryptor().decrypt(await strong.encrypt(data, pw), pw);

What it costs

A key is derived on every operation: the password is an argument, not instance state, so nothing is cached between calls. At the 600,000-iteration default that is roughly 65 ms per read or write on a desktop, and several times that on a mid-range phone. Ten values written in a loop means ten derivations.

Budget for it: batch a page's writes into one object rather than one key per field, and keep hot-path values out of encrypted storage. Where the threat model allows it, lowering the count is a deliberate, recorded choice:

// Recorded in the ciphertext, so existing data is unaffected.
const cheap = new AesGcmEncryptor({ iterations: 100_000 });

100,000 is the lowest count the package writes with. Anything below it is refused with INVALID_ITERATIONS, because a low count makes the password cheap to brute-force from a stolen ciphertext. Test suites, which need speed and protect nothing, can opt out:

const forTests = new AesGcmEncryptor({ iterations: 1000, allowWeakIterations: true });

Reading is unaffected: a ciphertext written below the minimum still decrypts.

The count a read derives with comes from the stored value, and it has to be used before the authentication tag can be checked. Whoever can write to the store can therefore raise it, up to 5,000,000, and make a read that is going to fail cost about eight times the default first. Cap it at the highest count your application ever wrote with:

const encryptor = new AesGcmEncryptor({ maxIterations: 600_000 });

A value declaring more is then refused with INVALID_ITERATIONS without deriving a key at that count. While allowLegacy is on (the default), the same bytes are still tried once as a headerless 1.x value, at its fixed 100,000 iterations, before the refusal; with allowLegacy: false nothing is derived at all. The same encryptor refuses to write above its own cap, so a per-call iterations higher than maxIterations fails with INVALID_ARGUMENT instead of producing a value it could not read back. The cap is not on by default, because a store may hold values written with a higher count than the one configured today.

Amortising the derivation properly needs an encryptor that holds a CryptoKey instead of a password. That is a different envelope mode and is not part of 2.0.0.

Raising the parameters does not upgrade existing data on its own. rewrap() does. It returns false when the value was already current, so it is safe to call on every key:

await storage.rewrap('user', password); // true if the value was rewritten

needsRewrap() answers without the password, which makes it useful for counting what is left to migrate but not for deciding what to skip: about one 1.x ciphertext in 200,000 starts with bytes that read like a current header. rewrap() decrypts, so it is never fooled. Run it over every key before turning legacy reads off.

You can also inspect a ciphertext without the password:

import { inspect, needsRewrap, rewrap } from '@azemzemi/cryptobox';

inspect(ciphertext); // { version: 2, iterations: 600000, contextBound: true }
needsRewrap(ciphertext); // true while it is below the current parameters
await rewrap(ciphertext, password, { context: 'tenant:42' });

Once the stored data has been migrated, close the door on the older format:

const storage = createSecureMemoryStorage({ allowLegacy: false });

allowLegacy can be set on the store or on the encryptor (new AesGcmEncryptor({ allowLegacy: false })). The store's setting wins when both are given.

A 1.x value that was missed by the migration is then refused, usually as UNSUPPORTED_ENVELOPE. About one in 256 starts with the byte that announces the current format and is reported as MALFORMED_CIPHERTEXT or DECRYPTION_FAILED instead, so do not read those two codes as proof that the data is damaged.

rewrap() re-reads the value before writing it back and leaves it alone if it changed, but two migrations running at once (two tabs, two workers) can still overwrite each other. Run it from one place.

Custom Storage

IStorage accepts synchronous and asynchronous backends alike, so the same SecureStorage works over localStorage, IndexedDB, chrome.storage, React Native's AsyncStorage or a server-side key-value store.

import { SecureStorage, AesGcmEncryptor } from '@azemzemi/cryptobox';
import type { IStorage } from '@azemzemi/cryptobox';

class IndexedDbStorage implements IStorage {
  async setItem(key: string, value: string): Promise<void> {}
  async getItem(key: string): Promise<string | null> {
    return null;
  }
  async removeItem(key: string): Promise<void> {}
}

const storage = new SecureStorage(new IndexedDbStorage(), new AesGcmEncryptor());

A custom IEncryptor receives context and allowLegacy in its options. If it ignores them, key binding and downgrade protection are off for that store.

Utilities

import {
  timingSafeEqual,
  timingSafeEqualBuffer,
  randomDelay,
  safeJsonParse,
  safeJsonStringify,
  encodeBase64,
  decodeBase64,
} from '@azemzemi/cryptobox';

timingSafeEqual removes the data-dependent early exit, which is the part a JavaScript library can control. It is best-effort: the engine's string representation and JIT are not under its control, and input length is not hidden. For byte comparison on Node.js, crypto.timingSafeEqual is the stronger primitive.

Ciphertext format

base64( version(1) || iterations(4, big-endian) || salt(16) || iv(12) || ciphertext+tag )

The 5-byte header is passed to AES-GCM as additional authenticated data, together with the caller's context. Neither the declared version nor the declared iteration count can be altered without invalidating the tag, and a ciphertext cannot be replayed under a different context.

Version Written by Layout Header authenticated Context
0 1.0.x salt || iv || body none none
2 2.x headered yes yes

Version 0 is still read transparently, so upgrading does not strand existing data. It carries no context binding and uses 100,000 PBKDF2 iterations: that is what rewrap() upgrades.

Device fingerprinting

Fingerprinting ships under its own entry point. It only runs in a browser, and collecting device characteristics carries privacy obligations that the rest of the package does not impose on its consumers.

import {
  getDeviceFingerprint,
  isDeviceFingerprintAvailable,
} from '@azemzemi/cryptobox/fingerprint';

Warning

Never use getDeviceFingerprint() as an encryption password. The value is not stable: a browser update, a new monitor, a timezone change or an anti-fingerprinting setting all change it, and the data encrypted under the old value becomes permanently unrecoverable. Use it as a signal (for example, to force re-authentication when a session appears on a different device), never as key material.

Migrating from 1.0.x

Important

has() is now asynchronous. In JavaScript without type checking, if (storage.has(k)) still compiles and is now always true: a promise is truthy. This is the one change that fails silently instead of loudly, so grep for .has( before upgrading.

- if (storage.has('session')) { … }
+ if (await storage.has('session')) { … }

TypeScript reports it as a type error, so only untyped call sites are at risk.

The 1.0.x aliases are gone. Replacements:

Removed Use instead
encryptData / decryptData new AesGcmEncryptor() + .encrypt() / .decrypt()
encryptToken / decryptToken encrypt / decrypt
SecureLocalStorage / SecureSessionStorage / SecureMemoryStorage createSecureLocalStorage() and friends
LocalTokenStorage / SessionTokenStorage / MemoryTokenStorage LocalStorage / SessionStorage / MemoryStorage
TokenStorage IStorage
getDeviceFingerprint from the main entry @azemzemi/cryptobox/fingerprint

Two further signature changes:

- storage.remove('key')         // void
+ await storage.remove('key')   // Promise<void>

- createSecureLocalStorage(myEncryptor)
+ createSecureLocalStorage({ encryptor: myEncryptor })

Errors are now CryptoBoxError. Several messages changed since 1.0.2, so code that matched on message text must move to isCryptoBoxError(error, code).

Behaviour that changes without a signature change:

  • require('@azemzemi/cryptobox') works. In 1.0.2 the CommonJS entry resolved to an empty object on Node 22+ and threw ERR_REQUIRE_ESM on Node 18 to 20.
  • PBKDF2 defaults to 600,000 iterations instead of 100,000, so encryption is roughly six times slower. Existing ciphertexts still decrypt at their recorded count.
  • deriveKey(password, salt) follows the same default. If you called it directly in 1.x without an iteration count, pass 100_000 explicitly to keep deriving the same key.
  • 1.x cannot read what 2.0 writes. The upgrade is one-way for stored data: after a rollback to 1.x, or while an old tab or service worker still runs the 1.x bundle, every value written by 2.0 fails to decrypt. Ship 2.0 to every client that shares a store before relying on it.
  • A wrong password and corrupted data now fail identically, and the failure no longer names the storage key. In 1.0.2 the error was a decryption oracle.
  • null round-trips. undefined, functions and symbols are rejected instead of silently producing a corrupt ciphertext.
  • MemoryStorage.getItem() returns '' for a stored empty string rather than null.
  • LocalStorage / SessionStorage throw STORAGE_UNAVAILABLE on first use outside a browser instead of a bare ReferenceError. Constructing them is always safe.
  • A password must be a string, and a non-empty one to encrypt. undefined and null used to be coerced, silently encrypting under '' or 'null'. Data that 1.x wrote under an empty password still decrypts.

Stored data needs no migration to keep working. To gain context binding and the current iteration count on data written by 1.0.x, run rewrap() (see Tuning the KDF).

Security

  • AES-256-GCM authenticated encryption
  • PBKDF2-HMAC-SHA256, 600,000 iterations by default (OWASP recommendation)
  • A fresh random salt and IV per encryption
  • The envelope header is authenticated, so its version and iteration count cannot be altered. With allowLegacy: false, a downgrade to the 1.x format is rejected
  • Ciphertexts are bound to a context, so relocating one does not decrypt it
  • Uniform failure for wrong passwords, corrupted data and mismatched contexts, so the error is not a decryption oracle
  • Iteration counts read from a ciphertext are range-checked, so a hostile envelope cannot force unbounded key-derivation work

This library has not been audited by a third party. The reviews behind the list above were done by the maintainers. It is also client-side encryption: it protects data at rest against someone reading the storage, not against script running on your own origin: an XSS reads the plaintext after decryption regardless of the cipher.

See SECURITY.md for the threat model, the audit status and vulnerability reporting.

License

MIT

About

Password-based encryption for browser storage and Node.js. AES-256-GCM on the Web Crypto API, zero dependencies.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

13 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages