Skip to content

Add WebAssembly support: browser keyrings, an in-memory backend and WASI - #8

Merged
mikelodder7 merged 18 commits into
mikelodder7:mainfrom
dougcooper:feat/wasm-support
Nov 21, 2026
Merged

mikelodder7 merged 18 commits into
mikelodder7:mainfrom
dougcooper:feat/wasm-support

Conversation

@dougcooper

Copy link
Copy Markdown

Why

cryptex had no backend that could run in a browser: the OS keyrings need an OS, file and encrypted-vfs are SQLCipher plus a bundled C VFS, and YubiHSM needs USB. This adds WASM support for both wasm32-unknown-unknown and WASI, with the browser as the primary target and persistence built in rather than left to the caller.

This addresses #7: a TursoKeyring can now adopt a caller's connection or run through a caller's IO, which is what a consumer that already has an OPFS-backed turso_core::IO in a worker needs.

What is new

Feature wasm32-unknown-unknown WASI Notes
memory yes yes sealed image in RAM, export/import
turso yes yes Turso's page encryption, plus in-memory and OPFS keyrings
turso-encrypted-io builds yes the file-backed page store is native only
web-storage yes no a MemoryKeyring in localStorage
indexeddb yes no encrypted image snapshots, one per keyring
opfs yes no the database file itself, in the origin private file system
js yes no the wasm-bindgen Keyring class
file, encrypted-vfs, OS keyrings, yubihsm-* no no compile error naming the problem, not a linker failure

