Appearance
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:
initOpenTelemetry()configureFallbackCache(...)assertValidConfig(...)— fail-fast on invalid envloadTrustedKeys()— must load at least one trusted keyloadSharedDeps()— optional; host still runs if missingreloadManifests():- Discover local features
- Optionally discover remote features
- Verify release index and manifest signatures
- Verify manifest schema and integrity
- Detect route conflicts
- Rebuild static allowlist
- Start HTTP server with
serve({ fetch: app.fetch, port }) - Optionally start artifact watcher (
HOT_REFRESH_WATCH=1) - Optionally start remote poll loop (
FEATURE_REMOTE_POLL_MS > 0)
In-memory host state
| Variable | Type | Purpose |
|---|---|---|
manifests | FeatureManifest[] | All loaded feature manifests |
serverFnModules | Map<string, ServerFunctionModuleEntry> | Loaded server function modules |
trustedPublicKeys | Record<string, string> | Ed25519 public keys for verification |
routeConflicts | RouteConflict[] | Detected route overlaps |
versionHistory | Map<string, FeatureVersionHistory> | Version load history per feature |
sharedDepsManifest | SharedDepsManifest | null | Shared dependency versions and filenames |
hostSharedVersions | Record<string, string> | Package name to version lookup |
sharedAssetAllowlist | Set<string> | Allowed shared asset filenames |
staticAssetAllowlist | Set<string> | Allowed feature static asset paths |
reloadManifests() clears mutable discovery state before rebuilding. Remote manifests override local manifests by featureId.
Endpoint matrix
| Route | Method | Middleware | Purpose |
|---|---|---|---|
/_health | GET | request-id, logging | Host and runtime snapshot |
/_health/:featureId | GET | request-id, logging | Per-feature status |
/_admin | GET | no-store, admin auth | Admin dashboard |
/_admin/api/manifests | GET | no-store, admin auth | Manifest and version JSON |
/_admin/refresh | POST | no-store, admin auth, CSRF | Force manifest reload |
/rpc/:featureId/:fnName | POST | rate-limit, body-limit, RPC chain | Server function execution |
/api and /api/* | ALL | rate-limit, proxy handler | Upstream forwarding |
/host/:filename | GET | — | Host static assets |
/shared/:filename | GET | — | Shared dep bundles |
/static/:featureId/* | GET | — | Feature versioned assets |
/ | GET | — | Redirect to /_examples |
* | GET | — | Application 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:
ALLOW_UNAUTHENTICATED_ADMIN=1— allow allADMIN_AUTH_TOKENconfigured — require matching bearer token- Otherwise piggyback on effective
RPC_AUTH_MODE - 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
rpcRateLimitrpcBodyLimit— parses and storesrpcParsedArgscreateRpcContextMiddleware()createRpcTokenAuthMiddleware(...)createRpcFeatureVisibilityMiddleware(...)createRpcFunctionAuthorizationMiddleware(...)- Terminal executor (proxy or local call)
Auth modes
Effective mode priority:
dfs-oidc-verified— if DFS config exists andDFS_VALIDATE_ACCESS_TOKEN=1static-token— ifRPC_AUTH_TOKENsettrusted-cluster— ifDIPS_TRUST_CLUSTER_AUTH=1none
A custom plugin (HOST_AUTH_PLUGIN) can allow/deny/skip before the built-in auth mode runs.
Function authorization
The authorization middleware enforces:
- Feature exists in loaded manifests
- Function name is declared in
manifest.serverFunctions.exports - If local module loaded: function must be in
allowedExportsand be callable - If endpoint configured: URL is sanitized, proxy target built as
<endpoint>/<fnName> - 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:
- Require
API_PROXY_BASE_URL, else501 - Optional path allowlist (
API_PROXY_ALLOWED_PATHS), else403 - Optional circuit breaker open check, else
503 - Optional trust-cluster identity/ingress checks, else
401 - Sanitize inbound headers (strip hop-by-hop, host, content-length)
- Identity enrichment: custom plugin first, then fallback
- Forward to upstream with timeout
- Update circuit breaker on outcome
- 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>:
- Load and verify signed
releases.json - Sort versions by semver, try active version first
- For each candidate version: read manifest, verify hash, verify signature, validate schema, verify integrity, optionally import server module
- First successful version becomes active
- Failed attempts recorded in rollback history
Remote CDN load path
Enabled when FEATURE_REMOTE_INDEX_URL is set:
- Fetch remote index JSON
- Parse feature descriptors (
featureId,releasesUrl, optionalbaseUrl) - 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
- 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:
- Host CSS (
/host/shell.css) - Feature CSS links (unless shadow DOM mode)
- Optional import map for shared deps
- Optional modulepreload hints
- Topbar (domain features only) and mount container
- Optional shadow DOM mount setup script
- Bootstrap globals (
window.__FEATURE_BOOTSTRAP__,window.__HOST_RUNTIME_PERMISSIONS__,window.__HOST_MODULE_REGISTRY__) - Bootstrap failure handlers (resource error, runtime error, promise rejection)
- Host runtime scripts (event bus, host store, lifecycle)
- Capability wrapper script (permission-scoped runtime API)
- 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
tabIdper tab, optional cross-tab fanout viaBroadcastChannel
Host store (@favn/host-store)
get,set,getAll,onChange(keyed and global subscriptions)selectedPatientkey 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.