Skip to content

Host Internals

Deep reference for the host runtime. The composition root is apps/host/src/server.ts.

Startup sequence

start() executes these phases in order:

  1. initOpenTelemetry()
  2. configureFallbackCache(...)
  3. assertValidConfig(...) — fail-fast on invalid env
  4. loadTrustedKeys() — must load at least one trusted key
  5. loadSharedDeps() — optional; host still runs if missing
  6. reloadManifests():
    • Discover local features
    • Optionally discover remote features
    • Verify release index and manifest signatures
    • Verify manifest schema and integrity
    • Detect route conflicts
    • Rebuild static allowlist
  7. Start HTTP server with serve({ fetch: app.fetch, port })
  8. Optionally start artifact watcher (HOT_REFRESH_WATCH=1)
  9. Optionally start remote poll loop (FEATURE_REMOTE_POLL_MS > 0)

In-memory host state

VariableTypePurpose
manifestsFeatureManifest[]All loaded feature manifests
serverFnModulesMap<string, ServerFunctionModuleEntry>Loaded server function modules
trustedPublicKeysRecord<string, string>Ed25519 public keys for verification
routeConflictsRouteConflict[]Detected route overlaps
versionHistoryMap<string, FeatureVersionHistory>Version load history per feature
sharedDepsManifestSharedDepsManifest | nullShared dependency versions and filenames
hostSharedVersionsRecord<string, string>Package name to version lookup
sharedAssetAllowlistSet<string>Allowed shared asset filenames
staticAssetAllowlistSet<string>Allowed feature static asset paths

reloadManifests() clears mutable discovery state before rebuilding. Remote manifests override local manifests by featureId.

Endpoint matrix

