> Complete content index: https://sirannon.sondelali.com/llms.txt

# Encryption

> Encrypt a database and its backups, change the key while the database stays open, and recover after an interrupted change.

URL: https://sirannon.sondelali.com/docs/encryption
Section: Operations
Version: 0.4 (@delali/sirannon-db@0.4.1, latest)

Sirannon can encrypt a database file, its write-ahead log, and its backups under a key that you supply. Someone who copies those files will need the key to read the rows. Encryption protects stored data; use TLS and authentication to protect access through the [server](/docs/security).

## Choose a driver that can encrypt

On Node.js, install Sirannon's SQLite build beside the library:

```bash pm
pnpm add -E @delali/sirannon-db @delali/sirannon-sqlite
```

| Driver | Encryption support |
| --- | --- |
| `betterSqlite3({ encryption: true })` | The driver encrypts with AEGIS-256 through `@delali/sirannon-sqlite`. |
| `expoSqlite()` | The driver encrypts with SQLCipher 4 when the app enables SQLCipher. |
| `nodeSqlite()`, `bunSqlite()`, and `waSqlite()` | The drivers refuse a keyed open with `ENCRYPTION_UNSUPPORTED`. |

Sirannon publishes native builds for Linux, macOS, and Windows on x64 and arm64. A missing or incompatible build fails with `ENCRYPTION_UNSUPPORTED`. `sqliteBindingPath` accepts the path of a build compiled from the release's `native/sqlite` directory.

Node and Expo use different file formats. The key alone cannot make one driver open the other's encrypted file. To move between them, decrypt the file through its current driver, transfer it through a protected channel, and encrypt it through the destination driver.

## Open a file under a key

A key loader returns exactly 32 raw bytes as a `Uint8Array`, either directly or as `{ key, id }`. Sirannon stores the optional identifier inside the database and in backup records, so an operator can find the key needed for a restore.

Store a random key in a key service, an operating-system keychain, or a secret file that only the application account can read. A password needs a password-hashing function to derive the bytes before Sirannon receives them. Sirannon performs no password derivation.

Set `SIRANNON_KEY_FILE` to a secret file containing those raw bytes. Set `SIRANNON_KEY_ID` to an identifier that your key inventory recognises. Save this complete file as `encrypted-ledger.ts`:

```ts title="encrypted-ledger.ts"
import { mkdir, readFile } from 'node:fs/promises'
import { type EncryptionKey, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'

const keyFile = process.env.SIRANNON_KEY_FILE
const keyId = process.env.SIRANNON_KEY_ID
if (!keyFile || !keyId) throw new Error('Set SIRANNON_KEY_FILE and SIRANNON_KEY_ID')

const loadKey = async (): Promise<EncryptionKey> => ({
  key: new Uint8Array(await readFile(keyFile)),
  id: keyId,
})

await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3({ encryption: true }) })

try {
  const db = await sirannon.open('ledger', './data/ledger.db', { encryption: { key: loadKey } })
  await db.execute('CREATE TABLE IF NOT EXISTS entries (id INTEGER PRIMARY KEY, amount INTEGER NOT NULL)')
  await db.execute('INSERT INTO entries (id, amount) VALUES (?, ?) ON CONFLICT(id) DO NOTHING', [1, 4200])
  console.log(await db.query('SELECT id, amount FROM entries ORDER BY id'))
  console.log(await db.encryptionStatus())
} finally {
  await sirannon.shutdown()
}
```

For a new file, Sirannon encrypts it from creation. An existing plaintext file needs `changeEncryption`; supplying a key at open fails with `DATABASE_NOT_ENCRYPTED`. An in-memory database cannot encrypt.

The driver option enables the encrypting engine for every database opened through it. A database opened without `DatabaseOptions.encryption` remains plaintext.

Sirannon calls the loader when it opens connections, including after a writer-worker restart, a restore, or a key change. Sirannon copies the returned bytes and wipes that copy after the connections open. Keep the loader available for the lifetime of the database, and make it return the same key until a key change succeeds.

## Change the key of an open database

`changeEncryption` takes a loader for the target key. The same method encrypts a plaintext database or, with `key: null`, removes encryption. A change needs free disk space for another copy of the database.

For a rotation, retain the current settings and set `SIRANNON_NEXT_KEY_FILE` and `SIRANNON_NEXT_KEY_ID`. Replace `encrypted-ledger.ts` with the complete file below:

```ts title="encrypted-ledger.ts"
import { mkdir, readFile } from 'node:fs/promises'
import { type EncryptionKey, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'

const keyFile = process.env.SIRANNON_KEY_FILE
const keyId = process.env.SIRANNON_KEY_ID
if (!keyFile || !keyId) throw new Error('Set SIRANNON_KEY_FILE and SIRANNON_KEY_ID')

const loadKey = async (): Promise<EncryptionKey> => ({
  key: new Uint8Array(await readFile(keyFile)),
  id: keyId,
})

const nextKeyFile = process.env.SIRANNON_NEXT_KEY_FILE // [!code ++]
const nextKeyId = process.env.SIRANNON_NEXT_KEY_ID // [!code ++]
if (!nextKeyFile || !nextKeyId) throw new Error('Set SIRANNON_NEXT_KEY_FILE and SIRANNON_NEXT_KEY_ID') // [!code ++]

const loadNextKey = async (): Promise<EncryptionKey> => ({ // [!code ++]
  key: new Uint8Array(await readFile(nextKeyFile)), // [!code ++]
  id: nextKeyId, // [!code ++]
})

await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3({ encryption: true }) })

try {
  const db = await sirannon.open('ledger', './data/ledger.db', { encryption: { key: loadKey } })
  await db.execute('CREATE TABLE IF NOT EXISTS entries (id INTEGER PRIMARY KEY, amount INTEGER NOT NULL)')
  await db.execute('INSERT INTO entries (id, amount) VALUES (?, ?) ON CONFLICT(id) DO NOTHING', [1, 4200])
  console.log(await db.query('SELECT id, amount FROM entries ORDER BY id'))
  const status = await db.changeEncryption({ key: loadNextKey }) // [!code ++]
  console.log(status) // [!code ++]
  if (status.change.reopenError) throw new Error('Retain the new key and reopen the database with it') // [!code ++]
} finally {
  await sirannon.shutdown()
}
```

