Authentication identifies a caller, while authorisation determines which databases, rows, and operations that caller can reach. Sirannon calls your hooks for both checks. The server serves SQL, device sync, restores, and encryption changes only when you set the server option for each one.
Built-in protections
The server binds to loopback by default and refuses network SQL until you set acceptSql: true. Registered operations define the SQL on the server and the arguments that a caller can send. The server fills an argument that you declare through fromIdentity from the authenticated identity, so only the server sets that argument.
Drivers bind values separately from the SQL. Change capture validates and escapes table and column identifiers, while the migration loaders and the backup functions refuse a path with control characters or traversal segments. The tenant resolver validates each ID before it derives a file path.
query and execute refuse with FORBIDDEN_SQL the statements that can write outside the database or around the state that Sirannon manages. Sirannon refuses ATTACH and DETACH, which open other files, and VACUUM INTO, which writes a copy of the database to any path that the process can write. It also refuses the temp_store_directory and data_store_directory pragmas, which change the directories where SQLite writes files, as well as the writable_schema and wal_checkpoint pragmas. The same check refuses statements that touch the _sirannon tables or modify the sqlite_ catalogue, and statements that create or drop a temporary table, view, index, or trigger. Sirannon refuses the transaction-control statements too, because they can split the transactions that Sirannon manages. Error codes lists every refused statement.
The server caps inbound bodies and outbound WebSocket buffering, and it replaces the message of an internal error before it sends the error to a client. Read-only connections refuse writes. Each of these checks protects one boundary, while only your authorisation hooks can grant a caller access to a database.
Choose a deployment boundary
Expose registered operations to browser and mobile clients only after you authenticate the caller and authorise the database and the rows. Use fromIdentity for ownership arguments, and include those arguments in every SQL condition that applies.
Place a server with SQL turned on behind access controls that admit only trusted service code, because an authenticated SQL caller can compose statements outside the registered operations.
A server-side application can also call embedded Sirannon directly and serve a separate application API to its clients. That application can then coordinate database work with external services without giving its clients database access.
Identify every caller
The server calls authenticate before every database route and WebSocket upgrade, while it serves the health and capability routes without that hook. Throw RequestDeniedError to refuse access, and return the identity only once every check passes.
The complete access.ts module below checks an expiring application credential and a separate operator credential for the orders database of one account. Supply two distinct secret hexadecimal tokens, the trusted origin of the application, and an ISO expiry timestamp through the environment variables in the code.
The module compares configured credentials and issues no user sessions. In a deployed application, replace that comparison with a lookup in your session service, and leave the route and database checks in place.
import { timingSafeEqual } from 'node:crypto'
import { type RequestContext, RequestDeniedError } from '@delali/sirannon-db'
interface Identity {
userId: string
role: 'application' | 'operator'
}
const required = (key: string): string => {
const value = process.env[key]
if (!value) throw new Error(`Set ${key}`)
return value
}
const appToken = required('SIRANNON_APP_TOKEN')
const operatorToken = required('SIRANNON_OPERATOR_TOKEN')
const appOrigin = required('SIRANNON_APP_ORIGIN')
const expiresAt = Date.parse(required('SIRANNON_APP_EXPIRES_AT'))
if (!/^[a-f0-9]{64}$/.test(appToken) || !/^[a-f0-9]{64}$/.test(operatorToken) || appToken === operatorToken) {
throw new Error('Configure two distinct secret 64-character hexadecimal credentials')
}
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
throw new Error('Configure an application credential that has not expired')
}
const matches = (offered: string | undefined, expected: string): boolean => {
const receivedBytes = Buffer.from(offered ?? '')
const expectedBytes = Buffer.from(expected)
return receivedBytes.length === expectedBytes.length && timingSafeEqual(receivedBytes, expectedBytes)
}
export const authorizeClusterStatus = (context: RequestContext): boolean =>
context.databaseId === 'orders' && matches(context.headers.authorization, `Bearer ${operatorToken}`)
export const authenticate = (context: RequestContext): Identity => {
if (context.databaseId !== 'orders') {
throw new RequestDeniedError(403, 'FORBIDDEN', 'Database access refused')
}
const isUpgrade = context.headers['sec-websocket-key'] !== undefined
if (isUpgrade && context.headers.origin !== undefined && context.headers.origin !== appOrigin) {
throw new RequestDeniedError(403, 'FORBIDDEN_ORIGIN', 'Origin refused')
}
if (matches(context.headers.authorization, `Bearer ${operatorToken}`)) {
return { userId: 'operator', role: 'operator' }
}
const protocols = (context.headers['sec-websocket-protocol'] ?? '').split(',').map((value: string): string => value.trim())
const ticket = protocols.find((value: string): boolean => value.startsWith('ticket.'))?.slice('ticket.'.length)
const isBearer = matches(context.headers.authorization, `Bearer ${appToken}`)
const isTicket = isUpgrade && context.headers.origin === appOrigin && matches(ticket, appToken)
if (Date.now() >= expiresAt || (!isBearer && !isTicket)) {
throw new RequestDeniedError(401, 'UNAUTHORIZED', 'Sign in again')
}
const resource = context.path.split('/')[3]
if (resource === 'backup' || resource === 'encryption' || resource === 'checkpoint') {
throw new RequestDeniedError(403, 'FORBIDDEN', 'Operator access required')
}
return { userId: 'account-42', role: 'application' }
}Pass authenticate and authorizeClusterStatus to createServer, as the server guide shows. Bind registered ownership arguments to the returned userId. The example gives the application identity access to the database of one account, so in a service with many accounts, the session lookup has to return the right identity for each account.
The module refuses the application identity on the backup, encryption, and checkpoint routes, so only an operator can call them. Authorise an ID before a lifecycle resolver opens a file for it. A validated file path prevents traversal, but only your authorisation check can establish who may open that database.
The server answers with HOOK_ERROR when the hook returns an object shaped like a refusal or throws an unexpected error. For an unexpected error, the server leaves the details of the error out of the answer. The server sends the status, code, and message of a deliberate RequestDeniedError to the caller, so leave secrets out of those messages.
Authenticate WebSocket upgrades
A browser WebSocket has no API for custom headers, so send an HTTP bearer credential in headers and a short-lived ticket in webSocketProtocols. The module above accepts ticket. followed by the application credential until the configured expiry.
Check the Origin of the browser against an explicit allowlist. That check adds to authentication without replacing it, because a caller outside a browser can set any Origin header.
The client offers sirannon.v1 before the credential subprotocols. The server selects that public identifier, so the upgrade response contains none of the credentials. The server refuses an incompatible offer with UNSUPPORTED_SUBPROTOCOL.
Every subprotocol in an offer has to be a distinct, non-empty HTTP token, which unpadded base64url and hexadecimal encodings both satisfy. Leave credentials out of URLs, access logs, and error text.
In a deployed session service, issue tickets with a short expiry and the intended database scope. Plan how a reconnecting client obtains a fresh ticket, because the server refuses an expired credential.
Tell a refused connection from a dropped one
When the server refuses a WebSocket upgrade with 401 or 403, it closes the socket with 4401 or 4403. The SDK then raises UNAUTHORIZED or FORBIDDEN and stops reconnecting that client, so construct a new client once you have a valid credential.
After a temporary disconnect, the client reconnects and restores its subscriptions. When the server refuses a subscription during that restore, the client ends that subscription and calls its onError callback. The client SDK explains the other close codes.
Guard the cluster endpoint
GET /db/:id/cluster can return peer addresses and authority metadata, so configure authorizeClusterStatus alongside getClusterStatus. When the gate returns false, the server refuses access with 404, while it answers with HOOK_ERROR when the gate throws.
The gate in the example accepts the operator credential for the orders database. Store that credential only in trusted operator processes and topology clients.
Limit the backup and checkpoint routes to operators
Through the seven routes under /db/:id/backup, a caller can inspect backups, start a capture, and replace a database. A caller can also checkpoint the write-ahead log through POST /db/:id/checkpoint, which the server serves whatever acceptSql is set to. On a database with backups, the server answers each checkpoint only after a turn of the backup cycle ends, so the answer can wait for a full copy. The server authorises these routes only through authenticate, so check their paths and roles inside authenticate, as access.ts does.
acceptBackupRestore: true requires authentication and turns the restore route on, but the hook has to limit that route to operators as well. Server restore explains the replacement and its status route.
A backup contains the data of the database. Limit destination credentials to the storage prefix and the operations that the backups require. Retain the encryption key of every chain that you can restore, because Sirannon needs the key of a chain to restore an encrypted database from it.
Guard subscriptions, snapshots, and device sync
The server applies the row condition of a registered read only to that read, so an ordinary table subscription can deliver any row of its table. With SQL turned off, the server accepts a table subscription only through onBeforeSubscribe, which has to check the table, the identity, and the filter before it permits the subscription.
For a shared table, require an ownership filter that your hook derives from the authenticated identity, because a caller can supply any owner ID. Filters change which rows enter and leave the subscribed set, as change data capture explains.
A snapshot copies whole tables. Permit it in onBeforeSnapshot only when the caller may read every row of each requested table, because Sirannon applies the row conditions of registered reads only to those reads.
The server serves device sync only when you set acceptDeviceSync: true, which also requires authentication. A push can modify application rows outside the registered writes, so give each account a separate synced database when the accounts need isolation.
Store the account of each device durably, and check it in both onBeforePush and onBeforeSubscribe, because a process loses every association in its memory when it restarts. The server calls the push hook once for each table before it applies a batch, so a refusal from the hook stops the whole batch.
The server refuses a device timestamp more than 300,000 milliseconds ahead of its clock with DEVICE_CLOCK_AHEAD. That check refuses a stamp far in the future, but it authorises neither the database nor the device.
Protect encryption operations and keys
acceptEncryptionChange is separate from the SQL and restore permissions. Turning it on requires authenticate and encryptionKeys. Limit both the change route and the status route to operators.
A caller supplies a key reference, which the server resolves inside the process, so network requests contain no raw keys. Leave raw keys out of logs as well. Limit the key loader to trusted secret storage, retain each old key for as long as you store a backup under it, and check reopenError after a key change completes.
Encryption protects database files at rest. An authorised SQL reader receives plaintext through Sirannon, while TLS, not encryption, protects HTTP and WebSocket traffic. Encryption explains the ciphers of each driver and the recovery requirements.
TLS, CORS, and the SQL escape hatch
The built-in server serves plain HTTP and WebSocket. Terminate TLS at the proxy or edge of your deployment and give clients an HTTPS base URL, from which the SDK derives a WSS URL for its socket.
CORS is off by default. When a browser needs HTTP access, allow only trusted origins, because cors: true permits every origin. CORS controls only which browser origins can read HTTP responses, while the server checks WebSocket upgrades through authenticate.
Bind user input as parameters, and choose identifiers in application code. Leave SQL off for untrusted clients, because a caller with arbitrary SQL can bypass the row limits of the registered operations.
Checklist
- Authenticate database routes and socket upgrades, and authorise the database before you resolve its path.
- Derive ownership arguments from the authenticated identity, and apply them in every relevant statement.
- Restrict table subscriptions, whole-table snapshots, and device pushes separately.
- Limit the backup, restore, checkpoint, encryption, and cluster metadata routes to authorised operators.
- Use TLS for traffic beyond the host, and restrict browser origins.
- Bound request bodies, outbound buffering, and application retries.
- Redact credentials, keys, and sensitive SQL values from logs.
- Retain the keys that your backup retention requires, and test a restore before you delete older chains.