RouteMethodMiddlewarePurpose
/_healthGETrequest-id, loggingHost and runtime snapshot
/_health/:featureIdGETrequest-id, loggingPer-feature status
/_adminGETno-store, admin authAdmin dashboard
/_admin/api/manifestsGETno-store, admin authManifest and version JSON
/_admin/refreshPOSTno-store, admin auth, CSRFForce manifest reload
/rpc/:featureId/:fnNamePOSTrate-limit, body-limit, RPC chainServer function execution
/api and /api/*ALLrate-limit, proxy handlerUpstream forwarding
/host/:filenameGETHost static assets
/shared/:filenameGETShared dep bundles
/static/:featureId/*GETFeature versioned assets
/GETRedirect to /_examples
*GETApplication feature shell render catch-all

Global middleware

Applied at app.use('*', ...):

  • Assigns and propagates x-request-id
  • Logs method, path, status, and duration via structured logger
  • Wraps unhandled exceptions via app.onError(...) into standardized JSON 500

Admin auth model

Middleware precedence:

  1. ALLOW_UNAUTHENTICATED_ADMIN=1 — allow all
  2. ADMIN_AUTH_TOKEN configured — require matching bearer token
  3. Otherwise piggyback on effective RPC_AUTH_MODE
  4. If no auth mode configured — deny with 503

CSRF (adminMutationCsrfMiddleware) is enforced on admin mutations unless a bearer or forwarded token is present. Validates same-origin via origin or referer.

RPC execution

Core route: POST /rpc/:featureId/:fnName.

Middleware chain

  1. rpcRateLimit
  2. rpcBodyLimit — parses and stores rpcParsedArgs
  3. createRpcContextMiddleware()
  4. createRpcTokenAuthMiddleware(...)
  5. createRpcFeatureVisibilityMiddleware(...)
  6. createRpcFunctionAuthorizationMiddleware(...)
  7. Terminal executor (proxy or local call)

Auth modes

Effective mode priority:

  1. dfs-oidc-verified — if DFS config exists and DFS_VALIDATE_ACCESS_TOKEN=1
  2. static-token — if RPC_AUTH_TOKEN set
  3. trusted-cluster — if DIPS_TRUST_CLUSTER_AUTH=1
  4. none

A custom plugin (HOST_AUTH_PLUGIN) can allow/deny/skip before the built-in auth mode runs.

Function authorization

The authorization middleware enforces:

  1. Feature exists in loaded manifests
  2. Function name is declared in manifest.serverFunctions.exports
  3. If local module loaded: function must be in allowedExports and be callable
  4. If endpoint configured: URL is sanitized, proxy target built as <endpoint>/<fnName>
  5. Otherwise: return 503 server_functions_unavailable

Module mode vs endpoint proxy

Module mode — host imports server-functions.js in-process from artifacts or remote CDN (with digest verification). Protected by RPC_MAX_EXECUTION_MS timeout.

Endpoint proxy mode — host forwards to manifest.serverFunctions.endpoint/<fnName> with headers (x-request-id, x-cdn-loader-feature-id, x-cdn-loader-function, x-cdn-loader-context) and body { args, context }.

API proxy

Handler: apps/host/src/api/proxy.ts.

Flow:

  1. Require API_PROXY_BASE_URL, else 501
  2. Optional path allowlist (API_PROXY_ALLOWED_PATHS), else 403
  3. Optional circuit breaker open check, else 503
  4. Optional trust-cluster identity/ingress checks, else 401
  5. Sanitize inbound headers (strip hop-by-hop, host, content-length)
  6. Identity enrichment: custom plugin first, then fallback
  7. Forward to upstream with timeout
  8. Update circuit breaker on outcome
  9. Return response with sanitized headers and x-request-id

The circuit breaker uses closed/open/half-open states. It opens after consecutive failures and transitions to half-open after a reset timeout.

Artifact and manifest loading

Primary file: apps/host/src/startup/manifest-loader.ts.

Local load path

Per feature directory in artifacts/<featureId>:

  1. Load and verify signed releases.json
  2. Sort versions by semver, try active version first
  3. For each candidate version: read manifest, verify hash, verify signature, validate schema, verify integrity, optionally import server module
  4. First successful version becomes active
  5. Failed attempts recorded in rollback history

Remote CDN load path

Enabled when FEATURE_REMOTE_INDEX_URL is set:

  1. Fetch remote index JSON
  2. Parse feature descriptors (featureId, releasesUrl, optional baseUrl)
  3. For each remote feature: load and verify signed releases, try versions active-first, fetch and verify manifest, rewrite asset paths to absolute remote URLs, verify integrity by fetching remote assets
  4. Merge into host set — remote features override local features with the same featureId

Remote server functions use either endpoint proxy mode or digest-verified remote module mode.

Shell rendering

Renderer: apps/host/src/shell-renderer.ts.

HTML composition

renderShell(...) outputs in order:

  1. Host CSS (/host/shell.css)
  2. Feature CSS links (unless shadow DOM mode)
  3. Optional import map for shared deps
  4. Optional modulepreload hints
  5. Topbar (domain features only) and mount container
  6. Optional shadow DOM mount setup script
  7. Bootstrap globals (window.__FEATURE_BOOTSTRAP__, window.__HOST_RUNTIME_PERMISSIONS__, window.__HOST_MODULE_REGISTRY__)
  8. Bootstrap failure handlers (resource error, runtime error, promise rejection)
  9. Host runtime scripts (event bus, host store, lifecycle)
  10. Capability wrapper script (permission-scoped runtime API)
  11. Feature entrypoint module scripts with integrity

CSP construction

Per request:

  • Script nonce is random
  • Remote asset origins collected from entrypoints and integrity keys
  • CSP includes default-src 'self', script-src 'self' 'nonce-...', remote origins for style/img/font, connect-src 'self', object-src 'none', base-uri 'none', frame-ancestors 'none'

Import map behavior

The import map is generated only when a shared deps manifest exists and at least one loaded feature declares shared packages. For routed pages, the host includes shared requirements from the active domain feature plus all loaded facet features. Mapped specifiers include subpaths like react/jsx-runtime and react-dom/client.

Module registry behavior

featureType: facet manifests are not route-mounted. Instead, they are exposed through window.__HOST_MODULE_REGISTRY__ for consumption via @favn/feature-sdk (listModules(), mountModule(), unmountModule()). Legacy featureType: module is accepted and normalized.

Fallback UX

The shell installs a fallback handler that renders emergency UI when module scripts fail to load, bootstrap throws, or an unhandled promise rejection occurs. When feature mount succeeds, __FEATURE_BOOTSTRAP_COMPLETE__() disables the fallback.

Host runtime APIs

Event bus (@favn/event-bus)

  • publish(channel, topic, payload), subscribe(channel, topic, callback) with unsubscribe
  • Wildcard matching (*), peek(channel, topic) for last value, log(channel?) for history
  • Unique tabId per tab, optional cross-tab fanout via BroadcastChannel

Host store (@favn/host-store)

  • get, set, getAll, onChange (keyed and global subscriptions)
  • selectedPatient key is persisted in localStorage

Lifecycle API

Exposed as __HOST_LIFECYCLE__:

  • onCleanup(fn), unmount(), trackInterval(id), trackTimeout(id)

Capability enforcement

Before feature scripts run, the shell wraps host APIs to enforce manifest runtime.permissions. Denied operations log warnings and return safe values rather than throwing.