On the next process start, use the new key file and identifier as the current settings. To encrypt a plaintext file, omit `encryption` from `sirannon.open` and pass the target loader to `changeEncryption`. To decrypt, open with the current loader and call `changeEncryption({ key: null })`; later opens then omit `encryption`.

Sirannon copies a snapshot under the target key, applies writes committed during that copy, and pauses writes for the final catch-up and file replacement. It preserves rows, rowids, and triggers. A schema change or a write that the copier cannot reproduce aborts the change and leaves the current file in place.

## Read progress and recover from a failure

While a change proceeds, another caller can await `encryptionStatus()`. The `change.state` field is `idle`, `copying`, `catching-up`, `swapping`, `done`, or `failed`. Progress can include `rowsCopied`, `rounds`, `startedAt`, and `finishedAt`. The status contains the cipher and optional key identifier, never the key bytes.

Check `change.reopenError` even when the state is `done`. Once Sirannon replaces the file, the new key is in force. A subsequent failure to reopen connections reports `done` with `reopenError`, so retain the new key, close the database, and reopen with that key.

Keep both keys until the operation settles. If the process stops during replacement, the next open uses the marker beside the file to complete or discard the replacement. A rejected key then produces a message explaining whether the file requires the key from before or after the change. Preserve the database and its marker together during recovery.

| Code | What the caller needs to check |
| --- | --- |
| `INVALID_ENCRYPTION_KEY` | The loader must return exactly 32 bytes. |
| `ENCRYPTION_KEY_UNAVAILABLE` | The loader threw or rejected; inspect the server-side cause. |
| `ENCRYPTION_KEY_MISSING` | The encrypted file needs a loader at open. |
| `ENCRYPTION_KEY_REJECTED` | The key is wrong, or another cipher encrypted the file. |
| `ENCRYPTED_PAGE_CORRUPT` | A later page failed authentication; investigate corruption. |
| `ENCRYPTION_CHANGE_IN_PROGRESS` | Another change is active on this database. |
| `ENCRYPTION_CHANGE_ABORTED` | The copy could not preserve a concurrent change. |
| `READ_ONLY` | A read-only database cannot change encryption. |
| `REPLICATION_ACTIVE` | Stop replication and close its separate writer before replacing the file. |

## Retain the keys needed by backups

Sirannon encrypts full copies, change pieces, and streamed copies under the database key. When a key has an identifier, each chain record includes `keyId`. Retain every chain's key for as long as that chain remains available for restoration.

A key change causes the next backup capture to begin a new chain with a full copy under the new key. `restoreBackup` accepts `encryption: { key: loader }` alongside an encrypting driver, and the loader must return the key for the selected chain. The restored file remains encrypted under that key. A server-side restore uses the open database's current key. See [restoring a database](/docs/backup-restore).

## Restrict key changes over the network

The server provides `POST /db/{id}/encryption` and `GET /db/{id}/encryption`. The POST body is `{ keyRef }`, where the value is a string of 1 to 256 characters, or `null` to decrypt. The GET route returns the local encryption status.

The POST route defaults to closed with `403 ENCRYPTION_CHANGE_NOT_ACCEPTED`. Enabling `acceptEncryptionChange` also requires `authenticate` and an `encryptionKeys(databaseId, keyRef)` resolver, or server creation fails with `INVALID_ENCRYPTION_CHANGE`.

Restrict both routes to operator credentials in `authenticate`. Resolve each permitted database and key reference through an allowlist or your key service; never concatenate an unchecked reference into a secret-file path. Requests contain references, while the resolver returns the key inside the server.

The POST route returns `202` after the change starts. Poll the GET route for completion, including `reopenError`. The server sanitises encryption errors before sending them to a client. See [server](/docs/server) and [error codes](/docs/error-codes).

## Change one replicated node at a time

An active replication engine prevents a key change or restore with `REPLICATION_ACTIVE`, because the engine has a separate connection to the file. Stop the engine, close that writer connection, change the key, and restart the engine with every connection under the new key. A snapshot connection needs the key too.

An encrypted node refuses to send batches or snapshots to a plaintext peer with `ENCRYPTION_REQUIRED`. When encrypting a group, encrypt the replicas first, fail over to an encrypted replica, and encrypt the former primary last. The [replication guide](/docs/distributed-replication) describes the connection setup.

## Enable encryption in an Expo app

Expo support is experimental. Enable `useSQLCipher` in the `expo-sqlite` config plugin and rebuild the app:

```json title="app.json"
{
  "expo": {
    "plugins": [["expo-sqlite", { "useSQLCipher": true }]]
  }
}
```

Encrypted opens require `expo-sqlite` 15.0.0 or later with SQLCipher 4.6.0 or later. Plaintext databases retain the package's lower peer requirement. An older app or one built without SQLCipher fails a keyed open with `ENCRYPTION_UNSUPPORTED`.

Supply `DatabaseOptions.encryption.key` from the device's keychain when opening through `expoSqlite()`. Expo uses SQLCipher 4's default scheme with the raw key.

Key changes also require `expo-file-system` 19.0.0 or later. Once an app build can change keys, retain that dependency in every later build, because recovery after an interrupted change uses `expo-file-system/legacy` to inspect the files beside the database.
