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
@@ -10,6 +10,7 @@ import type {
|
||||
PermissionRegistry,
|
||||
} from "@ekklesia/core/authorization";
|
||||
import type { DashboardStore } from "@ekklesia/core/dashboard";
|
||||
import type { DeviceStore } from "@ekklesia/core/devices";
|
||||
import { type EkklesiaIdentityRuntime, IdentityRuntimeError } from "@ekklesia/core/identity";
|
||||
import type {
|
||||
DiscoveredModule,
|
||||
@@ -27,6 +28,7 @@ import { Hono } from "hono";
|
||||
import { cors } from "hono/cors";
|
||||
import { AUTH_REQUEST_MAX_BODY_BYTES, platformBodyLimit } from "./body-limits.js";
|
||||
import { createDashboardRoutes } from "./dashboard-routes.js";
|
||||
import { createDeviceRoutes } from "./device-routes.js";
|
||||
import type { DisplayHostAssets } from "./display-host-assets.js";
|
||||
import { createGrantsRoutes } from "./grants-routes.js";
|
||||
import { createModuleConfigurationRoutes } from "./module-configuration-routes.js";
|
||||
@@ -68,6 +70,17 @@ export interface CreateApiAppOptions {
|
||||
* is: a caller that publishes no module UI must say so explicitly with an empty registry, never
|
||||
* fall through to an implicit one. See `./module-ui-routes.js`. */
|
||||
readonly moduleUi: ModuleUiPublicationRegistry;
|
||||
/**
|
||||
* Managed display devices. Optional so every existing composition — and every test that has no
|
||||
* interest in devices — builds unchanged; when it is absent no pairing route is mounted, no
|
||||
* device cookie is ever read, and a device principal simply cannot come into being.
|
||||
*/
|
||||
readonly devices?: {
|
||||
readonly store: DeviceStore;
|
||||
/** Whether the deployment is reached over https, so the device cookies can assert `Secure`
|
||||
* without becoming unusable on a plaintext development origin. */
|
||||
readonly secureCookies: boolean;
|
||||
};
|
||||
/** Surface-owned display host assets, read once by production startup. Optional only when the
|
||||
* eligible publication registry contains no display entrypoint; route composition rejects an
|
||||
* inconsistent display-bearing registry synchronously. */
|
||||
@@ -369,6 +382,23 @@ export function createApiApp(options: CreateApiAppOptions): Hono {
|
||||
...(options.displayHostAssets ? { assets: options.displayHostAssets } : {}),
|
||||
});
|
||||
|
||||
if (options.devices) {
|
||||
// Host-owned device identity. Siblings of `/api/v1/modules/...`, reachable by no module, and
|
||||
// mounted only when the deployment actually composed device support.
|
||||
app.route(
|
||||
"/",
|
||||
createDeviceRoutes({
|
||||
devices: options.devices.store,
|
||||
evaluator: options.authorization.evaluator,
|
||||
moduleUi: options.moduleUi,
|
||||
registry: options.authorization.registry,
|
||||
runtime,
|
||||
secureCookies: options.devices.secureCookies,
|
||||
trustedOrigins: allowedOrigins,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Layered deliberately on top of the generic inventory above rather than merged into it: the
|
||||
// inventory stays the host-neutral "what is mountable" contract a standalone host could consume,
|
||||
// and this adds Ekklesia's own presentation of those same modules. See `./dashboard-routes.js`.
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type DashboardDrizzleDatabase,
|
||||
} from "@ekklesia/core/dashboard";
|
||||
import { createValidatedPostgresPool, type PostgresPoolOptions } from "@ekklesia/core/database";
|
||||
import { createDeviceDrizzleView, type DeviceDrizzleDatabase } from "@ekklesia/core/devices";
|
||||
import { createIdentityDrizzleView, type IdentityDrizzleDatabase } from "@ekklesia/core/identity";
|
||||
import {
|
||||
createModuleConfigurationView,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
|
||||
export interface ApiDatabaseHandle {
|
||||
readonly authorization: AuthorizationDrizzleDatabase;
|
||||
readonly devices: DeviceDrizzleDatabase;
|
||||
readonly dashboard: DashboardDrizzleDatabase;
|
||||
readonly identity: IdentityDrizzleDatabase;
|
||||
readonly module: ModuleDatabase;
|
||||
@@ -50,6 +52,7 @@ export function createApiDatabase(
|
||||
return Object.freeze({
|
||||
authorization: createAuthorizationDrizzleView(pool),
|
||||
close,
|
||||
devices: createDeviceDrizzleView(pool),
|
||||
dashboard: createDashboardDrizzleView(pool),
|
||||
identity: createIdentityDrizzleView(pool),
|
||||
module: createModuleDatabaseView(pool),
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createDevicePrincipal, type EkklesiaPrincipal } from "@ekklesia/contracts";
|
||||
import type { DeviceStore } from "@ekklesia/core/devices";
|
||||
import { DEVICE_LAST_SEEN_THROTTLE_MS } from "@ekklesia/core/devices";
|
||||
import type { EkklesiaIdentityRuntime } from "@ekklesia/core/identity";
|
||||
import { DEVICE_SESSION_COOKIE } from "./device-routes.js";
|
||||
|
||||
/**
|
||||
* Extends principal resolution with managed devices, without touching how a *person* is resolved
|
||||
* (ADR 0036).
|
||||
*
|
||||
* Composition rather than modification is deliberate. Core's identity runtime is the Better Auth
|
||||
* boundary and knows only about human sessions; teaching it about devices would put two unrelated
|
||||
* credential systems behind one implementation and make "which one answered?" an internal detail.
|
||||
* Wrapping keeps Better Auth's behaviour byte-for-byte unchanged — including that an infrastructure
|
||||
* failure still throws rather than degrading to anonymous — and adds exactly one fallback.
|
||||
*
|
||||
* **A human session always wins.** If Better Auth resolves a person, that is the answer and the
|
||||
* device cookie is never even read. This matters because a browser can hold both: an administrator
|
||||
* who opens a display page on their own laptop after pairing it stays themself, and no device
|
||||
* cookie can dilute or replace a human identity.
|
||||
*
|
||||
* Because every gate in the platform — the display page, the descriptor, module HTTP routes,
|
||||
* realtime — resolves principals through this one function, a device becomes a principal in exactly
|
||||
* one place, and every authorization decision about it is still made by the ordinary evaluator.
|
||||
*/
|
||||
export interface DevicePrincipalOptions {
|
||||
readonly runtime: EkklesiaIdentityRuntime;
|
||||
readonly devices: DeviceStore;
|
||||
readonly now?: () => Date;
|
||||
}
|
||||
|
||||
/** RFC 6265 `cookie-string` parsing, matching how Core's own session-cookie detection reads a
|
||||
* header: split on `;`, take the text before the first `=` as the name, compare whole names
|
||||
* exactly. Never a substring test, so `x_ekklesia_device_session` is correctly not a match. */
|
||||
function readCookie(headers: Headers, name: string): string | undefined {
|
||||
const header = headers.get("cookie");
|
||||
if (header === null) {
|
||||
return undefined;
|
||||
}
|
||||
for (const pair of header.split(";")) {
|
||||
const separator = pair.indexOf("=");
|
||||
if (separator === -1) {
|
||||
continue;
|
||||
}
|
||||
if (pair.slice(0, separator).trim() === name) {
|
||||
const value = pair.slice(separator + 1).trim();
|
||||
return value.length === 0 ? undefined : value;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function withDevicePrincipals(options: DevicePrincipalOptions): EkklesiaIdentityRuntime {
|
||||
const now = options.now ?? ((): Date => new Date());
|
||||
|
||||
return Object.freeze({
|
||||
handleAuthRequest: (request: Request): Promise<Response> =>
|
||||
options.runtime.handleAuthRequest(request),
|
||||
|
||||
async resolvePrincipal(headers: Headers): Promise<EkklesiaPrincipal> {
|
||||
// Unchanged, including its failure behaviour: a genuine outage still throws rather than
|
||||
// silently letting a device credential answer a question about a person.
|
||||
const human = await options.runtime.resolvePrincipal(headers);
|
||||
if (human.kind !== "anonymous") {
|
||||
return human;
|
||||
}
|
||||
|
||||
const credential = readCookie(headers, DEVICE_SESSION_COOKIE);
|
||||
if (credential === undefined) {
|
||||
return human;
|
||||
}
|
||||
|
||||
const at = now();
|
||||
const device = await options.devices.resolveCredential(credential, at);
|
||||
if (!device) {
|
||||
// A revoked, expired, or simply wrong credential is anonymous — never an error the caller
|
||||
// could use to tell those three apart.
|
||||
return human;
|
||||
}
|
||||
|
||||
// Throttled here as well as in SQL: the common case must not even issue a statement, or a
|
||||
// display polling realtime would turn an operational nicety into continuous write traffic.
|
||||
const lastSeen = device.lastSeenAt;
|
||||
if (
|
||||
lastSeen === undefined ||
|
||||
at.getTime() - lastSeen.getTime() >= DEVICE_LAST_SEEN_THROTTLE_MS
|
||||
) {
|
||||
await options.devices.touchLastSeen(device.deviceId, at).catch(() => undefined);
|
||||
}
|
||||
|
||||
return createDevicePrincipal(device.deviceId);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
import { safeParseEkklesiaDeviceId } from "@ekklesia/contracts";
|
||||
import { CORE_DEVICES_MANAGE } from "@ekklesia/core/authorization";
|
||||
import type { DeviceStore } from "@ekklesia/core/devices";
|
||||
import { DEVICE_CREDENTIAL_TTL_MS } from "@ekklesia/core/devices";
|
||||
import type { ModuleUiPublicationRegistry } from "@ekklesia/core/modules";
|
||||
import type { Context, Hono } from "hono";
|
||||
import { Hono as HonoApp } from "hono";
|
||||
import { getCookie, setCookie } from "hono/cookie";
|
||||
import {
|
||||
type AuthorizationMiddlewareOptions,
|
||||
getAuthorizedPrincipal,
|
||||
requirePermission,
|
||||
requireTrustedOrigin,
|
||||
} from "./authorization-middleware.js";
|
||||
import { CORE_MUTATION_MAX_BODY_BYTES, platformBodyLimit } from "./body-limits.js";
|
||||
|
||||
/**
|
||||
* Host-owned device identity transport: pairing a display, and managing what has been paired
|
||||
* (ADR 0036).
|
||||
*
|
||||
* Both prefixes are siblings of `/api/v1/modules/...` and cannot collide with any module route.
|
||||
* Nothing here is reachable by module code, and no module-facing contract mentions any of it — a
|
||||
* module receives a principal and its permissions, and never learns that pairing exists.
|
||||
*/
|
||||
export const DEVICE_PAIRING_PREFIX = "/api/v1/device-pairing";
|
||||
export const DEVICES_PREFIX = "/api/v1/devices";
|
||||
|
||||
/**
|
||||
* The device's two cookies, deliberately named nothing like Better Auth's session cookie.
|
||||
*
|
||||
* Distinct names are what keep the two identity systems from being confused for one another: the
|
||||
* human resolver looks only for Better Auth's cookie and the device resolver looks only for these,
|
||||
* so neither can ever be satisfied by the other's credential no matter what a caller sends.
|
||||
*/
|
||||
export const DEVICE_PAIRING_COOKIE = "ekklesia_device_pairing";
|
||||
export const DEVICE_SESSION_COOKIE = "ekklesia_device_session";
|
||||
|
||||
/** How often an unpaired screen should ask again. Slow enough that a waiting display is not a load
|
||||
* source, fast enough that someone standing at the screen sees it come alive. */
|
||||
export const DEVICE_PAIRING_POLL_INTERVAL_MS = 3_000;
|
||||
|
||||
export interface DeviceRoutesOptions extends AuthorizationMiddlewareOptions {
|
||||
readonly devices: DeviceStore;
|
||||
/** The same eligible/running publication registry the display routes use. It is the only source
|
||||
* of the permission a pairing request may ask for. */
|
||||
readonly moduleUi: ModuleUiPublicationRegistry;
|
||||
readonly trustedOrigins: ReadonlySet<string>;
|
||||
/** True when the platform is reached over https, which is what `Secure` requires to be usable at
|
||||
* all. Derived from the validated identity base URL, never from a request. */
|
||||
readonly secureCookies: boolean;
|
||||
readonly now?: () => Date;
|
||||
}
|
||||
|
||||
function noStore(c: Context): void {
|
||||
c.header("Cache-Control", "no-store");
|
||||
}
|
||||
|
||||
function sanitizedFailure(c: Context, status: 400 | 403 | 404 | 503, code: string): Response {
|
||||
noStore(c);
|
||||
return c.json({ code }, status);
|
||||
}
|
||||
|
||||
async function readJsonObject(c: Context): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const body: unknown = await c.req.json();
|
||||
return typeof body === "object" && body !== null && !Array.isArray(body)
|
||||
? (body as Record<string, unknown>)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function readString(body: Record<string, unknown>, key: string, max: number): string | undefined {
|
||||
const value = body[key];
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length === 0 || trimmed.length > max ? undefined : trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes one of the device cookies.
|
||||
*
|
||||
* `HttpOnly` so no script — least of all a module's display bundle, which runs in this very page —
|
||||
* can read the value; `SameSite=Strict` because a display only ever talks to the host that serves
|
||||
* it and nothing legitimate arrives cross-site; host-only (no `Domain`) so a sibling hostname
|
||||
* cannot claim it; `Path=/` because the credential is presented to the descriptor, the module API,
|
||||
* and realtime alike. `Secure` follows the deployment's own scheme — asserting it on a plaintext
|
||||
* development origin would make the cookie silently unusable rather than more secure.
|
||||
*/
|
||||
function writeDeviceCookie(
|
||||
c: Context,
|
||||
options: DeviceRoutesOptions,
|
||||
name: string,
|
||||
value: string,
|
||||
maxAgeSeconds: number,
|
||||
): void {
|
||||
setCookie(c, name, value, {
|
||||
httpOnly: true,
|
||||
maxAge: maxAgeSeconds,
|
||||
path: "/",
|
||||
sameSite: "Strict",
|
||||
secure: options.secureCookies,
|
||||
});
|
||||
}
|
||||
|
||||
export function createDeviceRoutes(options: DeviceRoutesOptions): Hono {
|
||||
const routes = new HonoApp();
|
||||
const now = options.now ?? ((): Date => new Date());
|
||||
const requireManage = requirePermission(options, CORE_DEVICES_MANAGE);
|
||||
const requireOrigin = requireTrustedOrigin(options.trustedOrigins);
|
||||
const mutationBodyLimit = platformBodyLimit(CORE_MUTATION_MAX_BODY_BYTES);
|
||||
|
||||
/**
|
||||
* An unpaired display asks to be paired.
|
||||
*
|
||||
* The **only** thing the caller supplies is which module's display it is sitting on, and even
|
||||
* that is not taken at its word: the module is looked up in the publication registry and the
|
||||
* permission is read from that module's validated display declaration. A browser therefore cannot
|
||||
* ask to be granted `core.devices.manage`, another module's permission, or anything else — the
|
||||
* request records the permission the host derived, and approval grants exactly that.
|
||||
*/
|
||||
routes.post(
|
||||
`${DEVICE_PAIRING_PREFIX}/requests`,
|
||||
requireOrigin,
|
||||
mutationBodyLimit,
|
||||
async (c: Context) => {
|
||||
const body = await readJsonObject(c);
|
||||
const moduleId = body === undefined ? undefined : readString(body, "moduleId", 128);
|
||||
if (moduleId === undefined) {
|
||||
return sanitizedFailure(c, 400, "INVALID_REQUEST");
|
||||
}
|
||||
const display = options.moduleUi
|
||||
.listDisplays()
|
||||
.find((candidate) => candidate.moduleId === moduleId);
|
||||
if (!display) {
|
||||
// Unknown, dashboard-only, disabled, or dependency-blocked all answer the same way, so
|
||||
// pairing never becomes a way to enumerate what is installed.
|
||||
return sanitizedFailure(c, 404, "NOT_FOUND");
|
||||
}
|
||||
|
||||
try {
|
||||
const at = now();
|
||||
const created = await options.devices.createPairingRequest({
|
||||
moduleId: display.moduleId,
|
||||
now: at,
|
||||
permissionId: display.displayPermission,
|
||||
});
|
||||
writeDeviceCookie(
|
||||
c,
|
||||
options,
|
||||
DEVICE_PAIRING_COOKIE,
|
||||
created.claimSecret,
|
||||
Math.max(1, Math.ceil((created.expiresAt.getTime() - at.getTime()) / 1000)),
|
||||
);
|
||||
noStore(c);
|
||||
// The code is returned because it has to be shown on the screen. The claim secret is not:
|
||||
// it goes only into the HttpOnly cookie above, so reading the code off a television tells
|
||||
// an onlooker nothing they could use.
|
||||
return c.json(
|
||||
{
|
||||
code: created.code,
|
||||
expiresAt: created.expiresAt.toISOString(),
|
||||
pollIntervalMs: DEVICE_PAIRING_POLL_INTERVAL_MS,
|
||||
},
|
||||
201,
|
||||
);
|
||||
} catch {
|
||||
return sanitizedFailure(c, 503, "DEVICE_PAIRING_UNAVAILABLE");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* The display asks whether it has been approved yet, and collects its credential when it has.
|
||||
*
|
||||
* Authority here is the claim cookie and nothing else. The pairing code is not accepted — it is
|
||||
* public, printed across a screen, and a flow that issued a credential to whoever presented it
|
||||
* would hand the device's identity to anyone who walked past. Consumption is single-use inside
|
||||
* the store, so a replayed or concurrent claim never yields a second credential.
|
||||
*/
|
||||
routes.post(
|
||||
`${DEVICE_PAIRING_PREFIX}/claims`,
|
||||
requireOrigin,
|
||||
mutationBodyLimit,
|
||||
async (c: Context) => {
|
||||
const claimSecret = getCookie(c, DEVICE_PAIRING_COOKIE);
|
||||
if (claimSecret === undefined || claimSecret.length === 0) {
|
||||
return sanitizedFailure(c, 400, "DEVICE_PAIRING_UNKNOWN");
|
||||
}
|
||||
try {
|
||||
const at = now();
|
||||
const result = await options.devices.claimPairingRequest({ claimSecret, now: at });
|
||||
noStore(c);
|
||||
if (result.paired) {
|
||||
writeDeviceCookie(
|
||||
c,
|
||||
options,
|
||||
DEVICE_SESSION_COOKIE,
|
||||
result.paired.credential,
|
||||
Math.floor(DEVICE_CREDENTIAL_TTL_MS / 1000),
|
||||
);
|
||||
// The pairing cookie has done its job; leaving it would keep a spent secret on the device.
|
||||
writeDeviceCookie(c, options, DEVICE_PAIRING_COOKIE, "", 0);
|
||||
// Deliberately no credential, device id, or permission in the body: the browser needs to
|
||||
// know only that it may now load the display, and everything it needs travels in the
|
||||
// Set-Cookie header where script cannot reach it.
|
||||
return c.json({ status: "paired" as const }, 200);
|
||||
}
|
||||
return c.json({ status: result.status }, 200);
|
||||
} catch {
|
||||
return sanitizedFailure(c, 503, "DEVICE_PAIRING_UNAVAILABLE");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* An administrator types the code from the screen and sees what it is asking for, before deciding.
|
||||
*
|
||||
* The code travels in a request body rather than a path or query so it does not land in access
|
||||
* logs, browser history, or a `Referer`. Reaching this at all requires `core.devices.manage`, so
|
||||
* it is not an enumeration oracle for anyone who is not already trusted to approve pairings.
|
||||
*/
|
||||
routes.post(
|
||||
`${DEVICE_PAIRING_PREFIX}/lookups`,
|
||||
requireOrigin,
|
||||
mutationBodyLimit,
|
||||
requireManage,
|
||||
async (c: Context) => {
|
||||
const body = await readJsonObject(c);
|
||||
const code = body === undefined ? undefined : readString(body, "code", 16);
|
||||
if (code === undefined || !/^[0-9]{6}$/u.test(code)) {
|
||||
return sanitizedFailure(c, 400, "INVALID_REQUEST");
|
||||
}
|
||||
try {
|
||||
const found = await options.devices.findPendingByCode(code, now());
|
||||
if (!found) {
|
||||
return sanitizedFailure(c, 404, "DEVICE_PAIRING_UNKNOWN");
|
||||
}
|
||||
noStore(c);
|
||||
return c.json(
|
||||
{
|
||||
expiresAt: found.expiresAt.toISOString(),
|
||||
moduleId: found.moduleId,
|
||||
permissionId: found.permissionId,
|
||||
requestedAt: found.createdAt.toISOString(),
|
||||
},
|
||||
200,
|
||||
);
|
||||
} catch {
|
||||
return sanitizedFailure(c, 503, "DEVICE_PAIRING_UNAVAILABLE");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/** Approval. The administrator names the device; the unpaired screen never names itself. */
|
||||
routes.post(
|
||||
`${DEVICE_PAIRING_PREFIX}/approvals`,
|
||||
requireOrigin,
|
||||
mutationBodyLimit,
|
||||
requireManage,
|
||||
async (c: Context) => {
|
||||
const body = await readJsonObject(c);
|
||||
const code = body === undefined ? undefined : readString(body, "code", 16);
|
||||
const deviceName = body === undefined ? undefined : readString(body, "deviceName", 128);
|
||||
if (code === undefined || !/^[0-9]{6}$/u.test(code) || deviceName === undefined) {
|
||||
return sanitizedFailure(c, 400, "INVALID_REQUEST");
|
||||
}
|
||||
const principal = getAuthorizedPrincipal(c);
|
||||
if (principal.kind !== "authenticated") {
|
||||
// Unreachable through `requireManage`, which only ever admits a person. Stated rather than
|
||||
// assumed, so a device could never be recorded as having approved its own pairing.
|
||||
return sanitizedFailure(c, 403, "AUTHORIZATION_DENIED");
|
||||
}
|
||||
try {
|
||||
const approved = await options.devices.approvePairingRequest({
|
||||
approvedBy: principal.userId,
|
||||
code,
|
||||
deviceName,
|
||||
now: now(),
|
||||
});
|
||||
if (!approved) {
|
||||
// Expired, already approved, already consumed, or never existed. One answer for all of
|
||||
// them: which one it was is not information this endpoint owes anybody.
|
||||
return sanitizedFailure(c, 404, "DEVICE_PAIRING_UNKNOWN");
|
||||
}
|
||||
noStore(c);
|
||||
return c.json({ moduleId: approved.moduleId, permissionId: approved.permissionId }, 200);
|
||||
} catch {
|
||||
return sanitizedFailure(c, 503, "DEVICE_PAIRING_UNAVAILABLE");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
routes.get(DEVICES_PREFIX, requireManage, async (c: Context) => {
|
||||
try {
|
||||
const devices = await options.devices.listDevices();
|
||||
noStore(c);
|
||||
return c.json(
|
||||
{
|
||||
devices: devices.map((device) => ({
|
||||
createdAt: device.createdAt.toISOString(),
|
||||
id: device.id,
|
||||
name: device.name,
|
||||
permissions: device.permissions,
|
||||
revoked: device.revokedAt !== undefined,
|
||||
...(device.lastSeenAt === undefined
|
||||
? {}
|
||||
: { lastSeenAt: device.lastSeenAt.toISOString() }),
|
||||
...(device.revokedAt === undefined
|
||||
? {}
|
||||
: { revokedAt: device.revokedAt.toISOString() }),
|
||||
})),
|
||||
},
|
||||
200,
|
||||
);
|
||||
} catch {
|
||||
return sanitizedFailure(c, 503, "DEVICE_LOOKUP_UNAVAILABLE");
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Revocation, which is a server-side fact rather than a request that the remote browser discard
|
||||
* anything. The device's own copy of its credential keeps existing and stops working.
|
||||
*/
|
||||
routes.post(
|
||||
`${DEVICES_PREFIX}/:deviceId/revoke`,
|
||||
requireOrigin,
|
||||
mutationBodyLimit,
|
||||
requireManage,
|
||||
async (c: Context) => {
|
||||
const parsed = safeParseEkklesiaDeviceId(c.req.param("deviceId"));
|
||||
if (!parsed.success) {
|
||||
return sanitizedFailure(c, 400, "INVALID_REQUEST");
|
||||
}
|
||||
const principal = getAuthorizedPrincipal(c);
|
||||
if (principal.kind !== "authenticated") {
|
||||
return sanitizedFailure(c, 403, "AUTHORIZATION_DENIED");
|
||||
}
|
||||
try {
|
||||
await options.devices.revokeDevice({
|
||||
deviceId: parsed.data,
|
||||
now: now(),
|
||||
revokedBy: principal.userId,
|
||||
});
|
||||
} catch {
|
||||
return sanitizedFailure(c, 404, "NOT_FOUND");
|
||||
}
|
||||
noStore(c);
|
||||
return c.body(null, 204);
|
||||
},
|
||||
);
|
||||
|
||||
return routes;
|
||||
}
|
||||
@@ -39,8 +39,22 @@ export interface HostModuleDisplayDescriptor {
|
||||
readonly permissions: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Who the host resolved as the viewer of this display.
|
||||
*
|
||||
* The descriptor reports it because the display host must not ask `/api/v1/principal` — that
|
||||
* endpoint answers a question about *people*, and a paired device is deliberately anonymous to it
|
||||
* (ADR 0036). Reading the viewer from the response that already performed the authorization means
|
||||
* the display never has to infer "no human session, so presumably a device", and the two identity
|
||||
* classes never have to be told apart by elimination.
|
||||
*/
|
||||
export type HostDisplayViewer =
|
||||
| { readonly kind: "authenticated"; readonly userId: string }
|
||||
| { readonly kind: "device"; readonly deviceId: string };
|
||||
|
||||
export interface HostModuleDisplayResource {
|
||||
readonly module: HostModuleDisplayDescriptor;
|
||||
readonly viewer: HostDisplayViewer;
|
||||
}
|
||||
|
||||
export interface ModuleDisplayRoutesOptions extends AuthorizationMiddlewareOptions {
|
||||
@@ -96,12 +110,26 @@ function snapshotAssets(input: DisplayHostAssets): DisplayHostAssets {
|
||||
}
|
||||
}
|
||||
|
||||
function describeViewer(principal: EkklesiaPrincipal): HostDisplayViewer | undefined {
|
||||
if (principal.kind === "authenticated") {
|
||||
return { kind: "authenticated", userId: principal.userId };
|
||||
}
|
||||
if (principal.kind === "device") {
|
||||
return { deviceId: principal.deviceId, kind: "device" };
|
||||
}
|
||||
// Unreachable behind the permission gate: the display permission is `restricted`, which no
|
||||
// anonymous principal satisfies. Stated rather than assumed.
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function describeDisplay(
|
||||
options: ModuleDisplayRoutesOptions,
|
||||
principal: EkklesiaPrincipal,
|
||||
display: PublishableModuleDisplay,
|
||||
viewer: HostDisplayViewer,
|
||||
): Promise<HostModuleDisplayResource> {
|
||||
return {
|
||||
viewer,
|
||||
module: {
|
||||
api: { baseUrl: moduleApiBaseUrl(display.moduleId) },
|
||||
display: { url: moduleDisplayUiArtifactUrl(display) },
|
||||
@@ -126,7 +154,21 @@ function mountDisplay(
|
||||
// neither the permission nor the artifact; it can only hit this exact pre-composed route.
|
||||
const requireDisplayPermission = requirePermission(options, display.displayPermission);
|
||||
|
||||
app.get(moduleDisplayPageUrl(display.moduleId), requireDisplayPermission, () => {
|
||||
/**
|
||||
* The page itself is **not** permission-gated, and the descriptor below still is.
|
||||
*
|
||||
* An unattended screen has no identity until someone pairs it, so a gate here would mean a new
|
||||
* television could only ever be told 403 — there would be nowhere for it to display a pairing
|
||||
* code, and the only way to adopt one would be to sign a human into it, which is exactly the
|
||||
* model this pass exists to remove (ADR 0036).
|
||||
*
|
||||
* Serving it costs nothing, because it carries nothing: these are the same inert, module-agnostic
|
||||
* bytes for every display, with no module id, no data, and one absolute script URL that was
|
||||
* already public. Authorization lives entirely in the descriptor — the page can render, and then
|
||||
* learns it may show only a pairing code. What this does reveal is that a module with a display
|
||||
* exists at that path, which any pairing flow must reveal to the device it is pairing.
|
||||
*/
|
||||
app.get(moduleDisplayPageUrl(display.moduleId), () => {
|
||||
return new Response(options.assets.html, {
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
@@ -141,7 +183,12 @@ function mountDisplay(
|
||||
c.header("Cache-Control", "no-store");
|
||||
c.header("Vary", "Origin, Cookie");
|
||||
try {
|
||||
return c.json(await describeDisplay(options, getAuthorizedPrincipal(c), display), 200);
|
||||
const principal = getAuthorizedPrincipal(c);
|
||||
const viewer = describeViewer(principal);
|
||||
if (!viewer) {
|
||||
return displayFailure(c);
|
||||
}
|
||||
return c.json(await describeDisplay(options, principal, display, viewer), 200);
|
||||
} catch {
|
||||
return displayFailure(c);
|
||||
}
|
||||
|
||||
+19
-2
@@ -11,6 +11,7 @@ import {
|
||||
createAuthorizationStore,
|
||||
} from "@ekklesia/core/authorization";
|
||||
import { createDashboardStore } from "@ekklesia/core/dashboard";
|
||||
import { createDeviceStore } from "@ekklesia/core/devices";
|
||||
import { createIdentityRuntime, type IdentityRateLimitOverride } from "@ekklesia/core/identity";
|
||||
import {
|
||||
createEnvironmentModuleSecretSource,
|
||||
@@ -32,7 +33,6 @@ import {
|
||||
import { type ServerType, serve } from "@hono/node-server";
|
||||
import type { Hono } from "hono";
|
||||
import { createApiApp } from "./app.js";
|
||||
import { loadDisplayHostAssets } from "./display-host-assets.js";
|
||||
import {
|
||||
type ClientAddressConfigInput,
|
||||
type ClientAddressResolver,
|
||||
@@ -41,6 +41,8 @@ import {
|
||||
} from "./client-address.js";
|
||||
import { type ApiRuntimeConfig, createApiRuntimeConfig } from "./config.js";
|
||||
import { type ApiDatabaseHandle, createApiDatabase } from "./database.js";
|
||||
import { withDevicePrincipals } from "./device-principal.js";
|
||||
import { loadDisplayHostAssets } from "./display-host-assets.js";
|
||||
import { prepareStartupModuleInventory } from "./platform-permissions.js";
|
||||
|
||||
const connectionTimeoutMs = 10_000;
|
||||
@@ -419,6 +421,7 @@ export async function startApi(
|
||||
let services: ModuleRuntimeServices;
|
||||
let runtime: ReturnType<typeof createIdentityRuntime>;
|
||||
let authorizationStore: ReturnType<typeof createAuthorizationStore>;
|
||||
let deviceStore: ReturnType<typeof createDeviceStore>;
|
||||
try {
|
||||
services = Object.freeze({ database: databaseHandle.module });
|
||||
runtime = createIdentityRuntime({
|
||||
@@ -427,12 +430,16 @@ export async function startApi(
|
||||
...(options.rateLimitOverride ? { rateLimitOverride: options.rateLimitOverride } : {}),
|
||||
});
|
||||
authorizationStore = createAuthorizationStore(databaseHandle.authorization);
|
||||
deviceStore = createDeviceStore(databaseHandle.devices);
|
||||
} catch (error) {
|
||||
await safeCloseDatabase(databaseHandle);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const evaluator = createAuthorizationEvaluator({
|
||||
// Device authority reaches the one evaluator here. There is no second decision point: a device
|
||||
// is allowed or denied by the same function, with the same deny-by-default, as a person.
|
||||
devices: deviceStore,
|
||||
grants: authorizationStore,
|
||||
platformOwners: authorizationStore,
|
||||
});
|
||||
@@ -572,7 +579,17 @@ export async function startApi(
|
||||
},
|
||||
// A typed view over the same single pool as identity, authorization, and the module facade.
|
||||
dashboard: createDashboardStore(databaseHandle.dashboard),
|
||||
runtime,
|
||||
devices: {
|
||||
// `Secure` follows the deployment's own scheme, read from the already-validated identity
|
||||
// base URL rather than from any request. Production is https by configuration policy, so a
|
||||
// real deployment always gets a Secure device cookie; a plaintext development origin would
|
||||
// silently drop one.
|
||||
secureCookies: config.identity.baseUrl.startsWith("https://"),
|
||||
store: deviceStore,
|
||||
},
|
||||
// Principal resolution, extended with managed devices. A human session still wins, and this
|
||||
// is the only place a device credential ever becomes a principal.
|
||||
runtime: withDevicePrincipals({ devices: deviceStore, runtime }),
|
||||
trustedOrigins: config.identity.trustedOrigins,
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@@ -223,6 +223,7 @@ async function applyCoreMigrations(url: string): Promise<void> {
|
||||
"core:0003_dashboard_navigation_tables",
|
||||
"core:0004_module_lifecycle_state",
|
||||
"core:0005_module_configuration",
|
||||
"core:0006_device_identity",
|
||||
]);
|
||||
expect(aggregate.migrations[0]?.checksum).toBe(
|
||||
"f8f2086ef06f7a6943e8ffc4350bb010b37aed04c0a72030d2b153c986b1325f",
|
||||
@@ -2517,10 +2518,10 @@ describe.sequential("live API — installed module permission end-to-end", () =>
|
||||
expect(moduleCheck).toMatchObject({ status: "pass" });
|
||||
expect(moduleCheck?.details).toEqual(["calendar 0.1.0"]);
|
||||
expect(permissionsCheck).toMatchObject({
|
||||
// Core's own five (`core.authorization.grants.manage`, `core.modules.ui.read`,
|
||||
// Core's own six (`core.authorization.grants.manage`, `core.modules.ui.read`,
|
||||
// `core.dashboard.navigation.manage`, `core.modules.lifecycle.manage`,
|
||||
// `core.modules.configuration.manage`) plus the fixture module's one.
|
||||
details: ["6 permissions registered"],
|
||||
// `core.modules.configuration.manage`, `core.devices.manage`) plus the fixture module's one.
|
||||
details: ["7 permissions registered"],
|
||||
status: "pass",
|
||||
});
|
||||
// Doctor and permission composition read only the manifest — the fixture's register/start
|
||||
|
||||
@@ -0,0 +1,810 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
createAuthorizationDrizzleDatabase,
|
||||
createInitialPlatformOwner,
|
||||
} from "@ekklesia/core/authorization";
|
||||
import {
|
||||
createBootstrapIdentityCreator,
|
||||
createIdentityDrizzleDatabase,
|
||||
} from "@ekklesia/core/identity";
|
||||
import {
|
||||
applyModuleMigrations,
|
||||
createPostgresMigrationDatabase,
|
||||
discoverAllMigrations,
|
||||
} from "@ekklesia/core/migrations";
|
||||
import { Client, type QueryResultRow } from "pg";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { createApiRuntimeConfig } from "../src/config.js";
|
||||
import { type RunningApi, startApi } from "../src/server.js";
|
||||
|
||||
/**
|
||||
* Device pairing end to end, against real PostgreSQL and the real HTTP transport (ADR 0036).
|
||||
*
|
||||
* The whole point is that none of this is mocked. A screen with no identity asks to be paired, a
|
||||
* real administrator signs in through the real login transport and approves it, the host issues a
|
||||
* credential in a real `Set-Cookie`, and the resulting device opens a real display descriptor and a
|
||||
* real realtime stream — and is then revoked and loses all of it. Anything short of that would
|
||||
* prove that rows were written, not that a television in a foyer works.
|
||||
*/
|
||||
const integrationDatabaseUrlEnvironment = "EKKLESIA_MIGRATION_TEST_DATABASE_URL";
|
||||
const repositoryRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
|
||||
const coreMigrationsDirectory = path.join(repositoryRoot, "core", "drizzle");
|
||||
const trackedDatabases = new Set<string>();
|
||||
const trackedDirectories: string[] = [];
|
||||
let databaseCounter = 0;
|
||||
|
||||
const identityBaseUrl = "https://identity.example.test";
|
||||
const dashboardOrigin = "https://dashboard.example.test";
|
||||
const untrustedOrigin = "https://evil.example.test";
|
||||
const ownerPassword = "correct horse battery staple";
|
||||
const displayPermission = "announcements.slideshow.view";
|
||||
|
||||
class IntegrationHarnessError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "IntegrationHarnessError";
|
||||
this.stack = `${this.name}: ${this.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
function baseDatabaseUrl(): string {
|
||||
const url = process.env[integrationDatabaseUrlEnvironment];
|
||||
if (typeof url !== "string" || url.trim() === "") {
|
||||
throw new IntegrationHarnessError("The integration database URL is not configured.");
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function databaseUrl(name: string): string {
|
||||
const url = new URL(baseDatabaseUrl());
|
||||
url.pathname = `/${name}`;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
async function openAdministrativeClient(): Promise<Client> {
|
||||
const client = new Client({ connectionString: baseDatabaseUrl() });
|
||||
await client.connect();
|
||||
return client;
|
||||
}
|
||||
|
||||
async function safeQuery<T extends QueryResultRow>(
|
||||
client: Client,
|
||||
text: string,
|
||||
values: readonly unknown[] = [],
|
||||
): Promise<T[]> {
|
||||
try {
|
||||
return (await client.query<T>(text, [...values])).rows;
|
||||
} catch {
|
||||
throw new IntegrationHarnessError("An integration database statement failed.");
|
||||
}
|
||||
}
|
||||
|
||||
async function query<T extends QueryResultRow>(
|
||||
url: string,
|
||||
text: string,
|
||||
values: readonly unknown[] = [],
|
||||
): Promise<T[]> {
|
||||
const client = new Client({ connectionString: url });
|
||||
await client.connect();
|
||||
try {
|
||||
return await safeQuery<T>(client, text, values);
|
||||
} finally {
|
||||
await client.end().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
/** A display-capable module: one display entrypoint, one restricted permission protecting it, and
|
||||
* one realtime channel gated by that same permission. */
|
||||
async function createDisplayModuleDirectory(): Promise<string> {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "ekklesia-device-pairing-"));
|
||||
trackedDirectories.push(directory);
|
||||
const moduleDirectory = path.join(directory, "announcements");
|
||||
await mkdir(path.join(moduleDirectory, "dist/server"), { recursive: true });
|
||||
await mkdir(path.join(moduleDirectory, "dist/ui"), { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
path.join(moduleDirectory, "package.json"),
|
||||
JSON.stringify({
|
||||
ekklesia: { layer: "module" },
|
||||
name: "@test/module-announcements",
|
||||
type: "module",
|
||||
version: "1.0.0",
|
||||
}),
|
||||
),
|
||||
writeFile(
|
||||
path.join(moduleDirectory, "ekklesia.module.json"),
|
||||
JSON.stringify({
|
||||
compatibility: { moduleSdk: "^0.1.0", platform: "^0.1.0" },
|
||||
entrypoints: {
|
||||
display: { artifact: "./dist/ui/display.js", permission: displayPermission },
|
||||
server: "./dist/server/index.js",
|
||||
},
|
||||
id: "announcements",
|
||||
manifestVersion: 6,
|
||||
name: "Announcements fixture",
|
||||
permissions: [
|
||||
{
|
||||
baseline: "restricted",
|
||||
description: "View the announcement slideshow.",
|
||||
id: displayPermission,
|
||||
},
|
||||
],
|
||||
version: "1.0.0",
|
||||
}),
|
||||
),
|
||||
writeFile(
|
||||
path.join(moduleDirectory, "dist/server/index.js"),
|
||||
`export default {
|
||||
id: "announcements",
|
||||
version: "1.0.0",
|
||||
register({ realtime }) {
|
||||
realtime.channel({ channel: "state", permission: ${JSON.stringify(displayPermission)} });
|
||||
},
|
||||
start({ realtime }) {
|
||||
realtime.publish("state", { slides: [] });
|
||||
},
|
||||
stop() {},
|
||||
};\n`,
|
||||
),
|
||||
writeFile(path.join(moduleDirectory, "dist/ui/display.js"), "export function mount() {}\n"),
|
||||
]);
|
||||
return directory;
|
||||
}
|
||||
|
||||
async function createMigratedDatabase(label: string): Promise<string> {
|
||||
databaseCounter += 1;
|
||||
const name =
|
||||
`ekk_device_${label}_${databaseCounter}_${randomBytes(4).toString("hex")}`.toLowerCase();
|
||||
const admin = await openAdministrativeClient();
|
||||
try {
|
||||
await safeQuery(admin, `create database "${name}"`);
|
||||
} finally {
|
||||
await admin.end().catch(() => undefined);
|
||||
}
|
||||
trackedDatabases.add(name);
|
||||
const url = databaseUrl(name);
|
||||
const emptyModules = await mkdtemp(path.join(tmpdir(), "ekklesia-device-no-modules-"));
|
||||
try {
|
||||
const aggregate = await discoverAllMigrations({
|
||||
coreMigrationsDirectory,
|
||||
moduleDiscovery: {
|
||||
moduleSdkVersion: "0.1.0",
|
||||
modulesDirectory: emptyModules,
|
||||
platformVersion: "0.1.0",
|
||||
},
|
||||
});
|
||||
await applyModuleMigrations({ aggregate, database: createPostgresMigrationDatabase(url) });
|
||||
} finally {
|
||||
await rm(emptyModules, { force: true, recursive: true });
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
async function startPlatform(url: string, modulesDirectory: string): Promise<RunningApi> {
|
||||
const config = createApiRuntimeConfig(
|
||||
{
|
||||
databaseUrl: url,
|
||||
host: "127.0.0.1",
|
||||
identity: {
|
||||
baseUrl: identityBaseUrl,
|
||||
// The production posture: no public signup anywhere in this suite.
|
||||
publicSignupEnabled: false,
|
||||
secret: "integration-test-secret-0123456789abcdefgh",
|
||||
trustedOrigins: [identityBaseUrl, dashboardOrigin],
|
||||
},
|
||||
port: 0,
|
||||
},
|
||||
{ environment: "development" },
|
||||
);
|
||||
return startApi(config, {
|
||||
modulesDirectoryOverride: modulesDirectory,
|
||||
rateLimitOverride: { max: 1000, window: 1 },
|
||||
});
|
||||
}
|
||||
|
||||
function apiOrigin(running: RunningApi): string {
|
||||
const address = running.server.address();
|
||||
if (!address || typeof address !== "object") {
|
||||
throw new IntegrationHarnessError("The API integration server has no bound address.");
|
||||
}
|
||||
return `http://127.0.0.1:${address.port}`;
|
||||
}
|
||||
|
||||
/** Matches a cookie by suffix, because Better Auth prefixes its session cookie with `__Secure-`
|
||||
* whenever the configured base URL is https — which this harness's is. */
|
||||
function cookiePair(response: Response, name: string): string | undefined {
|
||||
for (const header of response.headers.getSetCookie()) {
|
||||
const pair = header.split(";")[0]?.trim() ?? "";
|
||||
const cookieName = pair.slice(0, Math.max(0, pair.indexOf("=")));
|
||||
if (cookieName === name || cookieName.endsWith(name)) {
|
||||
return pair;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function setCookieFor(response: Response, name: string): string | undefined {
|
||||
return response.headers.getSetCookie().find((header) => header.startsWith(`${name}=`));
|
||||
}
|
||||
|
||||
async function createOwner(url: string, origin: string): Promise<string> {
|
||||
const email = `owner-${randomBytes(4).toString("hex")}@example.test`;
|
||||
const authorization = createAuthorizationDrizzleDatabase(url);
|
||||
const identity = createIdentityDrizzleDatabase(url, {});
|
||||
try {
|
||||
await createInitialPlatformOwner(
|
||||
{
|
||||
authorizationDb: authorization.db,
|
||||
createIdentity: createBootstrapIdentityCreator(identity.db),
|
||||
identityDb: identity.db,
|
||||
},
|
||||
{ email, name: "Platform Owner", password: ownerPassword },
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([authorization.close(), identity.close()]);
|
||||
}
|
||||
const signIn = await fetch(`${origin}/api/auth/sign-in/email`, {
|
||||
body: JSON.stringify({ email, password: ownerPassword }),
|
||||
headers: { "content-type": "application/json", origin: dashboardOrigin },
|
||||
method: "POST",
|
||||
});
|
||||
const cookie = cookiePair(signIn, "better-auth.session_token");
|
||||
if (signIn.status !== 200 || cookie === undefined) {
|
||||
throw new IntegrationHarnessError("The platform owner could not sign in.");
|
||||
}
|
||||
return cookie;
|
||||
}
|
||||
|
||||
interface Platform {
|
||||
readonly api: RunningApi;
|
||||
readonly origin: string;
|
||||
readonly url: string;
|
||||
readonly ownerCookie: string;
|
||||
readonly close: () => Promise<void>;
|
||||
}
|
||||
|
||||
async function platform(label: string): Promise<Platform> {
|
||||
const url = await createMigratedDatabase(label);
|
||||
const modulesDirectory = await createDisplayModuleDirectory();
|
||||
const api = await startPlatform(url, modulesDirectory);
|
||||
const origin = apiOrigin(api);
|
||||
const ownerCookie = await createOwner(url, origin);
|
||||
return {
|
||||
api,
|
||||
close: async () => {
|
||||
await api.shutdown();
|
||||
},
|
||||
origin,
|
||||
ownerCookie,
|
||||
url,
|
||||
};
|
||||
}
|
||||
|
||||
/** The device's own browser: no human session, only whatever cookies the host has set on it. */
|
||||
class DeviceBrowser {
|
||||
#cookies = new Map<string, string>();
|
||||
|
||||
constructor(private readonly origin: string) {}
|
||||
|
||||
absorb(response: Response): void {
|
||||
for (const header of response.headers.getSetCookie()) {
|
||||
const pair = header.split(";")[0] ?? "";
|
||||
const separator = pair.indexOf("=");
|
||||
if (separator === -1) {
|
||||
continue;
|
||||
}
|
||||
const name = pair.slice(0, separator).trim();
|
||||
const value = pair.slice(separator + 1).trim();
|
||||
if (value.length === 0 || /max-age=0/iu.test(header)) {
|
||||
this.#cookies.delete(name);
|
||||
} else {
|
||||
this.#cookies.set(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
header(): string {
|
||||
return [...this.#cookies].map(([name, value]) => `${name}=${value}`).join("; ");
|
||||
}
|
||||
|
||||
has(name: string): boolean {
|
||||
return this.#cookies.has(name);
|
||||
}
|
||||
|
||||
overwrite(name: string, value: string): void {
|
||||
this.#cookies.set(name, value);
|
||||
}
|
||||
|
||||
async request(path: string, init: RequestInit = {}): Promise<Response> {
|
||||
const cookie = this.header();
|
||||
const response = await fetch(`${this.origin}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
origin: dashboardOrigin,
|
||||
...(cookie.length > 0 ? { cookie } : {}),
|
||||
...(init.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
this.absorb(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
post(path: string, body: unknown): Promise<Response> {
|
||||
return this.request(path, {
|
||||
body: JSON.stringify(body),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function adminRequest(
|
||||
origin: string,
|
||||
cookie: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
overrides: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
return fetch(`${origin}${path}`, {
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
headers: {
|
||||
cookie,
|
||||
origin: dashboardOrigin,
|
||||
...(body === undefined ? {} : { "content-type": "application/json" }),
|
||||
...(overrides.headers as Record<string, string> | undefined),
|
||||
},
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
/** Drives a screen from "nobody has paired me" to "I hold a device session". */
|
||||
async function pairDevice(
|
||||
platform: Platform,
|
||||
device: DeviceBrowser,
|
||||
deviceName = "Foyer TV",
|
||||
): Promise<{ readonly code: string }> {
|
||||
const requested = await device.post("/api/v1/device-pairing/requests", {
|
||||
moduleId: "announcements",
|
||||
});
|
||||
if (requested.status !== 201) {
|
||||
throw new IntegrationHarnessError("The pairing request was refused.");
|
||||
}
|
||||
const { code } = (await requested.json()) as { code: string };
|
||||
const approved = await adminRequest(
|
||||
platform.origin,
|
||||
platform.ownerCookie,
|
||||
"/api/v1/device-pairing/approvals",
|
||||
{ code, deviceName },
|
||||
);
|
||||
if (approved.status !== 200) {
|
||||
throw new IntegrationHarnessError("The pairing approval was refused.");
|
||||
}
|
||||
const claimed = await device.post("/api/v1/device-pairing/claims", {});
|
||||
if (((await claimed.json()) as { status: string }).status !== "paired") {
|
||||
throw new IntegrationHarnessError("The device was not issued a session.");
|
||||
}
|
||||
return { code };
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
const admin = await openAdministrativeClient().catch(() => undefined);
|
||||
if (admin) {
|
||||
try {
|
||||
for (const name of trackedDatabases) {
|
||||
await safeQuery(admin, `drop database if exists "${name}" with (force)`).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await admin.end().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
for (const directory of trackedDirectories.splice(0)) {
|
||||
await rm(directory, { force: true, recursive: true }).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
describe.sequential("display device pairing, end to end", () => {
|
||||
it("takes an unpaired screen all the way to a working display, and back off again", async () => {
|
||||
const running = await platform("e2e");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
// 1. The screen loads. It has no identity, so the descriptor refuses it — but the page it
|
||||
// needs in order to show a code is served.
|
||||
expect((await device.request("/display/announcements")).status).toBe(200);
|
||||
expect((await device.request("/api/v1/module-displays/announcements")).status).toBe(403);
|
||||
|
||||
// 2. It asks to be paired and receives a code plus an HttpOnly claim cookie.
|
||||
const requested = await device.post("/api/v1/device-pairing/requests", {
|
||||
moduleId: "announcements",
|
||||
});
|
||||
expect(requested.status).toBe(201);
|
||||
const body = (await requested.json()) as Record<string, unknown>;
|
||||
expect(body.code).toMatch(/^[0-9]{6}$/u);
|
||||
// The claim secret is never in the body — only in a cookie script cannot read.
|
||||
expect(JSON.stringify(body)).not.toContain("claim");
|
||||
const claimCookie = setCookieFor(requested, "ekklesia_device_pairing");
|
||||
expect(claimCookie).toMatch(/HttpOnly/iu);
|
||||
|
||||
// 3. Nothing has happened yet: polling says pending, and the display is still refused.
|
||||
expect(
|
||||
(
|
||||
(await (await device.post("/api/v1/device-pairing/claims", {})).json()) as {
|
||||
status: string;
|
||||
}
|
||||
).status,
|
||||
).toBe("pending");
|
||||
|
||||
// 4. The administrator looks the code up, sees what it wants, and approves it by name.
|
||||
const lookup = await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
"/api/v1/device-pairing/lookups",
|
||||
{ code: body.code },
|
||||
);
|
||||
expect(lookup.status).toBe(200);
|
||||
expect(await lookup.json()).toMatchObject({
|
||||
moduleId: "announcements",
|
||||
permissionId: displayPermission,
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
"/api/v1/device-pairing/approvals",
|
||||
{ code: body.code, deviceName: "Foyer TV" },
|
||||
)
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
// 5. The screen collects its credential — through Set-Cookie, never through JSON.
|
||||
const claimed = await device.post("/api/v1/device-pairing/claims", {});
|
||||
expect(await claimed.json()).toEqual({ status: "paired" });
|
||||
const sessionCookie = setCookieFor(claimed, "ekklesia_device_session");
|
||||
expect(sessionCookie).toMatch(/HttpOnly/iu);
|
||||
expect(sessionCookie).toMatch(/SameSite=Strict/iu);
|
||||
expect(sessionCookie).toMatch(/Path=\//u);
|
||||
expect(sessionCookie).not.toMatch(/Domain=/iu);
|
||||
// The spent pairing cookie is cleared rather than left on the device.
|
||||
expect(device.has("ekklesia_device_pairing")).toBe(false);
|
||||
expect(device.has("ekklesia_device_session")).toBe(true);
|
||||
|
||||
// 6. The display now works, and reports the device as its viewer.
|
||||
const descriptor = await device.request("/api/v1/module-displays/announcements");
|
||||
expect(descriptor.status).toBe(200);
|
||||
const descriptorBody = (await descriptor.json()) as {
|
||||
viewer: { kind: string; deviceId?: string };
|
||||
module: { permissions: string[] };
|
||||
};
|
||||
expect(descriptorBody.viewer.kind).toBe("device");
|
||||
expect(descriptorBody.viewer.deviceId).toMatch(/^[0-9a-f-]{36}$/u);
|
||||
// Exactly the one permission it was paired for.
|
||||
expect(descriptorBody.module.permissions).toEqual([displayPermission]);
|
||||
|
||||
// 7. Realtime, through the ordinary permission-gated channel.
|
||||
const stream = await device.request("/api/v1/module-realtime/announcements/state", {
|
||||
headers: { accept: "text/event-stream" },
|
||||
});
|
||||
expect(stream.status).toBe(200);
|
||||
expect(stream.headers.get("content-type")).toContain("text/event-stream");
|
||||
await stream.body?.cancel();
|
||||
|
||||
// 8. The device is still nobody as far as the Dashboard is concerned.
|
||||
expect(await (await device.request("/api/v1/principal")).json()).toEqual({
|
||||
kind: "anonymous",
|
||||
});
|
||||
expect((await device.request("/api/v1/dashboard/navigation")).status).toBe(403);
|
||||
expect((await device.request("/api/v1/devices")).status).toBe(403);
|
||||
|
||||
// 9. The administrator revokes it.
|
||||
const devices = (await (
|
||||
await adminRequest(running.origin, running.ownerCookie, "/api/v1/devices")
|
||||
).json()) as { devices: Array<{ id: string; name: string; permissions: string[] }> };
|
||||
expect(devices.devices).toHaveLength(1);
|
||||
expect(devices.devices[0]?.name).toBe("Foyer TV");
|
||||
expect(devices.devices[0]?.permissions).toEqual([displayPermission]);
|
||||
const revoked = await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
`/api/v1/devices/${devices.devices[0]?.id}/revoke`,
|
||||
{},
|
||||
);
|
||||
expect(revoked.status).toBe(204);
|
||||
|
||||
// 10. Everything it could do, it can no longer do — while still holding its cookie.
|
||||
expect(device.has("ekklesia_device_session")).toBe(true);
|
||||
expect((await device.request("/api/v1/module-displays/announcements")).status).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await device.request("/api/v1/module-realtime/announcements/state", {
|
||||
headers: { accept: "text/event-stream" },
|
||||
})
|
||||
).status,
|
||||
).toBe(403);
|
||||
// And the screen can start over: the page it needs for a new code is still served.
|
||||
expect((await device.request("/display/announcements")).status).toBe(200);
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stores no usable credential, and puts none in any response body", async () => {
|
||||
const running = await platform("secrets");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
await pairDevice(running, device);
|
||||
const credential = device.header().replace(/^.*ekklesia_device_session=/u, "");
|
||||
expect(credential.length).toBeGreaterThan(20);
|
||||
|
||||
const stored = await query<{ credential_hash: string; name: string }>(
|
||||
running.url,
|
||||
`select credential_hash, name from ekklesia_core_device`,
|
||||
);
|
||||
expect(stored).toHaveLength(1);
|
||||
// The raw credential is nowhere in the database — only an irreversible digest of it.
|
||||
expect(stored[0]?.credential_hash).not.toContain(credential);
|
||||
expect(stored[0]?.credential_hash).toMatch(/^[0-9a-f]{64}$/u);
|
||||
|
||||
const everything = JSON.stringify(
|
||||
await query(running.url, `select * from ekklesia_core_device_pairing_request`),
|
||||
);
|
||||
expect(everything).not.toContain(credential);
|
||||
|
||||
// The descriptor a module's UI can read carries no credential either.
|
||||
const descriptor = await device.request("/api/v1/module-displays/announcements");
|
||||
expect(await descriptor.text()).not.toContain(credential);
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
|
||||
describe("pairing cannot be talked into anything", () => {
|
||||
it("derives the permission from the display, never from the request", async () => {
|
||||
const running = await platform("derive");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
// The browser tries to name its own permission and its own module.
|
||||
const requested = await device.post("/api/v1/device-pairing/requests", {
|
||||
moduleId: "announcements",
|
||||
permission: "core.devices.manage",
|
||||
permissionId: "core.devices.manage",
|
||||
});
|
||||
expect(requested.status).toBe(201);
|
||||
const { code } = (await requested.json()) as { code: string };
|
||||
|
||||
const lookup = await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
"/api/v1/device-pairing/lookups",
|
||||
{ code },
|
||||
);
|
||||
// The host recorded the display's own declared permission and ignored the rest.
|
||||
expect(await lookup.json()).toMatchObject({ permissionId: displayPermission });
|
||||
|
||||
const stored = await query<{ permission_id: string }>(
|
||||
running.url,
|
||||
`select permission_id from ekklesia_core_device_pairing_request`,
|
||||
);
|
||||
expect(stored.map((row) => row.permission_id)).toEqual([displayPermission]);
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses to start pairing for a module that has no display", async () => {
|
||||
const running = await platform("nodisplay");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
for (const moduleId of ["calendar", "core", "../announcements", ""]) {
|
||||
const response = await device.post("/api/v1/device-pairing/requests", { moduleId });
|
||||
expect(response.status, moduleId).toBeGreaterThanOrEqual(400);
|
||||
}
|
||||
expect(
|
||||
await query(running.url, `select id from ekklesia_core_device_pairing_request`),
|
||||
).toHaveLength(0);
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("issues nothing to someone who knows only the code", async () => {
|
||||
const running = await platform("codeonly");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
const onlooker = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
const requested = await device.post("/api/v1/device-pairing/requests", {
|
||||
moduleId: "announcements",
|
||||
});
|
||||
const { code } = (await requested.json()) as { code: string };
|
||||
await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
"/api/v1/device-pairing/approvals",
|
||||
{
|
||||
code,
|
||||
deviceName: "Foyer TV",
|
||||
},
|
||||
);
|
||||
|
||||
// Someone who read the code off the television — and even guessed the request exists —
|
||||
// holds no claim cookie, so there is nothing for them to collect.
|
||||
const stolen = await onlooker.post("/api/v1/device-pairing/claims", {});
|
||||
expect(stolen.status).toBe(400);
|
||||
expect(onlooker.has("ekklesia_device_session")).toBe(false);
|
||||
|
||||
// The real screen still gets its credential.
|
||||
const claimed = await device.post("/api/v1/device-pairing/claims", {});
|
||||
expect(await claimed.json()).toEqual({ status: "paired" });
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("approval is an administrator's act", () => {
|
||||
it("refuses an anonymous or unauthorized caller, and enforces a trusted origin", async () => {
|
||||
const running = await platform("approve");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
const requested = await device.post("/api/v1/device-pairing/requests", {
|
||||
moduleId: "announcements",
|
||||
});
|
||||
const { code } = (await requested.json()) as { code: string };
|
||||
|
||||
// Anonymous.
|
||||
const anonymous = await fetch(`${running.origin}/api/v1/device-pairing/approvals`, {
|
||||
body: JSON.stringify({ code, deviceName: "Intruder TV" }),
|
||||
headers: { "content-type": "application/json", origin: dashboardOrigin },
|
||||
method: "POST",
|
||||
});
|
||||
expect(anonymous.status).toBe(403);
|
||||
|
||||
// The paired-device cookie is not an administrator either — a device can never approve
|
||||
// another device, or itself.
|
||||
const selfApproval = await device.post("/api/v1/device-pairing/approvals", {
|
||||
code,
|
||||
deviceName: "Self TV",
|
||||
});
|
||||
expect(selfApproval.status).toBe(403);
|
||||
|
||||
// A real administrator from an untrusted origin: CSRF policy applies before anything else.
|
||||
const crossOrigin = await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
"/api/v1/device-pairing/approvals",
|
||||
{ code, deviceName: "Foyer TV" },
|
||||
{ headers: { origin: untrustedOrigin } },
|
||||
);
|
||||
expect(crossOrigin.status).toBe(403);
|
||||
|
||||
// Nothing was approved by any of that.
|
||||
expect(
|
||||
(
|
||||
(await (await device.post("/api/v1/device-pairing/claims", {})).json()) as {
|
||||
status: string;
|
||||
}
|
||||
).status,
|
||||
).toBe("pending");
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("cannot approve the same code twice, and cannot mint two credentials from one", async () => {
|
||||
const running = await platform("single");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
const requested = await device.post("/api/v1/device-pairing/requests", {
|
||||
moduleId: "announcements",
|
||||
});
|
||||
const { code } = (await requested.json()) as { code: string };
|
||||
expect(
|
||||
(
|
||||
await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
"/api/v1/device-pairing/approvals",
|
||||
{ code, deviceName: "Foyer TV" },
|
||||
)
|
||||
).status,
|
||||
).toBe(200);
|
||||
// A second approval of the same code finds nothing pending.
|
||||
expect(
|
||||
(
|
||||
await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
"/api/v1/device-pairing/approvals",
|
||||
{ code, deviceName: "Second TV" },
|
||||
)
|
||||
).status,
|
||||
).toBe(404);
|
||||
|
||||
// Two claims race for one approved request; exactly one credential may exist.
|
||||
const [first, second] = await Promise.all([
|
||||
device.post("/api/v1/device-pairing/claims", {}),
|
||||
device.post("/api/v1/device-pairing/claims", {}),
|
||||
]);
|
||||
const statuses = [
|
||||
((await first.json()) as { status: string }).status,
|
||||
((await second.json()) as { status: string }).status,
|
||||
];
|
||||
expect(statuses.filter((status) => status === "paired")).toHaveLength(1);
|
||||
expect(await query(running.url, `select id from ekklesia_core_device`)).toHaveLength(1);
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("re-pairs a revoked screen into a fresh identity, leaving the old credential dead", async () => {
|
||||
const running = await platform("repair");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
await pairDevice(running, device, "Foyer TV");
|
||||
const firstCredential = device.header().replace(/^.*ekklesia_device_session=/u, "");
|
||||
const listed = (await (
|
||||
await adminRequest(running.origin, running.ownerCookie, "/api/v1/devices")
|
||||
).json()) as { devices: Array<{ id: string }> };
|
||||
await adminRequest(
|
||||
running.origin,
|
||||
running.ownerCookie,
|
||||
`/api/v1/devices/${listed.devices[0]?.id}/revoke`,
|
||||
{},
|
||||
);
|
||||
|
||||
await pairDevice(running, device, "Foyer TV (replaced)");
|
||||
const secondCredential = device.header().replace(/^.*ekklesia_device_session=/u, "");
|
||||
expect(secondCredential).not.toBe(firstCredential);
|
||||
expect((await device.request("/api/v1/module-displays/announcements")).status).toBe(200);
|
||||
|
||||
// Re-pairing creates a new identity rather than reviving the revoked one, so the old
|
||||
// credential can never come back — presenting it again is simply anonymous.
|
||||
const revokedBrowser = new DeviceBrowser(running.origin);
|
||||
revokedBrowser.overwrite("ekklesia_device_session", firstCredential);
|
||||
expect((await revokedBrowser.request("/api/v1/module-displays/announcements")).status).toBe(
|
||||
403,
|
||||
);
|
||||
|
||||
const devices = (await (
|
||||
await adminRequest(running.origin, running.ownerCookie, "/api/v1/devices")
|
||||
).json()) as { devices: Array<{ revoked: boolean }> };
|
||||
expect(devices.devices).toHaveLength(2);
|
||||
expect(devices.devices.filter((entry) => entry.revoked)).toHaveLength(1);
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a human administrator's own session unaffected by a device cookie", async () => {
|
||||
const running = await platform("mixed");
|
||||
const device = new DeviceBrowser(running.origin);
|
||||
try {
|
||||
await pairDevice(running, device);
|
||||
const deviceCredential = device.header();
|
||||
|
||||
// A browser presenting both: the person still wins, and stays a person.
|
||||
const both = await fetch(`${running.origin}/api/v1/principal`, {
|
||||
headers: { cookie: `${running.ownerCookie}; ${deviceCredential}` },
|
||||
});
|
||||
expect(((await both.json()) as { kind: string }).kind).toBe("authenticated");
|
||||
|
||||
// And that administrator can still open the display for testing, as a human.
|
||||
const descriptor = await fetch(`${running.origin}/api/v1/module-displays/announcements`, {
|
||||
headers: { cookie: `${running.ownerCookie}; ${deviceCredential}` },
|
||||
});
|
||||
expect(descriptor.status).toBe(200);
|
||||
expect(((await descriptor.json()) as { viewer: { kind: string } }).viewer.kind).toBe(
|
||||
"authenticated",
|
||||
);
|
||||
} finally {
|
||||
await running.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ import { Client, type QueryResultRow } from "pg";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { createApiRuntimeConfig } from "../src/config.js";
|
||||
import { createApiDatabase } from "../src/database.js";
|
||||
import { startApi, type RunningApi } from "../src/server.js";
|
||||
import { type RunningApi, startApi } from "../src/server.js";
|
||||
|
||||
/**
|
||||
* Proves `ModuleRuntimeServices.database` against real PostgreSQL: an installed test module
|
||||
@@ -223,6 +223,7 @@ async function applyCoreMigrations(url: string): Promise<void> {
|
||||
"core:0003_dashboard_navigation_tables",
|
||||
"core:0004_module_lifecycle_state",
|
||||
"core:0005_module_configuration",
|
||||
"core:0006_device_identity",
|
||||
]);
|
||||
await applyModuleMigrations({ aggregate, database: createPostgresMigrationDatabase(url) });
|
||||
} finally {
|
||||
@@ -251,6 +252,7 @@ async function applyMigrationsWithModule(url: string): Promise<void> {
|
||||
"core:0003_dashboard_navigation_tables",
|
||||
"core:0004_module_lifecycle_state",
|
||||
"core:0005_module_configuration",
|
||||
"core:0006_device_identity",
|
||||
"db-facade:0000_initial",
|
||||
]);
|
||||
expect(aggregate.migrations[0]?.checksum).toBe(
|
||||
|
||||
@@ -220,7 +220,7 @@ function signedIn(): EkklesiaPrincipal {
|
||||
}
|
||||
|
||||
describe("module display routes — authorization and descriptor", () => {
|
||||
it("does not let an anonymous viewer open either the page or descriptor", async () => {
|
||||
it("gives an unpaired viewer the inert shell but never the descriptor", async () => {
|
||||
const { app } = await install({ display: true });
|
||||
|
||||
const [page, descriptor] = await Promise.all([
|
||||
@@ -228,18 +228,22 @@ describe("module display routes — authorization and descriptor", () => {
|
||||
app.request(moduleDisplayDescriptorUrl("announcements")),
|
||||
]);
|
||||
|
||||
expect(page.status).toBe(403);
|
||||
// The page is deliberately open: a television nobody has paired has no identity to present, and
|
||||
// a 403 here would leave it nowhere to show a pairing code (ADR 0036). It carries nothing —
|
||||
// the same module-agnostic bytes every display gets, with no module id and no data.
|
||||
expect(page.status).toBe(200);
|
||||
expect(await page.text()).toBe(displayHostAssets.html);
|
||||
|
||||
// Authorization is entirely in the descriptor, and it has not moved.
|
||||
expect(descriptor.status).toBe(403);
|
||||
expect(page.headers.get("cache-control")).toBe("no-store");
|
||||
expect(descriptor.headers.get("cache-control")).toBe("no-store");
|
||||
expect(await page.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
|
||||
expect(await descriptor.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
|
||||
});
|
||||
|
||||
it("requires the declared display permission, not merely an authenticated principal", async () => {
|
||||
const { app } = await install({ display: true, principal: signedIn() });
|
||||
|
||||
expect((await app.request(moduleDisplayPageUrl("announcements"))).status).toBe(403);
|
||||
// Being signed in is not being permitted, and the descriptor is where that is decided.
|
||||
expect((await app.request(moduleDisplayDescriptorUrl("announcements"))).status).toBe(403);
|
||||
});
|
||||
|
||||
@@ -260,6 +264,7 @@ describe("module display routes — authorization and descriptor", () => {
|
||||
expect(page.headers.get("x-content-type-options")).toBe("nosniff");
|
||||
expect(await page.text()).toBe(displayHostAssets.html);
|
||||
expect(await descriptor.json()).toEqual({
|
||||
viewer: { kind: "authenticated", userId: viewerId },
|
||||
module: {
|
||||
api: { baseUrl: moduleApiBaseUrl("announcements") },
|
||||
display: {
|
||||
|
||||
Reference in New Issue
Block a user