pglite-cipher: encryption at rest for PGlite

pglite-cipher encrypts a PGlite database, the Postgres build that runs in the browser, the way SQLCipher encrypts SQLite. It is a PGlite filesystem (EncryptedFs) that seals every file under PGDATA with AES-256-GCM through WebCrypto and stores the blocks in IndexedDB. It has no runtime dependencies.

What it does

Install and quick start

npm install pglite-cipher @electric-sql/pglite
import { PGlite } from '@electric-sql/pglite';
import { EncryptedFs, IndexedDbBackend, importKek } from 'pglite-cipher';

const key = await importKek(rawKey); // 32 random bytes, e.g. from the OS keychain
const fs = new EncryptedFs({ backend: new IndexedDbBackend('data'), key, mode: 'open-or-create' });
const pg = await PGlite.create({ fs, relaxedDurability: true });

await pg.exec('CREATE TABLE IF NOT EXISTS notes (id serial PRIMARY KEY, body text)');
await fs.syncToFs(false); // sync when it matters, e.g. when the page is hidden
await pg.close();

@electric-sql/pglite (^0.5.10) is a peer dependency.

Questions

How do I encrypt a PGlite database?

Pass an EncryptedFs from pglite-cipher as PGlite's fs option, as above. Moving an existing idb:// database over is covered in the existing-app guide.

Is there a SQLCipher for Postgres in the browser?

pglite-cipher fills that role for PGlite. The comparison sets it against SQLCipher and other options.

Where should the key come from?

In an app, 32 random bytes from the iOS Keychain, Android Keystore or the OS secret store. On the web, derive one from a passphrase in your app. See the keys guide.

What does it not protect?

While the database is open its contents are plaintext in memory, and exports such as dumpDataDir() are plaintext. A rollback of the whole store to an older full copy opens. See SECURITY.md.

How fast is it?

The demo times plain and encrypted stores in your own browser. Device measurements are in performance.md.

Licence

FSL-1.1-ALv2, © Bishwajeet Parhi. Each release becomes Apache 2.0 two years after it ships.