feat: mount discovered module UI in a minimal Ekklesia browser host
Phase 6C pass 2. Every link in the module UI chain existed except the one that closes it: a module could be authored, built, validated, published at a browser URL, and loaded by a generic loader — and nothing in Ekklesia did any of it. There was no browser application at all. Two pieces were missing. A browser could not discover what to mount, and it must not work that out for itself. GET /api/v1/module-ui is the inventory: per publishable module, its id and version, the server-produced artifact URL, the server-produced root of the module's own API, and the subset of that module's declared permissions the caller holds. Five fields, each because building a ModuleUiHostContext needs it — no filesystem paths, and no name/icon/folder/order, because navigation metadata is a design that does not exist yet. Its module set is the ADR 0025 publication registry rather than a rescan, so the inventory and the artifact route cannot disagree. It requires a new Core permission, core.modules.ui.read (baseline authenticated), because it is precisely the enumeration the anonymous artifact route deliberately withholds. Both URLs are server-produced. moduleUiArtifactUrl already existed; moduleApiBaseUrl is now exported and moduleRoutePath builds on it, so each URL shape has exactly one author. Without it the shell would hardcode /api/v1/modules/<id> — the prefix ADR 0022 forbids a module UI from spelling, reappearing in the host instead. surfaces/shell (@ekklesia/shell) is the repository's first surface: a small React application built to static files by its own esbuild script. It resolves the principal, fetches the inventory, builds the host context entirely from server-derived data, and hands the artifact URL to @ekklesia/module-ui-host. One frame per selection — keyed by module identity — defeats the stale-load race; the host owns the container, the loading state, and every failure, so a broken module costs its own panel rather than the shell. The shell statically imports no module, and both levels are checked: no source import may name a module, and the emitted bundle must contain exactly one dynamic import (the loader's) with no module id, no /api/v1/modules, no eval, and no blob URL. Permission hints come from Core's own evaluator and stay presentation-only — the end-to-end test has a UI holding no grant call its API anyway and still receive 403. Surfaces may now depend only on browser-safe shared roles; @ekklesia/contracts is deliberately excluded, since its barrel pulls Drizzle's types and Node's globals into the browser — the hole ADR 0024 closed one layer down. Not the Dashboard: no navigation, grouping, icons, ordering, design system, or routing. The selector is a list of module ids. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
7a76ff6f26
commit
616c1d4834
@@ -0,0 +1,247 @@
|
||||
import type { ModuleUiPrincipal } from "@ekklesia/module-ui-sdk";
|
||||
|
||||
/**
|
||||
* How this shell reaches the Ekklesia API.
|
||||
*
|
||||
* `apiBaseUrl` is an absolute **origin** (`https://ekklesia.example.test`, `http://127.0.0.1:3000`)
|
||||
* rather than something read from a global. The browser entry point supplies it — from a build-time
|
||||
* value when the shell and the API are served from different origins in development, and from
|
||||
* `window.location.origin` otherwise — so every function below is a pure function of its arguments
|
||||
* and can be exercised without a DOM, a `window`, or a page. Nothing here reads a global.
|
||||
*/
|
||||
export interface EkklesiaHostConfig {
|
||||
readonly apiBaseUrl: string;
|
||||
/** Injected so tests can drive the real protocol against a real in-process app without a socket.
|
||||
* Production composition leaves this unset and the platform `fetch` is used. */
|
||||
readonly fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
/** Root-relative platform paths. The shell never builds a module UI artifact URL or a module API
|
||||
* URL — the server produces both and hands them over in the inventory — so these two are the only
|
||||
* URLs it knows, and they are the two that describe the platform itself rather than any module. */
|
||||
const PRINCIPAL_PATH = "/api/v1/principal";
|
||||
const MODULE_UI_INVENTORY_PATH = "/api/v1/module-ui";
|
||||
|
||||
export type HostProtocolErrorCode =
|
||||
/** The caller is not signed in, or lacks `core.modules.ui.read`. */
|
||||
| "HOST_UNAUTHENTICATED"
|
||||
/** The API answered, but not with something this shell understands. */
|
||||
| "HOST_RESPONSE_INVALID"
|
||||
/** The API could not be reached, or failed. */
|
||||
| "HOST_REQUEST_FAILED"
|
||||
/** A module UI asked for something outside its own API root. */
|
||||
| "MODULE_API_PATH_INVALID";
|
||||
|
||||
const errorMessages: Readonly<Record<HostProtocolErrorCode, string>> = Object.freeze({
|
||||
HOST_REQUEST_FAILED: "Ekklesia could not be reached.",
|
||||
HOST_RESPONSE_INVALID: "Ekklesia returned a response this host does not understand.",
|
||||
HOST_UNAUTHENTICATED: "You need to sign in to Ekklesia to use this page.",
|
||||
MODULE_API_PATH_INVALID: "A module asked for a path outside its own API.",
|
||||
});
|
||||
|
||||
/**
|
||||
* Carries a stable code and a fixed, user-safe message — never a URL, a response body, a server
|
||||
* path, or a caught cause — matching every other Ekklesia error boundary. The originating error is
|
||||
* attached as `cause` for browser-console diagnostics and is never rendered.
|
||||
*/
|
||||
export class HostProtocolError extends Error {
|
||||
readonly code: HostProtocolErrorCode;
|
||||
|
||||
constructor(code: HostProtocolErrorCode, options?: { readonly cause?: unknown }) {
|
||||
super(errorMessages[code], options);
|
||||
this.name = "HostProtocolError";
|
||||
this.code = code;
|
||||
this.stack = `${this.name}: ${this.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One module UI this host may mount, exactly as the server described it.
|
||||
*
|
||||
* This mirrors the server's `HostModuleUiDescriptor` (`apps/api/src/module-ui-inventory.ts`) rather
|
||||
* than importing it: a surface may not depend on an app, and the type on either side of an HTTP
|
||||
* boundary should be validated on arrival rather than assumed. `parseHostModuleUiInventory` below is
|
||||
* that validation, and the end-to-end test feeds a real server response through it so the two
|
||||
* declarations are proven to agree instead of merely looking similar.
|
||||
*/
|
||||
export interface HostModuleUiDescriptor {
|
||||
readonly id: string;
|
||||
readonly version: string;
|
||||
/** Server-produced. The shell resolves it against `apiBaseUrl` and hands it to the generic loader
|
||||
* unchanged; it never constructs, parses, or pattern-matches this URL. */
|
||||
readonly uiUrl: string;
|
||||
/** Server-produced root of this module's own HTTP API. */
|
||||
readonly apiBaseUrl: string;
|
||||
/** Granted ids only, already evaluated server-side. Presentation hints, never authority. */
|
||||
readonly permissions: readonly string[];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function nestedString(value: unknown, key: string): string | undefined {
|
||||
return isRecord(value) ? nonEmptyString(value[key]) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both URLs in a descriptor must be **root-relative** paths, exactly as the server produces them.
|
||||
*
|
||||
* Enforced rather than assumed. The shell resolves each against the configured API origin, so an
|
||||
* absolute or protocol-relative value arriving here would silently redirect a module's script import
|
||||
* or its API calls to another origin. This does not defend against a compromised server — one could
|
||||
* serve anything at the real URL — but it does pin the wire contract, so a proxy rewrite, a
|
||||
* misconfiguration, or a future server-side bug fails loudly here instead of quietly changing where
|
||||
* browser code is fetched from.
|
||||
*/
|
||||
function rootRelativePath(value: unknown, key: string): string | undefined {
|
||||
const candidate = nestedString(value, key);
|
||||
if (candidate === undefined || !candidate.startsWith("/") || candidate.startsWith("//")) {
|
||||
return undefined;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict, total validation of the inventory document. Anything unexpected — a missing field, a
|
||||
* non-array `modules`, a permission entry that is not a string — fails the whole parse rather than
|
||||
* yielding a half-built descriptor, because a descriptor with a missing URL would surface much later
|
||||
* as an inexplicable mount failure.
|
||||
*/
|
||||
export function parseHostModuleUiInventory(payload: unknown): readonly HostModuleUiDescriptor[] {
|
||||
const modules = isRecord(payload) ? payload.modules : undefined;
|
||||
if (!Array.isArray(modules)) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return Object.freeze(
|
||||
modules.map((entry): HostModuleUiDescriptor => {
|
||||
const id = nestedString(entry, "id");
|
||||
const version = nestedString(entry, "version");
|
||||
const uiUrl = isRecord(entry) ? rootRelativePath(entry.ui, "url") : undefined;
|
||||
const apiBaseUrl = isRecord(entry) ? rootRelativePath(entry.api, "baseUrl") : undefined;
|
||||
const permissions = isRecord(entry) ? entry.permissions : undefined;
|
||||
if (
|
||||
id === undefined ||
|
||||
version === undefined ||
|
||||
uiUrl === undefined ||
|
||||
apiBaseUrl === undefined ||
|
||||
!Array.isArray(permissions) ||
|
||||
permissions.some((permission) => typeof permission !== "string")
|
||||
) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return Object.freeze({
|
||||
apiBaseUrl,
|
||||
id,
|
||||
permissions: Object.freeze([...(permissions as string[])]),
|
||||
uiUrl,
|
||||
version,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** `/api/v1/principal`'s two documented shapes, narrowed to the browser-owned `ModuleUiPrincipal`
|
||||
* the UI SDK defines. Nothing else the endpoint might ever return is carried into module UI. */
|
||||
export function parseHostPrincipal(payload: unknown): ModuleUiPrincipal {
|
||||
if (!isRecord(payload)) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
if (payload.kind === "anonymous") {
|
||||
return { kind: "anonymous" };
|
||||
}
|
||||
const userId = nonEmptyString(payload.userId);
|
||||
if (payload.kind === "authenticated" && userId !== undefined) {
|
||||
return { kind: "authenticated", userId };
|
||||
}
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
|
||||
/** Resolves a root-relative platform path against the configured API origin. The one place the
|
||||
* shell turns a server-produced path into an absolute URL. */
|
||||
export function resolveApiUrl(config: EkklesiaHostConfig, rootRelativePath: string): string {
|
||||
return new URL(rootRelativePath, config.apiBaseUrl).href;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every request this shell makes to Ekklesia carries credentials.
|
||||
*
|
||||
* Same-origin that is simply the session cookie. Split-origin — the development shape the platform's
|
||||
* trusted-origin configuration already supports — it is what makes the cookie travel at all, and it
|
||||
* works only because the API reflects an exact trusted origin with
|
||||
* `Access-Control-Allow-Credentials: true` and never a wildcard. This does not weaken that policy;
|
||||
* it is the client half of it.
|
||||
*/
|
||||
async function requestPlatformJson(
|
||||
config: EkklesiaHostConfig,
|
||||
rootRelativePath: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> {
|
||||
const performRequest = config.fetch ?? fetch;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await performRequest(resolveApiUrl(config, rootRelativePath), {
|
||||
credentials: "include",
|
||||
headers: { accept: "application/json" },
|
||||
...(signal ? { signal } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new HostProtocolError("HOST_REQUEST_FAILED", { cause: error });
|
||||
}
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new HostProtocolError("HOST_UNAUTHENTICATED");
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new HostProtocolError("HOST_REQUEST_FAILED");
|
||||
}
|
||||
try {
|
||||
return (await response.json()) as unknown;
|
||||
} catch (error) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID", { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
/** Who is viewing. Anonymous is a normal answer, not a failure: the shell renders a sign-in prompt
|
||||
* rather than an error, and never asks for the inventory it would be refused. */
|
||||
export async function loadHostPrincipal(
|
||||
config: EkklesiaHostConfig,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ModuleUiPrincipal> {
|
||||
return parseHostPrincipal(await requestPlatformJson(config, PRINCIPAL_PATH, signal));
|
||||
}
|
||||
|
||||
/** Which module UIs this viewer may mount, where to fetch each, and what they may do inside it. */
|
||||
export async function loadModuleUiInventory(
|
||||
config: EkklesiaHostConfig,
|
||||
signal?: AbortSignal,
|
||||
): Promise<readonly HostModuleUiDescriptor[]> {
|
||||
return parseHostModuleUiInventory(
|
||||
await requestPlatformJson(config, MODULE_UI_INVENTORY_PATH, signal),
|
||||
);
|
||||
}
|
||||
|
||||
export interface HostBootstrap {
|
||||
readonly principal: ModuleUiPrincipal;
|
||||
readonly modules: readonly HostModuleUiDescriptor[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The shell's whole startup sequence, in one explicit function: resolve who is viewing, then ask
|
||||
* what they may mount. Sequential rather than parallel on purpose — an anonymous viewer is told to
|
||||
* sign in and the inventory is never requested, so the shell does not depend on a `403` to discover
|
||||
* something `/api/v1/principal` already said plainly.
|
||||
*/
|
||||
export async function bootstrapHost(
|
||||
config: EkklesiaHostConfig,
|
||||
signal?: AbortSignal,
|
||||
): Promise<HostBootstrap> {
|
||||
const principal = await loadHostPrincipal(config, signal);
|
||||
if (principal.kind === "anonymous") {
|
||||
return { modules: Object.freeze([]), principal };
|
||||
}
|
||||
return { modules: await loadModuleUiInventory(config, signal), principal };
|
||||
}
|
||||
Reference in New Issue
Block a user