import http from 'http'; import https from 'https'; import { Router, Request, Response, NextFunction, RequestHandler, Express } from 'express'; import { WebSocketServer, WebSocket } from 'ws'; import { UserRole, RegisterNodeInput, NodeHeartbeat, PodStatus, WsMessage as WsMessage$3, SignallingMessage, RoutingRequest, RoutingResponse, PodGroupStore, User } from '@stark-o/shared'; import { MongoAbility, MongoQuery } from '@casl/ability'; import { RateLimitRequestHandler } from 'express-rate-limit'; import { SlowDownRequestHandler } from 'express-slow-down'; /** * WebSocket Connection Manager * @module @stark-o/server/ws/connection-manager * * Manages WebSocket connections for the orchestrator server. * Handles authentication, message routing, and connection lifecycle. */ /** * Generic WebSocket message structure */ interface WsMessage$2 { type: string; payload: T; correlationId?: string; } /** * Connection metadata stored for each WebSocket */ interface ConnectionInfo { /** Unique connection ID */ id: string; /** WebSocket instance */ ws: WebSocket; /** User ID (from authentication) */ userId?: string; /** User roles (from authentication) */ userRoles?: UserRole[]; /** IP address of the client */ ipAddress?: string; /** User agent string */ userAgent?: string; /** Node IDs registered on this connection */ nodeIds: Set; /** When the connection was established */ connectedAt: Date; /** Last activity timestamp */ lastActivity: Date; /** Whether the connection is authenticated */ isAuthenticated: boolean; /** Connection type: 'agent' for node agents (Supabase JWT), 'pod' for pod subprocesses (pod token) */ connectionType?: 'agent' | 'pod'; /** * Per-connection message processing queue. * Each incoming message chains onto this promise so that messages from the * same connection are processed strictly in order. Without this, two * rapid-fire status updates (e.g. 'starting' then 'running') can race * through concurrent async handlers and the later DB write wins — which * may be the earlier status, leaving the pod stuck. */ messageQueue: Promise; } /** * All WebSocket message types handled by the connection manager */ type WsMessageType = 'connected' | 'disconnect' | 'error' | 'node:register' | 'node:register:ack' | 'node:register:error' | 'node:reconnect' | 'node:reconnect:ack' | 'node:reconnect:error' | 'node:heartbeat' | 'node:heartbeat:ack' | 'node:heartbeat:error' | 'auth:authenticate' | 'auth:authenticated' | 'auth:error' | 'ping' | 'pong'; /** * Authentication result */ interface AuthResult { success: boolean; userId?: string; userRoles?: UserRole[]; error?: string; } /** * Authentication handler function type */ type AuthHandler = (token: string) => Promise; /** * Connection manager options */ interface ConnectionManagerOptions { /** Ping interval in milliseconds (default: 30000) */ pingInterval?: number; /** Pong timeout in milliseconds (default: 10000) */ pongTimeout?: number; /** Maximum message size in bytes (default: 1MB) */ maxMessageSize?: number; /** Authentication handler */ authHandler?: AuthHandler; /** Whether to require authentication (default: true in production) */ requireAuth?: boolean; } /** * WebSocket Connection Manager * * Manages all WebSocket connections to the orchestrator server. * Handles: * - Connection lifecycle (connect, disconnect, reconnect) * - Authentication * - Message routing to appropriate handlers * - Heartbeat/ping-pong for connection health * - Connection tracking and cleanup */ declare class ConnectionManager { private connections; /** Reverse index: nodeId → connectionId */ private nodeToConnection; /** Reverse index: podId → connectionId (for direct pod connections) */ private podToConnection; /** Reverse index: connectionId → Set of podIds (for cleanup on disconnect) */ private connectionToPods; /** * Tracks WebRTC signaling peers: podId → Set of podIds that have * exchanged signals with it. Used to send `network:peer-gone` * notifications when a pod disconnects so the other side can * tear down the dead PeerConnection immediately. */ private signalingPeers; /** Current connection being processed (for registration callbacks) */ private currentConnectionId; private pingInterval; private readonly options; private networkHandlers; private podGroupHandlers; constructor(options?: ConnectionManagerOptions); /** * Attach the connection manager to a WebSocket server */ attach(wss: WebSocketServer): void; /** * Register a pod's direct connection for WebRTC signaling. * Also marks the connection as authenticated (pod tokens are validated by the network handler). */ private registerPodConnection; /** * Get all active connections */ getConnections(): Map; /** * Get connection by ID */ getConnection(connectionId: string): ConnectionInfo | undefined; /** * Get connection count */ getConnectionCount(): number; /** * Get authenticated connection count */ getAuthenticatedConnectionCount(): number; /** * Close all connections and cleanup */ shutdown(): void; /** * Handle a new WebSocket connection */ private handleConnection; /** * Handle incoming WebSocket message. * * Messages from the same connection are processed strictly in order by * chaining onto `conn.messageQueue`. Without serialisation, two rapid-fire * status updates (e.g. 'starting' then 'running') race through concurrent * async handlers and the later DB write wins — which may be the earlier * status, leaving the pod stuck. */ private handleMessage; /** * Route message to the appropriate handler */ private routeMessage; /** * Handle authentication message */ private handleAuthenticate; /** * Handle WebSocket close event */ private handleClose; /** * Handle WebSocket error */ private handleError; /** * Handle pong response (for connection health checking) */ private handlePong; /** * Get the first node ID from a connection (for chaos proxy) */ private getFirstNodeId; /** * Create a WsConnection interface for handlers */ private createWsConnection; /** * Send a message to a WebSocket */ private sendMessage; /** * Send an error message to a WebSocket */ private sendError; /** * Start the ping interval for connection health checking */ private startPingInterval; /** * Extract IP address from the request */ private extractIpAddress; /** * Register a node ID to a connection */ registerNodeToConnection(connectionId: string, nodeId: string): void; /** * Unregister a node ID from a connection */ unregisterNodeFromConnection(connectionId: string, nodeId: string): void; /** * Get all node IDs for a connection */ getConnectionNodes(connectionId: string): Set; /** * Broadcast a message to all authenticated connections */ broadcast(message: WsMessage$2, filter?: (conn: ConnectionInfo) => boolean): void; /** * Send a message to a specific connection */ sendToConnection(connectionId: string, message: WsMessage$2): boolean; /** * Send a message to a specific node by its nodeId (not connectionId). * Uses the nodeToConnection reverse index. */ sendToNodeId(nodeId: string, message: WsMessage$2): boolean; /** * Send a message to a pod. * * First tries direct pod connection (pod subprocess connected directly), * then falls back to routing through the node agent hosting the pod. */ sendToPod(podId: string, message: WsMessage$2): boolean; /** * Record that two pods have exchanged WebRTC signaling. This is a * bidirectional relationship so that when either pod disconnects we can * notify the other. */ private trackSignalingPeers; /** * Notify all known signaling peers that `deadPodId` is gone, and clean up * the tracking entries. Recipients should tear down the dead * PeerConnection and (if applicable) re-route through the orchestrator. */ private notifyPeerGone; } /** * Create a connection manager instance */ declare function createConnectionManager(options?: ConnectionManagerOptions): ConnectionManager; /** * Pod Scheduler Service * @module @stark-o/server/services/scheduler-service * * Reactive background service that schedules pending pods to available nodes. * Triggers immediately on pod creation and node registration/reconnection, * with a fallback interval for consistency. */ /** * Scheduler service configuration */ interface SchedulerServiceConfig { /** Interval between scheduling runs in milliseconds (default: 5000) */ scheduleInterval?: number; /** Maximum pods to schedule per run (default: 10) */ maxPodsPerRun?: number; /** Whether to start the scheduler automatically (default: true) */ autoStart?: boolean; } /** * Pod Scheduler Service * * Reactive scheduler that runs on-demand when pods are created or nodes * come online, with a fallback interval for consistency: * 1. Queries pending pods ordered by priority * 2. Finds compatible online nodes for each pod * 3. Schedules pods to nodes (updates database) * 4. Sends pod:deploy messages to nodes via WebSocket */ declare class SchedulerService { private config; private connectionManager; private intervalTimer; private isRunning; private isProcessing; /** * Set to true when triggerSchedule() is called during an active cycle. * Causes another scheduling cycle to run immediately after the current one finishes. */ private pendingSchedule; /** * Timestamp of last completed scheduling cycle. * Used to debounce triggerSchedule() calls that arrive shortly after * a cycle already ran (e.g. pod creation + interval timer racing). */ private lastScheduleAt; /** Minimum gap in ms between scheduling cycles triggered externally */ private static readonly SCHEDULE_DEBOUNCE_MS; constructor(config?: SchedulerServiceConfig); /** * Attach a connection manager for sending messages to nodes */ attach(connectionManager: ConnectionManager): void; /** * Start the scheduling loop */ start(): void; /** * Stop the scheduling loop */ stop(): void; /** * Run a single scheduling cycle */ private runSchedulingCycle; /** * Main scheduling logic - find pending pods and schedule them */ private schedulePendingPods; /** * Schedule a single pod to an available node */ private schedulePod; /** * Send pod:deploy message to a node via WebSocket */ private deployPodToNode; /** * Trigger an immediate scheduling cycle (reactive trigger). * Debounced: if a scheduling cycle completed within SCHEDULE_DEBOUNCE_MS, * the call is coalesced into a pending flag so the next cycle picks it up * instead of racing with the just-finished cycle. */ triggerSchedule(): Promise; /** * Check if the scheduler is running */ isActive(): boolean; } /** * Get or create the singleton scheduler service */ declare function getSchedulerService(config?: SchedulerServiceConfig): SchedulerService; /** * Service Controller Service * @module @stark-o/server/services/service-controller * * Background service that reconciles services by: * 1. Checking desired vs actual pod counts * 2. Creating pods for under-replicated services * 3. Handling DaemonSet mode (replicas=0) by deploying to all matching nodes * 4. Cleaning up pods when services are deleted */ /** * Service controller configuration */ interface ServiceControllerConfig { /** Interval between reconciliation runs in milliseconds (default: 10000) */ reconcileInterval?: number; /** Whether to start the controller automatically (default: true) */ autoStart?: boolean; /** Number of consecutive failures before triggering auto-rollback (default: 3) */ maxConsecutiveFailures?: number; /** Initial backoff duration in milliseconds after failures (default: 60000 = 1 min) */ initialBackoffMs?: number; /** Maximum backoff duration in milliseconds (default: 3600000 = 1 hour) */ maxBackoffMs?: number; /** Time window in milliseconds to detect rapid pod failures (default: 60000 = 1 min) */ failureDetectionWindowMs?: number; } /** * Service Controller Service * * Runs a background loop that reconciles services: * - For replicas > 0: maintains exactly N pods * - For replicas = 0 (DaemonSet): maintains 1 pod per matching node */ declare class ServiceController { private config; private intervalTimer; private isRunning; private isProcessing; /** * Set to true when triggerReconcile() is called during an active cycle. * Causes another reconcile to run immediately after the current one finishes. * This prevents lost reconciles when orphaned pods are stopped mid-cycle. */ private pendingReconcile; /** * Timestamp of last completed reconcile cycle. * Used to debounce triggerReconcile() calls that arrive shortly after * a cycle already ran (e.g. reconnect handler + interval timer racing). */ private lastReconcileAt; /** Minimum gap in ms between reconcile cycles triggered externally */ private static readonly RECONCILE_DEBOUNCE_MS; /** * Per-service lock set. While a service ID is in this set, no other * reconcile pass can create pods for it. Prevents the triggered-reconcile * vs interval-reconcile race from double-creating pods. */ private reconcilingServices; constructor(config?: ServiceControllerConfig); /** * Start the reconciliation loop */ start(): void; /** * Stop the reconciliation loop */ stop(): void; /** * Run a single reconciliation cycle */ private runReconcileLoop; /** * Main reconciliation logic */ private reconcileServices; /** * Check and update services that follow the latest pack version * If a new pack version exists, update the service and trigger a rolling update * Includes crash-loop protection to prevent infinite upgrade/fail cycles */ private reconcileFollowLatestVersions; /** * Trigger a rolling update of pods for a service * Marks existing pods for replacement with new version */ private triggerRollingUpdate; /** * Check if a service is in failure backoff for a specific version */ private isInFailureBackoff; /** * Calculate exponential backoff duration based on consecutive failures */ private calculateBackoffMs; /** * Detect crash loop and handle auto-rollback if needed * Returns true if service should skip further reconciliation */ private detectAndHandleCrashLoop; /** * Reconcile a single service */ private reconcileService; /** * Inner reconciliation logic for a single service (called under per-service lock) */ private reconcileServiceInner; /** * Reconcile DaemonSet mode (replicas = 0) * Creates one pod per matching node */ private reconcileDaemonSet; /** * Reconcile regular service (replicas > 0) */ private reconcileReplicas; /** * Filter nodes eligible for a service based on scheduling constraints and runtime */ private filterEligibleNodes; /** * Create a pod for a service with proper incarnation tracking */ private createPodForService; /** * Send pod:deploy message to a node via WebSocket * Used for DaemonSet pods that are pre-assigned to specific nodes */ private deployPodToNode; /** * Trigger an immediate reconciliation cycle. * Debounced: if a reconcile completed within RECONCILE_DEBOUNCE_MS, the call * is coalesced into a pending flag so the next interval picks it up instead * of racing with pod creation from the just-finished cycle. */ triggerReconcile(): Promise; /** * Check if the controller is running */ isActive(): boolean; } /** * Get or create the singleton service controller */ declare function getServiceController(config?: ServiceControllerConfig): ServiceController; /** * Node Health Service * @module @stark-o/server/services/node-health-service * * Background service that manages node health with a lease-based model to prevent * double-deploy bugs during transient disconnections. * * Lease Model: * 1. On disconnect: node becomes 'suspect' (not immediately offline) * 2. While suspect: pods remain logically owned, no replacements scheduled * 3. If reconnects before lease expires: restore to online, nothing else changes * 4. If lease expires: node becomes 'offline', pods are REVOKED (not just failed) */ /** * Node health service configuration */ interface NodeHealthServiceConfig { /** Interval between health checks in milliseconds (default: 30000 = 30 seconds) */ checkInterval?: number; /** Heartbeat timeout for marking online nodes as suspect (default: 60000 = 60 seconds) */ heartbeatTimeout?: number; /** Lease duration before suspect nodes become offline (default: 120000 = 2 minutes) */ leaseTimeout?: number; /** Whether to start the service automatically when attached (default: true) */ autoStart?: boolean; /** * Called when pods are revoked during lease expiry. * Use this to clean up ephemeral state (PodGroupStore, ServiceRegistry, etc.) * that the DB-level revocation doesn't cover. */ onPodsRevoked?: (nodeId: string, podIds: string[]) => void; } /** * Node Health Service * * Runs a background loop that: * 1. Checks online nodes for stale heartbeats -> marks as 'suspect' * 2. Checks suspect nodes for lease expiration -> marks as 'offline' + revokes pods * 3. Uses incarnation tracking to prevent double-deploy bugs */ declare class NodeHealthService { private config; private intervalTimer; private isRunning; private isProcessing; constructor(config?: NodeHealthServiceConfig); /** * Start the health check loop */ start(): void; /** * Stop the health check loop */ stop(): void; /** * Check if the service is running */ isActive(): boolean; /** * Run a single health check cycle */ private runHealthCheck; /** * Find nodes that are marked online but haven't sent a heartbeat recently. * Marks them as 'suspect' - pods remain logically owned, no replacements yet. */ private markStaleNodesAsSuspect; /** * Check suspect nodes for lease expiration. * When lease expires: mark offline, REVOKE pods (with incarnation tracking). */ private expireNodeLeases; } /** * Create a node health service instance */ declare function createNodeHealthService(config?: NodeHealthServiceConfig): NodeHealthService; /** * Ingress Manager Service * @module @stark-o/server/services/ingress-manager * * Manages ingress ports for services. When a service declares an ingress port, * the orchestrator: * 1. Opens an HTTP listener on that port. * 2. Routes incoming requests to a healthy pod using modulus-based selection * (request parameter → pod index). * 3. Relays request/response data to the selected pod via WebSocket * (the orchestrator's existing WebSocket connection to the node agent). * 4. Re-balances when pods die or become unhealthy. * 5. Cleans up the listener and channels when the service is removed. * 6. Restores all ingress listeners on server restart by reading from DB. */ /** * Ingress Manager * * Singleton service that opens HTTP listeners for services with ingress ports * and proxies traffic to pods via the orchestrator's WebSocket data plane. */ declare class IngressManager { /** port → IngressBinding */ private bindings; /** correlationId → PendingRequest (in-flight proxied requests) */ private pendingRequests; /** Default timeout for proxied requests (30 s) */ private readonly requestTimeoutMs; /** Host to bind ingress listeners to */ private readonly host; /** Cached SSL options for HTTPS ingress listeners */ private sslOptions; constructor(options?: { requestTimeoutMs?: number; host?: string; }); /** * Load or read cached SSL options from the same .cache/ directory * that the main server uses. Falls back to self-signed generation * via the `selfsigned` package if no certs exist yet. */ private getSslOptions; /** * Open an ingress listener for a service. * Idempotent – if a listener already exists on this port for the same * service it is a no-op; if a *different* service claims the port an * error is thrown. */ openIngress(serviceId: string, serviceName: string, port: number): Promise; /** * Close the ingress listener for a service (by service ID). * Also aborts any in-flight requests belonging to this service. */ closeIngress(serviceId: string): Promise; /** * Close ingress by port number. */ closeIngressByPort(port: number): Promise; /** * Handle an incoming WebSocket response from a pod for a proxied ingress request. * Called by the connection manager when it receives an `ingress:response` message. */ handleIngressResponse(correlationId: string, payload: { status: number; headers?: Record; body?: string; }): void; /** * Check if a port is bound to an ingress. */ hasIngress(port: number): boolean; /** * Get the service ID for a port. */ getServiceIdForPort(port: number): string | undefined; /** * List all active ingress bindings (for debugging / status API). */ listBindings(): Array<{ port: number; serviceId: string; serviceName: string; }>; /** * Shut down all ingress listeners. Called during server shutdown. */ shutdown(): Promise; /** * Handle an incoming HTTP request on an ingress port. * 1. Checks network policy (exposed flag via evaluateNetworkPolicy). * 2. Selects a pod using modulus on the request counter. * 3. Sends the request payload to the pod via WebSocket. * 4. Waits for the pod's response (or timeout). */ private handleIngressRequest; /** * Select a pod and relay the request via WebSocket. */ private routeToPoD; /** * Try sending to alternative healthy pods when the primary is unreachable. */ private tryFallbackPods; /** * Send a message to a node by looking up its connection in the connection manager. */ private sendViaNodeLookup; /** * Extract a route key from the request for affinity-based routing. * Checks `X-Stark-Route` header, then `stark-route` query param. * Returns null if no explicit key is provided (falls back to counter). */ private extractRouteKey; /** * Simple string hash for non-numeric route keys. */ private hashString; /** * Flatten Node.js IncomingHttpHeaders to simple Record. */ private flattenHeaders; } /** * Get or create the singleton ingress manager. */ declare function getIngressManager(options?: { requestTimeoutMs?: number; host?: string; }): IngressManager; /** * Central API Router * * Combines all REST API routes into a single router. * @module @stark-o/server/api/router */ /** * API router configuration options */ interface ApiRouterOptions { /** Enable request logging */ enableLogging?: boolean; /** API version prefix (default: 'v1') */ apiVersion?: string; /** Enable rate limiting (default: true in production, false in test) */ enableRateLimiting?: boolean; } /** * GET /health - Health check endpoint */ declare function healthCheck(_req: Request, res: Response): Promise; /** * GET /ready - Readiness check endpoint */ declare function readinessCheck(_req: Request, res: Response): Promise; /** * GET /live - Liveness check endpoint */ declare function livenessCheck(_req: Request, res: Response): Promise; /** * Request logging middleware */ declare function requestLoggingMiddleware(req: Request, res: Response, next: NextFunction): void; /** * Error handling middleware */ declare function errorHandlingMiddleware(err: Error, req: Request, res: Response, _next: NextFunction): void; /** * 404 Not Found handler */ declare function notFoundHandler(req: Request, res: Response): void; /** * Create the central API router */ declare function createApiRouter(options?: ApiRouterOptions): Router; /** * Pack REST API Endpoints * * Provides REST endpoints for pack registration and management. * @module @stark-o/server/api/packs */ /** * POST /api/packs - Register a new pack */ declare function registerPack(req: Request, res: Response): Promise; /** * GET /api/packs - List packs with pagination and filtering */ declare function listPacks(req: Request, res: Response): Promise; /** * GET /api/packs/:id - Get pack by ID */ declare function getPackById(req: Request, res: Response): Promise; /** * GET /api/packs/:name/versions - List all versions of a pack */ declare function listPackVersions(req: Request, res: Response): Promise; /** * PATCH /api/packs/:id - Update pack metadata */ declare function updatePack(req: Request, res: Response): Promise; /** * DELETE /api/packs/:id - Delete a pack */ declare function deletePack(req: Request, res: Response): Promise; /** * Creates the packs router */ declare function createPacksRouter(): Router; /** * Pod REST API Endpoints * * Provides REST endpoints for pod creation, management, and status retrieval. * @module @stark-o/server/api/pods */ /** * POST /api/pods - Create a new pod */ declare function createPod(req: Request, res: Response): Promise; /** * GET /api/pods - List pods with pagination and filtering */ declare function listPods(req: Request, res: Response): Promise; /** * GET /api/pods/:id - Get pod by ID */ declare function getPodById(req: Request, res: Response): Promise; /** * GET /api/pods/:id/status - Get pod status summary */ declare function getPodStatus(req: Request, res: Response): Promise; /** * DELETE /api/pods/:id - Stop and delete a pod */ declare function deletePod(req: Request, res: Response): Promise; /** * GET /api/pods/:id/history - Get pod history */ declare function getPodHistory(req: Request, res: Response): Promise; /** * Creates the pods router */ declare function createPodsRouter(): Router; /** * Node REST API Endpoints * * Provides REST endpoints for node registration and management. * @module @stark-o/server/api/nodes */ /** * POST /api/nodes - Register a new node */ declare function registerNode(req: Request, res: Response): Promise; /** * GET /api/nodes - List nodes with pagination and filtering */ declare function listNodes(req: Request, res: Response): Promise; /** * GET /api/nodes/:id - Get a node by ID */ declare function getNodeById(req: Request, res: Response): Promise; /** * GET /api/nodes/name/:name - Get a node by name */ declare function getNodeByName(req: Request, res: Response): Promise; /** * PATCH /api/nodes/:id - Update a node */ declare function updateNode(req: Request, res: Response): Promise; /** * DELETE /api/nodes/:id - Delete a node */ declare function deleteNode(req: Request, res: Response): Promise; /** * Create and configure the nodes router */ declare function createNodesRouter(): Router; /** * Auth REST API Endpoints * * Provides REST endpoints for user authentication. * - POST /auth/register - Register a new user * - POST /auth/login - Login an existing user * - POST /auth/logout - Logout the current user * - POST /auth/refresh - Refresh access token using refresh token * * @module @stark-o/server/api/auth */ /** * POST /auth/register - Register a new user */ declare function register(req: Request, res: Response): Promise; /** * POST /auth/login - Login an existing user */ declare function login(req: Request, res: Response): Promise; /** * POST /auth/logout - Logout the current user */ declare function logout(req: Request, res: Response): Promise; /** * GET /auth/setup/status - Check if setup is needed (no users exist) and registration status */ declare function setupStatus(_req: Request, res: Response): Promise; /** * POST /auth/setup - Create the first admin user (only works when no users exist) */ declare function setup(req: Request, res: Response): Promise; /** * POST /auth/users - Create a new user (admin only) */ declare function createUser(req: Request, res: Response): Promise; /** * GET /auth/users - List all users (admin only) */ declare function listUsers(req: Request, res: Response): Promise; /** * Creates the auth router with all endpoints */ declare function createAuthRouter(): Router; /** * Namespace REST API Endpoints * * Provides REST endpoints for namespace CRUD operations. * @module @stark-o/server/api/namespaces */ /** * POST /api/namespaces - Create a new namespace */ declare function createNamespaceHandler(req: Request, res: Response): Promise; /** * GET /api/namespaces - List namespaces with pagination and filtering */ declare function listNamespacesHandler(req: Request, res: Response): Promise; /** * GET /api/namespaces/:id - Get namespace by ID */ declare function getNamespaceByIdHandler(req: Request, res: Response): Promise; /** * GET /api/namespaces/name/:name - Get namespace by name */ declare function getNamespaceByNameHandler(req: Request, res: Response): Promise; /** * PUT /api/namespaces/:id - Update a namespace */ declare function updateNamespaceHandler(req: Request, res: Response): Promise; /** * DELETE /api/namespaces/:id - Delete a namespace */ declare function deleteNamespaceHandler(req: Request, res: Response): Promise; /** * DELETE /api/namespaces/name/:name - Delete a namespace by name */ declare function deleteNamespaceByNameHandler(req: Request, res: Response): Promise; /** * GET /api/namespaces/:id/quota - Get namespace quota info */ declare function getNamespaceQuotaHandler(req: Request, res: Response): Promise; /** * Creates the namespaces router with all endpoints */ declare function createNamespacesRouter(): Router; /** * Config REST API Endpoints * * Provides REST endpoints for application configuration. * - GET /config - Get current configuration (public) * - PUT /config - Update configuration (admin only) * * @module @stark-o/server/api/config */ /** * GET /config - Get current application configuration * This endpoint is public (no authentication required) */ declare function getConfig(_req: Request, res: Response): Promise; /** * PUT /config - Update application configuration (admin only) */ declare function putConfig(req: Request, res: Response): Promise; /** * Creates the config router with all endpoints */ declare function createConfigRouter(): Router; /** * Service REST API Endpoints * * Provides REST endpoints for service creation, management, and status retrieval. * @module @stark-o/server/api/services */ /** * Create and configure the services router */ declare function createServicesRouter(): Router; /** * Default router instance */ declare const servicesRouter: Router; /** * Secrets REST API Endpoints * * Provides REST endpoints for secret lifecycle management. * Secret values are NEVER returned in API responses — only metadata. * * @module @stark-o/server/api/secrets */ /** * Create the secrets router */ declare function createSecretsRouter(): Router; /** * WebSocket Node Handler * @module @stark-o/server/ws/handlers/node-handler * * Handles WebSocket messages for node registration, heartbeat, and disconnect. */ /** * WebSocket message types for nodes */ type WsNodeMessageType = 'node:register' | 'node:register:ack' | 'node:register:error' | 'node:reconnect' | 'node:reconnect:ack' | 'node:reconnect:error' | 'node:heartbeat' | 'node:heartbeat:ack' | 'node:heartbeat:error' | 'node:disconnect'; /** * WebSocket message structure * Type is loosely typed to allow connection manager to pass messages */ interface WsMessage$1 { type: string; payload: T; correlationId?: string; } /** * WebSocket connection interface */ interface WsConnection$1 { id: string; send: (data: string) => void; close: () => void; terminate: () => void; userId?: string; userRoles?: UserRole[]; } /** * Handle node registration via WebSocket */ declare function handleNodeRegister(ws: WsConnection$1, message: WsMessage$1): Promise; /** * Handle node heartbeat via WebSocket */ declare function handleNodeHeartbeat(ws: WsConnection$1, message: WsMessage$1): Promise; /** * Reconnect payload */ interface ReconnectNodePayload { nodeId: string; /** Optional capabilities update - allows updating Node.js version on reconnect */ capabilities?: { version?: string; features?: string[]; [key: string]: unknown; }; /** * Pod IDs currently running on the node. * Used to detect orphaned pods after node restart. * If a pod is in the DB but not in this list, it means the node lost it (e.g., after restart). */ runningPodIds?: string[]; /** UUID identifying the machine this node runs on */ machineId?: string; } /** * Handle node reconnection via WebSocket * Used when a node with an existing nodeId reconnects after a connection drop */ declare function handleNodeReconnect(ws: WsConnection$1, message: WsMessage$1): Promise; /** * Handle node disconnect (connection closed) * Marks nodes as SUSPECT (not offline) to allow reconnection within lease period. * Pods remain logically owned during suspect period - no replacements scheduled. * The NodeHealthService will expire the lease and revoke pods if node doesn't reconnect. */ declare function handleNodeDisconnect(ws: WsConnection$1): Promise; /** * WebSocket Pod Handler * @module @stark-o/server/ws/handlers/pod-handler * * Handles WebSocket messages for pod lifecycle operations with history tracking. */ /** * WebSocket message types for pods */ type WsPodMessageType = 'pod:schedule' | 'pod:schedule:ack' | 'pod:schedule:error' | 'pod:start' | 'pod:start:ack' | 'pod:start:error' | 'pod:stop' | 'pod:stop:ack' | 'pod:stop:error' | 'pod:fail' | 'pod:fail:ack' | 'pod:fail:error' | 'pod:evict' | 'pod:evict:ack' | 'pod:evict:error' | 'pod:restart' | 'pod:restart:ack' | 'pod:restart:error' | 'pod:status:update' | 'pod:status:update:ack' | 'pod:status:update:error'; /** * WebSocket message structure */ interface WsMessage { type: string; payload: T; correlationId?: string; } /** * WebSocket connection interface */ interface WsConnection { id: string; send: (data: string) => void; close: () => void; terminate: () => void; userId?: string; userRoles?: UserRole[]; nodeId?: string; } /** * Pod schedule payload */ interface PodSchedulePayload { podId: string; nodeId: string; message?: string; } /** * Pod status update payload */ interface PodStatusUpdatePayload { podId: string; status: PodStatus; message?: string; reason?: string; /** Pod incarnation - used to reject late messages from old incarnations */ incarnation?: number; } /** * Pod action payload (stop, fail, evict, restart) */ interface PodActionPayload { podId: string; message?: string; reason?: string; /** Pod incarnation - used to reject late messages from old incarnations */ incarnation?: number; } /** * Handle pod scheduling from a node */ declare function handlePodSchedule(ws: WsConnection, message: WsMessage): Promise; /** * Handle pod start notification from a node */ declare function handlePodStart(ws: WsConnection, message: WsMessage): Promise; /** * Handle pod stop request */ declare function handlePodStop(ws: WsConnection, message: WsMessage): Promise; /** * Handle pod failure notification from a node */ declare function handlePodFail(ws: WsConnection, message: WsMessage): Promise; /** * Handle pod eviction request */ declare function handlePodEvict(ws: WsConnection, message: WsMessage): Promise; /** * Handle pod restart request */ declare function handlePodRestart(ws: WsConnection, message: WsMessage): Promise; /** * Handle generic pod status update */ declare function handlePodStatusUpdate(ws: WsConnection, message: WsMessage): Promise; /** * Pod handler message routing */ declare function routePodMessage(ws: WsConnection, message: WsMessage): Promise | void; /** * Network WebSocket Handler * * Handles WebSocket messages related to inter-service networking: * - WebRTC signalling relay (offer/answer/ICE candidates between pods) * - Pod routing requests (when pods connect directly for routing) * - Pod registration (pods connecting directly for WebRTC signaling) * * Architecture: * - Pods connect directly to orchestrator via WebSocket for signaling * - Orchestrator relays WebRTC signals between pods * - Orchestrator never handles data traffic after WebRTC handshake * * @module @stark-o/server/ws/handlers/network-handler */ /** * Interface for the connection manager used to send messages to pods. */ interface NetworkConnectionManager { /** Send a WsMessage to a specific pod */ sendToPod?(podId: string, message: WsMessage$3): boolean; /** Send a WsMessage to a specific node */ sendToNode?(nodeId: string, message: WsMessage$3): boolean; /** Register a pod's WebSocket connection for direct signaling */ registerPodConnection?(podId: string, serviceId: string): void; } /** * Install network-related WebSocket message handlers. * * Call this from the connection manager setup to register handlers * for network message types. */ declare function createNetworkWsHandlers(connectionManager: NetworkConnectionManager): { /** * Handle a WebRTC signalling relay message. * Forwards the signal to the target pod via the connection manager. * For pod connections, validates that sourcePodId matches the authenticated identity. * Agent connections are trusted to relay on behalf of any pod they manage. */ handleSignalRelay(message: WsMessage$3, connUserId?: string, connectionType?: "agent" | "pod"): void; /** * Handle a routing request from a pod (via WebSocket instead of HTTP). * Returns a routing response to the requesting pod. * For pod connections, validates that callerPodId matches the authenticated identity. * Agent connections are trusted to route on behalf of any pod they manage. */ handleRoutingRequest(message: WsMessage$3, sendResponse: (response: WsMessage$3) => void, connUserId?: string, connectionType?: "agent" | "pod"): void; /** * Handle a pod's service registry heartbeat. * The pod tells the orchestrator which service it hosts. * For pod connections, validates that podId matches the authenticated identity. */ handleRegistryHeartbeat(message: WsMessage$3<{ serviceId: string; podId: string; nodeId: string; }>, connUserId?: string, connectionType?: "agent" | "pod"): void; /** * Handle pod registration for direct WebRTC signaling. * Called when a pod subprocess connects directly to orchestrator. * Validates pod auth token to prevent spoofing. */ handlePodRegister(message: WsMessage$3<{ podId: string; serviceId: string; authToken?: string; }>, sendResponse: (response: WsMessage$3) => void): void; /** * Handle pod disconnection → unregister from registry and discard any * queued signals addressed to this pod. */ handlePodDisconnected(podId: string): void; }; /** * Network-related WS message types. */ declare const NETWORK_WS_TYPES: { /** WebRTC signalling relay */ readonly SIGNAL: "network:signal"; /** Routing request (pod → orchestrator) */ readonly ROUTE_REQUEST: "network:route:request"; /** Routing response (orchestrator → pod) */ readonly ROUTE_RESPONSE: "network:route:response"; /** Registry heartbeat (pod → orchestrator) */ readonly REGISTRY_HEARTBEAT: "network:registry:heartbeat"; /** Pod registration for direct signaling */ readonly POD_REGISTER: "network:pod:register"; }; /** * PodGroup WebSocket Handler * * Centralises PodGroup membership on the orchestrator server. * Pods communicate group operations (join, leave, getGroupPods, etc.) via WS, * and the orchestrator maintains a single authoritative PodGroupStore backed * by node-cache. * * After group discovery, pods still talk to each other directly over WebRTC — * this handler only manages the *membership* metadata. * * Message types handled: * group:join — join a group * group:leave — leave a specific group * group:leave-all — leave all groups (graceful shutdown) * group:get-pods — list members of a group * group:get-groups — list groups a pod belongs to * * @module @stark-o/server/ws/handlers/podgroup-handler */ /** Exposed for testing — resets the central store. */ declare function resetCentralPodGroupStore(): void; interface GroupJoinPayload { podId: string; groupId: string; ttl?: number; metadata?: Record; } interface GroupLeavePayload { podId: string; groupId: string; } interface GroupLeaveAllPayload { podId: string; } interface GroupGetPodsPayload { groupId: string; } interface GroupGetGroupsPayload { podId: string; } declare const PODGROUP_WS_TYPES: { readonly JOIN: "group:join"; readonly JOIN_ACK: "group:join:ack"; readonly LEAVE: "group:leave"; readonly LEAVE_ACK: "group:leave:ack"; readonly LEAVE_ALL: "group:leave-all"; readonly LEAVE_ALL_ACK: "group:leave-all:ack"; readonly GET_PODS: "group:get-pods"; readonly GET_PODS_ACK: "group:get-pods:ack"; readonly GET_GROUPS: "group:get-groups"; readonly GET_GROUPS_ACK: "group:get-groups:ack"; readonly ERROR: "group:error"; }; declare function createPodGroupWsHandlers(): { /** * Handle group:join — add a pod to a group. */ handleJoin(message: WsMessage$3, sendResponse: (response: WsMessage$3) => void, connUserId?: string, connectionType?: "agent" | "pod"): void; /** * Handle group:leave — remove a pod from a specific group. */ handleLeave(message: WsMessage$3, sendResponse: (response: WsMessage$3) => void, connUserId?: string, connectionType?: "agent" | "pod"): void; /** * Handle group:leave-all — remove a pod from every group. * Typically called during graceful shutdown. */ handleLeaveAll(message: WsMessage$3, sendResponse: (response: WsMessage$3) => void, connUserId?: string, connectionType?: "agent" | "pod"): void; /** * Handle group:get-pods — return current members of a group. */ handleGetPods(message: WsMessage$3, sendResponse: (response: WsMessage$3) => void): void; /** * Handle group:get-groups — return all groups a pod belongs to. */ handleGetGroups(message: WsMessage$3, sendResponse: (response: WsMessage$3) => void): void; /** * Called when a pod disconnects — clean up all its group memberships. */ handlePodDisconnected(podId: string): void; /** Expose the central store for testing / advanced use. */ getStore(): PodGroupStore; }; /** * Authentication Middleware * * JWT validation middleware for Express routes. * Validates Bearer tokens using Supabase Auth and attaches user to request. * * @module @stark-o/server/middleware/auth-middleware */ /** * Extended Express Request with authenticated user */ interface AuthenticatedRequest extends Request { /** Authenticated user from JWT token */ user: User; /** Access token used for authentication */ accessToken: string; /** Correlation ID for request tracing */ correlationId: string; } /** * Middleware options */ interface AuthMiddlewareOptions { /** Custom header name for authorization (default: 'Authorization') */ headerName?: string; /** Whether to skip authentication for OPTIONS requests (default: true) */ skipOptionsRequests?: boolean; } /** * Extracts the Bearer token from the Authorization header * @param authHeader - The Authorization header value * @returns The token or null if not valid */ declare function extractBearerToken(authHeader: string | undefined): string | null; /** * Creates an authentication middleware that validates JWT tokens * * @param options - Middleware options * @returns Express middleware function * * @example * ```typescript * import { createAuthMiddleware, AuthenticatedRequest } from './middleware/auth-middleware'; * * const authMiddleware = createAuthMiddleware(); * * router.get('/protected', authMiddleware, (req, res) => { * const { user } = req as AuthenticatedRequest; * res.json({ message: `Hello, ${user.displayName}` }); * }); * ``` */ declare function createAuthMiddleware(options?: AuthMiddlewareOptions): RequestHandler; /** * Optional authentication middleware - proceeds even without valid token * * Useful for routes that have different behavior for authenticated vs anonymous users. * * @param options - Middleware options * @returns Express middleware function * * @example * ```typescript * router.get('/public', optionalAuthMiddleware(), (req, res) => { * const user = (req as Partial).user; * if (user) { * res.json({ message: `Hello, ${user.displayName}` }); * } else { * res.json({ message: 'Hello, guest!' }); * } * }); * ``` */ declare function createOptionalAuthMiddleware(options?: AuthMiddlewareOptions): RequestHandler; /** * Type guard to check if request is authenticated */ declare function isAuthenticated(req: Request): req is AuthenticatedRequest; /** * Default auth middleware instance with standard configuration */ declare const authMiddleware: RequestHandler; /** * Default optional auth middleware instance */ declare const optionalAuthMiddleware: RequestHandler; /** * Role-Based Access Control (RBAC) Middleware * * Uses CASL library to define and enforce permissions based on user roles. * Provides fine-grained access control for packs, nodes, pods, and namespaces. * * @module @stark-o/server/middleware/rbac-middleware */ /** * Actions that can be performed on resources */ type Action = 'create' | 'read' | 'update' | 'delete' | 'manage'; /** * Resource types in the system */ type Subject = 'Pack' | 'Pod' | 'Node' | 'Namespace' | 'User' | 'ClusterConfig' | 'all'; /** * CASL ability type for the application */ type AppAbility = MongoAbility<[Action, Subject], MongoQuery>; /** * Extended request with CASL ability */ interface AuthorizedRequest extends AuthenticatedRequest { /** CASL ability for authorization checks */ ability: AppAbility; } /** * RBAC middleware options */ interface RbacMiddlewareOptions { /** Action required to access the route */ action: Action; /** Subject type the action is performed on */ subject: Subject; /** Optional condition check function */ conditionCheck?: (req: Request, user: User) => boolean; } /** * Defines abilities for a user based on their roles * * Role permissions: * - admin: Full access to all resources (manage all) * - user: Self-service users - can CRUD own packs, pods, nodes; read namespaces * - node: Node agents - can create/update own node, update pods assigned to it, read packs * - viewer: Read-only access to packs, pods, nodes, namespaces * * Note: Ownership-based access control (e.g., user can only update their own resources) * is enforced in route handlers. * * @param user - The authenticated user * @returns CASL MongoAbility instance */ declare function defineAbilityFor(user: User): AppAbility; /** * Attaches CASL ability to an authenticated request * * This middleware should be used after auth middleware. * It creates a CASL ability based on the user's roles. * * @returns Express middleware function * * @example * ```typescript * router.get('/protected', * authMiddleware, * attachAbility(), * (req, res) => { * const { ability } = req as AuthorizedRequest; * if (ability.can('read', 'Pack')) { * // User can read packs * } * } * ); * ``` */ declare function attachAbility(): RequestHandler; /** * Creates an authorization middleware that checks if the user can perform an action * * This middleware should be used after auth middleware and attachAbility middleware. * * @param action - The action to check (create, read, update, delete, manage) * @param subject - The resource type to check against * @param options - Additional options for authorization * @returns Express middleware function * * @example * ```typescript * // Require 'create' permission on 'Pack' * router.post('/packs', * authMiddleware, * attachAbility(), * authorize('create', 'Pack'), * createPackHandler * ); * * // Require 'manage' permission on 'Node' * router.delete('/nodes/:id', * authMiddleware, * attachAbility(), * authorize('delete', 'Node'), * deleteNodeHandler * ); * ``` */ declare function authorize(action: Action, subject: Subject, options?: { conditionCheck?: (req: Request, user: User) => boolean; }): RequestHandler; /** * Creates a middleware that requires any of the specified roles * * Simpler alternative to CASL-based authorization for basic role checks. * * @param roles - Array of roles, any of which grants access * @returns Express middleware function * * @example * ```typescript * // Allow admin or node agents * router.put('/nodes/:id', * authMiddleware, * requireAnyRole(['admin', 'node']), * updateNodeHandler * ); * ``` */ declare function requireAnyRole(roles: UserRole[]): RequestHandler; /** * Creates a middleware that requires all of the specified roles * * @param roles - Array of roles, all of which are required for access * @returns Express middleware function * * @example * ```typescript * // Require both admin and operator roles (uncommon but possible) * router.post('/cluster/config', * authMiddleware, * requireAllRoles(['admin']), * updateClusterConfigHandler * ); * ``` */ declare function requireAllRoles(roles: UserRole[]): RequestHandler; /** * Checks resource ownership for authorization * * Use this in route handlers to verify the user owns a resource before allowing modification. * * @param user - The authenticated user * @param resourceOwnerId - The owner ID of the resource * @returns true if user is owner or has admin/operator role * * @example * ```typescript * // In route handler * if (!checkOwnership(req.user, pack.ownerId)) { * return sendForbidden(res, 'update', 'Pack'); * } * ``` */ declare function checkOwnership(user: User, resourceOwnerId: string): boolean; /** * Type guard to check if request has ability attached */ declare function hasAbility(req: Request): req is AuthorizedRequest; /** * Middleware that attaches CASL ability (use after authMiddleware) */ declare const abilityMiddleware: RequestHandler; /** * Pre-configured authorization middlewares for common patterns */ declare const requireAdmin: RequestHandler; declare const requireNode: RequestHandler; declare const requireViewer: RequestHandler; declare const canCreatePack: RequestHandler; declare const canReadPack: RequestHandler; declare const canUpdatePack: RequestHandler; declare const canDeletePack: RequestHandler; declare const canManagePack: RequestHandler; declare const canCreatePod: RequestHandler; declare const canReadPod: RequestHandler; declare const canUpdatePod: RequestHandler; declare const canDeletePod: RequestHandler; declare const canManagePod: RequestHandler; declare const canCreateNode: RequestHandler; declare const canReadNode: RequestHandler; declare const canUpdateNode: RequestHandler; declare const canDeleteNode: RequestHandler; declare const canManageNode: RequestHandler; declare const canCreateNamespace: RequestHandler; declare const canReadNamespace: RequestHandler; declare const canUpdateNamespace: RequestHandler; declare const canDeleteNamespace: RequestHandler; declare const canManageNamespace: RequestHandler; declare const canReadClusterConfig: RequestHandler; declare const canManageClusterConfig: RequestHandler; declare const canReadUser: RequestHandler; declare const canManageUser: RequestHandler; /** * Rate Limiting Middleware * * Protects the API from abuse by limiting request rates per client. * Uses express-rate-limit for hard caps and express-slow-down for * progressive throttling (adding delay instead of blocking). * * @module @stark-o/server/middleware/rate-limit-middleware */ /** * Rate limit configuration options */ interface RateLimitConfig { /** Window duration in milliseconds (default: 15 minutes) */ windowMs?: number; /** Maximum requests per window (default: 100) */ max?: number; /** Message to send when rate limit is exceeded */ message?: string; /** Whether to skip successful requests in count (default: false) */ skipSuccessfulRequests?: boolean; /** Whether to skip failed requests in count (default: false) */ skipFailedRequests?: boolean; /** Whether to add rate limit headers to response (default: true) */ standardHeaders?: boolean; /** Whether to include legacy X-RateLimit headers (default: false) */ legacyHeaders?: boolean; /** Key generator function for identifying clients */ keyGenerator?: (req: Request) => string; /** Handler for rate limit exceeded */ handler?: (req: Request, res: Response) => void; /** Skip rate limiting for certain requests */ skip?: (req: Request) => boolean; } /** * Create a rate limiting middleware with the given configuration */ declare function createRateLimitMiddleware(config?: RateLimitConfig): RateLimitRequestHandler; /** * Pre-configured rate limiters for different use cases */ /** * Standard API rate limiter * 10000 requests per 15 minutes */ declare const standardRateLimiter: RateLimitRequestHandler; /** * Authentication rate limiter (hard cap safety net) * 10000 requests per 15 minutes - only blocks truly abusive traffic. * Normal throttling is handled by authSlowDown below. */ declare const authRateLimiter: RateLimitRequestHandler; /** * Authentication slow-down middleware (progressive throttling) * After 100 requests in a 15-minute window, each subsequent request is * delayed by an additional 250 ms (101st → 250 ms, 102nd → 500 ms, …). * This throttles clients instead of rejecting them outright. */ declare const authSlowDown: SlowDownRequestHandler; /** * Combined auth throttle middleware. * Applies progressive slow-down first, then a hard rate-limit cap. * Use this on auth routes instead of authRateLimiter alone. */ declare function authThrottleMiddleware(req: Request, res: Response, next: NextFunction): void; /** * Pack upload rate limiter * 2000 uploads per hour */ declare const uploadRateLimiter: RateLimitRequestHandler; /** * WebSocket connection rate limiter * 500 connections per minute per IP */ declare const wsConnectionRateLimiter: RateLimitRequestHandler; /** * Health check exemption - skip rate limiting for health endpoints */ declare function skipHealthChecks(req: Request): boolean; /** * Create rate limiter that skips health checks */ declare const apiRateLimiter: RateLimitRequestHandler; /** * Create a custom rate limiter for specific routes */ declare function createCustomRateLimiter(windowMs: number, max: number, message?: string): RateLimitRequestHandler; /** * Middleware to attach rate limit info to request for logging */ declare const rateLimitInfoMiddleware: RequestHandler; /** * Stark Orchestrator Server * * Entry point for the HTTP REST API and WebSocket server. * @module @stark-o/server */ /** * Server configuration options */ interface ServerConfig { /** HTTPS port (default: 443) */ port: number; /** Internal HTTP port (default: 3000, only for internal proxy) */ httpPort: number; /** Hostname to bind to (default: '0.0.0.0') */ host: string; /** Enable CORS (default: true) */ enableCors: boolean; /** CORS allowed origins (default: ['https://localhost:*']) */ corsOrigins: string[]; /** Enable request logging (default: true) */ enableLogging: boolean; /** WebSocket path (default: '/ws') */ wsPath: string; /** Node environment */ nodeEnv: 'development' | 'production' | 'test'; /** Supabase URL */ supabaseUrl?: string; /** Supabase anon key */ supabaseAnonKey?: string; /** Path to SSL certificate file */ sslCert?: string; /** Path to SSL key file */ sslKey?: string; /** Expose HTTP on external interface (default: false, HTTP only on 127.0.0.1) */ exposeHttp: boolean; } /** * Server instance containing HTTP server and WebSocket server */ interface ServerInstance { /** Express application */ app: Express; /** HTTP server (internal, or external if exposeHttp is true) */ httpServer: http.Server; /** HTTPS server (always enabled) */ httpsServer: https.Server; /** WebSocket server (attached to HTTPS) */ wss: WebSocketServer; /** Connection manager for WebSocket */ connectionManager: ReturnType; /** Scheduler service for pod scheduling */ schedulerService: ReturnType; /** Service controller for reconciling services */ serviceController: ReturnType; /** Node health service for stale node detection */ nodeHealthService: ReturnType; /** Ingress manager for service port exposure */ ingressManager: ReturnType; /** Server configuration */ config: ServerConfig; /** Start the server */ start: () => Promise; /** Stop the server */ stop: () => Promise; } /** * Create and configure the server */ declare function createServer(config?: Partial): ServerInstance; export { type Action, type ApiRouterOptions, type AppAbility, type AuthHandler, type AuthMiddlewareOptions, type AuthResult, type AuthenticatedRequest, type AuthorizedRequest, type ConnectionInfo, ConnectionManager, type ConnectionManagerOptions, NETWORK_WS_TYPES, PODGROUP_WS_TYPES, type RateLimitConfig, type RbacMiddlewareOptions, type ReconnectNodePayload, type ServerConfig, type ServerInstance, type Subject, type WsConnection$1 as WsConnection, type WsMessage$2 as WsMessage, type WsMessageType, type WsNodeMessageType, type WsPodMessageType, abilityMiddleware, apiRateLimiter, attachAbility, authMiddleware, authRateLimiter, authSlowDown, authThrottleMiddleware, authorize, canCreateNamespace, canCreateNode, canCreatePack, canCreatePod, canDeleteNamespace, canDeleteNode, canDeletePack, canDeletePod, canManageClusterConfig, canManageNamespace, canManageNode, canManagePack, canManagePod, canManageUser, canReadClusterConfig, canReadNamespace, canReadNode, canReadPack, canReadPod, canReadUser, canUpdateNamespace, canUpdateNode, canUpdatePack, canUpdatePod, checkOwnership, createApiRouter, createAuthMiddleware, createAuthRouter, createConfigRouter, createConnectionManager, createCustomRateLimiter, createNamespaceHandler as createNamespace, createNamespacesRouter, createNetworkWsHandlers, createNodesRouter, createOptionalAuthMiddleware, createPacksRouter, createPod, createPodGroupWsHandlers, createPodsRouter, createRateLimitMiddleware, createSecretsRouter, createServer, createServicesRouter, createUser, defineAbilityFor, deleteNamespaceHandler as deleteNamespace, deleteNamespaceByNameHandler as deleteNamespaceByName, deleteNode, deletePack, deletePod as deletePodHandler, errorHandlingMiddleware, extractBearerToken, getConfig, getNamespaceByIdHandler as getNamespaceById, getNamespaceByNameHandler as getNamespaceByName, getNamespaceQuotaHandler as getNamespaceQuota, getNodeById, getNodeByName, getPackById, getPodById as getPodByIdHandler, getPodHistory, getPodStatus, handleNodeDisconnect, handleNodeHeartbeat, handleNodeReconnect, handleNodeRegister, handlePodEvict, handlePodFail, handlePodRestart, handlePodSchedule, handlePodStart, handlePodStatusUpdate, handlePodStop, hasAbility, healthCheck, isAuthenticated, listNamespacesHandler as listNamespaces, listNodes, listPackVersions, listPacks, listPods as listPodsHandler, listUsers as listUsersHandler, livenessCheck, login, logout, notFoundHandler, optionalAuthMiddleware, putConfig, rateLimitInfoMiddleware, readinessCheck, register, registerNode, registerPack, requestLoggingMiddleware, requireAdmin, requireAllRoles, requireAnyRole, requireNode, requireViewer, resetCentralPodGroupStore, routePodMessage, servicesRouter, setup, setupStatus, skipHealthChecks, standardRateLimiter, updateNamespaceHandler as updateNamespace, updateNode, updatePack, uploadRateLimiter, wsConnectionRateLimiter };