Networked access

Shared operations

Serve one operation set across tenant databases while authorising each database before automatic opening.

sharedOperations defines reads and writes for every database in a server's registry. A tenant created after deployment can use the same set without adding an entry to a database-specific operation map.

The server must authorise the database ID before its resolver opens a file. A valid credential for one customer provides no access to another customer's file.

Define the common operations

Save the complete shared-operations.ts module below. Each customer's separate database contains an invoices table, so these statements need no cross-customer row filter.

shared-operations.ts
import { type DatabaseOperations, type OperationArguments, type OperationStatement, RequestDeniedError } from '@delali/sirannon-db'
 
export interface Account {
  customer: string
}
 
export const sharedOperations: DatabaseOperations<Account> = {
  reads: {
    openInvoices: {
      columns: ['id', 'total'],
      statement: (): OperationStatement => ({
        sql: 'SELECT id, total FROM invoices WHERE paid = 0 ORDER BY id',
      }),
    },
  },
  writes: {
    raiseInvoice: {
      args: ['total'],
      statements: ({ total }: OperationArguments): OperationStatement => {
        if (typeof total !== 'number' || !Number.isSafeInteger(total) || total < 0) {
          throw new RequestDeniedError(400, 'INVALID_ARGUMENT', 'A non-negative safe integer total is required')
        }
        return { sql: 'INSERT INTO invoices (total, paid) VALUES (?, 0)', params: [total] }
      },
    },
  },
}

A database-specific entry in operations takes precedence over a shared operation with the same identifier. Other shared operations remain available there.

Open a tenant only after authorisation

The complete customer-server.ts file creates each tenant schema through registry migrations. Provide distinct secret SIRANNON_HARBOUR_TOKEN and SIRANNON_LUMEN_TOKEN values for the two example accounts.

This local example uses configured credentials. A deployed application can obtain the account from its existing session service while retaining the database comparison.

customer-server.ts
import { timingSafeEqual } from 'node:crypto'
import { mkdir } from 'node:fs/promises'
import { createTenantResolver, type RequestContext, RequestDeniedError, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { createServer } from '@delali/sirannon-db/server'
import { type Account, sharedOperations } from './shared-operations.js'
 
const required = (key: string): string => {
  const value = process.env[key]
  if (!value) throw new Error(`Set ${key}`)
  return value
}
const harbourToken = required('SIRANNON_HARBOUR_TOKEN')
const lumenToken = required('SIRANNON_LUMEN_TOKEN')
if (harbourToken === lumenToken) throw new Error('Configure distinct customer credentials')
 
const accounts: { token: Buffer; account: Account }[] = [
  { token: Buffer.from(`Bearer ${harbourToken}`), account: { customer: 'harbour-foods' } },
  { token: Buffer.from(`Bearer ${lumenToken}`), account: { customer: 'lumen-dental' } },
]
await mkdir('./data/customers', { recursive: true })
const sirannon = new Sirannon({
  driver: betterSqlite3(),
  migrations: [{
    version: 1,
    name: 'create_invoices',
    up: 'CREATE TABLE invoices (id INTEGER PRIMARY KEY, total INTEGER NOT NULL, paid INTEGER NOT NULL)',
    down: 'DROP TABLE invoices',
  }],
  lifecycle: {
    autoOpen: { resolver: createTenantResolver({ basePath: './data/customers' }) },
    maxOpen: 50,
    idleTimeout: 300_000,
  },
})
 
const server = createServer<Account>(sirannon, {
  host: '127.0.0.1',
  port: 9876,
  sharedOperations,
  authenticate: (context: RequestContext): Account => {
    const received = Buffer.from(context.headers.authorization ?? '')
    const match = accounts.find((entry: { token: Buffer; account: Account }): boolean =>
      entry.token.length === received.length && timingSafeEqual(entry.token, received))
    if (match === undefined) throw new RequestDeniedError(401, 'UNAUTHORIZED', 'Sign in to access invoices')
    if (context.databaseId !== match.account.customer) {
      throw new RequestDeniedError(403, 'FORBIDDEN', 'Database access refused')
    }
    const resource = context.path.split('/')[3]
    if (resource === 'backup' || resource === 'encryption') {
      throw new RequestDeniedError(403, 'FORBIDDEN', 'Operator access required')
    }
    return match.account
  },
})
 
const stop = async (): Promise<void> => {
  try {
    await server.close()
  } finally {
    await sirannon.shutdown()
  }
}
const handleSignal = (): void => {
  stop().catch((error: unknown): void => {
    console.error(error)
    process.exitCode = 1
  })
}
process.once('SIGINT', handleSignal)
process.once('SIGTERM', handleSignal)
 
try {
  await server.listen()
} catch (error: unknown) {
  await stop()
  throw error
}

createTenantResolver validates the identifier and derived path. The authentication hook separately compares that ID with the account before resolution. Registry migrations finish before the opened handle becomes available.

The open-database limit and idle timeout are example lifecycle settings. Size those values for the application's connection and memory budget. Hooks and lifecycle explains eviction.

Call the common operations

Start the server, then execute the complete customer-client.ts file with the same credentials. It writes an invoice for one account and demonstrates refusal when the other account requests that database.

customer-client.ts
import { operationRef } from '@delali/sirannon-db'
import { RemoteError, SirannonClient } from '@delali/sirannon-db/client'
 
const required = (key: string): string => {
  const value = process.env[key]
  if (!value) throw new Error(`Set ${key}`)
  return value
}
const connect = (token: string): SirannonClient => new SirannonClient('http://127.0.0.1:9876', {
  transport: 'http',
  headers: { Authorization: `Bearer ${token}` },
})
 
const openInvoices = operationRef<Record<string, never>, { id: number; total: number }>('openInvoices')
const raiseInvoice = operationRef<{ total: number }>('raiseInvoice')
const harbour = connect(required('SIRANNON_HARBOUR_TOKEN'))
const lumen = connect(required('SIRANNON_LUMEN_TOKEN'))
 
try {
  await harbour.database('harbour-foods').execute(raiseInvoice, { total: 18400 })
  console.log(await harbour.database('harbour-foods').query(openInvoices, {}))
  console.log(await lumen.database('lumen-dental').query(openInvoices, {}))
  try {
    await lumen.database('harbour-foods').query(openInvoices, {})
    throw new Error('Cross-customer access unexpectedly succeeded')
  } catch (error: unknown) {
    if (!(error instanceof RemoteError) || error.code !== 'FORBIDDEN') throw error
    console.log(error.code)
  }
} finally {
  harbour.close()
  lumen.close()
}

The stored invoices determine the printed arrays, so this example has no fixed result panel. Repeating the write creates another invoice; reconcile an uncertain reply before retrying that write.

Code generation can generate shared references from the sharedOperations export without starting a server. Security covers browser credentials and operator routes.