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
+92
View File
@@ -0,0 +1,92 @@
import type { EkklesiaHostConfig } from "./host-protocol.js";
import { resolveApiUrl } from "./host-protocol.js";
const SIGN_IN_PATH = "/api/auth/sign-in/email";
const SIGN_OUT_PATH = "/api/auth/sign-out";
export interface HostSignInCredentials {
readonly email: string;
readonly password: string;
}
export type HostAuthErrorCode =
| "AUTH_CREDENTIALS_INVALID"
| "AUTH_REQUEST_FAILED"
| "AUTH_SIGN_OUT_FAILED";
const errorMessages: Readonly<Record<HostAuthErrorCode, string>> = Object.freeze({
AUTH_CREDENTIALS_INVALID: "Email or password is incorrect.",
AUTH_REQUEST_FAILED: "Unable to sign in right now.",
AUTH_SIGN_OUT_FAILED: "Unable to sign out right now.",
});
/**
* A browser-safe authentication failure. It deliberately retains neither a response body nor the
* submitted credentials, a request URL, a Better Auth error, or a caught transport exception.
*/
export class HostAuthError extends Error {
readonly code: HostAuthErrorCode;
constructor(code: HostAuthErrorCode) {
super(errorMessages[code]);
this.name = "HostAuthError";
this.code = code;
this.stack = `${this.name}: ${this.message}`;
Object.freeze(this);
}
}
async function postJson(
config: EkklesiaHostConfig,
path: string,
body: unknown,
failureCode: Exclude<HostAuthErrorCode, "AUTH_CREDENTIALS_INVALID">,
signal?: AbortSignal,
): Promise<Response> {
const performRequest = config.fetch ?? fetch;
try {
return await performRequest(resolveApiUrl(config, path), {
body: JSON.stringify(body),
cache: "no-store",
credentials: "include",
headers: {
accept: "application/json",
"content-type": "application/json",
},
method: "POST",
redirect: "error",
...(signal ? { signal } : {}),
});
} catch {
// The thrown value may contain a URL or implementation detail. More importantly, this helper
// must never attach the request body (and therefore the password) as an error cause.
throw new HostAuthError(failureCode);
}
}
/**
* Uses Ekklesia's existing Better Auth transport without exposing Better Auth to browser packages.
* Success means only that the mutation succeeded; the shell must resolve `/api/v1/principal` before
* it renders authenticated content rather than trusting a response token or user object.
*/
export async function signInWithEmail(
config: EkklesiaHostConfig,
credentials: HostSignInCredentials,
signal?: AbortSignal,
): Promise<void> {
const response = await postJson(config, SIGN_IN_PATH, credentials, "AUTH_REQUEST_FAILED", signal);
if (response.status === 400 || response.status === 401) {
throw new HostAuthError("AUTH_CREDENTIALS_INVALID");
}
if (!response.ok) {
throw new HostAuthError("AUTH_REQUEST_FAILED");
}
}
/** Invalidates the server session. Hiding the shell without this successful mutation is not logout. */
export async function signOutHost(config: EkklesiaHostConfig, signal?: AbortSignal): Promise<void> {
const response = await postJson(config, SIGN_OUT_PATH, {}, "AUTH_SIGN_OUT_FAILED", signal);
if (!response.ok) {
throw new HostAuthError("AUTH_SIGN_OUT_FAILED");
}
}
+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" }}>
+7 -2
View File
@@ -43,8 +43,10 @@ const SEMANTIC_VERSION_PATTERN =
/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-(?:(?:0|[1-9][0-9]*|[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u;
export type HostProtocolErrorCode =
/** The caller is not signed in, or lacks `core.modules.ui.read`. */
/** The caller is not signed in. */
| "HOST_UNAUTHENTICATED"
/** The caller is signed in but may not read the Dashboard resource. */
| "HOST_ACCESS_DENIED"
/** The API answered, but not with something this shell understands. */
| "HOST_RESPONSE_INVALID"
/** The API could not be reached, or failed. */
@@ -61,6 +63,7 @@ export type HostProtocolErrorCode =
| "DISPLAY_ACCESS_DENIED";
const errorMessages: Readonly<Record<HostProtocolErrorCode, string>> = Object.freeze({
HOST_ACCESS_DENIED: "You do not have access to the Ekklesia Dashboard.",
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.",
@@ -460,7 +463,9 @@ export async function loadDashboardNavigation(
signal?: AbortSignal,
): Promise<DashboardNavigation> {
return parseDashboardNavigation(
await requestPlatformJson(config, DASHBOARD_NAVIGATION_PATH, signal),
await requestPlatformJson(config, DASHBOARD_NAVIGATION_PATH, signal, {
forbidden: "HOST_ACCESS_DENIED",
}),
);
}
+7
View File
@@ -39,3 +39,10 @@ export {
createModuleUiContext,
moduleUiSourceUrl,
} from "./module-context.js";
export {
HostAuthError,
type HostAuthErrorCode,
type HostSignInCredentials,
signInWithEmail,
signOutHost,
} from "./auth-protocol.js";
+12 -2
View File
@@ -220,6 +220,7 @@ function createModuleRealtimeClient(
function createModuleApiClient(
config: EkklesiaHostConfig,
descriptor: HostModuleUiDescriptor,
onAuthorizationResponse?: (status: 401 | 403) => void,
): ModuleUiApiClient {
const performRequest = config.fetch ?? fetch;
const moduleRoot = new URL(resolveApiUrl(config, descriptor.apiBaseUrl));
@@ -244,7 +245,13 @@ function createModuleApiClient(
// The module's own `init` is forwarded whole — method, headers, body, signal — and only
// `credentials` is imposed, because session handling is the host's job and a module UI never
// sees or supplies a token (ADR 0022). A module cannot opt out of it.
return performRequest(target.href, { ...init, credentials: "include" });
const response = await performRequest(target.href, { ...init, credentials: "include" });
if (response.status === 401 || response.status === 403) {
// This callback stays entirely on the host side. The module still receives its original
// response, and the public ModuleUiContext gains no authentication control or event.
onAuthorizationResponse?.(response.status);
}
return response;
},
});
}
@@ -253,6 +260,9 @@ export interface CreateModuleUiContextOptions {
readonly config: EkklesiaHostConfig;
readonly descriptor: HostModuleUiDescriptor;
readonly principal: ModuleUiPrincipal;
/** Host-only signal used by the Dashboard to revalidate an apparently expired session. It is not
* included in the returned ModuleUiHostContext and is intentionally absent from the UI SDK. */
readonly onAuthorizationResponse?: (status: 401 | 403) => void;
}
/**
@@ -271,7 +281,7 @@ export interface CreateModuleUiContextOptions {
export function createModuleUiContext(options: CreateModuleUiContextOptions): ModuleUiHostContext {
const granted = new Set(options.descriptor.permissions);
return Object.freeze({
api: createModuleApiClient(options.config, options.descriptor),
api: createModuleApiClient(options.config, options.descriptor, options.onAuthorizationResponse),
moduleId: options.descriptor.id,
permissions: Object.freeze({ has: (permissionId: string) => granted.has(permissionId) }),
principal: options.principal,
+113
View File
@@ -0,0 +1,113 @@
import { describe, expect, it, vi } from "vitest";
import { HostAuthError, signInWithEmail, signOutHost } from "../src/auth-protocol.js";
const apiBaseUrl = "https://ekklesia.example.test";
function recordingFetch(response: Response) {
const calls: Array<{ readonly init: RequestInit | undefined; readonly url: string }> = [];
const implementation = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
calls.push({ init, url: String(input) });
return response.clone();
}) as unknown as typeof fetch;
return { calls, implementation };
}
describe("browser authentication transport", () => {
it("posts email/password to the existing endpoint with browser-managed credentials", async () => {
const { calls, implementation } = recordingFetch(Response.json({ user: {} }));
const password = "correct horse battery staple";
await signInWithEmail(
{ apiBaseUrl, fetch: implementation },
{ email: "[email protected]", password },
);
expect(calls).toHaveLength(1);
expect(calls[0]?.url).toBe(`${apiBaseUrl}/api/auth/sign-in/email`);
expect(calls[0]?.url).not.toContain(password);
expect(calls[0]?.init).toMatchObject({
cache: "no-store",
credentials: "include",
method: "POST",
redirect: "error",
});
expect(JSON.parse(String(calls[0]?.init?.body))).toEqual({
email: "[email protected]",
password,
});
expect(calls[0]?.init?.headers).toEqual({
accept: "application/json",
"content-type": "application/json",
});
expect(JSON.stringify(calls[0]?.init?.headers).toLowerCase()).not.toContain("origin");
});
it("maps invalid credentials to one account-neutral, response-neutral failure", async () => {
for (const status of [400, 401]) {
const response = new Response(
JSON.stringify({ detail: "user exists at /private/database", email: "[email protected]" }),
{ status },
);
const { implementation } = recordingFetch(response);
const error = await signInWithEmail(
{ apiBaseUrl, fetch: implementation },
{ email: "[email protected]", password: "wrong-secret" },
).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(HostAuthError);
expect(error).toMatchObject({
code: "AUTH_CREDENTIALS_INVALID",
message: "Email or password is incorrect.",
});
expect(JSON.stringify(error)).not.toContain("[email protected]");
expect(JSON.stringify(error)).not.toContain("wrong-secret");
expect((error as Error).message).not.toContain("private");
}
});
it("sanitizes transport and server failures without retaining credentials or a cause", async () => {
const password = "do-not-log-this";
const implementation = vi.fn(async () => {
throw new Error(`network failed password=${password} /private/socket`);
}) as unknown as typeof fetch;
const error = await signInWithEmail(
{ apiBaseUrl, fetch: implementation },
{ email: "[email protected]", password },
).catch((caught: unknown) => caught);
expect(error).toMatchObject({
code: "AUTH_REQUEST_FAILED",
message: "Unable to sign in right now.",
});
expect("cause" in (error as object)).toBe(false);
expect(JSON.stringify(error)).not.toContain(password);
expect((error as Error).message).not.toContain("private");
});
it("posts an empty body to the existing sign-out endpoint", async () => {
const { calls, implementation } = recordingFetch(Response.json({ success: true }));
await signOutHost({ apiBaseUrl, fetch: implementation });
expect(calls).toHaveLength(1);
expect(calls[0]?.url).toBe(`${apiBaseUrl}/api/auth/sign-out`);
expect(calls[0]?.init).toMatchObject({
body: "{}",
credentials: "include",
method: "POST",
});
});
it("uses a sign-out-specific safe error", async () => {
const { implementation } = recordingFetch(
new Response("internal session token", { status: 500 }),
);
await expect(signOutHost({ apiBaseUrl, fetch: implementation })).rejects.toMatchObject({
code: "AUTH_SIGN_OUT_FAILED",
message: "Unable to sign out right now.",
});
});
});
+639 -5
View File
@@ -18,6 +18,7 @@ let consoleError: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
window.history.replaceState({}, "", "/");
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
@@ -134,6 +135,92 @@ function query(testId: string): Element | null {
return container.querySelector(`[data-testid="${testId}"]`);
}
async function setInput(testId: string, value: string): Promise<void> {
const input = query(testId) as HTMLInputElement | null;
if (!input) {
throw new Error(`missing input ${testId}`);
}
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
setter?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
async function submitLogin(): Promise<void> {
const form = query("host-login")?.querySelector("form");
if (!form) {
throw new Error("missing login form");
}
await act(async () => {
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
await Promise.resolve();
});
}
interface StatefulAuthPlatform {
readonly calls: Array<{ readonly init: RequestInit | undefined; readonly url: string }>;
readonly fetch: typeof fetch;
authenticated(): boolean;
setAuthenticated(value: boolean): void;
}
function statefulAuthPlatform(
options: {
readonly initiallyAuthenticated?: boolean;
readonly moduleStatus?: () => number;
readonly onModuleRequest?: () => Promise<void>;
readonly onPrincipalRequest?: (authenticated: boolean) => Promise<void>;
readonly onSignIn?: () => Promise<void>;
readonly onSignOut?: () => Promise<void>;
} = {},
): StatefulAuthPlatform {
let authenticated = options.initiallyAuthenticated ?? false;
const calls: StatefulAuthPlatform["calls"] = [];
const implementation = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
calls.push({ init, url });
if (url.endsWith("/api/auth/sign-in/email")) {
await options.onSignIn?.();
const body = JSON.parse(String(init?.body)) as { email?: unknown; password?: unknown };
if (body.email !== "[email protected]" || body.password !== "correct password") {
return Response.json({ code: "INVALID_EMAIL_OR_PASSWORD" }, { status: 401 });
}
authenticated = true;
return Response.json({ ok: true });
}
if (url.endsWith("/api/auth/sign-out")) {
await options.onSignOut?.();
authenticated = false;
return Response.json({ success: true });
}
if (url.endsWith("/api/v1/principal")) {
await options.onPrincipalRequest?.(authenticated);
return Response.json(
authenticated ? { kind: "authenticated", userId: "user-1" } : { kind: "anonymous" },
);
}
if (url.endsWith("/api/v1/dashboard/navigation")) {
return authenticated
? Response.json({ groups: [], ungrouped: [entry("example", "Example Module")] })
: Response.json({ code: "AUTHORIZATION_DENIED" }, { status: 403 });
}
if (url.includes("/api/v1/modules/example/")) {
await options.onModuleRequest?.();
return new Response("{}", { status: options.moduleStatus?.() ?? 200 });
}
return Response.json({ code: "NOT_FOUND" }, { status: 404 });
}) as unknown as typeof fetch;
return {
calls,
fetch: implementation,
authenticated: () => authenticated,
setAuthenticated: (value) => {
authenticated = value;
},
};
}
describe("Ekklesia shell — bootstrap", () => {
it("renders the module list the navigation returned", async () => {
await render({
@@ -147,17 +234,19 @@ describe("Ekklesia shell — bootstrap", () => {
expect(query("select-calendar")).not.toBeNull();
});
it("asks an anonymous viewer to sign in, and mounts nothing", async () => {
it("renders the host login for an anonymous viewer, and mounts nothing", async () => {
await render({ apiBaseUrl, fetch: platformFetch({ principal: { kind: "anonymous" } }) });
expect(query("host-signed-out")).not.toBeNull();
expect(query("host-login")).not.toBeNull();
expect(query("module-container")).toBeNull();
});
it("treats refused navigation as signed out rather than as a crash", async () => {
it("keeps an authenticated navigation denial distinct from sign-out", async () => {
await render({ apiBaseUrl, fetch: platformFetch({ navigationStatus: 403 }) });
expect(query("host-signed-out")).not.toBeNull();
expect(query("host-access-denied")).not.toBeNull();
expect(query("host-login")).toBeNull();
expect(query("host-logout")).not.toBeNull();
});
it("renders a host-owned error when the platform cannot be reached", async () => {
@@ -174,6 +263,549 @@ describe("Ekklesia shell — bootstrap", () => {
});
});
describe("Ekklesia shell — browser authentication", () => {
it("renders only a neutral loading state until principal resolves and fetches no navigation early", async () => {
let releasePrincipal: (() => void) | undefined;
const principalPending = new Promise<void>((resolve) => {
releasePrincipal = resolve;
});
const calls: string[] = [];
const fetchImplementation = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
calls.push(url);
if (url.endsWith("/api/v1/principal")) {
await principalPending;
return Response.json({ kind: "anonymous" });
}
return Response.json({ groups: [], ungrouped: [] });
}) as unknown as typeof fetch;
await render({ apiBaseUrl, fetch: fetchImplementation });
expect(query("host-loading")).not.toBeNull();
expect(query("host-login")).toBeNull();
expect(query("host-logout")).toBeNull();
expect(calls).toEqual([`${apiBaseUrl}/api/v1/principal`]);
await act(async () => {
releasePrincipal?.();
await principalPending;
});
expect(query("host-login")).not.toBeNull();
expect(calls).toEqual([`${apiBaseUrl}/api/v1/principal`]);
});
it("renders an accessible semantic email/password form with no signup or dead reset action", async () => {
const platform = statefulAuthPlatform();
await render({ apiBaseUrl, fetch: platform.fetch });
const email = query("login-email") as HTMLInputElement;
const password = query("login-password") as HTMLInputElement;
const form = query("host-login")?.querySelector("form");
const submit = form?.querySelector('button[type="submit"]') as HTMLButtonElement;
expect(email.type).toBe("email");
expect(email.autocomplete).toBe("username");
expect(email.labels?.[0]?.textContent).toContain("Email");
expect(password.type).toBe("password");
expect(password.autocomplete).toBe("current-password");
expect(password.labels?.[0]?.textContent).toContain("Password");
expect(submit.textContent).toBe("Sign in");
expect(form?.tagName).toBe("FORM");
expect(text()).not.toContain("Create account");
expect(text()).not.toContain("Forgot password");
});
it("fails invalid credentials generically, clears the password, and never puts it in a URL", async () => {
const platform = statefulAuthPlatform();
await render({ apiBaseUrl, fetch: platform.fetch });
await setInput("login-email", "[email protected]");
await setInput("login-password", "wrong and secret");
await submitLogin();
const error = query("host-login")?.querySelector('[role="alert"]');
expect(error?.textContent).toBe("Email or password is incorrect.");
expect((query("login-email") as HTMLInputElement).value).toBe("[email protected]");
expect((query("login-password") as HTMLInputElement).value).toBe("");
expect(document.activeElement).toBe(query("login-password"));
expect(platform.calls.map((call) => call.url).join("\n")).not.toContain("wrong and secret");
expect(consoleError).not.toHaveBeenCalled();
});
it("prevents duplicate submissions while one sign-in is pending", async () => {
let releaseSignIn: (() => void) | undefined;
const signInPending = new Promise<void>((resolve) => {
releaseSignIn = resolve;
});
const platform = statefulAuthPlatform({ onSignIn: () => signInPending });
await render({ apiBaseUrl, fetch: platform.fetch });
await setInput("login-email", "[email protected]");
await setInput("login-password", "correct password");
await submitLogin();
await submitLogin();
const signInCalls = platform.calls.filter((call) =>
call.url.endsWith("/api/auth/sign-in/email"),
);
expect(signInCalls).toHaveLength(1);
expect(
query("host-login")?.querySelector('button[type="submit"]')?.hasAttribute("disabled"),
).toBe(true);
await act(async () => {
releaseSignIn?.();
await signInPending;
await Promise.resolve();
});
expect(query("host-logout")).not.toBeNull();
});
it("clears the password while post-sign-in principal resolution is still pending", async () => {
let releasePrincipal: (() => void) | undefined;
const principalPending = new Promise<void>((resolve) => {
releasePrincipal = resolve;
});
const platform = statefulAuthPlatform({
onPrincipalRequest: (authenticated) => (authenticated ? principalPending : Promise.resolve()),
});
await render({ apiBaseUrl, fetch: platform.fetch });
await setInput("login-email", "[email protected]");
await setInput("login-password", "correct password");
await submitLogin();
expect(platform.authenticated()).toBe(true);
expect((query("login-password") as HTMLInputElement).value).toBe("");
expect(
JSON.parse(
String(
platform.calls.find((call) => call.url.endsWith("/api/auth/sign-in/email"))?.init?.body,
),
),
).toEqual({ email: "[email protected]", password: "correct password" });
expect(query("host-login")?.querySelector("form")?.getAttribute("aria-busy")).toBe("true");
await act(async () => {
releasePrincipal?.();
await principalPending;
await Promise.resolve();
});
expect(query("host-logout")).not.toBeNull();
});
it("submits from the password field with the Enter key", async () => {
let releaseSignIn: (() => void) | undefined;
const signInPending = new Promise<void>((resolve) => {
releaseSignIn = resolve;
});
const platform = statefulAuthPlatform({ onSignIn: () => signInPending });
await render({ apiBaseUrl, fetch: platform.fetch });
await setInput("login-email", "[email protected]");
await setInput("login-password", "correct password");
await act(async () => {
query("login-password")?.dispatchEvent(
new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key: "Enter" }),
);
await Promise.resolve();
});
expect(
platform.calls.filter((call) => call.url.endsWith("/api/auth/sign-in/email")),
).toHaveLength(1);
expect((query("login-password") as HTMLInputElement).value).toBe("");
await act(async () => {
releaseSignIn?.();
await signInPending;
await Promise.resolve();
});
expect(query("host-logout")).not.toBeNull();
});
it("re-resolves principal and navigation after login without a page reload", async () => {
const platform = statefulAuthPlatform();
const importer = vi.fn(async () => artifact("example", "0.1.0"));
await render({ apiBaseUrl, fetch: platform.fetch }, importer);
await setInput("login-email", "[email protected]");
await setInput("login-password", "correct password");
await submitLogin();
expect(query("host-login")).toBeNull();
expect(query("host-logout")).not.toBeNull();
expect(query("module-container")?.textContent).toBe("example mounted");
expect(importer).toHaveBeenCalledOnce();
expect(platform.calls.map((call) => new URL(call.url).pathname)).toEqual([
"/api/v1/principal",
"/api/auth/sign-in/email",
"/api/v1/principal",
"/api/v1/dashboard/navigation",
]);
});
it("keeps the current internal URL in place and ignores external or protocol-relative return inputs", async () => {
window.history.replaceState(
{},
"",
"/?returnTo=%2F%2Fevil.example.test%2Fsteal&next=https%3A%2F%2Fevil.example.test&backslash=%5C%5Cevil.example.test&scheme=javascript%3Aalert%281%29",
);
const expectedLocation = window.location.href;
const platform = statefulAuthPlatform();
await render({ apiBaseUrl, fetch: platform.fetch }, async () => artifact("example", "0.1.0"));
await setInput("login-email", "[email protected]");
await setInput("login-password", "correct password");
await submitLogin();
expect(window.location.href).toBe(expectedLocation);
expect(platform.calls.every((call) => new URL(call.url).origin === apiBaseUrl)).toBe(true);
expect(platform.calls.map((call) => call.url).join("\n")).not.toContain("evil.example.test");
expect(platform.calls.map((call) => call.url).join("\n")).not.toContain("javascript");
});
it("shows a safe retry when principal resolution is malformed or unavailable", async () => {
let healthy = false;
const fetchImplementation = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith("/api/v1/principal")) {
return healthy
? Response.json({ kind: "authenticated", userId: "user-1" })
: new Response("database failed at /private/path", { status: 503 });
}
return Response.json({ groups: [], ungrouped: [entry("example", "Example Module")] });
}) as unknown as typeof fetch;
await render({ apiBaseUrl, fetch: fetchImplementation }, async () =>
artifact("example", "0.1.0"),
);
expect(query("host-error")).not.toBeNull();
expect(text()).not.toContain("private");
healthy = true;
const retry = query("host-error")?.querySelector("button");
expect(retry).not.toBeNull();
await act(async () => {
(retry as HTMLButtonElement).click();
});
expect(query("host-logout")).not.toBeNull();
});
it("fails safely on a malformed successful principal response and recovers on retry", async () => {
let healthy = false;
const fetchImplementation = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith("/api/v1/principal")) {
return Response.json(
healthy
? { kind: "authenticated", userId: "user-1" }
: { kind: "authenticated", privatePath: "/sessions/private" },
);
}
return Response.json({ groups: [], ungrouped: [entry("example", "Example Module")] });
}) as unknown as typeof fetch;
await render({ apiBaseUrl, fetch: fetchImplementation }, async () =>
artifact("example", "0.1.0"),
);
expect(query("host-error")).not.toBeNull();
expect(text()).not.toContain("private");
expect(query("host-login")).toBeNull();
healthy = true;
const retry = query("host-error")?.querySelector("button");
expect(retry).not.toBeNull();
await act(async () => {
(retry as HTMLButtonElement).click();
await Promise.resolve();
});
expect(query("host-logout")).not.toBeNull();
});
});
describe("Ekklesia shell — logout and session expiration", () => {
it("unmounts module UI and closes realtime before completing server-side logout", async () => {
let releaseSignOut: (() => void) | undefined;
const signOutPending = new Promise<void>((resolve) => {
releaseSignOut = resolve;
});
const platform = statefulAuthPlatform({
initiallyAuthenticated: true,
onSignOut: () => signOutPending,
});
let unmountCalls = 0;
let closeCalls = 0;
const source = {
CLOSED: 2,
CONNECTING: 0,
OPEN: 1,
addEventListener: vi.fn(),
close: () => {
closeCalls += 1;
},
readyState: 0,
removeEventListener: vi.fn(),
} as unknown as EventSource;
await render(
{
apiBaseUrl,
eventSourceFactory: () => source,
fetch: platform.fetch,
},
async () => ({
default: {
id: "example",
mount(element: Element, context: ModuleUiHostContext) {
element.textContent = "example mounted";
const subscription = context.realtime.subscribe("state", {});
return () => {
unmountCalls += 1;
subscription.close();
};
},
version: "0.1.0",
},
}),
);
await act(async () => {
(query("host-logout") as HTMLButtonElement).click();
await Promise.resolve();
});
expect(query("host-signing-out")).not.toBeNull();
expect(query("module-container")).toBeNull();
expect(unmountCalls).toBe(1);
expect(closeCalls).toBe(1);
expect(platform.authenticated()).toBe(true);
await act(async () => {
releaseSignOut?.();
await signOutPending;
await Promise.resolve();
});
expect(platform.authenticated()).toBe(false);
expect(query("host-login")).not.toBeNull();
// A new shell resolves the invalidated server session as anonymous too.
await act(async () => root.unmount());
root = createRoot(container);
await render({ apiBaseUrl, fetch: platform.fetch });
expect(query("host-login")).not.toBeNull();
});
it("ignores a retained module request that resolves after logout unmounts its frame", async () => {
let authenticatedPrincipalRequests = 0;
let releaseModuleRequest: (() => void) | undefined;
const moduleRequestPending = new Promise<void>((resolve) => {
releaseModuleRequest = resolve;
});
let releaseSignOut: (() => void) | undefined;
const signOutPending = new Promise<void>((resolve) => {
releaseSignOut = resolve;
});
const platform = statefulAuthPlatform({
initiallyAuthenticated: true,
moduleStatus: () => 401,
onModuleRequest: () => moduleRequestPending,
onPrincipalRequest: (authenticated) => {
if (!authenticated) {
return Promise.resolve();
}
authenticatedPrincipalRequests += 1;
return authenticatedPrincipalRequests === 1
? Promise.resolve()
: Promise.reject(new Error("stale revalidation must never run"));
},
onSignOut: () => signOutPending,
});
const capture: { context?: ModuleUiHostContext; unmountCalls: number } = { unmountCalls: 0 };
await render({ apiBaseUrl, fetch: platform.fetch }, async () => sessionAwareArtifact(capture));
const lateRequest = capture.context?.api.request("retained-after-unmount");
if (!lateRequest) {
throw new Error("module context was not captured");
}
await act(async () => {
(query("host-logout") as HTMLButtonElement).click();
await Promise.resolve();
});
expect(query("host-signing-out")).not.toBeNull();
expect(capture.unmountCalls).toBe(1);
expect(platform.authenticated()).toBe(true);
await act(async () => {
releaseModuleRequest?.();
await lateRequest;
await Promise.resolve();
});
// The 401 belongs to a request retained by an already-unmounted module. It must not abort or
// replace the newer sign-out transition while the server still owns an authenticated session.
expect(query("host-signing-out")).not.toBeNull();
expect(query("host-login")).toBeNull();
expect(platform.authenticated()).toBe(true);
expect(authenticatedPrincipalRequests).toBe(1);
await act(async () => {
releaseSignOut?.();
await signOutPending;
await Promise.resolve();
});
expect(platform.authenticated()).toBe(false);
expect(query("host-login")).not.toBeNull();
});
it("does not claim logout succeeded when session invalidation fails", async () => {
const platform = statefulAuthPlatform({
initiallyAuthenticated: true,
onSignOut: () => Promise.reject(new Error("private session failure")),
});
await render({ apiBaseUrl, fetch: platform.fetch }, async () => artifact("example", "0.1.0"));
await act(async () => {
(query("host-logout") as HTMLButtonElement).click();
await Promise.resolve();
});
expect(query("host-sign-out-error")).not.toBeNull();
expect(query("host-login")).toBeNull();
expect(query("module-container")).toBeNull();
expect(text()).not.toContain("private session failure");
});
function sessionAwareArtifact(
capture: { context?: ModuleUiHostContext; unmountCalls: number },
options: { readonly subscribeToRealtime?: boolean } = {},
) {
return {
default: {
id: "example",
mount(element: Element, context: ModuleUiHostContext) {
capture.context = context;
element.textContent = "example mounted";
const subscription = options.subscribeToRealtime
? context.realtime.subscribe("state", {})
: undefined;
return () => {
capture.unmountCalls += 1;
subscription?.close();
element.textContent = "";
};
},
version: "0.1.0",
},
};
}
it("returns to login when a module API 401 recheck proves the session became anonymous", async () => {
const platform = statefulAuthPlatform({
initiallyAuthenticated: true,
moduleStatus: () => 401,
});
let closeCalls = 0;
const source = {
CLOSED: 2,
CONNECTING: 0,
OPEN: 1,
addEventListener: vi.fn(),
close: () => {
closeCalls += 1;
},
readyState: 0,
removeEventListener: vi.fn(),
} as unknown as EventSource;
const capture: { context?: ModuleUiHostContext; unmountCalls: number } = { unmountCalls: 0 };
await render(
{
apiBaseUrl,
eventSourceFactory: () => source,
fetch: platform.fetch,
},
async () => sessionAwareArtifact(capture, { subscribeToRealtime: true }),
);
platform.setAuthenticated(false);
const principalCallsBefore = platform.calls.filter((call) =>
call.url.endsWith("/api/v1/principal"),
).length;
await act(async () => {
await capture.context?.api.request("expired");
});
expect(query("host-login")).not.toBeNull();
expect(query("module-container")).toBeNull();
expect(capture.unmountCalls).toBe(1);
expect(closeCalls).toBe(1);
expect(platform.calls.filter((call) => call.url.endsWith("/api/v1/principal"))).toHaveLength(
principalCallsBefore + 1,
);
});
it("preserves an authenticated session after an ordinary module API 401", async () => {
const platform = statefulAuthPlatform({
initiallyAuthenticated: true,
moduleStatus: () => 401,
});
const capture: { context?: ModuleUiHostContext; unmountCalls: number } = { unmountCalls: 0 };
await render({ apiBaseUrl, fetch: platform.fetch }, async () => sessionAwareArtifact(capture));
await act(async () => {
const response = await capture.context?.api.request("module-authentication-required");
expect(response?.status).toBe(401);
await Promise.resolve();
});
expect(query("host-login")).toBeNull();
expect(query("module-container")?.textContent).toBe("example mounted");
expect(capture.unmountCalls).toBe(0);
expect(platform.calls.filter((call) => call.url.endsWith("/api/v1/principal"))).toHaveLength(2);
});
it("rechecks but does not log out an authenticated principal after an ordinary 403", async () => {
const platform = statefulAuthPlatform({
initiallyAuthenticated: true,
moduleStatus: () => 403,
});
const capture: { context?: ModuleUiHostContext; unmountCalls: number } = { unmountCalls: 0 };
await render({ apiBaseUrl, fetch: platform.fetch }, async () => sessionAwareArtifact(capture));
await act(async () => {
const response = await capture.context?.api.request("forbidden");
expect(response?.status).toBe(403);
await Promise.resolve();
});
expect(query("host-login")).toBeNull();
expect(query("module-container")?.textContent).toBe("example mounted");
expect(capture.unmountCalls).toBe(0);
expect(platform.calls.filter((call) => call.url.endsWith("/api/v1/principal"))).toHaveLength(2);
});
it("returns to login when a 403 recheck proves the session became anonymous", async () => {
const platform = statefulAuthPlatform({
initiallyAuthenticated: true,
moduleStatus: () => 403,
});
const capture: { context?: ModuleUiHostContext; unmountCalls: number } = { unmountCalls: 0 };
await render({ apiBaseUrl, fetch: platform.fetch }, async () => sessionAwareArtifact(capture));
platform.setAuthenticated(false);
await act(async () => {
await capture.context?.api.request("forbidden-after-expiry");
await Promise.resolve();
});
expect(query("host-login")).not.toBeNull();
expect(query("module-container")).toBeNull();
expect(capture.unmountCalls).toBe(1);
});
});
describe("Ekklesia shell — Dashboard navigation", () => {
const mediaGroup = () =>
group("media", "Media", [entry("video", "Video"), entry("livestream", "Livestream", "2.0.0")]);
@@ -209,7 +841,9 @@ describe("Ekklesia shell — Dashboard navigation", () => {
const labels = [...container.querySelectorAll("h2")].map((heading) => heading.textContent);
expect(labels).toEqual(["Planning", "Media"]);
const buttons = [...container.querySelectorAll("button")].map((button) => button.textContent);
const buttons = [...container.querySelectorAll("nav button")].map(
(button) => button.textContent,
);
expect(buttons).toEqual(["Calendar", "Livestream", "Video"]);
});
+42 -10
View File
@@ -128,16 +128,20 @@ describe("host protocol — descriptor validation", () => {
}
});
it("reports an unauthenticated caller distinctly from any other failure", async () => {
for (const status of [401, 403]) {
const { implementation } = stubFetch({
"/api/v1/dashboard/navigation": () =>
jsonResponse({ code: "AUTHORIZATION_DENIED" }, status),
});
await expect(
loadDashboardNavigation({ apiBaseUrl, fetch: implementation }),
).rejects.toMatchObject({ code: "HOST_UNAUTHENTICATED" });
}
it("distinguishes an authentication challenge from an authorization denial", async () => {
const unauthenticated = stubFetch({
"/api/v1/dashboard/navigation": () => jsonResponse({ code: "AUTHORIZATION_DENIED" }, 401),
});
await expect(
loadDashboardNavigation({ apiBaseUrl, fetch: unauthenticated.implementation }),
).rejects.toMatchObject({ code: "HOST_UNAUTHENTICATED" });
const forbidden = stubFetch({
"/api/v1/dashboard/navigation": () => jsonResponse({ code: "AUTHORIZATION_DENIED" }, 403),
});
await expect(
loadDashboardNavigation({ apiBaseUrl, fetch: forbidden.implementation }),
).rejects.toMatchObject({ code: "HOST_ACCESS_DENIED" });
const { implementation } = stubFetch({
"/api/v1/dashboard/navigation": () => jsonResponse({ code: "INTERNAL_ERROR" }, 500),
@@ -346,6 +350,34 @@ describe("module UI host context", () => {
});
});
it("reports only 401/403 to the host while returning the module's original response", async () => {
const statuses = [401, 403, 404, 200];
const onAuthorizationResponse = vi.fn();
const implementation = vi.fn(async () => {
const status = statuses.shift();
if (status === undefined) {
throw new Error("unexpected request");
}
return new Response("module response", { status });
}) as unknown as typeof fetch;
const context = createModuleUiContext({
config: { apiBaseUrl, fetch: implementation },
descriptor: exampleDescriptor,
onAuthorizationResponse,
principal: { kind: "authenticated", userId: "user-1" },
});
const responses = await Promise.all([
context.api.request("one"),
context.api.request("two"),
context.api.request("three"),
context.api.request("four"),
]);
expect(responses.map((response) => response.status)).toEqual([401, 403, 404, 200]);
expect(onAuthorizationResponse.mock.calls).toEqual([[401], [403]]);
});
it("refuses to address anything outside the module's own API", async () => {
const { calls, implementation } = recordingFetch();
const api = contextFor(implementation).api;
+12
View File
@@ -149,11 +149,21 @@ describe("the shell builds no module knowledge into its bundle", () => {
// time from the navigation the server resolved.
expect(bundle).toContain('"/api/v1/principal"');
expect(bundle).toContain('"/api/v1/dashboard/navigation"');
expect(bundle).toContain('"/api/auth/sign-in/email"');
expect(bundle).toContain('"/api/auth/sign-out"');
// The shell reads the navigation view, which already contains the inventory; it never calls
// the host-neutral inventory endpoint itself.
expect(bundle).not.toContain('"/api/v1/module-ui"');
});
it("contains only the browser HTTP auth adapter, never Better Auth or server identity internals", () => {
expect(bundle.toLowerCase()).not.toContain("better-auth");
expect(bundle.toLowerCase()).not.toContain("drizzle");
expect(bundle).not.toContain("EKKLESIA_IDENTITY_SECRET");
expect(bundle).not.toContain("bootstrapPlatformOwner");
expect(bundle).not.toContain("session_token");
});
it("bakes in no group, label, or placement", () => {
// Grouping is server-resolved configuration. A group id or label appearing in the bundle would
// mean the shell had an opinion about an arrangement it must only render.
@@ -208,6 +218,8 @@ describe("the display host is a separate generic browser bundle", () => {
expect(bundle).toContain('"/api/v1/principal"');
expect(bundle).toContain('"/api/v1/module-displays"');
expect(bundle).not.toContain('"/api/v1/dashboard/navigation"');
expect(bundle).not.toContain('"/api/auth/sign-in/email"');
expect(bundle).not.toContain('"/api/auth/sign-out"');
expect(bundle).not.toContain("Loading Ekklesia");
expect(bundle).not.toContain("Sign in to Ekklesia");
expect(bundle.toLowerCase()).not.toContain("socket.io");