Getting Started with Encryption

Encrypt columns so that only your users' devices can read them.
Note

End-to-end encryption has just been relaunched in Jazz. If you run into any issues, join us on Discord.

With end-to-end encryption, your users' devices encrypt the columns you choose before the data leaves them. The server stores and syncs the encrypted values and holds no keys. Permissions work as usual, and they also decide who gets the keys.

Encryption protects your data from anyone who gets the stored values outside Jazz, such as a leaked database, a backup or someone who reads the server's disk. See Encryption limits for more detail.

For a complete app, see the encrypted BandChat example. For how encryption works under the hood, see the protocol spec.

Declare the encrypted columns

Mark a column with .encrypted() and give its table a space. A space is a row whose members share one key, such as a project or a room. { space: "project" } names the relation that leads to the space row. A table whose rows are their own spaces uses { space: "id" }.

schema.ts
import { schema as s } from "jazz-tools";
​
export const schema = s.defineSchema({
projects: s.table({
name: s.string(),
}),
tasks: s.table(
{
projectId: s.uuid(),
title: s.string().encrypted({ equality: true }),
notes: s.string().optional().encrypted(),
},
{ project: s.rel("projects", "projectId") },
{ space: "project" },
),
});
​
const { definePermissions, isMember, session } = schema;
​
export const permissions = definePermissions({
projects: {
// isMember: the signed-in user has been added to this project, so they get its key.
read: (project) => isMember("projects", project.id),
insert: { "$createdBy.account": session.user },
update: { $createdBy: session.user },
},
tasks: {
read: (task) => isMember("projects", task.projectId),
insert: (task) => isMember("projects", task.projectId),
},
});

Run npx jazz-tools generate. Your code reads and writes an encrypted column as its plain type, so title is a string.

  • equality: true lets you filter the column by exact value. The server can then tell which rows share a value, but not what the value is. Other encrypted columns can't be filtered.
  • .encrypted() covers the whole stored value, including an array or a JSON value.
  • Computed fields, transformed columns, relation columns and columns with a merge strategy can't be encrypted. A space's id and the column its relation uses stay plain.
  • isMember(table, id) is true when the signed-in account is a member of that space. A space table's read rule must be isMember of its own id, as projects has above. You can combine it with other conditions in allOf. Deploy refuses the app otherwise.
  • Those other conditions decide which members Jazz sends the rows to, not who can decrypt them. Every member gets the keys, so a member who gets the encrypted values some other way can read them.

Sharing and keys covers members.

Set up the browser

Each device keeps its own keys. This section sets up a browser. For Node, React Native and the native platforms, see Other platforms.

import { createJazzClient } from "jazz-tools/client";
import { app } from "../jazz.generated.js";
​
export async function openBrowserClient() {
return createJazzClient({
serverUrl: "/jazz",
initial: "device",
encryption: { app },
client: () => import("jazz-tools/local-first"),
});
}

Encryption needs a signed-in account. initial: "device" signs this browser in as a device account; any other sign-in works too. A device account only syncs if your backend's authenticate returns acceptDeviceAccounts(request) for it; otherwise the server refuses it and ready() fails. Pass app so the client knows which columns are encrypted. Jazz keeps the keys in IndexedDB, protected by a WebCrypto key that scripts can use but can't export. Clearing the site's data removes the keys, and the browser is then a new device. All tabs of your app are one device. To keep the keys somewhere else, pass your own store next to app.

client loads the local-first client. Encryption needs it: the thin client doesn't include the encryption code or the key management, so it can't encrypt, decrypt or hold keys. The app starts on the thin client and upgrades in the background. Until the upgrade finishes:

  • Reads and writes of plain columns work.
  • A one-off read or write that touches an encrypted column waits up to 30 seconds for the upgrade. If the load fails or takes longer, the call rejects with EncryptionNeedsLocalFirstError. Without client it rejects at once.
  • A live query on an encrypted column waits for the upgrade with no time limit.
  • A write that waits is held in memory, and later writes queue behind it. They are lost if the page closes first.
  • A db.transaction callback that touches an encrypted column can run twice: the thin client can't finish it, so Jazz runs it again on the local-first client once that has loaded. Keep side effects out of it.

await db.encryption.ready() waits for the upgrade and for the device's keys.

Read and write

Create a project, add a task to it and read the task back:

export async function createProjectWithTask(db: Db) {
// Jazz adds you as the project's first member, and your first encrypted write makes its key.
const project = await db.insert(app.projects, { name: "Spring tour" }).wait({ tier: "global" });
const projectId = project.id;
​
await db.insert(app.tasks, { projectId, title: "Call the venue" }).wait({ tier: "global" });
// tasks[0].title is "Call the venue". The server stored only the encrypted value.
return db.all(app.tasks.where({ projectId, title: "Call the venue" }));
}

