feat: give display devices their own paired identity
CI / verify (pull_request) Successful in 40s
CI / infrastructure-smoke (pull_request) Successful in 21s
CI / migration-smoke (pull_request) Successful in 1m22s

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:
ekklesia
2026-08-23 23:41:03 -05:00
co-authored by Claude Opus 5
parent 3ce4fe03fe
commit 80189c8ae2
52 changed files with 5065 additions and 113 deletions
+248 -23
View File
@@ -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,
});
}