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]>
216 lines
8.3 KiB
TypeScript
216 lines
8.3 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
import {
|
|
bootstrapDisplayHost,
|
|
loadModuleDisplay,
|
|
moduleDisplayDescriptorPath,
|
|
parseDisplayRoute,
|
|
parseHostModuleDisplay,
|
|
} from "../src/host-protocol.js";
|
|
|
|
const apiBaseUrl = "https://ekklesia.example.test";
|
|
|
|
function displayPayload(overrides: Record<string, unknown> = {}): {
|
|
readonly module: Record<string, unknown>;
|
|
readonly viewer: Record<string, unknown>;
|
|
} {
|
|
return {
|
|
// The host states who it authorized, so the display never has to infer it from the absence of a
|
|
// human session (ADR 0036).
|
|
viewer: { kind: "authenticated", userId: "user-1" },
|
|
module: {
|
|
api: { baseUrl: "/api/v1/modules/announcements" },
|
|
display: { url: "/api/v1/module-ui/announcements/1.2.0/display" },
|
|
id: "announcements",
|
|
permissions: ["announcements.slideshow.view"],
|
|
realtime: { baseUrl: "/api/v1/module-realtime/announcements" },
|
|
version: "1.2.0",
|
|
...overrides,
|
|
},
|
|
};
|
|
}
|
|
|
|
function json(body: unknown, status = 200): Response {
|
|
return new Response(JSON.stringify(body), {
|
|
headers: { "content-type": "application/json" },
|
|
status,
|
|
});
|
|
}
|
|
|
|
describe("display host protocol — strict descriptor", () => {
|
|
it("parses the exact display role into the generic mount descriptor", () => {
|
|
const parsed = parseHostModuleDisplay(displayPayload());
|
|
|
|
expect(parsed).toEqual({
|
|
module: {
|
|
apiBaseUrl: "/api/v1/modules/announcements",
|
|
id: "announcements",
|
|
permissions: ["announcements.slideshow.view"],
|
|
realtimeBaseUrl: "/api/v1/module-realtime/announcements",
|
|
uiUrl: "/api/v1/module-ui/announcements/1.2.0/display",
|
|
version: "1.2.0",
|
|
},
|
|
viewer: { kind: "authenticated", userId: "user-1" },
|
|
});
|
|
expect(Object.isFrozen(parsed)).toBe(true);
|
|
expect(Object.isFrozen(parsed.module)).toBe(true);
|
|
expect(Object.isFrozen(parsed.module.permissions)).toBe(true);
|
|
});
|
|
|
|
it("rejects malformed identities, shapes, permissions, and any non-root-relative URL", () => {
|
|
const invalid: unknown[] = [
|
|
{},
|
|
{ ...displayPayload(), extra: true },
|
|
displayPayload({ id: "Announcements" }),
|
|
displayPayload({ id: "announcements/other" }),
|
|
displayPayload({ id: "a".repeat(65) }),
|
|
displayPayload({ version: "v1.2.0" }),
|
|
displayPayload({ version: "01.2.0" }),
|
|
displayPayload({ permissions: "announcements.slideshow.view" }),
|
|
displayPayload({ permissions: [""] }),
|
|
displayPayload({
|
|
permissions: ["announcements.slideshow.view", "announcements.slideshow.view"],
|
|
}),
|
|
displayPayload({ api: { baseUrl: "https://evil.example.test/api" } }),
|
|
displayPayload({ display: { url: "//evil.example.test/display.js" } }),
|
|
displayPayload({ display: { url: "/display.js?token=secret" } }),
|
|
displayPayload({ display: { url: "/api/%2e%2e/grants" } }),
|
|
displayPayload({ display: { url: "/api/%2Fgrants" } }),
|
|
displayPayload({ display: { url: "/api//display.js" } }),
|
|
displayPayload({ realtime: { baseUrl: "/\\evil.example.test/live" } }),
|
|
displayPayload({ display: { url: "/display.js", extra: true } }),
|
|
];
|
|
|
|
for (const payload of invalid) {
|
|
expect(() => parseHostModuleDisplay(payload), JSON.stringify(payload)).toThrowError(
|
|
expect.objectContaining({ code: "HOST_RESPONSE_INVALID" }),
|
|
);
|
|
}
|
|
});
|
|
|
|
it("does not accept a Dashboard artifact in place of a display artifact", () => {
|
|
const module = (displayPayload() as { module: Record<string, unknown> }).module;
|
|
const { display: _display, ...withoutDisplay } = module;
|
|
|
|
expect(() =>
|
|
parseHostModuleDisplay({
|
|
module: {
|
|
...withoutDisplay,
|
|
ui: { url: "/api/v1/module-ui/announcements/1.2.0" },
|
|
},
|
|
}),
|
|
).toThrowError(expect.objectContaining({ code: "HOST_RESPONSE_INVALID" }));
|
|
});
|
|
});
|
|
|
|
describe("display host protocol — outer route", () => {
|
|
it("accepts one exact stable version-independent module route", () => {
|
|
expect(parseDisplayRoute("/display/announcements")).toBe("announcements");
|
|
expect(moduleDisplayDescriptorPath("announcements")).toBe(
|
|
"/api/v1/module-displays/announcements",
|
|
);
|
|
});
|
|
|
|
it("rejects extra segments, trailing slashes, malformed escapes, and path escapes", () => {
|
|
for (const pathname of [
|
|
"/display",
|
|
"/display/",
|
|
"/display/announcements/",
|
|
"/display/announcements/settings",
|
|
"/display/%2fapi",
|
|
"/display/..",
|
|
"/display/%",
|
|
"/modules/announcements/display",
|
|
]) {
|
|
expect(() => parseDisplayRoute(pathname), pathname).toThrowError(
|
|
expect.objectContaining({ code: "DISPLAY_ROUTE_INVALID" }),
|
|
);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("display host protocol — authenticated bootstrap", () => {
|
|
it("asks only the descriptor, which is the display's actual authorization boundary", async () => {
|
|
const calls: Array<{ init: RequestInit | undefined; url: string }> = [];
|
|
const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = String(input);
|
|
calls.push({ init, url });
|
|
return json(displayPayload());
|
|
}) as unknown as typeof globalThis.fetch;
|
|
|
|
const bootstrap = await bootstrapDisplayHost({ apiBaseUrl, fetch }, "announcements");
|
|
|
|
expect(bootstrap.status).toBe("ready");
|
|
// Deliberately **not** principal-first, unlike the Dashboard: `/api/v1/principal` answers about
|
|
// people, and a paired device is anonymous to it by design, so asking it first would conclude
|
|
// that every display in the building was signed out (ADR 0036).
|
|
expect(calls.map((call) => call.url)).toEqual([
|
|
`${apiBaseUrl}/api/v1/module-displays/announcements`,
|
|
]);
|
|
expect(calls.every((call) => call.init?.credentials === "include")).toBe(true);
|
|
});
|
|
|
|
it("reports the viewer the host authorized, for a person and for a device alike", async () => {
|
|
const forViewer = async (viewer: Record<string, unknown>) => {
|
|
const fetch = vi.fn(async () =>
|
|
json({ ...displayPayload(), viewer }),
|
|
) as unknown as typeof globalThis.fetch;
|
|
return bootstrapDisplayHost({ apiBaseUrl, fetch }, "announcements");
|
|
};
|
|
|
|
expect((await forViewer({ kind: "authenticated", userId: "user-1" })).principal).toEqual({
|
|
kind: "authenticated",
|
|
userId: "user-1",
|
|
});
|
|
expect(
|
|
(await forViewer({ deviceId: "3f1c8a4e-1d2b-4c3a-9e5f-6a7b8c9d0e1f", kind: "device" }))
|
|
.principal,
|
|
).toEqual({ deviceId: "3f1c8a4e-1d2b-4c3a-9e5f-6a7b8c9d0e1f", kind: "device" });
|
|
});
|
|
|
|
it("refuses a descriptor that claims an anonymous or malformed viewer", async () => {
|
|
// A `restricted` display permission admits no anonymous principal, so a server saying it
|
|
// authorized one is a protocol violation rather than a state to render.
|
|
for (const viewer of [
|
|
{ kind: "anonymous" },
|
|
{ kind: "device" },
|
|
{ kind: "authenticated" },
|
|
{ deviceId: "", kind: "device" },
|
|
{ kind: "device", userId: "user-1" },
|
|
]) {
|
|
expect(() => parseHostModuleDisplay({ ...displayPayload(), viewer })).toThrowError(
|
|
expect.objectContaining({ code: "HOST_RESPONSE_INVALID" }),
|
|
);
|
|
}
|
|
});
|
|
|
|
it("distinguishes denied, unavailable, unauthenticated, and infrastructure failures safely", async () => {
|
|
for (const [status, code] of [
|
|
[401, "HOST_UNAUTHENTICATED"],
|
|
[403, "DISPLAY_ACCESS_DENIED"],
|
|
[404, "DISPLAY_NOT_AVAILABLE"],
|
|
[503, "HOST_REQUEST_FAILED"],
|
|
] as const) {
|
|
const fetch = vi.fn(async () =>
|
|
json({ detail: "/srv/modules/announcements secret-token" }, status),
|
|
) as unknown as typeof globalThis.fetch;
|
|
const error = await loadModuleDisplay({ apiBaseUrl, fetch }, "announcements").catch(
|
|
(caught: unknown) => caught,
|
|
);
|
|
|
|
expect(error).toMatchObject({ code });
|
|
expect((error as Error).message).not.toContain("/srv/");
|
|
expect((error as Error).message).not.toContain("secret-token");
|
|
}
|
|
});
|
|
|
|
it("rejects a stale or misrouted descriptor whose identity differs from the requested display", async () => {
|
|
const fetch = vi.fn(async () =>
|
|
json(displayPayload({ id: "calendar" })),
|
|
) as unknown as typeof globalThis.fetch;
|
|
|
|
await expect(loadModuleDisplay({ apiBaseUrl, fetch }, "announcements")).rejects.toMatchObject({
|
|
code: "HOST_RESPONSE_INVALID",
|
|
});
|
|
});
|
|
});
|