feat: give display devices their own paired identity
ADR 0033 gave Ekklesia a display host and ADR 0034 gave it a login page. Together, the only way to light a television in a foyer was to sign a human being into it and leave that session running on a screen anyone can walk up to: a person's credentials on a wall, a person's session as the thing signage depends on, and the display going dark when they are revoked or their session simply expires. A screen is not a person. Ekklesia now recognizes three principal classes — anonymous, authenticated human, and managed device — and a device is a first-class principal with its own credential and its own explicit permissions. It has no email, no password, and no row in the identity tables, and it satisfies the `authenticated` baseline never, so every route that settles for "somebody is signed in" stays closed to it. Device permissions live in their own table because ekklesia_core_grant.user_id is a non-null foreign key into the user table and making it polymorphic would rewrite the platform's central authorization record to serve one narrow case. That is a schema decision, not a second decision point: the evaluator gained one branch, so a device is allowed or denied by the same function, with the same deny-by-default, as anyone else — with no owner path it could reach and no baseline that stands in for a grant. The six-digit code is not the credential. It is printed across a screen in a public hallway, so it is treated as public: it identifies a request to an administrator and is worth nothing alone. Collecting the credential also requires a 256-bit claim secret held only in the requesting browser's HttpOnly cookie, and approving requires the restricted core.devices.manage permission. Without that split, reading a code off a wall would hand over the screen's identity. The permission a pairing asks for is read from the module's validated display declaration, never from the request, so a browser cannot ask to be granted core.devices.manage or another module's permission. Approval grants exactly that one permission. Credentials are stored only as SHA-256; the raw value exists in the Set-Cookie that issues it and the device's own cookie jar, and is never logged, returned in JSON, or placed in a URL. The cookie is HttpOnly, so the module display code running in that same page cannot read it. Revocation is a server-side column checked on every principal resolution, and re-pairing mints a new identity so an old credential can never come back. State transitions are conditional updates, so one code cannot be approved twice or claimed into two credentials under a race. /api/v1/principal still reports a device as anonymous: it is what the Dashboard uses to decide whether a person is signed in. Displays read their viewer from the descriptor instead, which already performed the authorization — so displays are descriptor-first while the Dashboard stays principal-first, and neither infers an identity by elimination. Proven end to end against real PostgreSQL and real HTTP: an unpaired screen shows a code, an owner approves it, the device opens the display descriptor and a realtime stream, and revocation closes both while the device still holds its cookie. An already-open SSE stream is bounded by realtime's existing five-minute reconnect rather than closed instantly, and that bound is documented rather than called immediate. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
3ce4fe03fe
commit
80189c8ae2
@@ -0,0 +1,207 @@
|
||||
import { type FormEvent, type ReactElement, useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
approveDevicePairing,
|
||||
type EkklesiaHostConfig,
|
||||
type HostDeviceSummary,
|
||||
listHostDevices,
|
||||
lookupDevicePairing,
|
||||
revokeHostDevice,
|
||||
} from "../host-protocol.js";
|
||||
|
||||
/**
|
||||
* The administrator's whole device surface: type the code from a screen, name it, approve it, and
|
||||
* later take it away again.
|
||||
*
|
||||
* Deliberately small. Device identity belongs to the platform rather than to any module, so it has
|
||||
* to live in the host — but this is infrastructure plumbing, not a fleet-management product, and
|
||||
* there is no grouping, filtering, bulk action, targeting, health, or remote control here on
|
||||
* purpose (ADR 0036). It renders only for an administrator who actually holds `core.devices.manage`:
|
||||
* a viewer without it is told nothing about which devices exist.
|
||||
*/
|
||||
const panelStyles = {
|
||||
action: {
|
||||
background: "transparent",
|
||||
border: "1px solid #d6d3d1",
|
||||
borderRadius: "0.25rem",
|
||||
cursor: "pointer",
|
||||
font: "inherit",
|
||||
padding: "0.25rem 0.5rem",
|
||||
},
|
||||
input: {
|
||||
border: "1px solid #d6d3d1",
|
||||
borderRadius: "0.25rem",
|
||||
font: "inherit",
|
||||
minWidth: 0,
|
||||
padding: "0.25rem 0.5rem",
|
||||
width: "100%",
|
||||
},
|
||||
meta: { color: "#78716c", fontSize: "0.8125rem", margin: 0 },
|
||||
row: {
|
||||
alignItems: "center",
|
||||
borderTop: "1px solid #e7e5e4",
|
||||
display: "flex",
|
||||
gap: "0.5rem",
|
||||
justifyContent: "space-between",
|
||||
padding: "0.375rem 0",
|
||||
},
|
||||
section: { display: "grid", gap: "0.5rem" },
|
||||
title: { fontSize: "0.8125rem", fontWeight: 600, letterSpacing: "0.04em", margin: 0 },
|
||||
} as const;
|
||||
|
||||
type PairingStep =
|
||||
| { readonly step: "idle" }
|
||||
| { readonly step: "busy" }
|
||||
| { readonly step: "found"; readonly moduleId: string; readonly permissionId: string }
|
||||
| { readonly step: "error"; readonly message: string };
|
||||
|
||||
export interface DevicePanelProps {
|
||||
readonly config: EkklesiaHostConfig;
|
||||
}
|
||||
|
||||
export function DevicePanel(props: DevicePanelProps): ReactElement | undefined {
|
||||
const { config } = props;
|
||||
const [devices, setDevices] = useState<readonly HostDeviceSummary[] | undefined>(undefined);
|
||||
const [permitted, setPermitted] = useState(true);
|
||||
const [code, setCode] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [pairing, setPairing] = useState<PairingStep>({ step: "idle" });
|
||||
|
||||
const refresh = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
setDevices(await listHostDevices(config));
|
||||
} catch {
|
||||
// The panel simply does not render for someone who may not manage devices; it never explains
|
||||
// what it would have shown.
|
||||
setPermitted(false);
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
if (!permitted) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const lookUp = async (event: FormEvent): Promise<void> => {
|
||||
event.preventDefault();
|
||||
setPairing({ step: "busy" });
|
||||
try {
|
||||
const found = await lookupDevicePairing(config, code.trim());
|
||||
setPairing({ moduleId: found.moduleId, permissionId: found.permissionId, step: "found" });
|
||||
} catch {
|
||||
// One message for expired, consumed, mistyped, and never-existed alike.
|
||||
setPairing({ message: "That code is not waiting for approval.", step: "error" });
|
||||
}
|
||||
};
|
||||
|
||||
const approve = async (): Promise<void> => {
|
||||
setPairing({ step: "busy" });
|
||||
try {
|
||||
await approveDevicePairing(config, code.trim(), name.trim());
|
||||
setCode("");
|
||||
setName("");
|
||||
setPairing({ step: "idle" });
|
||||
await refresh();
|
||||
} catch {
|
||||
setPairing({ message: "That code could not be approved.", step: "error" });
|
||||
}
|
||||
};
|
||||
|
||||
const revoke = async (deviceId: string): Promise<void> => {
|
||||
try {
|
||||
await revokeHostDevice(config, deviceId);
|
||||
await refresh();
|
||||
} catch {
|
||||
// Left to the next refresh rather than asserting a failure the operator cannot act on.
|
||||
}
|
||||
await refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<section data-testid="host-devices" style={panelStyles.section}>
|
||||
<h2 style={panelStyles.title}>DISPLAY DEVICES</h2>
|
||||
|
||||
<form onSubmit={(event) => void lookUp(event)} style={{ display: "grid", gap: "0.375rem" }}>
|
||||
<label htmlFor="device-pairing-code" style={panelStyles.meta}>
|
||||
Pairing code shown on the screen
|
||||
</label>
|
||||
<input
|
||||
autoComplete="off"
|
||||
data-testid="device-pairing-code-input"
|
||||
id="device-pairing-code"
|
||||
inputMode="numeric"
|
||||
maxLength={6}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
style={panelStyles.input}
|
||||
value={code}
|
||||
/>
|
||||
<button data-testid="device-pairing-lookup" style={panelStyles.action} type="submit">
|
||||
Find display
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{pairing.step === "found" ? (
|
||||
<div data-testid="device-pairing-found" style={{ display: "grid", gap: "0.375rem" }}>
|
||||
<p style={panelStyles.meta}>
|
||||
A display is asking to show <strong>{pairing.moduleId}</strong>.
|
||||
</p>
|
||||
<label htmlFor="device-pairing-name" style={panelStyles.meta}>
|
||||
Name this display
|
||||
</label>
|
||||
<input
|
||||
autoComplete="off"
|
||||
data-testid="device-pairing-name"
|
||||
id="device-pairing-name"
|
||||
maxLength={128}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder="Foyer TV"
|
||||
style={panelStyles.input}
|
||||
value={name}
|
||||
/>
|
||||
<button
|
||||
data-testid="device-pairing-approve"
|
||||
disabled={name.trim().length === 0}
|
||||
onClick={() => void approve()}
|
||||
style={panelStyles.action}
|
||||
type="button"
|
||||
>
|
||||
Approve
|
||||
</button>
|
||||
</div>
|
||||
) : undefined}
|
||||
|
||||
{pairing.step === "error" ? (
|
||||
<p data-testid="device-pairing-error" style={panelStyles.meta}>
|
||||
{pairing.message}
|
||||
</p>
|
||||
) : undefined}
|
||||
|
||||
{devices !== undefined && devices.length === 0 ? (
|
||||
<p data-testid="device-list-empty" style={panelStyles.meta}>
|
||||
No displays are paired.
|
||||
</p>
|
||||
) : undefined}
|
||||
|
||||
{devices?.map((device) => (
|
||||
<div data-testid={`device-${device.id}`} key={device.id} style={panelStyles.row}>
|
||||
<span>
|
||||
{device.name}
|
||||
{device.revoked ? " (revoked)" : ""}
|
||||
</span>
|
||||
{device.revoked ? undefined : (
|
||||
<button
|
||||
data-testid={`device-revoke-${device.id}`}
|
||||
onClick={() => void revoke(device.id)}
|
||||
style={panelStyles.action}
|
||||
type="button"
|
||||
>
|
||||
Revoke
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
HostProtocolError,
|
||||
loadHostPrincipal,
|
||||
} from "../host-protocol.js";
|
||||
import { DevicePanel } from "./DevicePanel.js";
|
||||
import { LoginForm } from "./LoginForm.js";
|
||||
import { ModuleUiFrame } from "./ModuleUiFrame.js";
|
||||
|
||||
@@ -157,9 +158,13 @@ async function resolveBootstrapState(
|
||||
): Promise<ResolvedBootstrapState> {
|
||||
try {
|
||||
const bootstrap = await bootstrapHost(config, signal);
|
||||
return bootstrap.principal.kind === "anonymous"
|
||||
? { status: "anonymous" }
|
||||
: { bootstrap, status: "ready" };
|
||||
// Only a person signs into the Dashboard. The test is `=== "authenticated"` and never "not
|
||||
// anonymous", so a principal class added later cannot quietly become a Dashboard login — which
|
||||
// is precisely how a paired display device would otherwise have walked in (ADR 0036). In
|
||||
// practice `/api/v1/principal` never reports a device at all; this is the second lock.
|
||||
return bootstrap.principal.kind === "authenticated"
|
||||
? { bootstrap: { ...bootstrap, principal: bootstrap.principal }, status: "ready" }
|
||||
: { status: "anonymous" };
|
||||
} catch (error) {
|
||||
if (error instanceof HostProtocolError && error.code === "HOST_UNAUTHENTICATED") {
|
||||
return { status: "anonymous" };
|
||||
@@ -167,9 +172,9 @@ async function resolveBootstrapState(
|
||||
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" };
|
||||
return principal.kind === "authenticated"
|
||||
? { principal, status: "access-denied" }
|
||||
: { status: "anonymous" };
|
||||
} catch {
|
||||
return { status: "failed" };
|
||||
}
|
||||
@@ -454,6 +459,7 @@ export function HostApp(props: HostAppProps): ReactElement {
|
||||
</button>
|
||||
</header>
|
||||
<aside style={shellStyles.aside}>
|
||||
<DevicePanel config={config} />
|
||||
{entries.length === 0 && groups.length === 0 ? (
|
||||
<p data-testid="host-empty" style={{ color: "#57534e", margin: 0 }}>
|
||||
No installed module provides a user interface.
|
||||
|
||||
@@ -7,11 +7,13 @@ import {
|
||||
HostProtocolError,
|
||||
} from "../host-protocol.js";
|
||||
import { DisplayUiFrame } from "./DisplayUiFrame.js";
|
||||
import { PairingScreen } from "./PairingScreen.js";
|
||||
|
||||
type DisplayState =
|
||||
| { readonly status: "loading"; readonly generation: number }
|
||||
| { readonly status: "ready"; readonly bootstrap: DisplayHostBootstrap & { status: "ready" } }
|
||||
| { readonly status: "signed-out" }
|
||||
/** No identity this display can use yet: show a pairing code rather than a human login form. */
|
||||
| { readonly status: "pairing" }
|
||||
| { readonly status: "unavailable" }
|
||||
| { readonly status: "failed" };
|
||||
|
||||
@@ -93,24 +95,26 @@ export function DisplayApp(props: DisplayAppProps): ReactElement {
|
||||
if (abort.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
setState(
|
||||
bootstrap.status === "signed-out"
|
||||
? { status: "signed-out" }
|
||||
: { bootstrap, status: "ready" },
|
||||
);
|
||||
setState({ bootstrap, status: "ready" });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (abort.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
// A denied or unauthenticated descriptor is the ordinary state of a screen nobody has
|
||||
// paired yet, not an error worth logging on every wall in the building.
|
||||
if (
|
||||
error instanceof HostProtocolError &&
|
||||
(error.code === "DISPLAY_ACCESS_DENIED" || error.code === "HOST_UNAUTHENTICATED")
|
||||
) {
|
||||
setState({ status: "pairing" });
|
||||
return;
|
||||
}
|
||||
console.error("[ekklesia] display host bootstrap failed", error);
|
||||
setState(
|
||||
error instanceof HostProtocolError &&
|
||||
(error.code === "DISPLAY_ACCESS_DENIED" || error.code === "DISPLAY_NOT_AVAILABLE")
|
||||
error instanceof HostProtocolError && error.code === "DISPLAY_NOT_AVAILABLE"
|
||||
? { status: "unavailable" }
|
||||
: error instanceof HostProtocolError && error.code === "HOST_UNAUTHENTICATED"
|
||||
? { status: "signed-out" }
|
||||
: { status: "failed" },
|
||||
: { status: "failed" },
|
||||
);
|
||||
});
|
||||
return () => abort.abort();
|
||||
@@ -123,10 +127,8 @@ export function DisplayApp(props: DisplayAppProps): ReactElement {
|
||||
{state.status === "loading" ? (
|
||||
<DisplayMessage testId="display-host-loading">Loading display…</DisplayMessage>
|
||||
) : undefined}
|
||||
{state.status === "signed-out" ? (
|
||||
<DisplayMessage onRetry={retry} testId="display-host-signed-out">
|
||||
Sign in to use this display.
|
||||
</DisplayMessage>
|
||||
{state.status === "pairing" ? (
|
||||
<PairingScreen config={config} moduleId={moduleId} onRetry={retry} />
|
||||
) : undefined}
|
||||
{state.status === "unavailable" ? (
|
||||
<DisplayMessage onRetry={retry} testId="display-host-unavailable">
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { type ReactElement, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
type EkklesiaHostConfig,
|
||||
HostProtocolError,
|
||||
pollDevicePairing,
|
||||
requestDevicePairing,
|
||||
} from "../host-protocol.js";
|
||||
|
||||
/**
|
||||
* What an unpaired screen shows: a short code, and nothing else of consequence.
|
||||
*
|
||||
* This page is looked at by whoever walks past a television, so it deliberately carries no request
|
||||
* id, no claim secret, no permission id, no module internals, and no server URL beyond the one the
|
||||
* browser is already on. The code is the only thing on it that means anything, and the code is
|
||||
* useless on its own — approving it requires an administrator, and collecting the credential
|
||||
* requires the HttpOnly cookie this browser holds and nobody watching can see (ADR 0036).
|
||||
*/
|
||||
const pairingStyles = {
|
||||
code: {
|
||||
fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
|
||||
fontSize: "clamp(3rem, 14vw, 9rem)",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.15em",
|
||||
lineHeight: 1.1,
|
||||
margin: 0,
|
||||
},
|
||||
hint: { color: "#78716c", margin: 0, maxWidth: "40ch" },
|
||||
root: {
|
||||
alignItems: "center",
|
||||
background: "#0c0a09",
|
||||
color: "#fafaf9",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "1.5rem",
|
||||
height: "100%",
|
||||
justifyContent: "center",
|
||||
minHeight: "100dvh",
|
||||
padding: "2rem",
|
||||
textAlign: "center",
|
||||
},
|
||||
title: { fontFamily: "system-ui, sans-serif", fontSize: "1.25rem", fontWeight: 500, margin: 0 },
|
||||
} as const;
|
||||
|
||||
type PairingState =
|
||||
| { readonly status: "requesting" }
|
||||
| { readonly status: "waiting"; readonly code: string }
|
||||
| { readonly status: "unavailable" };
|
||||
|
||||
export interface PairingScreenProps {
|
||||
readonly config: EkklesiaHostConfig;
|
||||
readonly moduleId: string;
|
||||
/** Called once the host has issued this device its session, so the display mounts itself without
|
||||
* anyone touching the television. */
|
||||
readonly onRetry: () => void;
|
||||
}
|
||||
|
||||
export function PairingScreen(props: PairingScreenProps): ReactElement {
|
||||
const { config, moduleId, onRetry } = props;
|
||||
const [state, setState] = useState<PairingState>({ status: "requesting" });
|
||||
const pairedRef = useRef(onRetry);
|
||||
pairedRef.current = onRetry;
|
||||
|
||||
useEffect(() => {
|
||||
const abort = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let stopped = false;
|
||||
|
||||
const stop = (): void => {
|
||||
stopped = true;
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
const begin = async (): Promise<void> => {
|
||||
let requested: { code: string; pollIntervalMs: number };
|
||||
try {
|
||||
requested = await requestDevicePairing(config, moduleId, abort.signal);
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
// Never surfaces the underlying reason on a public screen.
|
||||
if (!(error instanceof HostProtocolError)) {
|
||||
console.error("[ekklesia] pairing request failed");
|
||||
}
|
||||
setState({ status: "unavailable" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (stopped || abort.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
setState({ code: requested.code, status: "waiting" });
|
||||
|
||||
const poll = async (): Promise<void> => {
|
||||
if (stopped || abort.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
let status: string;
|
||||
try {
|
||||
status = await pollDevicePairing(config, abort.signal);
|
||||
} catch {
|
||||
// A transient failure is not a reason to abandon a screen that may be on a wall; it asks
|
||||
// again on the next tick.
|
||||
timer = setTimeout(() => void poll(), requested.pollIntervalMs);
|
||||
return;
|
||||
}
|
||||
if (status === "paired") {
|
||||
stop();
|
||||
pairedRef.current();
|
||||
return;
|
||||
}
|
||||
if (status === "expired" || status === "unknown") {
|
||||
// The code aged out before anyone approved it. Draw a fresh one rather than leaving a
|
||||
// dead number on the screen.
|
||||
stop();
|
||||
void begin();
|
||||
return;
|
||||
}
|
||||
timer = setTimeout(() => void poll(), requested.pollIntervalMs);
|
||||
};
|
||||
timer = setTimeout(() => void poll(), requested.pollIntervalMs);
|
||||
};
|
||||
|
||||
void begin();
|
||||
return () => {
|
||||
stop();
|
||||
abort.abort();
|
||||
};
|
||||
}, [config, moduleId]);
|
||||
|
||||
return (
|
||||
<div data-testid="display-pairing" style={pairingStyles.root}>
|
||||
{state.status === "waiting" ? (
|
||||
<>
|
||||
<p style={pairingStyles.title}>Pair this display</p>
|
||||
<p data-testid="display-pairing-code" style={pairingStyles.code}>
|
||||
{state.code}
|
||||
</p>
|
||||
<p style={pairingStyles.hint}>
|
||||
Enter this code in the Ekklesia dashboard to connect this screen. Waiting for approval…
|
||||
</p>
|
||||
</>
|
||||
) : undefined}
|
||||
{state.status === "requesting" ? (
|
||||
<p style={pairingStyles.title}>Preparing this display…</p>
|
||||
) : undefined}
|
||||
{state.status === "unavailable" ? (
|
||||
<p data-testid="display-pairing-unavailable" style={pairingStyles.title}>
|
||||
This display is not available.
|
||||
</p>
|
||||
) : undefined}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -231,13 +231,37 @@ function parseDescriptor(entry: unknown): HostModuleUiDescriptor {
|
||||
*/
|
||||
export interface HostModuleDisplayResponse {
|
||||
readonly module: HostModuleUiDescriptor;
|
||||
/** Who the host resolved as the viewer. Read from the response that already authorized this
|
||||
* display rather than from `/api/v1/principal`, which answers only about people. */
|
||||
readonly viewer: ModuleUiPrincipal;
|
||||
}
|
||||
|
||||
/** Strictly validates the host's statement of who is viewing. Only the two principal kinds a
|
||||
* `restricted` display permission can admit are accepted — an anonymous viewer here would mean the
|
||||
* server authorized a display for nobody, which is a protocol violation rather than a state to
|
||||
* render. */
|
||||
function parseDisplayViewer(payload: unknown): ModuleUiPrincipal {
|
||||
if (hasExactKeys(payload, ["kind", "userId"]) && payload.kind === "authenticated") {
|
||||
const userId = nonEmptyString(payload.userId);
|
||||
if (userId !== undefined) {
|
||||
return Object.freeze({ kind: "authenticated" as const, userId });
|
||||
}
|
||||
}
|
||||
if (hasExactKeys(payload, ["deviceId", "kind"]) && payload.kind === "device") {
|
||||
const deviceId = nonEmptyString(payload.deviceId);
|
||||
if (deviceId !== undefined) {
|
||||
return Object.freeze({ deviceId, kind: "device" as const });
|
||||
}
|
||||
}
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
|
||||
/** Strictly validates the display descriptor response, including every nested URL container. */
|
||||
export function parseHostModuleDisplay(payload: unknown): HostModuleDisplayResponse {
|
||||
if (!hasExactKeys(payload, ["module"])) {
|
||||
if (!hasExactKeys(payload, ["module", "viewer"])) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
const viewer = parseDisplayViewer(payload.viewer);
|
||||
const entry = payload.module;
|
||||
if (
|
||||
!hasExactKeys(entry, ["api", "display", "id", "permissions", "realtime", "version"]) ||
|
||||
@@ -278,9 +302,207 @@ export function parseHostModuleDisplay(payload: unknown): HostModuleDisplayRespo
|
||||
uiUrl,
|
||||
version,
|
||||
}),
|
||||
viewer,
|
||||
});
|
||||
}
|
||||
|
||||
/** A same-origin, credential-carrying platform mutation. Mirrors `auth-protocol.ts`'s `postJson`:
|
||||
* `redirect: "error"` so a misconfigured deployment cannot silently follow a redirect with the
|
||||
* device's cookies attached, and no thrown value ever carries the request body. */
|
||||
async function requestPlatformMutation(
|
||||
config: EkklesiaHostConfig,
|
||||
rootRelativePath: string,
|
||||
body: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> {
|
||||
const performRequest = config.fetch ?? fetch;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await performRequest(resolveApiUrl(config, rootRelativePath), {
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
credentials: "include",
|
||||
headers: { accept: "application/json", "content-type": "application/json" },
|
||||
method: "POST",
|
||||
redirect: "error",
|
||||
...(signal ? { signal } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new HostProtocolError("HOST_REQUEST_FAILED", { cause: error });
|
||||
}
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new HostProtocolError("HOST_UNAUTHENTICATED");
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new HostProtocolError("HOST_REQUEST_FAILED");
|
||||
}
|
||||
try {
|
||||
return (await response.json()) as unknown;
|
||||
} catch {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the host to start pairing this screen, and returns the code to put on it.
|
||||
*
|
||||
* The response deliberately carries no secret. The value that proves this browser is the one that
|
||||
* asked travels in an HttpOnly cookie the host sets, so nothing here — and nothing anyone reads off
|
||||
* the screen — can be used to collect the device's credential (ADR 0036).
|
||||
*/
|
||||
export async function requestDevicePairing(
|
||||
config: EkklesiaHostConfig,
|
||||
moduleId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ readonly code: string; readonly pollIntervalMs: number }> {
|
||||
const payload = await requestPlatformMutation(
|
||||
config,
|
||||
"/api/v1/device-pairing/requests",
|
||||
{ moduleId },
|
||||
signal,
|
||||
);
|
||||
if (!hasExactKeys(payload, ["code", "expiresAt", "pollIntervalMs"])) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
const code = nonEmptyString(payload.code);
|
||||
const pollIntervalMs = payload.pollIntervalMs;
|
||||
if (
|
||||
code === undefined ||
|
||||
typeof pollIntervalMs !== "number" ||
|
||||
!Number.isFinite(pollIntervalMs)
|
||||
) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return Object.freeze({ code, pollIntervalMs: Math.max(1000, Math.trunc(pollIntervalMs)) });
|
||||
}
|
||||
|
||||
/** Asks whether this screen has been approved yet. When it has, the host issues the device session
|
||||
* in a `Set-Cookie` the browser stores and this code never sees. */
|
||||
export async function pollDevicePairing(
|
||||
config: EkklesiaHostConfig,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const payload = await requestPlatformMutation(
|
||||
config,
|
||||
"/api/v1/device-pairing/claims",
|
||||
{},
|
||||
signal,
|
||||
);
|
||||
if (!hasExactKeys(payload, ["status"])) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
const status = nonEmptyString(payload.status);
|
||||
if (status === undefined) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
/** One paired display, as the administrator's panel shows it. Deliberately no credential, no hash,
|
||||
* and no pairing history — none of that is anything an operator can act on. */
|
||||
export interface HostDeviceSummary {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly permissions: readonly string[];
|
||||
readonly revoked: boolean;
|
||||
}
|
||||
|
||||
export async function lookupDevicePairing(
|
||||
config: EkklesiaHostConfig,
|
||||
code: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ readonly moduleId: string; readonly permissionId: string }> {
|
||||
const payload = await requestPlatformMutation(
|
||||
config,
|
||||
"/api/v1/device-pairing/lookups",
|
||||
{ code },
|
||||
signal,
|
||||
);
|
||||
if (!hasExactKeys(payload, ["expiresAt", "moduleId", "permissionId", "requestedAt"])) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
const moduleId = nonEmptyString(payload.moduleId);
|
||||
const permissionId = nonEmptyString(payload.permissionId);
|
||||
if (moduleId === undefined || permissionId === undefined) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return Object.freeze({ moduleId, permissionId });
|
||||
}
|
||||
|
||||
export async function approveDevicePairing(
|
||||
config: EkklesiaHostConfig,
|
||||
code: string,
|
||||
deviceName: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
await requestPlatformMutation(
|
||||
config,
|
||||
"/api/v1/device-pairing/approvals",
|
||||
{ code, deviceName },
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
export async function listHostDevices(
|
||||
config: EkklesiaHostConfig,
|
||||
signal?: AbortSignal,
|
||||
): Promise<readonly HostDeviceSummary[]> {
|
||||
const payload = await requestPlatformJson(config, "/api/v1/devices", signal, {
|
||||
forbidden: "HOST_ACCESS_DENIED",
|
||||
});
|
||||
if (typeof payload !== "object" || payload === null || !("devices" in payload)) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
const entries = (payload as { devices: unknown }).devices;
|
||||
if (!Array.isArray(entries)) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return Object.freeze(
|
||||
entries.map((entry) => {
|
||||
const id = nonEmptyString((entry as { id?: unknown }).id);
|
||||
const name = nonEmptyString((entry as { name?: unknown }).name);
|
||||
const permissions = (entry as { permissions?: unknown }).permissions;
|
||||
if (id === undefined || name === undefined || !Array.isArray(permissions)) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return Object.freeze({
|
||||
id,
|
||||
name,
|
||||
permissions: Object.freeze(permissions.map((permission) => String(permission))),
|
||||
revoked: (entry as { revoked?: unknown }).revoked === true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function revokeHostDevice(
|
||||
config: EkklesiaHostConfig,
|
||||
deviceId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const performRequest = config.fetch ?? fetch;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await performRequest(
|
||||
resolveApiUrl(config, `/api/v1/devices/${encodeURIComponent(deviceId)}/revoke`),
|
||||
{
|
||||
body: "{}",
|
||||
cache: "no-store",
|
||||
credentials: "include",
|
||||
headers: { accept: "application/json", "content-type": "application/json" },
|
||||
method: "POST",
|
||||
redirect: "error",
|
||||
...(signal ? { signal } : {}),
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HostProtocolError("HOST_REQUEST_FAILED", { cause: error });
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new HostProtocolError("HOST_REQUEST_FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads one exact `/display/<module-id>` pathname without accepting a trailing path or traversal. */
|
||||
export function parseDisplayRoute(pathname: string): string {
|
||||
const match = /^\/display\/([^/]+)$/u.exec(pathname);
|
||||
@@ -480,43 +702,46 @@ export async function loadModuleDisplay(
|
||||
config: EkklesiaHostConfig,
|
||||
moduleId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<HostModuleUiDescriptor> {
|
||||
): Promise<HostModuleDisplayResponse> {
|
||||
const payload = await requestPlatformJson(config, moduleDisplayDescriptorPath(moduleId), signal, {
|
||||
forbidden: "DISPLAY_ACCESS_DENIED",
|
||||
notFound: "DISPLAY_NOT_AVAILABLE",
|
||||
});
|
||||
const descriptor = parseHostModuleDisplay(payload).module;
|
||||
if (descriptor.id !== moduleId) {
|
||||
const response = parseHostModuleDisplay(payload);
|
||||
if (response.module.id !== moduleId) {
|
||||
throw new HostProtocolError("HOST_RESPONSE_INVALID");
|
||||
}
|
||||
return descriptor;
|
||||
return response;
|
||||
}
|
||||
|
||||
export type DisplayHostBootstrap =
|
||||
| {
|
||||
readonly status: "signed-out";
|
||||
readonly principal: Extract<ModuleUiPrincipal, { readonly kind: "anonymous" }>;
|
||||
}
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly descriptor: HostModuleUiDescriptor;
|
||||
readonly principal: Extract<ModuleUiPrincipal, { readonly kind: "authenticated" }>;
|
||||
};
|
||||
export type DisplayHostBootstrap = {
|
||||
readonly status: "ready";
|
||||
readonly descriptor: HostModuleUiDescriptor;
|
||||
readonly principal: ModuleUiPrincipal;
|
||||
};
|
||||
|
||||
/** Principal first, then protected display metadata; anonymous browsers never probe a module id. */
|
||||
/**
|
||||
* Descriptor first, deliberately — the opposite of the Dashboard's principal-first bootstrap.
|
||||
*
|
||||
* The Dashboard asks who you are before asking what you may mount, because it is asking about a
|
||||
* person and `/api/v1/principal` answers that plainly. A display cannot: a paired device is
|
||||
* anonymous to that endpoint by design (ADR 0036), so a principal-first display would conclude that
|
||||
* every device in the building was signed out. The descriptor is the actual authorization boundary
|
||||
* for a display, and it reports the viewer it authorized, so one request settles both questions for
|
||||
* a person and a device alike.
|
||||
*
|
||||
* A denied descriptor throws `DISPLAY_ACCESS_DENIED`, which is what the host turns into pairing.
|
||||
*/
|
||||
export async function bootstrapDisplayHost(
|
||||
config: EkklesiaHostConfig,
|
||||
moduleId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<DisplayHostBootstrap> {
|
||||
const principal = await loadHostPrincipal(config, signal);
|
||||
if (principal.kind === "anonymous") {
|
||||
return Object.freeze({ principal, status: "signed-out" });
|
||||
}
|
||||
const response = await loadModuleDisplay(config, moduleId, signal);
|
||||
return Object.freeze({
|
||||
descriptor: await loadModuleDisplay(config, moduleId, signal),
|
||||
principal,
|
||||
status: "ready",
|
||||
descriptor: response.module,
|
||||
principal: response.viewer,
|
||||
status: "ready" as const,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user