An equality filter works on an equality column when the query also names one space, as projectId does here. Other filters, ordering, grouping and aggregates on an encrypted column fail with an error that names the pattern. So does reading tasks as an include of projects: query the tasks of a project directly. Encryption limits lists every case.

Until a space's key reaches this device, writes to that space fail with key-pending. See When members get the key.

Rows this device cannot read

A read leaves out the rows this device can't decrypt and tells you which ones. unreadableRows(result) returns each with its table, id, column and a code such as key-pending, key-unavailable or invalid-ciphertext.

export async function readTaskPage(db: Db, projectId: string) {
const page = await db.all(app.tasks.where({ projectId }).limit(20));
const missing = unreadableRows(page);
// When `missing` isn't empty, this page is incomplete: `page.length + missing.length` rows matched.
return { page, missing };
}

limit and offset count the rows left out, so a page can be short or empty without being the last one. A key-pending row appears once its key arrives. Read again, or use a subscription, which updates by itself and carries the list with every result.

unreadableRows is exported from each framework's entry point and from jazz-tools/client. React's, Vue's and Solid's useAll and Svelte's QuerySubscription also return the list as unreadable, next to the data.

A device that has never synced doesn't know yet which rows are encrypted. Its live queries on encrypted columns stay loading until its first sync. db.encryption.readable() resolves when the device can read.

Other platforms

Everywhere outside the browser, you pass a private store that keeps the device's keys.

Node

Node has no default store. Pass a private store. Without one, opening the app fails with EncryptionStoreRequiredError.

import { createJazzClient, type PrivateStore } from "jazz-tools/backend";
import { app } from "../jazz.generated.js";
import permissions from "../jazz.permissions.json" with { type: "json" };
​
export async function openNodeClient(
serverUrl: string,
dataPath: string,
privateStore: PrivateStore,
) {
return createJazzClient({
serverUrl,
app,
permissions,
driver: { type: "persistent", dataPath },
initial: "device",
encryption: { store: privateStore },
});
}

React Native and Expo

Pass your generated app and a private store. The account store remembers the signed-in account. In Expo, import createJazzClient from jazz-tools/expo and leave the account store out.

import { createJazzClient } from "jazz-tools/react-native";
import { app } from "./jazz.generated";
import { accountStore, privateStore } from "./device-storage";
​
const session = await createJazzClient({
serverUrl: "https://app.example/jazz",
initial: "device",
store: accountStore,
encryption: { app, store: privateStore },
});
const status = await session.db.encryption.ready();

Rust, Swift, Kotlin and Go

Pass a private store in the client's encryption config, then call ready.

Experimental

use jazz_app_support::{Auth, Config, EncryptionConfig};
use std::rc::Rc;
​
pub async fn open_encrypted(files: AppFiles, app_id: AppId, device_key: DeviceKey) -> Result<Jazz> {
let config = Config::new(app_id)
.server("https://app.example/jazz")
.user(Auth::Device(device_key))
.encryption(EncryptionConfig::store(|| Rc::new(MyStore::open())).environment("production"));
let jazz = Jazz::open(files, config).await?;
// The device's status: "active", "awaiting-approval" or "reenrolled".
let status = jazz.encryption().ready(Duration::from_secs(30)).await?;
println!("device status: {status}");
Ok(jazz)
}

MyStore implements jazz_e2ee_client::PrivateStore. Turn on the e2ee-client feature of jazz-app-support.

ready returns the device's status. Devices and recovery explains each one.

On the backend

Your backend holds no keys. createJazz starts for an encrypted app and reads its plain columns as usual. Rows come back without their encrypted columns. A write, filter or ordering that names an encrypted column is refused. Query through keyless(app) so the types match:

const backendApp = keyless(app);
​
export async function readTasksOnBackend(jazz: Jazz) {
return jazz.db.all(backendApp.tasks); // each task.title is undefined
}

The private store holds the device's keys. Jazz calls these operations:

OperationWhat it does
openScope(scope)Returns the scope's incarnation, a number chosen when the scope is created.
load(scope, doc)Returns the saved document and its revision, or null.
loadAll(scope, incarnation)Returns every document of the scope from one snapshot, or throws PrivateStoreWipedError if the incarnation doesn't match. Optional in JavaScript and Go, required in Swift and Kotlin.
save(scope, incarnation, doc, bytes, expected)Replaces a document if the incarnation and the document's revision match. Otherwise it throws PrivateStoreWipedError or PrivateStoreConflictError.
list(scope), delete(scope)Lists a scope's documents. Removes a scope.
protect(secret), unprotect(blob)Encrypts a secret for storage, and decrypts it.