Rust API

  • MemoryKeyring: with_params, import, export, rekey. The blob carries the salt, cipher and Argon2 parameters, the header is the AAD, and it is hand-encoded rather than serde.
  • TursoKeyring: from_connection and with_io (addresses turso keyring cannot target wasm32-unknown-unknown: expose an IO/connection seam #7), in_memory, from_bytes, export, copy_under (non-destructive rekey), open_opfs.
  • cryptex::indexeddb::SnapshotStore, cryptex::web_storage, cryptex::opfs.
  • A PageStore trait under page_cipher, so the encrypted page layout [ct(4096)|nonce(12)|tag(16)] is shared by files, memory and OPFS and the bytes stay compatible across them.

JavaScript

const keyring = await Keyring.open("password=... salt=...", "settings");
await keyring.set("api-token", new TextEncoder().encode("s3cret"));
keyring.get("api-token"); // Uint8Array
await keyring.close();    // releases the Web Lock / OPFS handle

Options are { backend: "turso"|"memory", store: "indexeddb"|"opfs"|"localstorage"|"memory" }, defaulting to an encrypted Turso image in IndexedDB that is written after every resolved set/delete and guarded by a Web Lock, so a second tab is refused with AccessDenied instead of overwriting. rekey is available except on OPFS, where the database cannot be rewritten in place. Errors are Error whose message starts with the kind. examples/web/ has an IndexedDB page and an OPFS worker.

Also

  • block_on gains a bounded-poll wasm path (Turso's futures must complete in place; there is no thread to park), and a JavaScript-backed Clock, because Turso's DefaultClock calls Instant::now(), which panics on wasm32-unknown-unknown.
  • WASI: try_lock reporting Unsupported is treated as success and the default directory is ./.cryptex; the CLI is native-only and says so on wasm.
  • getrandom uses the wasm_js backend (set in .cargo/config.toml), with CI coverage for wasm32-unknown-unknown and both WASI targets.

Verification

  • native: 37 lib tests, 4 doctests, clippy -D warnings over file,serde,memory,turso,turso-encrypted-io
  • WASI under wasmtime: 25 tests
  • wasm-pack test --headless --chrome: 3 binding tests in tests/wasm.rs
  • a 25-check browser harness, kept outside the repo, covering IndexedDB persistence and encryption, wrong-key refusal, rekey, the second-tab lock, localStorage, memory import/export, and OPFS in a worker across a close and reopen
  • clippy clean for every wasm feature combination, cargo fmt --check clean

Notes for the reviewer

  • The version moves to 2.5.0. --all-features can no longer build (the browser features are wasm-only by design), so CI and docs.rs name their features explicitly.
  • OPFS needs createSyncAccessHandle(), which browsers expose only in a worker, so store: "opfs" is refused on the main thread.
  • The README documents the security caveat: any script on the origin can read IndexedDB, OPFS and localStorage, so the encryption protects against other origins and users, not a compromised page, and the browser may evict the data unless navigator.storage.persist() is granted.

Doug Cooper added 8 commits November 20, 2026 14:30
TursoKeyring can now adopt an already-open connection (from_connection)
or open through a caller-supplied turso IO (with_io), so a browser worker
can keep the keyring's secrets table next to its own tables in one OPFS
database. Rekey needs cryptex to own the storage, so it reports a clear
error for adopted keyrings.

turso_common::block_on no longer parks when built for wasm: it polls a
bounded number of times and fails instead of spinning forever.

The memory backend keeps secrets encrypted in RAM and seals them into a
single AEAD blob for export/import, which is the base for browser
storage and the JS bindings. CipherAlgorithm moved to its own module so
it no longer drags in the page cipher.

cargo check --target wasm32-unknown-unknown --no-default-features
--features turso passes; a wasm CI job covers it.
acquire_single_opener_lock treats an Unsupported lock as success, which
is what WASI reports, and the default keyring directory there is
./.cryptex instead of a home directory that does not exist.

Criterion is native-only (Rayon does not build for wasm) and the CLI is
split into src/native.rs so a wasm build of the binary compiles and
prints that it is unsupported.

cargo test --target wasm32-wasip1 --no-default-features
--features turso,memory passes under wasmtime.
Turso's file traffic now goes through a PageStore trait, so the page cipher
works over a native file, an in-memory buffer or (next) an OPFS handle.

On top of it, a Turso IO keeps every database and WAL file in memory, reads
and writes complete in place, and the clock comes from the JavaScript
runtime: the default clock calls Instant::now, which panics on wasm.

That gives TursoKeyring::in_memory, from_bytes and export, which is how a
browser persists a keyring without a filesystem.
IndexedDB keeps one encrypted image per keyring and takes a Web Lock named
after it, so a second tab fails instead of overwriting the first.

localStorage holds the same image for synchronous code that cannot await,
and OPFS gives a worker a real file, opened through sync access handles so
Turso never waits on a promise it cannot park for.
Keyring.open picks a backend (a Turso database or a plain memory image) and
a store (IndexedDB, localStorage, OPFS or none), so a page can keep secrets
without knowing which of them it needs. set and delete resolve once the
image reached storage; export copies it out.

Also add a browser example: IndexedDB from the page, OPFS from a worker.
…lose

An in-memory keyring opened its database under one fixed path, so two of
them shared a page cache and an encryption key. Give each its own path,
reopen an imported image under the path it was written as, and let a rekey
copy into a fresh database instead of replacing the one in place.

Closing a JavaScript keyring now drops the underlying database, which is
what releases an OPFS sync access handle or an IndexedDB lock, and the
flush no longer tries to export an OPFS keyring that has no image.
The memory backend writes its sealed image to IndexedDB too, so the only
difference from the default is that there is no database underneath. That
also makes the localStorage path the same code, and asking for OPFS with a
memory keyring is refused instead of silently losing the store.

Closing a keyring now waits for the Web Lock to actually be released: the
release is asynchronous, so reopening the same name in the same page could
otherwise be refused. Browser tests for the bindings join the repository as
tests/wasm.rs, run with .
The README gains the JavaScript API, the backend/store combinations, what
each store persists, the Web Lock that keeps two tabs from fighting over one
keyring, and the costs: any script on the origin can read browser storage,
the browser may evict it, and Argon2 blocks the thread it runs on.

CI builds the wasm package and runs tests/wasm.rs in headless Chrome, and
the version moves to 2.5.0.
@dougcooper
dougcooper marked this pull request as draft November 20, 2026 20:51
Doug Cooper added 2 commits November 20, 2026 16:02
The example pre-filled a password with spaces, which the whitespace-separated
connection string cannot carry, so Open failed with a parser byte offset. Use
a password without spaces and say why if one is typed. Reading a missing
secret then failed loudly too: the kind is in error.message, not in
String(error), which prepends "Error: ".
The page could read a secret but not ask a keyring what it holds. Add
TursoKeyring::keys and MemoryKeyring::keys, and SnapshotStore::list_names,
which reads IndexedDB without taking the lock, then expose them to
JavaScript as keyring.keys() and storedKeyrings(). The example page shows
both lists and opens a keyring when its name is clicked.
Doug Cooper added 4 commits November 20, 2026 16:46
storedKeyrings now takes a store: IndexedDB is still the default, and
localStorage and OPFS each have their own listing. Neither reads an image,
so both are safe while a tab holds the keyring open, and listing OPFS works
from a page even though opening one needs a worker.

The example page shows all three stores, tags each row with the store it
came from, and can open a keyring from either store the page can reach.
Turso's process-wide registry is keyed by the IO's file_id, so two IOs
holding a same-named file resolved to one open database: a keyring opened
from an image could read and write another keyring's secrets under the
other's key. Give every IO an id of its own, and open a restored image
under a fresh path instead of the one it recorded.

The snapshot reader also trusted a file count from an unauthenticated
header to size a map; a fifteen-byte input aborted the process. Refuse a
count that is not the database and its WAL, and check the stored value is
an image before converting it.
An imported blob carried its Argon2 costs in an unauthenticated header,
so a crafted image could demand terabytes and minutes of work before the
AEAD noticed. Bound them before deriving, and check the salt length with
checked arithmetic: on wasm32 the old check wrapped and a debug build
panicked slicing the blob.

On the browser side, a closed keyring now refuses every call instead of
silently accepting writes that go nowhere, a localStorage keyring takes
the same single-opener Web Lock as IndexedDB, an aborted transaction
rejects instead of hanging, and a repeated connection-string keyword is
an error rather than a silent override. Secret buffers and the AEAD key
schedules are zeroized.
The explicit feature lists replaced --all-features, which quietly stopped
linting, testing and documenting the YubiHSM backends; list them too. Give
the workflow a read-only token and build wasm-pack from a pinned version
instead of piping an unpinned installer into a shell.

The README now says what the encryption does not cover: a stale image is
not detected, and the connection string is a small DSL, so a password with
whitespace or quotes in it is not passed through unchanged.
@dougcooper
dougcooper marked this pull request as ready for review November 20, 2026 22:38
TursoKeyring carried the store and an Option<Arc<WebIo>> that was Some
exactly when cryptex made the database itself. Two fields, one meaning:
export and copy_under branched on the flag, each constructor patched it
afterwards, and on a native build the field was always None.

Make it one enum: Stored holds a file or a caller's connection, InMemory
holds the database cryptex made plus the IO that can copy it out. export
is now a match arm rather than a runtime check, and the two modes cannot
drift.

Also rename the opfs feature to turso-opfs. It is a Turso IO, not a store
that layers over export(), so it belongs beside turso-encrypted-io rather
than beside indexeddb and web-storage. The JS store name is unchanged.
mikelodder7 and others added 3 commits November 21, 2026 07:58
argon2 0.6, dirs 7, rusqlite 0.43, sqlite-plugin 0.11, turso 0.9.0-pre.6.
bindgen stays at 0.72 to match sqlite-plugin, so cargo-outdated ignores it.
The argon2 example test now builds into its own target dir; sharing the
unhashed rlib dropped memory and turso from the one doctests link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KiuMTUBySDSj38NVDFgn2b
…river

windows.rs uses as_chunks for the UTF-16 decode (chunks_exact_to_as_chunks).
file_common doctests import file_common::ConnectionParams, which exists
without the file feature. The browser tests use the runner's ChromeDriver,
which matches its Chrome; setup-chrome installed a newer driver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KiuMTUBySDSj38NVDFgn2b
@mikelodder7
mikelodder7 merged commit d3e1c3f into mikelodder7:main Nov 21, 2026
25 checks passed
@dougcooper
dougcooper deleted the feat/wasm-support branch November 21, 2026 17:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants