feat: add browser auth shell
CI / verify (pull_request) Successful in 38s
CI / infrastructure-smoke (pull_request) Successful in 12s
CI / migration-smoke (pull_request) Successful in 1m0s

This commit is contained in:
ekklesia
2026-08-23 22:01:26 -05:00
parent 91aa9c2930
commit a8c7c50b4d
26 changed files with 2702 additions and 194 deletions
+342 -68
View File
@@ -1,19 +1,40 @@
import type { ModuleUiImporter } from "@ekklesia/module-ui-host";
import { type ReactElement, useEffect, useState } from "react";
import { type ReactElement, useCallback, useEffect, useRef, useState } from "react";
import {
HostAuthError,
type HostSignInCredentials,
signInWithEmail,
signOutHost,
} from "../auth-protocol.js";
import {
bootstrapHost,
type DashboardNavigationEntry,
type EkklesiaHostConfig,
type HostBootstrap,
HostProtocolError,
loadHostPrincipal,
} from "../host-protocol.js";
import { LoginForm } from "./LoginForm.js";
import { ModuleUiFrame } from "./ModuleUiFrame.js";
type AuthenticatedPrincipal = Extract<
HostBootstrap["principal"],
{ readonly kind: "authenticated" }
>;
type BootstrapState =
| { readonly status: "loading" }
| { readonly status: "ready"; readonly bootstrap: HostBootstrap }
| { readonly status: "signed-out" }
| { readonly status: "failed" };
| { readonly status: "anonymous" }
| { readonly status: "access-denied"; readonly principal: AuthenticatedPrincipal }
| { readonly status: "failed" }
| { readonly status: "signing-out" }
| { readonly status: "sign-out-failed" };
type ResolvedBootstrapState = Extract<
BootstrapState,
{ readonly status: "ready" | "anonymous" | "access-denied" | "failed" }
>;
export interface HostAppProps {
/** Must be a stable reference: bootstrap re-runs whenever it changes, so a fresh object literal
@@ -25,6 +46,16 @@ export interface HostAppProps {
}
const shellStyles = {
action: {
background: "transparent",
border: "1px solid currentColor",
borderRadius: "0.25rem",
color: "inherit",
cursor: "pointer",
font: "inherit",
padding: "0.375rem 0.75rem",
},
actions: { display: "flex", gap: "0.5rem", justifyContent: "center" },
aside: { borderRight: "1px solid #e7e5e4", minWidth: "13rem", padding: "1rem" },
groupLabel: {
color: "#78716c",
@@ -34,11 +65,15 @@ const shellStyles = {
textTransform: "uppercase",
},
header: {
alignItems: "center",
borderBottom: "1px solid #e7e5e4",
display: "flex",
fontWeight: 600,
gridColumn: "1 / -1",
justifyContent: "space-between",
padding: "0.75rem 1rem",
},
heading: { font: "inherit", margin: 0 },
layout: {
color: "#1c1917",
display: "grid",
@@ -47,11 +82,19 @@ const shellStyles = {
minHeight: "100vh",
},
main: { padding: "1rem" },
message: { color: "#57534e", padding: "1rem" },
message: {
color: "#57534e",
display: "grid",
fontFamily: "system-ui, sans-serif",
gap: "0.75rem",
justifyItems: "center",
margin: 0,
padding: "1rem",
textAlign: "center",
},
} as const;
/** Identity, not placement: a module keeps the same selection key wherever it is arranged, so moving
* it between groups never resets what is open or remounts what is showing. */
/** Identity, not placement: moving a module between groups does not reset what is open. */
function moduleKey(entry: DashboardNavigationEntry): string {
return `${entry.descriptor.id}@${entry.descriptor.version}`;
}
@@ -90,77 +133,305 @@ function ModuleButton(props: {
);
}
function HostMessage(props: {
readonly children: string;
readonly testId: string;
readonly actions?: ReactElement;
}): ReactElement {
return (
<main aria-live="polite" data-testid={props.testId} style={shellStyles.message}>
<p style={{ margin: 0 }}>{props.children}</p>
{props.actions}
</main>
);
}
/**
* The Ekklesia browser shell: sign-in awareness, the Dashboard's configured navigation, and one
* mount target.
* Principal first, navigation second. A 403 after an authenticated principal is authorization, not
* evidence that the session vanished. Re-read the principal once only to close the narrow race where
* a session expires between those two sequential requests.
*/
async function resolveBootstrapState(
config: EkklesiaHostConfig,
signal: AbortSignal,
): Promise<ResolvedBootstrapState> {
try {
const bootstrap = await bootstrapHost(config, signal);
return bootstrap.principal.kind === "anonymous"
? { status: "anonymous" }
: { bootstrap, status: "ready" };
} catch (error) {
if (error instanceof HostProtocolError && error.code === "HOST_UNAUTHENTICATED") {
return { status: "anonymous" };
}
if (error instanceof HostProtocolError && error.code === "HOST_ACCESS_DENIED") {
try {
const principal = await loadHostPrincipal(config, signal);
return principal.kind === "anonymous"
? { status: "anonymous" }
: { principal, status: "access-denied" };
} catch {
return { status: "failed" };
}
}
return { status: "failed" };
}
}
/**
* The Ekklesia Dashboard shell and its host-owned authentication boundary.
*
* ## The shell renders the arrangement; it never computes one
*
* Groups, their order, their labels, which module sits where, and the order within each group all
* arrive already resolved from the server (ADR 0027). This component reads no manifest, performs no
* sorting, and knows nothing about how a placement is decided — so changing the Dashboard's ordering
* rules, or eventually where configuration is scoped, needs no change here at all. The module id is
* never displayed: the module's own manifest name is.
*
* ## Still not the finished Dashboard
*
* There is one level of grouping and no nesting, no icons, no drag and drop, no editor, no home
* screen or widgets, no theme, and no client routing — selection is state. What this proves is the
* layer beneath a Dashboard: persistent, platform-owned presentation configuration driving a real
* host that mounts flat, independent modules.
*
* Nothing about any specific module appears in this file, or anywhere in this package.
* The login form replaces the protected application in place. There is no redirect parameter, URL
* parser, location assignment, or client router in this shell, so the current internal Dashboard URL
* simply remains the current URL through sign-in and no external/protocol-relative return value can
* become a navigation sink. Modules receive the same five-field context after authentication; they
* neither render platform login nor receive sign-in/sign-out controls.
*/
export function HostApp(props: HostAppProps): ReactElement {
const [state, setState] = useState<BootstrapState>({ status: "loading" });
const [selectedKey, setSelectedKey] = useState<string | undefined>(undefined);
const [bootstrapAttempt, setBootstrapAttempt] = useState(0);
const activeTransitionRef = useRef<AbortController | undefined>(undefined);
const revalidationRef = useRef<AbortController | undefined>(undefined);
const generationRef = useRef(0);
const mountedRef = useRef(true);
const { config, importModule } = props;
const beginTransition = useCallback(() => {
activeTransitionRef.current?.abort();
revalidationRef.current?.abort();
revalidationRef.current = undefined;
const controller = new AbortController();
activeTransitionRef.current = controller;
generationRef.current += 1;
return { controller, generation: generationRef.current };
}, []);
const isCurrent = useCallback(
(controller: AbortController, generation: number): boolean =>
mountedRef.current &&
!controller.signal.aborted &&
activeTransitionRef.current === controller &&
generationRef.current === generation,
[],
);
const commitResolvedState = useCallback((resolved: ResolvedBootstrapState): void => {
setState(resolved);
if (resolved.status === "ready") {
const first = allEntries(resolved.bootstrap)[0];
setSelectedKey(first ? moduleKey(first) : undefined);
} else {
setSelectedKey(undefined);
}
}, []);
useEffect(() => {
const abort = new AbortController();
mountedRef.current = true;
return () => {
mountedRef.current = false;
activeTransitionRef.current?.abort();
revalidationRef.current?.abort();
};
}, []);
useEffect(() => {
// The value is an explicit manual-retry generation; reading it is what makes Retry re-run this
// otherwise config-driven bootstrap effect.
void bootstrapAttempt;
const { controller, generation } = beginTransition();
setState({ status: "loading" });
void bootstrapHost(config, abort.signal)
.then((bootstrap) => {
if (abort.signal.aborted) {
return;
setSelectedKey(undefined);
void resolveBootstrapState(config, controller.signal).then((resolved) => {
if (!isCurrent(controller, generation)) {
return;
}
if (resolved.status === "failed") {
console.error("[ekklesia] host bootstrap failed");
}
commitResolvedState(resolved);
activeTransitionRef.current = undefined;
});
return () => {
if (activeTransitionRef.current === controller) {
controller.abort();
activeTransitionRef.current = undefined;
}
};
}, [beginTransition, bootstrapAttempt, commitResolvedState, config, isCurrent]);
const authenticate = useCallback(
async (credentials: HostSignInCredentials, formSignal: AbortSignal): Promise<void> => {
const { controller, generation } = beginTransition();
const abortFromForm = (): void => controller.abort();
formSignal.addEventListener("abort", abortFromForm, { once: true });
try {
await signInWithEmail(config, credentials, controller.signal);
const resolved = await resolveBootstrapState(config, controller.signal);
if (!isCurrent(controller, generation)) {
throw new HostAuthError("AUTH_REQUEST_FAILED");
}
setState(
bootstrap.principal.kind === "anonymous"
? { status: "signed-out" }
: { bootstrap, status: "ready" },
);
const first = allEntries(bootstrap)[0];
setSelectedKey(first ? moduleKey(first) : undefined);
})
.catch((error: unknown) => {
if (abort.signal.aborted) {
return;
if (resolved.status === "failed") {
console.error("[ekklesia] post-sign-in principal resolution failed");
}
console.error("[ekklesia] host bootstrap failed", error);
setState(
error instanceof HostProtocolError && error.code === "HOST_UNAUTHENTICATED"
? { status: "signed-out" }
: { status: "failed" },
);
});
return () => abort.abort();
}, [config]);
commitResolvedState(resolved);
activeTransitionRef.current = undefined;
if (resolved.status === "anonymous" || resolved.status === "failed") {
throw new HostAuthError("AUTH_REQUEST_FAILED");
}
} finally {
formSignal.removeEventListener("abort", abortFromForm);
if (activeTransitionRef.current === controller) {
activeTransitionRef.current = undefined;
}
}
},
[beginTransition, commitResolvedState, config, isCurrent],
);
const signOut = useCallback(async (): Promise<void> => {
const { controller, generation } = beginTransition();
// The authenticated subtree disappears before the request starts. That synchronously schedules
// ModuleUiFrame cleanup, which invokes the module's unmount and closes its realtime subscriptions.
setSelectedKey(undefined);
setState({ status: "signing-out" });
try {
await signOutHost(config, controller.signal);
const principal = await loadHostPrincipal(config, controller.signal);
if (!isCurrent(controller, generation)) {
return;
}
setState(
principal.kind === "anonymous" ? { status: "anonymous" } : { status: "sign-out-failed" },
);
} catch {
if (isCurrent(controller, generation)) {
console.error("[ekklesia] sign out failed");
setState({ status: "sign-out-failed" });
}
} finally {
if (activeTransitionRef.current === controller) {
activeTransitionRef.current = undefined;
}
}
}, [beginTransition, config, isCurrent]);
const onAuthorizationResponse = useCallback(
(status: 401 | 403): void => {
// Module handlers are not the platform auth authority: one may emit an ordinary local 401,
// while Ekklesia authorization uses 403 for both anonymous and authenticated denials. Re-read
// principal once, de-duplicated across a burst of either status. Only an anonymous answer
// expires the shell; an authenticated answer leaves the module's original response alone. A
// principal failure is an unavailable platform, never a fabricated logout.
void status;
if (revalidationRef.current) {
return;
}
const controller = new AbortController();
const observedGeneration = generationRef.current;
revalidationRef.current = controller;
void loadHostPrincipal(config, controller.signal)
.then((principal) => {
if (
controller.signal.aborted ||
!mountedRef.current ||
generationRef.current !== observedGeneration
) {
return;
}
if (principal.kind === "anonymous") {
const transition = beginTransition();
transition.controller.abort();
activeTransitionRef.current = undefined;
setSelectedKey(undefined);
setState({ status: "anonymous" });
}
})
.catch(() => {
if (
controller.signal.aborted ||
!mountedRef.current ||
generationRef.current !== observedGeneration
) {
return;
}
const transition = beginTransition();
transition.controller.abort();
activeTransitionRef.current = undefined;
setSelectedKey(undefined);
console.error("[ekklesia] session revalidation failed");
setState({ status: "failed" });
})
.finally(() => {
if (revalidationRef.current === controller) {
revalidationRef.current = undefined;
}
});
},
[beginTransition, config],
);
const retryBootstrap = (): void => setBootstrapAttempt((current) => current + 1);
if (state.status === "loading") {
return <p style={shellStyles.message}>Loading Ekklesia…</p>;
return <HostMessage testId="host-loading">Loading Ekklesia…</HostMessage>;
}
if (state.status === "signed-out") {
return (
<p data-testid="host-signed-out" style={shellStyles.message}>
Sign in to Ekklesia to use the module host.
</p>
);
if (state.status === "anonymous") {
return <LoginForm onAuthenticate={authenticate} />;
}
if (state.status === "failed") {
return (
<p data-testid="host-error" style={shellStyles.message}>
Ekklesia could not be reached. Refresh to try again.
</p>
<HostMessage
actions={
<button onClick={retryBootstrap} style={shellStyles.action} type="button">
Retry
</button>
}
testId="host-error"
>
Ekklesia could not be reached.
</HostMessage>
);
}
if (state.status === "signing-out") {
return <HostMessage testId="host-signing-out">Signing out…</HostMessage>;
}
if (state.status === "sign-out-failed") {
return (
<HostMessage
actions={
<div style={shellStyles.actions}>
<button onClick={() => void signOut()} style={shellStyles.action} type="button">
Retry sign out
</button>
<button onClick={retryBootstrap} style={shellStyles.action} type="button">
Return to Ekklesia
</button>
</div>
}
testId="host-sign-out-error"
>
Ekklesia could not sign you out. Try again.
</HostMessage>
);
}
if (state.status === "access-denied") {
return (
<HostMessage
actions={
<button
data-testid="host-logout"
onClick={() => void signOut()}
style={shellStyles.action}
type="button"
>
Sign out
</button>
}
testId="host-access-denied"
>
You are signed in, but do not have access to this Dashboard.
</HostMessage>
);
}
@@ -171,7 +442,17 @@ export function HostApp(props: HostAppProps): ReactElement {
return (
<div style={shellStyles.layout}>
<header style={shellStyles.header}>Ekklesia</header>
<header style={shellStyles.header}>
<h1 style={shellStyles.heading}>Ekklesia</h1>
<button
data-testid="host-logout"
onClick={() => void signOut()}
style={shellStyles.action}
type="button"
>
Sign out
</button>
</header>
<aside style={shellStyles.aside}>
{entries.length === 0 && groups.length === 0 ? (
<p data-testid="host-empty" style={{ color: "#57534e", margin: 0 }}>
@@ -180,8 +461,6 @@ export function HostApp(props: HostAppProps): ReactElement {
) : (
<nav aria-label="Modules" style={{ display: "grid", gap: "1rem" }}>
{groups.map((group) => (
// An empty group still renders: an administrator created it, and hiding it would look
// like it had been deleted.
<section data-testid={`group-${group.id}`} key={group.id}>
<h2 style={shellStyles.groupLabel}>{group.label}</h2>
<div style={{ display: "grid", gap: "0.125rem" }}>
@@ -197,9 +476,6 @@ export function HostApp(props: HostAppProps): ReactElement {
</section>
))}
{ungrouped.length > 0 ? (
// Where a module lives until someone decides otherwise — including one installed five
// minutes ago. The heading is omitted when nothing is grouped, so an unconfigured
// installation reads as a plain module list rather than a mysterious "Other" bucket.
<section data-testid="group-ungrouped">
{groups.length > 0 ? <h2 style={shellStyles.groupLabel}>Other</h2> : undefined}
<div style={{ display: "grid", gap: "0.125rem" }}>
@@ -219,14 +495,12 @@ export function HostApp(props: HostAppProps): ReactElement {
</aside>
<main style={shellStyles.main}>
{selected ? (
// Keyed by module identity — not by group — so switching selection discards this frame and
// its container entirely, while re-grouping a module never remounts it. See
// `ModuleUiFrame` for why that is what makes a slow, stale load harmless.
<ModuleUiFrame
config={config}
descriptor={selected.descriptor}
{...(importModule ? { importModule } : {})}
key={moduleKey(selected)}
onAuthorizationResponse={onAuthorizationResponse}
principal={bootstrap.principal}
/>
) : undefined}
+200
View File
@@ -0,0 +1,200 @@
import {
type FormEvent,
type KeyboardEvent,
type ReactElement,
useEffect,
useRef,
useState,
} from "react";
import { HostAuthError, type HostSignInCredentials } from "../auth-protocol.js";
export interface LoginFormProps {
readonly onAuthenticate: (
credentials: HostSignInCredentials,
signal: AbortSignal,
) => Promise<void>;
}
const loginStyles = {
button: {
background: "#1c1917",
border: "1px solid #1c1917",
borderRadius: "0.375rem",
color: "#fafaf9",
cursor: "pointer",
font: "inherit",
fontWeight: 600,
padding: "0.625rem 0.875rem",
},
card: {
background: "#ffffff",
border: "1px solid #e7e5e4",
borderRadius: "0.75rem",
boxShadow: "0 12px 32px rgb(28 25 23 / 0.08)",
display: "grid",
gap: "1rem",
maxWidth: "24rem",
padding: "1.5rem",
width: "100%",
},
error: { color: "#9f1239", margin: 0 },
field: { display: "grid", gap: "0.375rem" },
form: { display: "grid", gap: "1rem" },
heading: { fontSize: "1.5rem", margin: 0 },
host: {
alignItems: "center",
background: "#fafaf9",
color: "#1c1917",
display: "flex",
fontFamily: "system-ui, sans-serif",
justifyContent: "center",
minHeight: "100vh",
padding: "1rem",
},
input: {
border: "1px solid #a8a29e",
borderRadius: "0.375rem",
font: "inherit",
padding: "0.625rem 0.75rem",
width: "100%",
},
introduction: { color: "#57534e", margin: 0 },
label: { fontWeight: 600 },
} as const;
/** Host-owned email/password sign-in. Modules never render or call this component. */
export function LoginForm(props: LoginFormProps): ReactElement {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [pending, setPending] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
const pendingRef = useRef(false);
const passwordRef = useRef<HTMLInputElement | null>(null);
const attemptRef = useRef<AbortController | undefined>(undefined);
const mountedRef = useRef(true);
useEffect(() => {
// React development effect replay cleans up and sets up the same mounted component again.
mountedRef.current = true;
return () => {
mountedRef.current = false;
attemptRef.current?.abort();
};
}, []);
useEffect(() => {
if (errorMessage && !pending) {
passwordRef.current?.focus();
}
}, [errorMessage, pending]);
const submit = async (event: FormEvent<HTMLFormElement>): Promise<void> => {
event.preventDefault();
// The ref closes the same-tick gap before React commits `pending`, while the disabled button
// covers ordinary button and keyboard interaction after that commit.
if (pendingRef.current) {
return;
}
pendingRef.current = true;
setPending(true);
setErrorMessage(undefined);
const attempt = new AbortController();
attemptRef.current = attempt;
try {
// Capture the submitted value for this one request, then remove it from React state and the
// DOM as soon as the credential callback has begun. Principal/navigation resolution may take
// much longer than the POST and must not keep the password resident in the form meanwhile.
const authentication = props.onAuthenticate({ email, password }, attempt.signal);
setPassword("");
await authentication;
} catch (error) {
if (!attempt.signal.aborted && mountedRef.current) {
setErrorMessage(
error instanceof HostAuthError ? error.message : "Unable to sign in right now.",
);
}
} finally {
if (attemptRef.current === attempt) {
attemptRef.current = undefined;
pendingRef.current = false;
if (mountedRef.current) {
setPending(false);
}
}
}
};
const submitOnEnter = (event: KeyboardEvent<HTMLFormElement>): void => {
if (
event.key !== "Enter" ||
event.defaultPrevented ||
event.repeat ||
event.nativeEvent.isComposing ||
!(event.target instanceof HTMLInputElement)
) {
return;
}
// Browsers implicitly submit a form from these fields. Calling requestSubmit explicitly keeps
// that keyboard contract testable in DOM implementations that do not emulate the default key
// action, while still using native constraint validation and the single onSubmit path.
event.preventDefault();
event.currentTarget.requestSubmit();
};
return (
<main data-testid="host-login" style={loginStyles.host}>
<section aria-labelledby="ekklesia-login-heading" style={loginStyles.card}>
<h1 id="ekklesia-login-heading" style={loginStyles.heading}>
Sign in to Ekklesia
</h1>
<p style={loginStyles.introduction}>Use your existing Ekklesia account.</p>
<form
aria-busy={pending}
onKeyDown={submitOnEnter}
onSubmit={submit}
style={loginStyles.form}
>
<label style={loginStyles.field}>
<span style={loginStyles.label}>Email</span>
<input
autoComplete="username"
data-testid="login-email"
disabled={pending}
inputMode="email"
name="email"
onChange={(event) => setEmail(event.currentTarget.value)}
required
style={loginStyles.input}
type="email"
value={email}
/>
</label>
<label style={loginStyles.field}>
<span style={loginStyles.label}>Password</span>
<input
aria-describedby={errorMessage ? "ekklesia-login-error" : undefined}
autoComplete="current-password"
data-testid="login-password"
disabled={pending}
name="password"
onChange={(event) => setPassword(event.currentTarget.value)}
ref={passwordRef}
required
style={loginStyles.input}
type="password"
value={password}
/>
</label>
{errorMessage ? (
<p id="ekklesia-login-error" role="alert" style={loginStyles.error}>
{errorMessage}
</p>
) : undefined}
<button disabled={pending} style={loginStyles.button} type="submit">
{pending ? "Signing in…" : "Sign in"}
</button>
</form>
</section>
</main>
);
}
+21 -3
View File
@@ -10,6 +10,8 @@ export interface ModuleUiFrameProps {
readonly config: EkklesiaHostConfig;
readonly descriptor: HostModuleUiDescriptor;
readonly principal: ModuleUiPrincipal;
/** Host-internal session signal. It never enters the module-facing context. */
readonly onAuthorizationResponse?: (status: 401 | 403) => void;
/** Test-only seam, forwarded to the generic loader so a test can hold an import pending and prove
* the stale-load rule. Production composition leaves it unset and the loader's own
* `(url) => import(url)` runs. */
@@ -49,7 +51,7 @@ export interface ModuleUiFrameProps {
export function ModuleUiFrame(props: ModuleUiFrameProps): ReactElement {
const containerRef = useRef<HTMLDivElement | null>(null);
const [status, setStatus] = useState<FrameStatus>("loading");
const { config, descriptor, importModule, principal } = props;
const { config, descriptor, importModule, onAuthorizationResponse, principal } = props;
useEffect(() => {
const container = containerRef.current;
@@ -60,11 +62,27 @@ export function ModuleUiFrame(props: ModuleUiFrameProps): ReactElement {
let mounted: Awaited<ReturnType<typeof loadModuleUi>> | undefined;
setStatus("loading");
const reportAuthorizationResponse = (status: 401 | 403): void => {
// A module may retain an in-flight request while logout or another auth transition unmounts
// this frame. Its eventual response still belongs to that module call, but must not be allowed
// to cancel or overwrite the newer host transition.
if (!cancelled) {
onAuthorizationResponse?.(status);
}
};
void (async () => {
try {
const instance = await loadModuleUi({
container,
context: createModuleUiContext({ config, descriptor, principal }),
context: createModuleUiContext({
config,
descriptor,
principal,
...(onAuthorizationResponse
? { onAuthorizationResponse: reportAuthorizationResponse }
: {}),
}),
...(importModule ? { importModule } : {}),
source: {
moduleId: descriptor.id,
@@ -94,7 +112,7 @@ export function ModuleUiFrame(props: ModuleUiFrameProps): ReactElement {
// already in progress, and a module that fails to clean up must not take the shell with it.
void mounted?.unmount().catch(() => undefined);
};
}, [config, descriptor, importModule, principal]);
}, [config, descriptor, importModule, onAuthorizationResponse, principal]);
return (
<section aria-live="polite" style={{ display: "grid", gap: "0.75rem" }}>