Keep the documents in files only your app can read. Have protect encrypt with a 32-byte key from the operating system's key store: the Keychain, the Android Keystore, Credential Manager or libsecret. Keep that key on the device, and keep the files out of backups and cloud sync. A copy of the files that comes with its key is a copy of the device.

Jazz calls the store one request at a time, so keep it fast and local. Throw on a real error. Only a missing document should read as absent, because an empty store looks like a new device.

This store for Node keeps its documents in a directory. Use one instance for a directory, and don't share the directory between processes.

import { mkdir, readFile, readdir, rename, rm, unlink, writeFile } from "node:fs/promises";
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
import {
PrivateStoreConflictError,
PrivateStoreWipedError,
type PrivateStore,
} from "jazz-tools/backend";
​
/** `machineKey` is 32 bytes from your operating system's key store. */
export function directoryStore(dir: string, machineKey: Buffer): PrivateStore {
const at = (scope: string) => {
if (!scope || scope === "." || scope === "..") throw new Error("Invalid scope name");
return `${dir}/${encodeURIComponent(scope)}`;
};
const docPath = (scope: string, doc: string) => {
if (!doc || doc.startsWith(".")) throw new Error("Invalid document name");
return `${at(scope)}/${encodeURIComponent(doc)}`;
};
const marker = (scope: string) => `${at(scope)}/.incarnation`;
const isMissing = (error: unknown) => (error as NodeJS.ErrnoException).code === "ENOENT";
const incarnationOf = async (scope: string) => {
try {
return BigInt(await readFile(marker(scope), "utf8"));
} catch (error) {
if (isMissing(error)) return null;
throw error;
}
};
const read = async (scope: string, doc: string) => {
try {
const text = await readFile(docPath(scope, doc), "utf8");
const { revision, bytes } = JSON.parse(text);
return { revision: BigInt(revision), bytes: new Uint8Array(Buffer.from(bytes, "base64")) };
} catch (error) {
// Only a missing file means "absent"; any other error must not read as a new device.
if (isMissing(error)) return null;
throw error;
}
};
let queue: Promise<unknown> = Promise.resolve();
// One operation at a time: a save checks and replaces atomically.
const serial = <T>(work: () => Promise<T>) => (queue = queue.then(work, work)) as Promise<T>;
return {
load: (scope, doc) =>
serial(async () => ((await incarnationOf(scope)) === null ? null : read(scope, doc))),
openScope: (scope) =>
serial(async () => {
const current = await incarnationOf(scope);
if (current !== null) return current;
​
await rm(at(scope), { recursive: true, force: true });
await mkdir(at(scope), { recursive: true, mode: 0o700 });
const incarnation = randomBytes(8).readBigUInt64BE() || 1n;
const pending = `${marker(scope)}.tmp`;
await writeFile(pending, incarnation.toString(), { mode: 0o600 });
await rename(pending, marker(scope));
return incarnation;
}),
save: (scope, incarnation, doc, bytes, expected) =>
serial(async () => {
if ((await incarnationOf(scope)) !== incarnation) throw new PrivateStoreWipedError();
const current = await read(scope, doc);
if ((current?.revision ?? null) !== expected) throw new PrivateStoreConflictError();
const revision = (current?.revision ?? 0n) + 1n;
const body = JSON.stringify({
revision: revision.toString(),
bytes: Buffer.from(bytes).toString("base64"),
});
const path = docPath(scope, doc);
const pending = `${at(scope)}/.document.tmp`;
await writeFile(pending, body, { mode: 0o600 });
await rename(pending, path);
return revision;
}),
list: (scope) =>
serial(async () => {
if ((await incarnationOf(scope)) === null) return [];
return (await readdir(at(scope)))
.filter((name) => !name.startsWith("."))
.map(decodeURIComponent);
}),
delete: (scope) =>
serial(async () => {
await unlink(marker(scope)).catch((error) => {
if (!isMissing(error)) throw error;
});
await rm(at(scope), { recursive: true, force: true });
}),
async protect(secret) {
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", machineKey, iv);
const sealed = Buffer.concat([cipher.update(secret), cipher.final()]);
return new Uint8Array(Buffer.concat([iv, cipher.getAuthTag(), sealed]));
},
async unprotect(blob) {
const bytes = Buffer.from(blob);
const decipher = createDecipheriv("aes-256-gcm", machineKey, bytes.subarray(0, 12));
decipher.setAuthTag(bytes.subarray(12, 28));
return new Uint8Array(Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]));
},
};
}

For tests, memoryPrivateStore() keeps keys in memory and protects nothing. Don't ship it.