Operations

Security

Authorise database access, restrict subscriptions and operator routes, and protect credentials and encryption keys.

Authentication identifies a caller; authorisation determines which database, rows, and operations that caller can access. Sirannon provides hooks for those checks, while SQL, device sync, restores, and encryption changes each have an explicit server option.

Built-in protections

The server defaults to loopback and refuses network SQL until acceptSql is true. Registered operations define server-side SQL and declared arguments. An argument filled through fromIdentity cannot also come from the caller.

Drivers bind values separately from SQL. Capture validates and escapes identifiers, while migration and backup paths reject control characters and traversal segments. Tenant resolution validates IDs before deriving file paths.

The server caps inbound bodies and outbound WebSocket buffering. It sanitises internal errors before sending them remotely. Read-only connections refuse writes. These checks protect their respective boundaries; they do not establish a caller's permission to read a database.

Choose a deployment boundary

Expose registered operations to browser and mobile clients only after authenticating the caller and authorising the database and rows. Use fromIdentity for ownership arguments, then include those arguments in every applicable SQL condition.

Keep a SQL-enabled server behind the access controls for trusted service code. An authenticated SQL caller can compose statements outside registered operations.

A server-side application can also call embedded Sirannon directly and expose its application API. This allows that application to coordinate database work with external services without granting database access to its clients.

Identify every caller

authenticate executes before database routes and WebSocket upgrades. Health and capability endpoints skip it. Throw RequestDeniedError to refuse access; return the identity only after all checks pass.

The complete access.ts module demonstrates an expiring application credential and a separate operator credential for one account's orders database. Supply two distinct secret hexadecimal tokens, the application's trusted origin, and an ISO expiry timestamp through the indicated environment variables.

This module checks configured credentials; it does not issue user sessions. A deployed application can replace that lookup with its session service while retaining the route and database checks.

access.ts
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') {
    throw new RequestDeniedError(403, 'FORBIDDEN', 'Operator access required')
  }
  return { userId: 'account-42', role: 'application' }
}

Pass authenticate and authorizeClusterStatus into createServer, as the server guide demonstrates. Bind registered ownership arguments to the returned userId. The example's application identity has access to one account's database; a multi-account service needs its session lookup to return the correct identity for each account.

Authorise an ID before calling a lifecycle resolver. A validated file path prevents traversal, but path validation does not establish who may open that database.

A refusal-shaped return object produces HOOK_ERROR. An unexpected exception also produces a sanitised hook error. A deliberate RequestDeniedError returns its configured status, code, and message, so keep those messages free of secrets.

Authenticate WebSocket upgrades

Browser WebSockets provide no custom-header API. 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 its configured expiry.

Validate the browser's Origin against an explicit allowlist. Origin checking supplements authentication; a non-browser caller can construct an Origin header.

The client offers sirannon.v1 before credential protocols. The server selects that public identifier, so the credential does not appear in the protocol response. An incompatible offer fails with UNSUPPORTED_SUBPROTOCOL.

Tickets must be non-empty HTTP tokens and must not repeat. Unpadded base64url and hexadecimal encodings fit that alphabet. Keep credentials out of URLs, access logs, and error text.

For a deployed session service, issue tickets with a short expiry and the intended database scope. Decide how reconnecting clients obtain fresh tickets, because reusing an expired credential must fail.

Tell a refused connection from a dropped one

A 401 or 403 WebSocket upgrade refusal closes with 4401 or 4403. The SDK raises UNAUTHORIZED or FORBIDDEN and stops reconnecting that refused client. Construct a new client after obtaining a valid credential.

A temporary disconnect can reconnect and restore subscriptions. A server refusal during restoration ends the affected subscription and reaches its onError callback. Client SDK explains the other close codes.

Guard the cluster endpoint

GET /db/:id/cluster can reveal peer addresses and authority metadata. Configure authorizeClusterStatus alongside getClusterStatus. Return false to refuse access with 404. Throwing an error produces HOOK_ERROR.

The example's gate accepts the operator credential for the orders database. Keep this credential in trusted operator and topology-client processes.

Keep the backup routes to operators

The seven routes under /db/:id/backup can inspect backups, trigger capture, and replace a database. They have no separate route authoriser, so check their paths and roles inside authenticate.

acceptBackupRestore: true requires authentication and permits the restore request, but the hook must also restrict it to operators. Server restore explains the replacement process and its status route.

A backup contains database data. Restrict destination credentials to the required storage prefix and operations. Retain the encryption keys needed by restorable chains, because possession of ciphertext alone cannot restore an encrypted database.

Guard subscriptions, snapshots, and device sync

A registered read's row condition does not restrict an ordinary table subscription. With SQL disabled, table subscriptions require onBeforeSubscribe. That hook must check the table, identity, and filter before permitting the subscription.

For a shared table, require an ownership filter derived from the authenticated identity. A caller-supplied owner ID alone establishes no permission. Filters affect membership changes, as change data capture explains.

Snapshots copy whole tables. Permit onBeforeSnapshot only when the caller may read every row in each requested table. A row-filtered registered read does not make a full-table snapshot safe.

Device sync remains disabled until acceptDeviceSync: true, which also requires authentication. A push can modify application rows outside registered writes. Give each account a separate synced database where accounts need isolation.

Persist each device's account association and verify it in both onBeforePush and onBeforeSubscribe. A process-local association disappears after a restart. The push hook executes once per table before applying a batch; a refusal prevents that batch from applying.

The server rejects device timestamps more than 300,000 milliseconds ahead of its clock with DEVICE_CLOCK_AHEAD. This limit prevents an arbitrarily distant future stamp; it does not replace database or device authorisation.

Protect encryption operations and keys

acceptEncryptionChange is separate from SQL and backup restore permissions. Enabling it requires authenticate and encryptionKeys. Authorise both the change request and status route for operators.

A caller supplies a key reference, which the server resolves internally. Keep raw keys outside network requests and logs. Restrict the key loader to trusted secret storage, retain old keys while backups need them, and check reopenError after a completed key change.

Encryption protects database files at rest. It does not prevent an authorised SQL reader from obtaining plaintext, and it does not encrypt HTTP or WebSocket traffic. Encryption explains the driver-specific ciphers and recovery requirements.

TLS, CORS, and the SQL escape hatch

The built-in server serves plain HTTP and WebSocket. Terminate TLS through the deployment's proxy or edge and give clients an HTTPS base URL. The SDK then uses WSS for its socket.

CORS defaults to disabled. Allow only trusted origins when a browser needs HTTP access. cors: true permits every origin. CORS does not authorise a request and does not protect WebSocket upgrades.

Keep user input in bound parameters and application-selected identifiers. Leave SQL disabled for untrusted clients, because arbitrary SQL can bypass row restrictions expressed in registered operations.

Checklist

  • Authenticate database routes and socket upgrades, and authorise the database before resolving 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.
  • Reserve backup, restore, encryption, and cluster metadata routes for authorised operators.
  • Use TLS for non-local traffic and restrict browser origins.
  • Bound request bodies, outbound buffering, and application retries.
  • Redact credentials, keys, and sensitive SQL values from logs.
  • Retain the keys required by the backup retention policy and test restoration before deleting older chains.