feat: add browser auth shell
This commit is contained in:
@@ -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}
|
||||
|
||||
Reference in New Issue
Block a user