DARBAR दरबार

Declarative API Router with Built-in Auth & Resilience

Unified, mesh-native API handler — routes declared as descriptor objects with auth levels mapped to mesh identity primitives.

Layer 28

The Royal Court

A darbar is the royal court — where petitions are heard, authority verified, and justice dispensed. In Nepal and across South Asia, the darbar was where subjects could approach the seat of power, each granted audience according to their standing. In yakmesh, DARBAR is the declarative API layer that receives every HTTP request, verifies the caller’s identity against mesh primitives (ML-DSA-65 signatures, JWT tokens, persistent IDs), and routes the request to the correct handler — or turns it away at the gate.

Why DARBAR?

Before DARBAR, yakmesh had ~195 routes scattered across three API layers with inconsistent auth patterns: some checked JWT manually, others verified peer signatures inline, many had no auth at all. DARBAR replaces all of this with a single declarative pattern:

Declarative

Routes are plain descriptor objects — method, path, auth level, handler. No middleware spaghetti.

Crash-Isolated

Each domain gets its own Express Router. A bad handler in one domain can’t take down another.

Mesh-Native

Auth levels map directly to mesh identity: peer signatures, persistent IDs, DOKO certs — not ad-hoc JWT checks.

Six Auth Levels

DARBAR defines a strict hierarchy of six authentication levels. Each level includes all the checks of the levels below it:

Level Auth Identity Example Routes
PUBLIC None Anonymous /health, /version, /docs
LOCAL Socket address 127.0.0.1 / ::1 /debug, /metrics
PEER ML-DSA-65 signature x-node-id + signed timestamp /gossip, /sync, /entropy
USER JWT Bearer token req.user { userId, role } /profile, /chat, /listings
ADMIN JWT + delegate set persistentId ∈ delegates /admin/users, /admin/moderation
HOST JWT + exact match persistentId === hostPersistentId /admin/shutdown, /admin/oracle
import { AuthLevel } from 'yakmesh/server/darbar';

// Auth hierarchy (lowest to highest):
// PUBLIC < LOCAL < PEER < USER < ADMIN < HOST

// PEER auth verifies ML-DSA-65 signatures:
// Headers: x-node-id, x-node-signature, x-node-timestamp
// Timestamp drift tolerance: 10 seconds
// Public keys resolved from peer registry (never from the request)

Domain-Based Routing

Routes are grouped into domains — logical units that share a URL prefix and are mounted as isolated Express Routers. If a domain’s routes throw, other domains continue serving:

import { createDarbar, AuthLevel } from 'yakmesh/server/darbar';

const darbar = createDarbar({
  verifyToken:      jwt.verify,
  resolveIdentity:  identityStore.resolve,
  hostPersistentId: () => nodeIdentity.persistentId,
  isDelegate:       (pid) => delegateSet.has(pid),
  resolvePeerKey:   (nodeId) => peerRegistry.getPublicKey(nodeId),
  verifySignature:  crypto.verifyMLDSA65,
});

// Mount domains
darbar.mount(app, [
  {
    domain: 'lighthouse',
    prefix: '/api/lighthouse',
    routes: [
      { method: 'GET',  path: '/',          auth: AuthLevel.PUBLIC,  handler: listServers },
      { method: 'POST', path: '/heartbeat', auth: AuthLevel.USER,    handler: heartbeat },
      { method: 'POST', path: '/register',  auth: AuthLevel.USER,    handler: registerServer },
    ],
  },
  {
    domain: 'governance',
    prefix: '/api/governance',
    routes: [
      { method: 'GET',  path: '/scores',    auth: AuthLevel.PUBLIC,  handler: getScores },
      { method: 'POST', path: '/vote',      auth: AuthLevel.USER,    handler: castVote },
      { method: 'POST', path: '/ban',       auth: AuthLevel.ADMIN,   handler: banPlayer },
    ],
  },
]);

// Error handler (after all routes)
app.use(darbar.errorHandler());

DarbarError & Error Codes

Handlers throw DarbarError to produce standardised JSON error responses. The global error handler maps each error code to the correct HTTP status:

ErrorCode HTTP Status When
AUTH_REQUIRED 401 Missing or invalid token/signature
FORBIDDEN 403 Authenticated but insufficient access level
NOT_FOUND 404 Resource does not exist
VALIDATION_ERROR 400 Invalid request body or parameters
RATE_LIMITED 429 Too many requests
INTERNAL_ERROR 500 Unexpected server error
import { DarbarError, ErrorCode } from 'yakmesh/server/darbar';

async function registerServer(req, res) {
  const { name, port } = req.body;
  if (!name) throw new DarbarError('Server name required', ErrorCode.VALIDATION_ERROR);
  if (port < 1024) throw new DarbarError('Port must be >= 1024', ErrorCode.VALIDATION_ERROR);

  const server = await serverDirectory.register({ name, port, owner: req.user.userId });
  res.json({ ok: true, serverId: server.id });
}

// Error response shape (automatic):
// { "error": "Server name required", "code": "VALIDATION_ERROR" }

DarbarConfig Interface

Each project provides a DarbarConfig object that plugs project-specific auth backends into the framework:

verifyToken(token){ userId, username, role } | null

JWT verification. Returns decoded payload or null.

resolveIdentity(userId){ persistentId, publicKey } | null

Maps a user ID to their mesh identity (persistentId from DOKO ceremony).

hostPersistentIdstring | () => string

The node operator’s persistent ID. Can be a getter for lazy resolution.

isDelegate(persistentId)boolean

Checks if a persistent ID is in the host’s admin delegate set.

resolvePeerKey(nodeId)publicKey | null

Resolves an ML-DSA-65 public key from the peer registry. Keys are NEVER taken from the request.

verifySignature(message, signature, publicKey)boolean

ML-DSA-65 signature verification for PEER-level auth.

Cross-Project Usage

DARBAR is shared across all yakmesh sub-projects. Each project provides its own DarbarConfig and domain descriptors:

yakmesh-node

Main mesh node. Domains: mesh, gossip, identity, files, admin, lighthouse, governance.

Config: ML-DSA-65 peer auth, DOKO identity, delegate set from governance.

C2C Game Server

Core to Cosmos. Domains: game state, realms, SEVA models, anti-cheat, server browser.

Config: Game JWT auth, server-local identity, host = game server operator.

yakapp

Desktop client. Domains: local API, preferences, wallet. All routes LOCAL auth.

Config: No JWT (desktop app), localhost only, host = app user.

API Reference

createDarbar(config){ mount, errorHandler, getMountedDomains, DarbarError, ErrorCode, AuthLevel }

Factory function. Create a DARBAR instance for a specific project.

darbar.mount(app, domains)void

Mount domain descriptors onto an Express app. Each domain gets crash-isolated routing.

darbar.errorHandler()(err, req, res, next) => void

Express 4-param error middleware. Maps DarbarError codes to HTTP status + JSON. Register after all routes.

darbar.getMountedDomains()Array<{ domain, prefix, routeCount }>

Summary of mounted domains for health/status endpoints.

Version History

Version Changes
v3.3.0 Initial DARBAR: 6 auth levels (PUBLIC–HOST), domain-based crash-isolated routing, DarbarError/ErrorCode, DarbarConfig interface, createDarbar() factory, asyncWrap error boundary, peer signature verification with 10s drift tolerance.